Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
Should methods in a Java interface be declared with or without the `public` access modifier?
Technically it doesn't matter, of course. A class method that implements an `interface` is always `public`. But what is a better convention?
Java itself is not consistent in this. See for instance `Collection` vs. `Comparable`, or `Future` vs. `ScriptEngine`.
|
The [JLS](http://docs.oracle.com/javase/specs/jls/se7/html/jls-9.html#jls-9.4) makes this clear:
> It is permitted, but discouraged as a matter of style, to redundantly specify the `public` and/or `abstract` modifier for a method declared in an interface.
|
The public modifier should be omitted in Java interfaces (in my opinion).
Since it does not add any extra information, it just draws attention away from the important stuff.
Most style-guides will recommend that you leave it out, but of course, the most important thing is to be consistent across your codebase, and especially for each interface. The following example could easily confuse someone, who is not 100% fluent in Java:
```
public interface Foo{
public void MakeFoo();
void PerformBar();
}
```
|
Should methods in a Java interface be declared with or without a public access modifier?
|
[
"",
"java",
"interface",
"coding-style",
"public-method",
""
] |
I'm writing a utility in Python that will attach changed files in Subversion to an email and send it when a subset of folders that are under source control in SVN have been changed. I am using the pysvn library to access the repository.
I have a copy of the files on my local file system and I do an update to check if the files have changed since the last time the utility was run.
I am at the point where I am translating the path names in SVN to the path names on my local copy.
Currently I have written the following to do the job:
```
def formatPaths(self, paths):
newPaths = list()
for path in paths:
path = path[len(self.basePath):]
path = path.replace("/", "\\")
newPaths.append(path)
return newPaths
```
self.basePath would be something like "/trunk/project1" and I'm looking to just get the relative path of a subset of folders (I.e. folder1 under "/trunk/project1").
Is this a good way to solve this problem or is there some magical function I missed?
|
Stay with the slice operator, but do not change the loop variable inside the loop. for fun, try the generator expression (or keep the listcomp).
```
baselen = len(self.basePath)
return (path[baselen:].replace("/", "\\") for path in paths)
```
Edit: `lstrip()' is not relevant here. From the [manual](http://docs.python.org/library/stdtypes.html#string-methods):
> str.lstrip([chars])
>
> Return a copy of the string with leading characters removed. If chars is omitted or
> None, whitespace characters are removed. If given and not None, chars must be a
> string; the characters in the string will be stripped from the beginning of the
> string this method is called on.
|
Hm... That would do it:
```
baselen = len(self.basePath)
for path in paths:
path = path[baselen:].replace("/", "\\")
newPaths.append(path)
return newPaths
```
If you like, you can do it like this:
```
baselen = len(self.basePath)
return (path[baselen:].replace("/", "\\") for path in paths)
```
Not calculating `baselen` in every loop iteration is also good practice.
|
Translate SVN path to local file system path in Python
|
[
"",
"python",
"svn",
""
] |
All I need is a way to make a property of one class only 'settable' from one other class (a sort of manager class).
Is this even possible in c#?
My colleague 'reliably' informs me that I have a design flaw, but I feel I should at least ask the community before I concede defeat!
|
No, it's not really possible to do this in any clean way in C#. You probably have a design flaw ;-)
|
You can use the `internal` modifier, which lets all types in the same assembly access the data (or nominated assemblies if using `[InternalsVisibleTo]` - but no: there is no `friend` equivalent in C#.
For example:
```
public string Foo {get; internal set;}
```
|
How can one type access a private setter of another type's property?
|
[
"",
"c#",
"access-modifiers",
""
] |
I have asp.net form that contains fields. When I access this window, my javascript functions can access the fields via the DOM with the getElementById() method and when I postpack to the server I am receiving the updates made by the client.
However, when I launch the form as a child window using Telerik's RadWindow control, the javascript can not access the hidden fields on the child form. Instead I get null.
My questions are:
1. Are hidden fields on a child window
not accessible when the window is
launched from a parent asp.net form?
2. Has anyone attempted this with Telerik controls and run into issues?
**EDIT**
Craig pointed out that the id may be different. Two additional questions then:
1. Can you ensure that the id you assign at the server is actually used?
2. Is using getElementByName() a better mechanism to access DOM elements?
|
To get the ID of your asp.net control do something like this:
```
<%= theControl.ClientID %>
```
getElementByName is not as commonly used as getElementById. The ID attribute is supposed to be unique for each element on the page whereas the name attribute can be duplicated.
|
It is quite possible that the element's ID is not what you think it is. Check the rendered page and see if the ID is there. I am guessing that the page is given a different ID since it is rendered inside another control.
If that is the case, you can have the form render some script that returns the element ID by accessing the controls client ID.
|
Are hidden fields on child window inaccessible from parent window
|
[
"",
"asp.net",
"javascript",
"telerik",
""
] |
What's the difference between the list methods `append()` and `extend()`?
|
[`.append()`](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) appends a specified object at the end of the list:
```
>>> x = [1, 2, 3]
>>> x.append([4, 5])
>>> print(x)
[1, 2, 3, [4, 5]]
```
[`.extend()`](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) extends the list by appending elements from the specified iterable:
```
>>> x = [1, 2, 3]
>>> x.extend([4, 5])
>>> print(x)
[1, 2, 3, 4, 5]
```
|
`.append()` adds an element to a list,
whereas `.extend()` concatenates the first list with another list/iterable.
```
>>> xs = ['A', 'B']
>>> xs
['A', 'B']
>>> xs.append("D")
>>> xs
['A', 'B', 'D']
>>> xs.append(["E", "F"])
>>> xs
['A', 'B', 'D', ['E', 'F']]
>>> xs.insert(2, "C")
>>> xs
['A', 'B', 'C', 'D', ['E', 'F']]
>>> xs.extend(["G", "H"])
>>> xs
['A', 'B', 'C', 'D', ['E', 'F'], 'G', 'H']
```
|
What is the difference between Python's list methods append and extend?
|
[
"",
"python",
"list",
"data-structures",
"append",
"extend",
""
] |
I came across an issue that makes me think there is bug in the 3.0 framework. When I try to use extension methods I get the following error:
```
Missing compiler required member
'System.Runtime.CompilerServices.ExtensionAttribute..ctor'
```
When using this simple code:
```
public static class StringUtils {
static void TestExtension(this String targetString) {
}
}
```
The only way to make this compile error go away is to add the following code:
```
namespace System.Runtime.CompilerServices {
public class ExtensionAttribute : Attribute { }
}
```
It's been a few months since I have used extensions methods, but I'm pretty sure I didn't have to do this. Has anyone else come across this issue?
|
I just ran into this problem myself.
In my case, it was because I converted a VS 2005/.Net 2.0 project to a VS 2008/.Net 3.5 project. The conversion tool kept references to System.Core 2.0, and I couldn't find an easy way to change the references to System.Core 3.5.
I ended up re-creating the project in VS 2008 from scratch, and it was created with proper references to System.Core 3.5
|
I have the exact same problem. The error `System.Runtime.CompilerServices.ExtensionAttribute..ctor` is rather cryptic, and could mean a number of different things.
However, for me It boiled down to the fact that I'm using `Newtonsoft.Json.Net`. I removed the reference to the file `Newtonsoft.Json.Net20.dll`, and the re-added it. After this my solution builds again.
The strangest thing is that when I tried to find out what was different after this procedure by using Subversion Diff, nothing appears to have changed.
So I really don't know what removing and re-adding this reference really does, but it does fix my build issue with this particular error message mentioned by the asker.
## *UPDATE 1*:
For those that come across this again, as the comenters pointed out, the proper way to fix this is to *[Download Json.Net's ZIP](http://json.codeplex.com/releases/view/50552), and there should be a 3.5 version, re-reference 3.5 every where you are using Json.Net and delete the old reference, as it is likely referencing an assembly that was built for older versions of .net.*
## *UPDATE 2*:
[Charlie Flowers](https://stackoverflow.com/users/80112/charlie-flowers) points out that the DLL NewtonSoft labels as being for 3.5 is actually not going to work with 3.5. You have to use the DLL they label as being for .net 2.0
|
Error when using extension methods in C#
|
[
"",
"c#",
".net-3.5",
"extension-methods",
""
] |
What is the most efficient way to store large arrays (10000x100) in a database, say, hsqldb? I need to do this for a certain math program that I'm writing in java. Please help.
The whole array will be retrieved and stored often (not so much individual elements). Also, some meta-data about the array needs to be stored about the array.
|
Great question.
Unless you want to translate your arrays into a set of normalized tables, which it sounds like you don't, you might want to contemplate serialization.
Serialization is a fancy word for turning objects into some format that you can save to disk or a database. The two major formats for serialization are binary and XML, and I'm betting that Java has some support for it.
Depending on what data types you're using, you should be able to turn your array into XML or binary and then save that to a single field in the database. You could get started with this technique in Java by checking out <http://java.sun.com/developer/technicalArticles/Programming/serialization/>. I know that it's built into .NET.
Hope that this helps. Let me know if I can give you any more direction.
|
How about storing the data as a BLOB and using Java to decode the BLOB into an actual Java array? It would be much more efficient for storing and retrieving the whole array in one gulp, but would be terrible for twiddling individual elements.
|
Storing arrays in databases
|
[
"",
"java",
"database",
"hsqldb",
""
] |
I'm trying to figure out how to restrict access to a page unless the page is navigated to from a specific "gate" page. Essentially I want the page to be unaccessible unless you're coming from the page that comes before it in my sitemap. I'm not certain this is even possible. If possible, can you limit your suggestions to using either html or javascript?
|
What if you encrypted a variable (like the current date) and placed that in the "gate" link. When you arrive at the new page, a script decrypts the variable and if it doesn't match or isn't even there, the script redirects to another page.
Something like:
```
<a href="restricted.php?pass=eERadWRWE3ad=">Go!</a>
```
**Edit**: I don't know JS well enough to print that code but I know there are [several libraries](http://www.google.com/search?q=javascript+encryption+library&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a) out there that can do all the encryption/decryption for you.
|
> If possible, can you limit your suggestions to using either html or javascript?
No. **Because there is no secure way** using only these two techniques. Everything that goes on on the client side may be manipulated (trivially easy). If you want to be sure, you have to enforce this on the server side by checking for the `REFERER` (sic!) header.
Mind, even this can be manipulated.
If you're using Apache with `mod_rewrite` enabled, the following code will restrict access according to the referring page:
```
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://www\.example\.com/.*
RewriteRule /* http://www.example.com/access-denied.html [R,L]
```
EDIT: I just checked [the manual](http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html#RewriteRule) … unfortunately, giving a 401 status code isn't possible here. So the above solution isn't perfect because although it blocks access, it doesn't set the HTTP status accordingly. :-/ Leaves a bad taste in my mouth.
|
Restricting access to page unless coming from a specific page
|
[
"",
"javascript",
"html",
""
] |
I'm currently working on an application which requires transmission of speech encoded to a specific audio format.
```
System.Speech.AudioFormat.SpeechAudioFormatInfo synthFormat =
new System.Speech.AudioFormat.SpeechAudioFormatInfo(System.Speech.AudioFormat.EncodingFormat.Pcm,
8000, 16, 1, 16000, 2, null);
```
This states that the audio is in PCM format, 8000 samples per second, 16 bits per sample, mono, 16000 average bytes per second, block alignment of 2.
When I attempt to execute the following code there is nothing written to my MemoryStream instance; however when I change from 8000 samples per second up to 11025 the audio data is written successfully.
```
SpeechSynthesizer synthesizer = new SpeechSynthesizer();
waveStream = new MemoryStream();
PromptBuilder pbuilder = new PromptBuilder();
PromptStyle pStyle = new PromptStyle();
pStyle.Emphasis = PromptEmphasis.None;
pStyle.Rate = PromptRate.Fast;
pStyle.Volume = PromptVolume.ExtraLoud;
pbuilder.StartStyle(pStyle);
pbuilder.StartParagraph();
pbuilder.StartVoice(VoiceGender.Male, VoiceAge.Teen, 2);
pbuilder.StartSentence();
pbuilder.AppendText("This is some text.");
pbuilder.EndSentence();
pbuilder.EndVoice();
pbuilder.EndParagraph();
pbuilder.EndStyle();
synthesizer.SetOutputToAudioStream(waveStream, synthFormat);
synthesizer.Speak(pbuilder);
synthesizer.SetOutputToNull();
```
There are no exceptions or errors recorded when using a sample rate of 8000 and I couldn't find anything useful in the documentation regarding SetOutputToAudioStream and why it succeeds at 11025 samples per second and not 8000. I have a workaround involving a wav file that I generated and converted to the correct sample rate using some sound editing tools, but I would like to generate the audio from within the application if I can.
One particular point of interest was that the SpeechRecognitionEngine accepts that audio format and successfully recognized the speech in my synthesized wave file...
Update: Recently discovered that this audio format succeeds for certain installed voices, but fails for others. It fails specifically for LH Michael and LH Michelle, and failure varies for certain voice settings defined in the PromptBuilder.
|
It's entirely possible that the LH Michael and LH Michelle voices simply don't support 8000 Hz sample rates (because they inherently generate samples > 8000 Hz). SAPI allows engines to reject unsupported rates.
|
I have created some classes in my [NAudio](http://www.codeplex.com/naudio) library to allow you to convert your audio data to a different sample rate, if you are stuck with 11025 from the synthesizer. Have a look at `WaveFormatConversionStream` (which uses ACM) or `ResamplerDMO` (uses a DirectX Media Object)
|
Question SpeechSynthesizer.SetOutputToAudioStream audio format problem
|
[
"",
"c#",
"audio",
"speech-recognition",
"text-to-speech",
""
] |
I've created a copy utility in c# (.NET 2.0 Framework) that copies files, directories and recursive sub directories etc. The program has a GUI that shows the current file being copied, the current file number (sequence), the total number of files to be copied and the percentage completed for the copy operations. There is also a progress bar, that is based on current file / total files.
My problem is related to copying large files. I've been unable to find a way to indicate the total copy progress of a large file (using my current class structure that utilitzes FileInfo.CopyTo method). As a workaround I've separated the file copy operations and GUI display to their own threads and set up a visual cue to show that work is being done. At least the user is aware that the program isn't frozen and is still copying files.
It would be nicer to be able to show the progress based on the total number of bytes or have some type of event that fires from the FileInfo.CopyTo method that indicates the total number of bytes copied from the current file.
I'm aware of the FileInfo.Length property, so I'm sure there is a way MacGuyver my own event that is based on this and have a handler on the GUI side of things reading the updates (maybe based on checking the FileInfo.Length property of the destination object using some type of timer?).
Does anyone know of a way to do this that I'm overlooking. If I can avoid it, I'd rather not rewrite my class to copy bytes through a stream and track it that way (though I'm thinking I might be stuck with going that route).
PS - I'm stuck with the .NET 2.0 framework for now, so any solution that requires features available in >= 3.0 only are not an option for me.
PPS - I'm open to solutions in any .NET language variety, not only c#.
|
The FileInfo.CopyTo is basically a wrapper around the Win32 API call "CopyFile" in the kernel32.dll. This method does not support progress callback.
However, the CopyFileEx method does, and you can write your own .NET wrapper around it in a few minutes, like it is described here:
[http://www.pinvoke.net/default.aspx/kernel32.CopyFileEx](https://web.archive.org/web/20200428185128/http://www.pinvoke.net/default.aspx/kernel32.CopyFileEx)
|
I also used the implementation provided in the [marked answer](https://stackoverflow.com/a/187842/73025). However I then created a wrapper to provide a nicer™ API to use from .NET.
**Usage:**
```
XCopy.Copy(networkFile.FullPath, temporaryFilename, true, true, (o, pce) =>
{
worker.ReportProgress(pce.ProgressPercentage, networkFile);
});
```
**Implementation**
```
/// <summary>
/// PInvoke wrapper for CopyEx
/// http://msdn.microsoft.com/en-us/library/windows/desktop/aa363852.aspx
/// </summary>
public class XCopy
{
public static void Copy(string source, string destination, bool overwrite, bool nobuffering)
{
new XCopy().CopyInternal(source, destination, overwrite, nobuffering, null);
}
public static void Copy(string source, string destination, bool overwrite, bool nobuffering, EventHandler<ProgressChangedEventArgs> handler)
{
new XCopy().CopyInternal(source, destination, overwrite, nobuffering, handler);
}
private event EventHandler Completed;
private event EventHandler<ProgressChangedEventArgs> ProgressChanged;
private int IsCancelled;
private int FilePercentCompleted;
private string Source;
private string Destination;
private XCopy()
{
IsCancelled = 0;
}
private void CopyInternal(string source, string destination, bool overwrite, bool nobuffering, EventHandler<ProgressChangedEventArgs> handler)
{
try
{
CopyFileFlags copyFileFlags = CopyFileFlags.COPY_FILE_RESTARTABLE;
if (!overwrite)
copyFileFlags |= CopyFileFlags.COPY_FILE_FAIL_IF_EXISTS;
if (nobuffering)
copyFileFlags |= CopyFileFlags.COPY_FILE_NO_BUFFERING;
Source = source;
Destination = destination;
if (handler != null)
ProgressChanged += handler;
bool result = CopyFileEx(Source, Destination, new CopyProgressRoutine(CopyProgressHandler), IntPtr.Zero, ref IsCancelled, copyFileFlags);
if (!result)
throw new Win32Exception(Marshal.GetLastWin32Error());
}
catch (Exception)
{
if (handler != null)
ProgressChanged -= handler;
throw;
}
}
private void OnProgressChanged(double percent)
{
// only raise an event when progress has changed
if ((int)percent > FilePercentCompleted)
{
FilePercentCompleted = (int)percent;
var handler = ProgressChanged;
if (handler != null)
handler(this, new ProgressChangedEventArgs((int)FilePercentCompleted, null));
}
}
private void OnCompleted()
{
var handler = Completed;
if (handler != null)
handler(this, EventArgs.Empty);
}
#region PInvoke
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CopyFileEx(string lpExistingFileName, string lpNewFileName, CopyProgressRoutine lpProgressRoutine, IntPtr lpData, ref Int32 pbCancel, CopyFileFlags dwCopyFlags);
private delegate CopyProgressResult CopyProgressRoutine(long TotalFileSize, long TotalBytesTransferred, long StreamSize, long StreamBytesTransferred, uint dwStreamNumber, CopyProgressCallbackReason dwCallbackReason,
IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData);
private enum CopyProgressResult : uint
{
PROGRESS_CONTINUE = 0,
PROGRESS_CANCEL = 1,
PROGRESS_STOP = 2,
PROGRESS_QUIET = 3
}
private enum CopyProgressCallbackReason : uint
{
CALLBACK_CHUNK_FINISHED = 0x00000000,
CALLBACK_STREAM_SWITCH = 0x00000001
}
[Flags]
private enum CopyFileFlags : uint
{
COPY_FILE_FAIL_IF_EXISTS = 0x00000001,
COPY_FILE_NO_BUFFERING = 0x00001000,
COPY_FILE_RESTARTABLE = 0x00000002,
COPY_FILE_OPEN_SOURCE_FOR_WRITE = 0x00000004,
COPY_FILE_ALLOW_DECRYPTED_DESTINATION = 0x00000008
}
private CopyProgressResult CopyProgressHandler(long total, long transferred, long streamSize, long streamByteTrans, uint dwStreamNumber,
CopyProgressCallbackReason reason, IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData)
{
if (reason == CopyProgressCallbackReason.CALLBACK_CHUNK_FINISHED)
OnProgressChanged((transferred / (double)total) * 100.0);
if (transferred >= total)
OnCompleted();
return CopyProgressResult.PROGRESS_CONTINUE;
}
#endregion
}
```
|
Can I show file copy progress using FileInfo.CopyTo() in .NET?
|
[
"",
"c#",
".net",
"copy",
"fileinfo",
""
] |
I have a database called foo and a database called bar. I have a table in foo called tblFoobar that I want to move (data and all) to database bar from database foo. What is the SQL statement to do this?
|
On SQL Server? and on the same database server? Use three part naming.
```
INSERT INTO bar..tblFoobar( *fieldlist* )
SELECT *fieldlist* FROM foo..tblFoobar
```
This just moves the data. If you want to move the table definition (and other attributes such as permissions and indexes), you'll have to do something else.
|
SQL Server Management Studio's "Import Data" task (right-click on the DB name, then tasks) will do most of this for you. Run it from the database you want to copy the data into.
If the tables don't exist it will create them for you, but you'll probably have to recreate any indexes and such. If the tables do exist, it will append the new data by default but you can adjust that (edit mappings) so it will delete all existing data.
I use this all the time and it works fairly well.
|
Copy tables from one database to another in SQL Server
|
[
"",
"sql",
"sql-server",
"copy",
"migrate",
"database-table",
""
] |
Is there some library for using some sort of cursor over a file? I have to read big files, but can't afford to read them all at once into memory. I'm aware of java.nio, but I want to use a higher level API.
A little backgrond: I have a tool written in GWT that analyzes submitted xml documents and then pretty prints the xml, among other things. Currently I'm writing the pretty printed xml to a temp file (my lib would throw me an OOMException if I use plain Strings), but the temp file's size are approaching 18 megs, I can't afford to respond a GWT RPC with 18 megs :)
So I can have a widget to show only a portion of the xml (check this [example](http://zwitserloot.com/tipit-gwtlib/example/)), but I need to read the corresponding portion of the file.
|
Have you taken a look at using FileChannels (i.e., memory mapped files)? Memory mapped files allow you to manipulate large files without bringing the entire file into memory.
Here's a link to a good introduction:
<http://www.developer.com/java/other/article.php/1548681>
|
Maybe [java.io.RandomAccessFile](https://docs.oracle.com/javase/1.5.0/docs/api/java/io/RandomAccessFile.html) can be of use to you.
|
Java File Cursor
|
[
"",
"java",
"performance",
"file",
"file-io",
""
] |
How can I get the BSSID / MAC (Media Access Control) address of the wireless access point my system is connected to using C#?
Note that I'm interested in the BSSID of the WAP. This is different from the MAC address of the networking portion of the WAP.
|
The following needs to be executed programmatically:
```
netsh wlan show networks mode=Bssid | findstr "BSSID"
```
The above shows the access point's wireless MAC addresses which is different from:
```
arp -a | findstr 192.168.1.254
```
This is because the access point has 2 MAC addresses. One for the wireless device and one for the networking device. I want the wireless MAC but get the networking MAC using *arp*.
Using the [Managed Wifi API](http://www.codeplex.com/managedwifi):
```
var wlanClient = new WlanClient();
foreach (WlanClient.WlanInterface wlanInterface in wlanClient.Interfaces)
{
Wlan.WlanBssEntry[] wlanBssEntries = wlanInterface.GetNetworkBssList();
foreach (Wlan.WlanBssEntry wlanBssEntry in wlanBssEntries)
{
byte[] macAddr = wlanBssEntry.dot11Bssid;
var macAddrLen = (uint) macAddr.Length;
var str = new string[(int) macAddrLen];
for (int i = 0; i < macAddrLen; i++)
{
str[i] = macAddr[i].ToString("x2");
}
string mac = string.Join("", str);
Console.WriteLine(mac);
}
}
```
|
```
using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
Process proc = new Process();
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = "cmd";
proc.StartInfo.Arguments = @"/C ""netsh wlan show networks mode=bssid | findstr BSSID """;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
Console.WriteLine(output);
}
}
```
Beware of syntax error like curly braces all that. But the concept is here. You may create Scan function by periodically invoking this process. Correct me if something goes wrong.
|
Get BSSID (MAC address) of wireless access point from C#
|
[
"",
"c#",
"wifi",
""
] |
I've been working on database-driven web applications for a few years now and recently took on a project involving a CMS that is XML-capable. This has led me to think about the usage of XML/XSLT in general and in what situations it would be more useful than the approach I've always used, which is storing all of my data in a (My)SQL database and then using PHP/Python/etc. to work with it on the web as needed.
There's obviously something I'm not "getting" here.. could anyone give me examples of applications where storing the data in XML files instead of in a database would be preferable?
|
To quote [This Book](http://www.amazon.com/exec/obidos/tg/detail/-/0321150406/102-0503816-7711357) (Effective XML: 50 Specific Ways to Improve Your XML):
> “XML is not a database. It was never
> meant to be a database. It is never
> going to be a database. Relational
> databases are proven technology with
> more than 20 years of implementation
> experience. They are solid, stable,
> useful products. They are not going
> away. XML is a very useful technology
> for moving data between different
> databases or between databases and
> other programs. However, it is not
> itself a database. Don't use it like
> one.“
I think this sums it up, if a little bluntly. XML is a data interchange format. One can have XML parsing libraries that can query a DOM with XPath expressions but that is not the same thing as a DBMS. You can build a DBMS with a DOM/XPath interface but to get ACID properties or scale to large data sets you need to implement a DBMS engine and a data format with indexes, logging and other artifacts of a DBMS - which (by definition) makes it something other than XML.
|
Use XML to create files that need to be sent to other applications. XML is more suited as data interchange format than as data storage format.
The following link is not bad to describe when using XML: [Why should I use XML ?](http://xml.silmaril.ie/whyxml.html)
|
When would I use XML instead of SQL?
|
[
"",
"sql",
"xml",
""
] |
I am trying to connect to a webservice over ssl with a client certificate. Is there an elegant way of doing this apart from shoving things like "javax.net.ssl.keyStore" into System.properties.
Any pointers to code examples would be appreciated.
|
You could just install the cert into the system keystore. (Location varies across platforms, and you will need admin rights).
|
Not sure if [this](http://blogs.oracle.com/andreas/entry/no_more_unable_to_find) is fully relevant, but still. This entry describes the way of generating the certificate and installing it on a local system without using the keytool. Probably you could reuse some parts of the (very simple) source code.
|
Java webservice (soap) client - use certificates
|
[
"",
"java",
"web-services",
"soap",
"certificate",
""
] |
I have a form that is sending in sizes of things, and I need to see what the strings are equal to so that I can set the price accordingly. When i try to do this, it says that they are not equal, and i get no prices. This is the code i'm using:
```
if ($_POST['sizes'] == "Small ($30)"){$total = "30";}
if ($_POST['sizes'] == "Medium ($40)"){$total = "40";}
if ($_POST['sizes'] == "Large ($50)"){$total = "50";}
else {$total = $_POST['price'];}
```
What am i doing wrong here? I can echo $\_POST['sizes'] and it gives me exactly one of those things.
|
What [Paul Dixon said](https://stackoverflow.com/questions/184703/compare-strings-given-in-post-with-php/184737#184737) is correct. Might I also recommend using a switch statement instead of that clunky chunk of if statements (which actually has a logic bug in it, I might add - `$total` will always equal `$_POST['price']` when not `'Large ($50)'`)
```
<?php
switch ( $_POST['sizes'] )
{
case 'Small ($30)' :
$total = 30;
break;
case 'Medium ($40)' :
$total = 40;
break;
case 'Large ($50)' :
$total = 50;
break;
default:
$total = $_POST['price'];
break;
}
?>
```
|
That's a good candidate for a switch/case statement, with your 'else' being a default.
Also, without using elseif's on Medium and Large, if your $\_POST['sizes'] is not Large, then your $total will always be $\_POST['price']. This could be throwing you off as well.
|
Compare Strings given in $_POST with php
|
[
"",
"php",
"post",
"compare",
""
] |
In Java, is there an elegant way to detect if an exception occurred prior to running the finally block? When dealing with "close()" statements, it's common to need exception handling within the finally block. Ideally, we'd want to maintain both exceptions and propagate them up (as both of them may contain useful information). The only way I can think of to do this is to have a variable outside the try-catch-finally scope to save a reference to a thrown exception. Then propagate the "saved" exception up with any that occur in the finally block.
Is there a more elegant way of doing this? Perhaps an API call that will reveal this?
Here's some rough code of what I'm talking about:
```
Throwable t = null;
try {
stream.write(buffer);
} catch(IOException e) {
t = e; //Need to save this exception for finally
throw e;
} finally {
try {
stream.close(); //may throw exception
} catch(IOException e) {
//Is there something better than saving the exception from the exception block?
if(t!=null) {
//propagate the read exception as the "cause"--not great, but you see what I mean.
throw new IOException("Could not close in finally block: " + e.getMessage(),t);
} else {
throw e; //just pass it up
}
}//end close
}
```
Obviously, there are a number of other similar kludges that might involve saving the exception as an member variable, returning it from a method, etc... but I'm looking for something a bit more elegant.
Maybe something like `Thread.getPendingException()` or something similar? For that matter, is there an elegant solution in other languages?
This question actually spawned from comments in [another question](https://stackoverflow.com/questions/183499/is-there-a-preference-for-nested-trycatch-blocks#183572) that raised an interesting question.
|
Your idea about setting a variable outside the scope of the try/catch/finally is correct.
There cannot be more than one exception propagating at once.
|
Instead of using a Boolean flag, I would store a reference to the Exception object.
That way, you not only have a way to check whether an exception occurred (the object will be null if no exception occurred), but you'll also have access to the exception object itself in your finally block if an exception did occur. You just have to remember to set the error object in all your catch blocks (iff rethrowing the error).
**I think this is a missing C# language feature that should be added.** The finally block should support a reference to the base Exception class similar to how the catch block supports it, so that a reference to the propagating exception is available to the finally block. This would be **an easy task for the compiler**, **saving us the work** of **manually** creating a local Exception variable and **remembering** to manually set its value before re-throwing an error, as well as preventing us from **making the mistake** of setting the Exception variable when not re-throwing an error (remember, it's only the uncaught exceptions we want to make visible to the finally block).
```
finally (Exception main_exception)
{
try
{
//cleanup that may throw an error (absolutely unpredictably)
}
catch (Exception err)
{
//Instead of throwing another error,
//just add data to main exception mentioning that an error occurred in the finally block!
main_exception.Data.Add( "finally_error", err );
//main exception propagates from finally block normally, with additional data
}
}
```
As demonstrated above... the reason that I'd like the exception available in the finally block, is that if my finally block did catch an exception of its own, then instead of **overwriting the main exception by throwing a new error (bad)** or just **ignoring the error (also bad)**, it could add the error as additional data to the original error.
|
Is it possible to detect if an exception occurred before I entered a finally block?
|
[
"",
"java",
"exception",
""
] |
Other than using raw XML, is there an easy way in .NET to open and read a config file belonging to another assembly...? I don't need to write to it, just grab a couple of values from it.
|
[Here's](http://msdn.microsoft.com/en-us/library/ms224437.aspx) MSDN on OpenExeConfiguration.
Edit: [link](http://www.eggheadcafe.com/software/aspnet/32181042/using-configurationmanage.aspx) to a how-to on eggheadcafe.com disappeared. Looks like EggheadCafe moved to NullSkull but dropped the article ID's.
|
Have you tried [`ConfigurationManager`](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx) and [`OpenExeConfiguration(path)`](http://msdn.microsoft.com/en-us/library/ms224437.aspx)? (in System.Configuration.dll)
|
Easiest way to read a config file belonging to another application
|
[
"",
"c#",
"configuration-files",
""
] |
The company I work for has a large webapp written in C++ as an ISAPI extension (not a filter). We're currently enhancing our system to integrate with several 3rd party tools that have SOAP interfaces. Rather than roll our own, I think it would probably be best if we used some SOAP library. Ideally, it would be free and open source, but have a license compatible with closed-source commercial software. We also need to support SSL for both incoming and outgoing SOAP messages.
One of the biggest concerns I have is that every SOAP library that I've looked at seems to have 2 modes of operation: standalone server and server module (either Apache module or ISAPI filter). Obviously, we can't use the standalone server. It seems to me that if it is running as a module, it won't be part of my app -- it won't have access to the rest of my code, so it won't be able to share data structures, etc. Is that a correct assumption? Each HTTP request processed by our app is handled by a separate thread (we manage our own thread pool), but we have lots of persistent data that is shared between those threads. I think the type of integration I'm looking for is to add some code to my app that looks at the request URL, sees that it is trying to access a SOAP service, and calls some function like soapService.handleRequest(). I'm not aware of anything that offers this sort of integration. We must be able to utilize data structures from our main app in the SOAP handler functions.
In addition to handling incoming SOAP requests, we're also going to be generating them (bi-directional communication with the 3rd parties). I assume pretty much any SOAP library will fulfill that purpose, right?
Can anyone suggest a SOAP library that is capable of this, or offer a suggestion on how to use a different paradigm? I've already looked at Apache Axis2, gSOAP and AlchemySOAP, but perhaps there's some feature of these that I overlooked. Thanks.
|
GSoap is a great open source cross platfrom soap stack.
# It is FAST.
# Great interop.
Many open source soap libraries don't have great interop with java/c#/python/whatever.
It parses HUGE payloads while using very little memory.
It is open source!
Since you are using an IIS extension, you would need to add the gsoap to your app, recompile your extension dll with this: <http://aberger.at/SOAP/iis_index.html>
and you should be ready to roll.
gSoap
<http://www.cs.fsu.edu/~engelen/soap.html>
|
Take a look at [ATL Server](http://www.codeplex.com/AtlServer) This library used to be shipped with Visual C++, but now it is a separate open source project
|
choosing a SOAP library to integrate with ISAPI webapp
|
[
"",
"c++",
"soap",
"isapi-extension",
""
] |
I'm currently using [Magpie RSS](http://magpierss.sourceforge.net/) but it sometimes falls over when the RSS or Atom feed isn't well formed. Are there any other options for parsing RSS and Atom feeds with PHP?
|
Your other options include:
* [SimplePie](http://simplepie.org/)
* [Last RSS](http://lastrss.oslab.net/)
* [PHP Universal Feed Parser](http://www.phpclasses.org/package/4548-PHP-Parse-RSS-and-ATOM-feeds.html)
|
I've always used [the SimpleXML functions built in to PHP](https://www.php.net/simplexml) to parse XML documents. It's one of the few generic parsers out there that has an intuitive structure to it, which makes it extremely easy to build a meaningful class for something specific like an RSS feed. Additionally, it will detect XML warnings and errors, and upon finding any you could simply run the source through something like HTML Tidy (as ceejayoz mentioned) to clean it up and attempt it again.
Consider this very rough, simple class using SimpleXML:
```
class BlogPost
{
var $date;
var $ts;
var $link;
var $title;
var $text;
}
class BlogFeed
{
var $posts = array();
function __construct($file_or_url)
{
$file_or_url = $this->resolveFile($file_or_url);
if (!($x = simplexml_load_file($file_or_url)))
return;
foreach ($x->channel->item as $item)
{
$post = new BlogPost();
$post->date = (string) $item->pubDate;
$post->ts = strtotime($item->pubDate);
$post->link = (string) $item->link;
$post->title = (string) $item->title;
$post->text = (string) $item->description;
// Create summary as a shortened body and remove images,
// extraneous line breaks, etc.
$post->summary = $this->summarizeText($post->text);
$this->posts[] = $post;
}
}
private function resolveFile($file_or_url) {
if (!preg_match('|^https?:|', $file_or_url))
$feed_uri = $_SERVER['DOCUMENT_ROOT'] .'/shared/xml/'. $file_or_url;
else
$feed_uri = $file_or_url;
return $feed_uri;
}
private function summarizeText($summary) {
$summary = strip_tags($summary);
// Truncate summary line to 100 characters
$max_len = 100;
if (strlen($summary) > $max_len)
$summary = substr($summary, 0, $max_len) . '...';
return $summary;
}
}
```
|
Best way to parse RSS/Atom feeds with PHP
|
[
"",
"php",
"parsing",
"rss",
"atom-feed",
""
] |
In one of my projects I need to build an ASP.NET page and some of the controls need to be created dynamically. These controls are added to the page by the code-behind class and they have some event-handlers added to them. Upon the PostBacks these event-handlers have a lot to do with what controls are then shown on the page. To cut the story short, this doesn't work for me and I don't seem to be able to figure this out.
So, as my project is quite involved, I decided to create a short example that doesn't work either but if you can tweak it so that it works, that would be great and I would then be able to apply your solution to my original problem.
The following example should dynamically create three buttons on a panel. When one of the buttons is pressed all of the buttons should be dynamically re-created except for the button that was pressed. In other words, just hide the button that the user presses and show the other two.
For your solution to be helpful you can't statically create the buttons and then use the Visible property (or drastically change the example in other ways) - you have to re-create all the button controls dynamically upon every PostBack (not necessarily in the event-handler though). This is not a trick-question - I really don't know how to do this. Thank you very much for your effort. Here is my short example:
## From the Default.aspx file:
```
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="ButtonsPanel" runat="server"></asp:Panel>
</div>
</form>
</body>
```
## From the Default.aspx.cs code-behind file:
```
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DynamicControls
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
AddButtons();
}
protected void AddButtons()
{
var lastClick = (string) Session["ClickedButton"] ?? "";
ButtonsPanel.Controls.Clear();
if (!lastClick.Equals("1")) AddButtonControl("1");
if (!lastClick.Equals("2")) AddButtonControl("2");
if (!lastClick.Equals("3")) AddButtonControl("3");
}
protected void AddButtonControl(String id)
{
var button = new Button {Text = id};
button.Click += button_Click;
ButtonsPanel.Controls.Add(button);
}
private void button_Click(object sender, EventArgs e)
{
Session["ClickedButton"] = ((Button) sender).Text;
AddButtons();
}
}
}
```
My example shows the three buttons and when I click one of the buttons, the pressed button gets hidden. Seems to work; but after this first click, I have to click each button **TWICE** for it to get hidden. !?
|
I think that you have to provide the same ID for your buttons every time you add them like this for example (in first line of `AddButtonControl` method):
```
var button = new Button { Text = id , ID = id };
```
---
**EDIT** - My solution without using session:
```
public partial class _Default : Page
{
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
AddButtons();
}
protected void AddButtons()
{
AddButtonControl("btn1", "1");
AddButtonControl("btn2", "2");
AddButtonControl("btn3", "3");
}
protected void AddButtonControl(string id, string text)
{
var button = new Button { Text = text, ID = id };
button.Click += button_Click;
ButtonsPanel.Controls.Add(button);
}
private void button_Click(object sender, EventArgs e)
{
foreach (Control control in ButtonsPanel.Controls)
control.Visible = !control.Equals(sender);
}
}
```
|
You need to make sure that your dynamic controls are being added during the `Pre_Init` event.
See here for the ASP.NET Page Lifecycle: <http://msdn.microsoft.com/en-us/library/ms178472.aspx>
When adding events you need to do it no later than the `Page_Load` method and they *need to be added every single request*, ie you should never wrap event assignment in a `!IsPostBack`.
You need to create dynamic controls ever single request as well. ViewState will not handle the recreation on your behalf.
|
How do I dynamically create/remove controls, with EventHandlers, to/from an ASP.NET page?
|
[
"",
"c#",
"asp.net",
""
] |
I have some Java code that uses curly braces in two ways
```
// Curly braces attached to an 'if' statement:
if(node.getId() != null)
{
node.getId().apply(this);
}
// Curly braces by themselves:
{
List<PExp> copy = new ArrayList<PExp>(node.getArgs());
for(PExp e : copy)
{
e.apply(this);
}
}
outAMethodExp(node);
```
What do those stand-alone curly braces after the first `if` statement mean?
|
The only purpose of the extra braces is to provide scope-limit. The `List<PExp> copy` will only exist within those braces, and will have no scope outside of them.
If this is generated code, I assume the code-generator does this so it can insert some code (such as this) without having to worry about how many times it has inserted a `List<PExp> copy` and without having to worry about possibly renaming the variables if this snippet is inserted into the same method more than once.
|
I second what matt b wrote, and I'll add that another use I've seen of anonymous braces is to declare an implicit constructor in anonymous classes. For example:
```
List<String> names = new ArrayList<String>() {
// I want to initialize this ArrayList instace in-line,
// but I can't define a constructor for an anonymous class:
{
add("Adam");
add("Eve");
}
};
```
Some unit-testing frameworks have taken this syntax to another level, which does allow some slick things which look totally uncompilable to work. Since they *look* unfamiliar, I am not such a big fan myself, but it is worthwhile to at least recognize what is going on if you run across this use.
|
What do curly braces in Java mean by themselves?
|
[
"",
"java",
"syntax",
"scope",
"curly-braces",
""
] |
How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way.
|
```
import time, datetime
d = datetime.datetime.now()
print time.mktime(d.timetuple())
```
|
For UTC calculations, `calendar.timegm` is the inverse of `time.gmtime`.
```
import calendar, datetime
d = datetime.datetime.utcnow()
print calendar.timegm(d.timetuple())
```
|
Converting datetime to POSIX time
|
[
"",
"python",
"datetime",
"posix",
""
] |
Is there some way I can define `String[int]` to avoid using `String.CharAt(int)`?
|
No, there isn't a way to do this.
This is a common question from developers who are coming to JavaScript from another language, where **operators can be defined or overridden** for a certain type.
In C++, it's not entirely out of the question to overload `operator*` on `MyType`, ending up with a unique asterisk operator for operations involving objects of type `MyType`. The readability of this practice might still be called into question, but the language affords for it, nevertheless.
In JavaScript, this is simply not possible. You will not be able to define a method which allows you to index chars from a `String` using brackets.
*@Lee Kowalkowski* brings up a good point, namely that it is, in a way, *possible* to access characters using the brackets, because the brackets can be used to access members of a JavaScript `Array`. This would involve creating a new `Array`, using each of the characters of the string as its members, and then accessing the `Array`.
This is probably a confusing approach. Some implementations of JavaScript will provide access to a string via the brackets and some will not, so it's not standard practice. The object may be confused for a string, and as JavaScript is a loosely typed language, there is already a risk of misrepresenting a type. Defining an array solely for the purposes of using a different syntax from what the language already affords is only gong to promote this type of confusion. This gives rise to *@Andrew Hedges*'s question: "Why fight the language?"..
There are **useful patterns in JavaScript** for **legitimate function overloading** and **polymorphic inheritance**. This isn't an example of either.
All semantics aside, the operators still haven't been overridden.
**Side note:** Developers who are accustomed to the conventions of strong type checking and classical inheritance are sometimes confused by JavaScript's C-family syntax. Under the hood, it is working in an unfamiliar way. It's best to write JavaScript in clean and unambiguous ways, in order to prevent confusion.
|
**Please note:** Before anybody *else* would like to vote my answer down, the question I answered was:
> **IE javascript string indexers**
>
> is there some way I can define string[int] to avoid using string.CharAt(int)?"
Nothing about specifically overriding brackets, or syntax, or best-practice, the question just asked for "some way". (And the only other answer said "No, there isn't.")
---
Well, there is actually, kind of:
```
var newArray = oldString.split('');
```
...now you can access newArray using bracket notation, because you've just converted it to an array.
|
In javascript, can I override the brackets to access characters in a string?
|
[
"",
"javascript",
"syntax",
"operators",
""
] |
Is it possible to use PHP's SimpleXML functions to create an XML object from scratch? Looking through the function list, there's ways to import an existing XML string into an object that you can then manipulate, but if I just want to generate an XML object programmatically from scratch, what's the best way to do that?
I figured out that you can use simplexml\_load\_string() and pass in the root string that you want, and then you've got an object you can manipulate by adding children... although this seems like kind of a hack, since I have to actually hardcode some XML into the string before it can be loaded.
I've done it using the [DOMDocument functions](https://www.php.net/manual/en/book.domxml.php), although it's a little confusing because I'm not sure what the DOM has to do with creating a pure XML document... so maybe it's just badly named :-)
|
Sure you can. Eg.
```
<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>
```
Output
```
<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
<content type="latest"/>
</news>
```
Have fun.
|
In PHP5, you should use the [Document Object Model](https://www.php.net/manual/en/book.dom.php "Document Object Model") class instead.
Example:
```
$domDoc = new DOMDocument;
$rootElt = $domDoc->createElement('root');
$rootNode = $domDoc->appendChild($rootElt);
$subElt = $domDoc->createElement('foo');
$attr = $domDoc->createAttribute('ah');
$attrVal = $domDoc->createTextNode('OK');
$attr->appendChild($attrVal);
$subElt->appendChild($attr);
$subNode = $rootNode->appendChild($subElt);
$textNode = $domDoc->createTextNode('Wow, it works!');
$subNode->appendChild($textNode);
echo htmlentities($domDoc->saveXML());
```
|
Using SimpleXML to create an XML object from scratch
|
[
"",
"php",
"xml",
"simplexml",
""
] |
I have a standard .NET windows service written in C#.
Can it install itself without using InstallUtil?
Should I use the service installer class? How should I use it?
I want to be able to call the following:
```
MyService.exe -install
```
And it will have the same effect as calling:
```
InstallUtil MyService.exe
```
|
Yes, that is fully possible (i.e. I do exactly this); you just need to reference the right dll (System.ServiceProcess.dll) and add an installer class...
[Here's an example:](http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/4d45e9ea5471cba4/4519371a77ed4a74)
```
[RunInstaller(true)]
public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
{
public MyServiceInstallerProcess()
{
this.Account = ServiceAccount.NetworkService;
}
}
[RunInstaller(true)]
public sealed class MyServiceInstaller : ServiceInstaller
{
public MyServiceInstaller()
{
this.Description = "Service Description";
this.DisplayName = "Service Name";
this.ServiceName = "ServiceName";
this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
}
}
static void Install(bool undo, string[] args)
{
try
{
Console.WriteLine(undo ? "uninstalling" : "installing");
using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
{
IDictionary state = new Hashtable();
inst.UseNewContext = true;
try
{
if (undo)
{
inst.Uninstall(state);
}
else
{
inst.Install(state);
inst.Commit(state);
}
}
catch
{
try
{
inst.Rollback(state);
}
catch { }
throw;
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
}
```
|
Take a look at the [InstallHelper](http://msdn.microsoft.com/en-us/library/system.configuration.install.managedinstallerclass.installhelper.aspx) method of the [ManagedInstaller](http://msdn.microsoft.com/en-us/library/system.configuration.install.managedinstallerclass.aspx) class. You can install a service using:
```
string[] args;
ManagedInstallerClass.InstallHelper(args);
```
This is exactly what InstallUtil does. The arguments are the same as for InstallUtil.
The benefits of this method are that it involves no messing in the registry, and it uses the same mechanism as InstallUtil.
|
Install a .NET windows service without InstallUtil.exe
|
[
"",
"c#",
".net",
"deployment",
"windows-services",
"installutil",
""
] |
I'd like to have it yell hooray whenever an assert statement succeeds, or at the very least have it display the number of successful assert statements that were encountered.
I'm using JUnit4.
Any suggestions?
|
If you want to see some output for each successful assertion, another simple approach which requires no external dependencies or source code, would be to define your own Assert class which delegates all methods to the standard JUnit Assert class, as well as logging successful assertions (failed assertions will be reported as usual by the JUnit class).
You then run a global search-and-replace on your test classes from "org.junit.Assert" => "com.myco.test.Assert", which should fix-up all regular and static import statements.
You could also then easily migrate your approach to the quieter-is-better-camp and change the wrapper class to just report the total # of passed assertions per test or per class, etc.
|
Adding some info that would have been helpful to me when I wanted JUnit to be more verbose and stumbled on this question. Maybe it will help other testers in the future.
If you are running JUnit from Ant, and want to see what tests are being run, you can add the following to your task:
```
<junit showoutput="true" printsummary="on" enabletestlistenerevents="true" fork="@{fork}" forkmode="once" haltonfailure="no" timeout="1800000">
```
Note that showoutput, printsummary, and enabletestlistenerevents are what helped, not the other task attributes. If you set these, you'll get output like:
```
Running com.foo.bar.MyTest
junit.framework.TestListener: tests to run: 2
junit.framework.TestListener: startTest(myTestOne)
junit.framework.TestListener: endTest(myTestOne)
junit.framework.TestListener: startTest(myTestTwo)
junit.framework.TestListener: endTest(myTestTwo)
Tests run: 2, Failures: 0, Errors: 0, Time elapsed: 0.495 sec
```
This was useful to me when my tests were timing out and I wasn't sure which tests were actually taking too long, and which tests got cancelled because they were unlucky enough to be running when the time was up.
|
Can I make JUnit more verbose?
|
[
"",
"java",
"junit",
""
] |
I've recently decided that I just have to finally learn C/C++, and there is one thing I do not really understand about pointers or more precisely, their definition.
How about these examples:
1. `int* test;`
2. `int *test;`
3. `int * test;`
4. `int* test,test2;`
5. `int *test,test2;`
6. `int * test,test2;`
Now, to my understanding, the first three cases are all doing the same: Test is not an int, but a pointer to one.
The second set of examples is a bit more tricky. In case 4, both test and test2 will be pointers to an int, whereas in case 5, only test is a pointer, whereas test2 is a "real" int. What about case 6? Same as case 5?
|
4, 5, and 6 are the same thing, only *test* is a pointer. If you want two pointers, you should use:
```
int *test, *test2;
```
Or, even better (to make everything clear):
```
int* test;
int* test2;
```
|
White space around asterisks have no significance. All three mean the same thing:
```
int* test;
int *test;
int * test;
```
The "`int *var1, var2`" is an evil syntax that is just meant to confuse people and should be avoided. It expands to:
```
int *var1;
int var2;
```
|
Placement of the asterisk in pointer declarations
|
[
"",
"c++",
"c",
"pointers",
"declaration",
""
] |
Notice in the bottom right hand corner of this page it has the SVN revision id? I'm assuming that's dynamic.
I'd love to add that to some of my sites, just as a comment in the source to make sure code pushes are going through.
NOTE: You can also assume that the working directory of the site in question is an svn checkout of the repo in question.
**Edit:** I'm looking for the global revision number, not the revision number of the file I'm looking at.
|
You can use the [`svnversion`](http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.ref.svnversion) CLI utility to get a more specific look at the revision, including the highest number. You could then use regular expressions to parse this.
Subversion has no concept of a global revision; rather, you'd have to recursively look through the working copy to find the highest revision number. `svnversion` does that for you.
|
The keyword subsitution method isn't reliable because it will provide the revision of the file rather than the whole codebase that you're deploying, which I presume is what you're after.
Typically I use ANT to deploy from subversion, and in the build script I'd use the replace task to substitue a revision token in a layout template or common header file with the revision number of the codebase that I'm deploying - see below. Although if anyone has a better method I'd love to hear it!
```
<svn username="${svn.username}" password="${svn.password}" javaHL="${svn.javahl}">
<status path="${dir.build}" revisionProperty="svn.status.revision" />
</svn>
<replace dir="${dir.build}" token="%revision%" value="${svn.status.revision}">
<include name="**/*.php" />
</replace>
```
|
Easy way to embed svn revision number in page in PHP?
|
[
"",
"php",
"svn",
"versioning",
"revision",
""
] |
I have the following HTML node structure:
```
<div id="foo">
<div id="bar"></div>
<div id="baz">
<div id="biz"></div>
</div>
<span></span>
</div>
```
How do I count the number of immediate children of `foo`, that are of type `div`? In the example above, the result should be two (`bar` and `baz`).
|
```
$("#foo > div").length
```
Direct children of the element with the id 'foo' which are divs. Then retrieving the size of the wrapped set produced.
|
I recommend using `$('#foo').children().size()` for better performance.
I've created a [jsperf](http://jsperf.com/jquery-child-ele-size) test to see the speed difference and the `children()` method beaten the child selector (#foo > div) approach by at least **60%** in Chrome (canary build v15) **20-30%** in Firefox (v4).
By the way, needless to say, these two approaches produce same results (in this case, 1000).
[Update] I've updated the test to include the size() vs length test, and they doesn't make much difference (result: `length` usage is slightly faster (2%) than `size()`)
*[Update] Due to the incorrect markup seen in the OP (before 'markup validated' update by me), both `$("#foo > div").length` & `$('#foo').children().length` resulted the same ([jsfiddle](http://jsfiddle.net/LavMc/)). But for correct answer to get ONLY 'div' children, one SHOULD use child selector for correct & better performance*
|
Count immediate child div elements using jQuery
|
[
"",
"javascript",
"jquery",
"dom",
"jquery-selectors",
""
] |
I'm wondering if a Java library can be called from a VB.net application.
(A Google search turns up lots of shady answers, but nothing definitive)
|
No, you can't. Unless you are willing to use some "J#" libraries (which is not nearly the same as Java) or [IKVM](http://www.ikvm.net/) which is a Java implementation that runs on top of .NET, but as their documentation says:
> IKVM.OpenJDK.ClassLibrary.dll: compiled version of the Java class libraries derived from the OpenJDK class library with some parts filled in with code from GNU Classpath and IcedTea, plus some additional IKVM.NET specific code.
So it's not the real deal.
|
I am author of [jni4net](http://jni4net.sf.net/), open source intraprocess bridge between JVM and CLR. It's build on top of JNI and PInvoke. No C/C++ code needed. I hope it will help you.
|
Can you use Java libraries in a VB.net program?
|
[
"",
"java",
"vb.net",
""
] |
I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area.
Is something like this possible with jQuery?
```
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
```
|
> Note: Using `stopPropagation` is something that should be avoided as it breaks normal event flow in the DOM. See [this CSS Tricks article](https://css-tricks.com/dangers-stopping-event-propagation/) for more information. Consider using [this method](https://stackoverflow.com/a/3028037/561309) instead.
Attach a click event to the document body which closes the window. Attach a separate click event to the container which stops propagation to the document body.
```
$(window).click(function() {
//Hide the menus if visible
});
$('#menucontainer').click(function(event){
event.stopPropagation();
});
```
|
You can listen for a **click** event on `document` and then make sure `#menucontainer` is not an ancestor or the target of the clicked element by using [`.closest()`](http://api.jquery.com/closest/).
If it is not, then the clicked element is outside of the `#menucontainer` and you can safely hide it.
```
$(document).click(function(event) {
var $target = $(event.target);
if(!$target.closest('#menucontainer').length &&
$('#menucontainer').is(":visible")) {
$('#menucontainer').hide();
}
});
```
### Edit – 2017-06-23
You can also clean up after the event listener if you plan to dismiss the menu and want to stop listening for events. This function will clean up only the newly created listener, preserving any other click listeners on `document`. With ES2015 syntax:
```
export function hideOnClickOutside(selector) {
const outsideClickListener = (event) => {
const $target = $(event.target);
if (!$target.closest(selector).length && $(selector).is(':visible')) {
$(selector).hide();
removeClickListener();
}
}
const removeClickListener = () => {
document.removeEventListener('click', outsideClickListener);
}
document.addEventListener('click', outsideClickListener);
}
```
### Edit – 2018-03-11
For those who don't want to use jQuery. Here's the above code in plain vanillaJS (ECMAScript6).
```
function hideOnClickOutside(element) {
const outsideClickListener = event => {
if (!element.contains(event.target) && isVisible(element)) { // or use: event.target.closest(selector) === null
element.style.display = 'none';
removeClickListener();
}
}
const removeClickListener = () => {
document.removeEventListener('click', outsideClickListener);
}
document.addEventListener('click', outsideClickListener);
}
const isVisible = elem => !!elem && !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); // source (2018-03-11): https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js
```
**NOTE:**
This is based on Alex comment to just use `!element.contains(event.target)` instead of the jQuery part.
But `element.closest()` is now also available in all major browsers (the W3C version differs a bit from the jQuery one).
Polyfills can be found here: [Element.closest()](https://developer.mozilla.org/en-US/docs/Web/API/Element/closest)
### Edit – 2020-05-21
In the case where you want the user to be able to click-and-drag inside the element, then release the mouse outside the element, without closing the element:
```
...
let lastMouseDownX = 0;
let lastMouseDownY = 0;
let lastMouseDownWasOutside = false;
const mouseDownListener = (event: MouseEvent) => {
lastMouseDownX = event.offsetX;
lastMouseDownY = event.offsetY;
lastMouseDownWasOutside = !$(event.target).closest(element).length;
}
document.addEventListener('mousedown', mouseDownListener);
```
And in `outsideClickListener`:
```
const outsideClickListener = event => {
const deltaX = event.offsetX - lastMouseDownX;
const deltaY = event.offsetY - lastMouseDownY;
const distSq = (deltaX * deltaX) + (deltaY * deltaY);
const isDrag = distSq > 3;
const isDragException = isDrag && !lastMouseDownWasOutside;
if (!element.contains(event.target) && isVisible(element) && !isDragException) { // or use: event.target.closest(selector) === null
element.style.display = 'none';
removeClickListener();
document.removeEventListener('mousedown', mouseDownListener); // Or add this line to removeClickListener()
}
}
```
|
How do I detect a click outside an element?
|
[
"",
"javascript",
"jquery",
"click",
""
] |
I feel like I should know this, but I haven't been able to figure it out...
I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.
|
The answers involving introspection via `inspect` and the like are reasonable. But there may be another option, depending on your situation:
If your integration test is written with the [unittest](http://docs.python.org/library/unittest.html) module, then you could use `self.id()` within your TestCase.
|
This seems to be the simplest way using module `inspect`:
```
import inspect
def somefunc(a,b,c):
print "My name is: %s" % inspect.stack()[0][3]
```
You could generalise this with:
```
def funcname():
return inspect.stack()[1][3]
def somefunc(a,b,c):
print "My name is: %s" % funcname()
```
Credit to [Stefaan Lippens](http://stefaanlippens.net/python_inspect) which was found via google.
|
How do I get the name of a function or method from within a Python function or method?
|
[
"",
"python",
""
] |
I am using [this](http://www.codeproject.com/KB/vb/TabPages.aspx) - otherwise excellent - vb tab control in one of my c# apps. When the app using it is installed on another machine, Windows tells the user in its usual friendly and descriptive manner that "The application encountered a problem and needs to close". I guess the control has some hidden vb-related dependency, but what can that be?
Any ideas guys?
|
Since the tab control appears to be managed code as well, your 'crash' is most likely an unhandled .NET exception.
Looking at the error details (by expanding the error dialog using the button provided for that purpose...) should give you the exception message, which should give you an idea of what's going on. If it's a missing dependency DLL, the name should be included in the message.
To get the full exception, including the stack trace, one of the following should work:
* Least effort: in the first line of your own managed code, add [an unhandled exception handler](http://blogs.microsoft.co.il/blogs/sasha/archive/2007/12/30/clr-and-unhandled-exception-filters.aspx) which shows the full exception in a message box or logs it to a file prior to rethrowing it
* Medium effort: attach a debugger to the process on the client machine. If it's on your local network, [setting up remote debugging](http://support.microsoft.com/kb/910448) should be trivial, and should also allow you to debug exceptions that occur prior to your first line of code executing (which may very well be the case if the error is binding-related...)
* Most effort: obtain the crash dump file from the client machine, and look at the managed exception using Windbg and the [SOS debugging extensions](http://msdn.microsoft.com/en-us/library/bb190764.aspx). Getting productive with the tools involved will take some time, but on the plus side *will* teach you valuable debug ninja skills that will allow you to tackle pretty much any 'mysterious crash'...
BTW, all standard 'VB dependencies' are part of the default .NET Framework install, so that's not your problem -- only the exact exception (and possibly stack trace) will tell you what's going on.
|
Click the 'What data does this error report contain?' button and there will be more descriptive info. (i.e. type of the thrown exception, module etc.).
For additional info see [Dr. Watson vs. CLR.](http://blogs.msdn.com/vipul/archive/2007/01/22/Dr.-watson-and-the-common-language-runtime.aspx)
|
VB control crashes my app
|
[
"",
"c#",
".net",
"vb.net",
""
] |
I have a library A, that I develop. When I deploy it on a machine, the corresponding *libA.so* and *libA-X.Y.Z.so* are put in /usr/lib (X.Y.Z being the version number).
Now I develop a library B, which uses A. When I link B, I use the flag -lA. Then "*ldd libB.so*" gives me :
```
(...)
libA-X.Y.Z.so => /usr/lib/libA-X.Y.Z.so
(...)
```
My problem is that when I release a new version of A (X.Y.ZZ), I also have to release a new version of B. Otherwise, someone installing the latest A won't be able to install B which will be looking for the version X.Y.Z which doesn't exist.
How do I solve this problem ? How can I tell B to look for libA.so and not libA-X.Y.Z.so ? Or is it wrong to do so ? even unsafe ?
**Update 1** : library A (that I inherited from someone else) uses autotools.
**Update 2** : when I build library A, I can see : *"-Wl,-soname -Wl,libA-0.6.1.so"*. If I understand properly that means that we are forcing the soname to be *libA-0.6.1.so*. Is that right ? Now my problem is that I have no clue how to modify this behaviour in a project which uses autotools. I googled for a while but can't find any useful information. Should I modify configure.in or a Makefile.am ?
|
When you create libA.so, pass the -soname option to the linker (if you linking through gcc, use -Wl,-soname). Then, when B gets linked, the linker refers to A through its soname, not through its filename. On the target system, make sure you have a link from the soname to the real file. See
<http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html>
|
This also works in Windows as "DLL hell" :).
If B needs a specific version of A and you would link to libA not libA-X.Y.Z then only substituting libA with newer version might cause B not to load or crash.
But of course you can do a symlink from libA-X.Y.Z to libA-X1.Y1.Z1. If no APIs changed and only implementations than you should be safe.
|
C++ : how to link against libA.so and not libA-X.Y.Z.so
|
[
"",
"c++",
"linker",
"versions",
""
] |
How do people approach mocking out TcpClient (or things like TcpClient)?
I have a service that takes in a TcpClient. Should I wrap that in something else more mockable? How should I approach this?
|
When coming to mock classes that are not test friendly (i.e. sealed/not implementing any interface/methods are not virtual), you would probably want to use the [Adapter](http://en.wikipedia.org/wiki/Adapter_pattern) design pattern.
In this pattern you add a wrapping class that implements an interface. You should then mock the interface, and make sure all your code uses that interface instead of the unfriendly concrete class. It would look something like this:
```
public interface ITcpClient
{
Stream GetStream();
// Anything you need here
}
public class TcpClientAdapter: ITcpClient
{
private TcpClient wrappedClient;
public TcpClientAdapter(TcpClient client)
{
wrappedClient = client;
}
public Stream GetStream()
{
return wrappedClient.GetStream();
}
}
```
|
I think @Hitchhiker is on the right track, but I also like to think about abstracting out things like that just a step further.
I wouldn't mock out the TcpClient directly, because that would still tie you too closely to the underlying implementation even though you've written tests. That is, your implementation is tied to a TcpClient method specifically. Personally, I would try something like this:
```
[Test]
public void TestInput(){
NetworkInputSource mockInput = mocks.CreateMock<NetworkInputSource>();
Consumer c = new Consumer(mockInput);
c.ReadAll();
// c.Read();
// c.ReadLine();
}
public class TcpClientAdapter : NetworkInputSource
{
private TcpClient _client;
public string ReadAll()
{
return new StreamReader(_tcpClient.GetStream()).ReadToEnd();
}
public string Read() { ... }
public string ReadLine() { ... }
}
public interface NetworkInputSource
{
public string ReadAll();
public string Read();
public string ReadLine();
}
```
This implementation will decouple you from Tcp related details altogether (if that is a design goal), and you can even pipe in test input from a hard coded set of values, or a test input file. Very hand if you are on the road to testing your code for the long haul.
|
TDD and Mocking out TcpClient
|
[
"",
"c#",
"networking",
"tdd",
"mocking",
""
] |
I'm looking for a good JavaScript RegEx to convert names to proper cases. For example:
```
John SMITH = John Smith
Mary O'SMITH = Mary O'Smith
E.t MCHYPHEN-SMITH = E.T McHyphen-Smith
John Middlename SMITH = John Middlename SMITH
```
Well you get the idea.
Anyone come up with a comprehensive solution?
|
Something like this?
```
function fix_name(name) {
var replacer = function (whole,prefix,word) {
ret = [];
if (prefix) {
ret.push(prefix.charAt(0).toUpperCase());
ret.push(prefix.substr(1).toLowerCase());
}
ret.push(word.charAt(0).toUpperCase());
ret.push(word.substr(1).toLowerCase());
return ret.join('');
}
var pattern = /\b(ma?c)?([a-z]+)/ig;
return name.replace(pattern, replacer);
}
```
|
Wimps!.... Here's my second attempt. Handles "John SMITH", "Mary O'SMITH" "John Middlename SMITH", "E.t MCHYPHEN-SMITH" and "JoHn-JOE MacDoNAld"
```
Regex fixnames = new Regex("(Ma?C)?(\w)(\w*)(\W*)");
string newName = fixnames.Replace(badName, NameFixer);
static public string NameFixer(Match match)
{
string mc = "";
if (match.Groups[1].Captures.Count > 0)
{
if (match.Groups[1].Captures[0].Length == 3)
mc = "Mac";
else
mc = "Mc";
}
return
mc
+match.Groups[2].Captures[0].Value.ToUpper()
+match.Groups[3].Captures[0].Value.ToLower()
+match.Groups[4].Captures[0].Value;
}
```
NOTE: By the time I realized you wanted a Javascript solution instead of a .NET one, I was having too much funny to stop....
|
JS Regex For Human Names
|
[
"",
"javascript",
"regex",
"string",
"text",
""
] |
I've got a User table with a bitmask that contains the user's roles. The linq query below returns all the users whose roles include 1, 4 or 16.
```
var users = from u in dc.Users
where ((u.UserRolesBitmask & 1) == 1)
|| ((u.UserRolesBitmask & 4) == 4)
|| ((u.UserRolesBitmask & 16) == 16)
select u;
```
I'd like to rewrite this into the method below to returns all the users from the given roles so I can reuse it:
```
private List<User> GetUsersFromRoles(uint[] UserRoles) {}
```
Any pointers on how to dynamically build my query? Thanks
|
You can use the [PredicateBuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx) class.
PredicateBuilder has been released in the [LINQKit NuGet package](https://www.nuget.org/packages/LinqKit/)
> LINQKit is a free set of extensions for LINQ to SQL and Entity Framework power users.
|
Assuming your UserRoles values are themselves bitmasks, would something like this work?
```
private List<User> GetUsersFromRoles(uint[] UserRoles) {
uint roleMask = 0;
for (var i = 0; i < UserRoles.Length;i++) roleMask= roleMask| UserRoles[i];
// roleMasknow contains the OR'ed bitfields of the roles we're looking for
return (from u in dc.Users where (u.UserRolesBitmask & roleMask) > 0) select u);
}
```
There's probably a nice LINQ syntax that'll work in place of the loops, but the concept should be the same.
|
How do you add dynamic 'where' clauses to a linq query?
|
[
"",
"c#",
"linq",
"dynamic",
""
] |
I am just starting to fiddle with Excel via C# to be able to automate the creation, and addition to an Excel file.
I can open the file and update its data and move through the existing worksheets. My problem is how can I add new sheets?
I tried:
```
Excel.Worksheet newWorksheet;
newWorksheet = (Excel.Worksheet)excelApp.ThisWorkbook.Worksheets.Add(
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
```
But I get below *COM Exception* and my googling has not given me any answer.
> Exception from HRESULT: 0x800A03EC Source is: "Interop.Excel"
I am hoping someone maybe able to put me out of my misery.
|
You need to add a COM reference in your project to the **"`Microsoft Excel 11.0 Object Library`"** - or whatever version is appropriate.
This code works for me:
```
private void AddWorksheetToExcelWorkbook(string fullFilename,string worksheetName)
{
Microsoft.Office.Interop.Excel.Application xlApp = null;
Workbook xlWorkbook = null;
Sheets xlSheets = null;
Worksheet xlNewSheet = null;
try {
xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
return;
// Uncomment the line below if you want to see what's happening in Excel
// xlApp.Visible = true;
xlWorkbook = xlApp.Workbooks.Open(fullFilename, 0, false, 5, "", "",
false, XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
xlSheets = xlWorkbook.Sheets as Sheets;
// The first argument below inserts the new worksheet as the first one
xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
xlNewSheet.Name = worksheetName;
xlWorkbook.Save();
xlWorkbook.Close(Type.Missing,Type.Missing,Type.Missing);
xlApp.Quit();
}
finally {
Marshal.ReleaseComObject(xlNewSheet);
Marshal.ReleaseComObject(xlSheets);
Marshal.ReleaseComObject(xlWorkbook);
Marshal.ReleaseComObject(xlApp);
xlApp = null;
}
}
```
> Note that you want to be very careful about [properly cleaning up and releasing your COM object references](https://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects-in-c). Included in that StackOverflow question is a useful rule of thumb: *"Never use 2 dots with COM objects"*. In your code; you're going to have real trouble with that. *My demo code above does NOT properly clean up the Excel app, but it's a start!*
Some other links that I found useful when looking into this question:
* [Opening and Navigating Excel with C#](http://www.codeproject.com/KB/office/csharp_excel.aspx)
* [How to: Use COM Interop to Create an Excel Spreadsheet (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/ms173186(VS.80).aspx)
* [How to: Add New Worksheets to Workbooks](http://msdn.microsoft.com/en-us/library/6fczc37s(VS.80).aspx)
According to MSDN
> To use COM interop, you must have
> administrator or Power User security
> permissions.
Hope that helps.
|
Would like to thank you for some excellent replies. @AR., your a star and it works perfectly. I had noticed last night that the `Excel.exe` was not closing; so I did some research and found out about how to release the COM objects. Here is my final code:
```
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using Excel;
namespace testExcelconsoleApp
{
class Program
{
private String fileLoc = @"C:\temp\test.xls";
static void Main(string[] args)
{
Program p = new Program();
p.createExcel();
}
private void createExcel()
{
Excel.Application excelApp = null;
Excel.Workbook workbook = null;
Excel.Sheets sheets = null;
Excel.Worksheet newSheet = null;
try
{
FileInfo file = new FileInfo(fileLoc);
if (file.Exists)
{
excelApp = new Excel.Application();
workbook = excelApp.Workbooks.Open(fileLoc, 0, false, 5, "", "",
false, XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
sheets = workbook.Sheets;
//check columns exist
foreach (Excel.Worksheet sheet in sheets)
{
Console.WriteLine(sheet.Name);
sheet.Select(Type.Missing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
}
newSheet = (Worksheet)sheets.Add(sheets[1], Type.Missing, Type.Missing, Type.Missing);
newSheet.Name = "My New Sheet";
newSheet.Cells[1, 1] = "BOO!";
workbook.Save();
workbook.Close(null, null, null);
excelApp.Quit();
}
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(newSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
newSheet = null;
sheets = null;
workbook = null;
excelApp = null;
GC.Collect();
}
}
}
}
```
Thank you for all your help.
|
C# - How to add an Excel Worksheet programmatically - Office XP / 2003
|
[
"",
"c#",
"excel",
"com",
"office-interop",
"worksheet",
""
] |
I am deciding on a framework to try out for PHP. I have narrowed it down to CakePHP and CodeIgniter. I have a couple of questions for any of you who have used or are familiar with both:
1. I like the fact that CakePHP keeps most of the code outside of the webroot by default. Especially since I may end up using a single framework install for multiple apps. I see CodeIgniter will do that too, but you have to configure it and move some stuff around. Is that workaround secure and reliable, or is it an afterthought hack?
2. Which (if not both) is easier to upgrade, and maintain over the long term? As new versions of the framework (and PHP itself) come out. I don't want to find my stuff either breaking, or becoming outdated.
**Edit:**
This is a very old post, but I thought I would update it with what I finally ended up doing, which was to use Kohana.
|
You should **try** both frameworks for a week or so, building something trivial (like a blog or wiki) in both, and see which you prefer using. Whatever makes the most sense *to you* will probably sustain you the longest through upgrades an deprecations.
CakePHP is in a bit of a volatile state right now, still unearthing bugs while pushing to release version 1.2 (which is not backward compatible). I wouldn't suggest building a critical application with it if you need something rock solid *right now*. If you can wait a month or two for things to settle, then it's probably a moot point.
To address your concerns:
1) Cake and CI do it the same way (iirc). They are equally secure, reliable, and hackish on this front.
2) Everything changes. If you need concrete, perpetual assurance of stability and backward compatibility, roll your own framework. There's not that much to it, and you're guaranteed that nothing changes unless you want it to.
|
I have deployed multiple applications on CakePHP and it's been a very, very, nice experience. You can't go wrong either way, as both are solid.
|
Which framework should I use to ensure better longterm upgrade / maintainability, CakePHP or CodeIgniter?
|
[
"",
"php",
"codeigniter",
"cakephp",
"maintainability",
""
] |
When I try to add a HTTP header key/value pair on a `WebRequest` object, I get the following exception:
> This header must be modified using the appropriate property
I've tried adding new values to the `Headers` collection by using the Add() method but I still get the same exception.
```
webRequest.Headers.Add(HttpRequestHeader.Referer, "http://stackoverflow.com");
```
I can get around this by casting the WebRequest object to a HttpWebRequest and setting the properties such as `httpWebReq.Referer ="http://stackoverflow.com"`, but this only works for a handful of headers that are exposed via properties.
I'd like to know if there's a way to get a finer grained control over modifying headers with a request for a remote resource.
|
If you need the short and technical answer go right to the last section of the answer.
If you want to know better, read it all, and i hope you'll enjoy...
---
I countered this problem too today, and what i discovered today is that:
1. the above answers are true, as:
1.1 it's telling you that the header you are trying to add already exist and you should then modify its value using the appropriate property (the indexer, for instance), instead of trying to add it again.
1.2 Anytime you're changing the headers of an `HttpWebRequest`, you need to use the appropriate properties on the object itself, if they exist.
Thanks FOR and Jvenema for the leading guidelines...
2. But, What i found out, and **that was the missing piece in the puzzle** is that:
2.1 The `WebHeaderCollection` class is generally accessed through `WebRequest`.Headers or `WebResponse`.Headers. **Some common headers are considered restricted and are either exposed directly by the API (such as Content-Type) or protected by the system and cannot be changed.**
The restricted headers are:
* `Accept`
* `Connection`
* `Content-Length`
* `Content-Type`
* `Date`
* `Expect`
* `Host`
* `If-Modified-Since`
* `Range`
* `Referer`
* `Transfer-Encoding`
* `User-Agent`
* `Proxy-Connection`
---
So, next time you are facing this exception and don't know how to solve this, remember that there are some restricted headers, and the solution is to modify their values using the appropriate property explicitly from the `WebRequest`/`HttpWebRequest` class.
---
Edit: (useful, from comments, comment by user [Kaido](https://stackoverflow.com/questions/239725/cannot-set-some-http-headers-when-using-system-net-webrequest#comment15470171_4752359))
> Solution is to check if the header exists already or is restricted (`WebHeaderCollection.IsRestricted(key)`) before calling add
|
I ran into this problem with a custom web client. I think people may be getting confused because of multiple ways to do this. When using `WebRequest.Create()` you can cast to an `HttpWebRequest` and use the property to add or modify a header. When using a `WebHeaderCollection` you may use the `.Add("referer","my_url")`.
Ex 1
```
WebClient client = new WebClient();
client.Headers.Add("referer", "http://stackoverflow.com");
client.Headers.Add("user-agent", "Mozilla/5.0");
```
Ex 2
```
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Referer = "http://stackoverflow.com";
request.UserAgent = "Mozilla/5.0";
response = (HttpWebResponse)request.GetResponse();
```
|
Cannot set some HTTP headers when using System.Net.WebRequest
|
[
"",
"c#",
"header",
"webrequest",
""
] |
What is the best way to graph scatter plots in C++?
Do you write data to a file and use another tool? Is there a library like matplotlib in Python?
|
I always write out data and then using [gnuplot](http://www.gnuplot.info/) to create my graphs. It is by far the best way I have found of producing graphs in a variety of formats: eps, png, jpeg, xpm, you name it.
`gnuplot` will do scatter plot very easily. Provided the `x` and `y` values are in 2 space-separated columnss, then
```
plot "data.txt" using 1:2
```
Will give you a quick scatter plot. Then you can adjust it and what not using other gnuplot commands.
If you are involved in sciences, then learning `gnuplot` will be very valuable to you. It kicks the crap out of doing excel plots for sure and it eases the task of making plots to include in papers.
|
If you are looking for a C++ library rather than I independent plotting tool like gnuplot, I would consider the following:
* [Koolplot](http://www.codecutter.net/tools/koolplot/byExample.html)
* [dislin](http://www.mps.mpg.de/dislin/) ([Wikipedia article on dislin](http://en.wikipedia.org/wiki/DISLIN))
dislin seems to be the more interesting of the two. Here is a description extracted from the wikipedia article:
> DISLIN is a high-level and easy to use plotting library developed by Helmut Michels at the Max Planck Institute in Katlenburg-Lindau, Germany. Helmut Michels currently works as a mathematician and Unix system manager at the computer center of the institute.
>
> The DISLIN library contains routines and functions for displaying data as curves, bar graphs, pie charts, 3D-colour plots, surfaces, contours and maps. Several output formats are supported such as X11, VGA, PostScript, PDF, CGM, HPGL, SVG, PNG, BMP, PPM, GIF and TIFF.
>
> DISLIN is available for the programming languages Fortran 77, Fortran 90/95 and C. Plotting extensions for the languages Perl, Python and Java are also supported for most operating systems. The current version of DISLIN is 9.4, released in October 2008. The first version 1.0 was released in December 1986.
>
> The DISLIN software is free for non-commercial use.
|
Scatter Plots in C++
|
[
"",
"c++",
"data-visualization",
"scatter-plot",
""
] |
I am looking for an addon that can say characters vocally. It is for non-commercial use, and it would be nice if it can vocalize more languages, like asian, english etc...
I have googled it, but can't seem to find anything for free use.
Update: This is for web use
|
You could try <http://espeak.sourceforge.net/> and make an mp3 of the word, then stream it to a flash application (you could use darwin for the streaming).
|
You can convert the text to speech in Java using freetts1.2 API. It is quite simple to use. This link could be useful for you which has an example program.
<http://learnsharelive.blogspot.com/2011/01/convert-text-to-speech-java-freetts12.html>
|
(Vocal code) Need some help finding text-to-speech addon
|
[
"",
"java",
"flash",
"text-to-speech",
""
] |
I am experimenting with calling delegate functions from a delegate array. I've been able to create the array of delegates, but how do I call the delegate?
```
public delegate void pd();
public static class MyClass
{
static void p1()
{
//...
}
static void p2 ()
{
//...
}
//...
static pd[] delegates = new pd[] {
new pd( MyClass.p1 ),
new pd( MyClass.p2)
/* ... */
};
}
public class MainClass
{
static void Main()
{
// Call pd[0]
// Call pd[1]
}
}
```
**EDIT:** The reason for the array is that I need to call the delegate functions by an index as needed. They are not run in response to an event. I see a critical (stupid) error in my code as I had tried to execute the delegate function using the pd[] type rather than the name of the array (delegates).
|
If they're all the same type, why not just combine them into a single multicast delegate?
```
static pd delegateInstance = new pd(MyClass.p1) + new pd(MyClass.p2) ...;
...
pd();
```
|
```
public class MainClass
{
static void Main()
{
pd[0]();
pd[1]();
}
}
```
|
Delegate Array in C#
|
[
"",
"c#",
"arrays",
"delegates",
""
] |
**EDIT:** See [my working code](https://stackoverflow.com/questions/218909/returning-a-pdf-file-from-a-java-bean-to-a-jsp#221252) in the answers below.
---
**In brief:** I have a JSP file which calls a method in a Java Bean. This method creates a PDF file and in theory, returns it to the JSP so that the user can download it. However, upon loading the PDF, Adobe Reader gives the error: *File does not begin with '%PDF-'*.
**In detail:** So far, the JSP successfully calls the method, the PDF is created and then the JSP appears to give the user the finished PDF file. However, as soon as Adobe Reader tries to open the PDF file, it gives an error: *File does not begin with '%PDF-'*. Just for good measure, I have the method create the PDF on my Desktop so that I can check it; when I open it normally within Windows is appears fine. So why is the output from the JSP different?
To create the PDF, I'm using [Apache FOP](http://xmlgraphics.apache.org/fop). I'm following one of their most basic examples, with the exception of passing the resulting PDF to a JSP instead of simply saving it to the local machine. I have been following their [basic usage pattern](http://xmlgraphics.apache.org/fop/0.95/embedding.html#basics) and [this example code](http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/examples/embedding/java/embedding/ExampleFO2PDF.java?view=markup).
Here's my JSP file:
```
<%@ taglib uri="utilTLD" prefix="util" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>
<%@ page language="java" session="false" %>
<%@ page contentType="application/pdf" %>
<%-- Construct and initialise the PrintReportsBean --%>
<jsp:useBean id="printReportsBean" scope="request" class="some.package.printreports.PrintReportsBean" />
<jsp:setProperty name="printReportsBean" property="*"/>
<c:set scope="page" var="xml" value="${printReportsBean.download}"/>
```
Here's my Java Bean method:
```
//earlier in the class...
private static FopFactory fopFactory = FopFactory.newInstance();
public File getDownload() throws UtilException {
OutputStream out = null;
File pdf = new File("C:\\documents and settings\\me\\Desktop\\HelloWorld.pdf");
File fo = new File("C:\\somedirectory", "HelloWorld.fo");
try {
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
out = new FileOutputStream(pdf);
out = new BufferedOutputStream(out);
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(); //identity transformer
Source src = new StreamSource(fo);
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(src, res);
return pdf;
} catch (Exception e) {
throw new UtilException("Could not get download. Msg = "+e.getMessage());
} finally {
try {
out.close();
} catch (IOException io) {
throw new UtilException("Could not close OutputStream. Msg = "+io.getMessage());
}
}
}
```
I realise that this is a very specific problem, but any help would be much appreciated!
|
The way I have implemented this type of feature in the past is to make a servlet write the contents of the PDF file out to the response as a stream. I don't have the source code with me any longer (and it's been at least a year since I did any servlet/jsp work), but here is what you might want to try:
In a servlet, get a handle on the response's output stream. Change the mime type of the response to "application/pdf", and have the servlet do the file handling you have in your example. Only, instead of returning the File object, have the servlet write the file to the output stream. See examples of file i/o and just replace any outfile.write(...) lines with responseStream.write(...) and you should be set to go. Once you flush and close the output stream, and do the return, if I remember correctly, the browser should be able to pick up the pdf from the response.
|
Ok, I got this working. Here's how I did it:
JSP:
```
<%@ taglib uri="utilTLD" prefix="util" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>
<%@ page language="java" session="false" %>
<%@ page contentType="application/pdf" %>
<%-- Construct and initialise the PrintReportsBean --%>
<jsp:useBean id="printReportsBean" scope="request" class="some.package.PrintReportsBean" />
<jsp:setProperty name="printReportsBean" property="*"/>
<%
// get report format as input parameter
ServletOutputStream servletOutputStream = response.getOutputStream();
// reset buffer to remove any initial spaces
response.resetBuffer();
response.setHeader("Content-disposition", "attachment; filename=HelloWorld.pdf");
// check that user is authorised to download product
printReportsBean.getDownload(servletOutputStream);
%>
```
Java Bean method:
```
//earlier in the class...
private static FopFactory fopFactory = FopFactory.newInstance();
public void getDownload(ServletOutputStream servletOutputStream) throws UtilException {
OutputStream outputStream = null;
File fo = new File("C:\\some\\path", "HelloWorld.fo");
try {
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
outputStream = new BufferedOutputStream(servletOutputStream);
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, outputStream);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(); //identity transformer
Source src = new StreamSource(fo);
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(src, res);
} catch (Exception e) {
throw new UtilException("Could not get download. Msg = "+e.getMessage());
} finally {
try {
outputStream.close();
} catch (IOException io) {
throw new UtilException("Could not close OutputStream. Msg = "+io.getMessage());
}
}
}
```
Thanks to everyone for their input!
|
Returning a PDF file from a Java Bean to a JSP
|
[
"",
"java",
"jsp",
"pdf",
"xsl-fo",
"apache-fop",
""
] |
I'm trying to write a python script that packages our software. This script needs to build our product, and package it. Currently we have other scripts that do each piece individually which include csh, and perl scripts. One such script is run like:
```
sudo mod args
```
where mod is a perl script; so in python I would do
```
proc = Popen(['sudo', 'mod', '-p', '-c', 'noresource', '-u', 'dtt', '-Q'], stderr=PIPE, stdout=PIPE, stdin=PIPE)
```
The problem is that this mod script needs a few questions answered. For this I thought that the traditional
```
(stdout, stderr) = proc.communicate(input='y')
```
would work. I don't think it's working because the process that Popen is controlling is sudo, not the mod script that is asking the question. Is there any way to communicate with the mod script and still run it through sudo?
|
I would choose to go with Pexpect.
```
import pexpect
child = pexpect.spawn ('sudo mod -p -c noresource -u dtt -Q')
child.expect ('First question:')
child.sendline ('Y')
child.expect ('Second question:')
child.sendline ('Yup')
```
|
I think you should remove the `sudo` in your `Popen` call and require the user of *your* script to type `sudo`.
This additionally makes more explicit the need for elevated privileges in your script, instead of hiding it inside `Popen`.
|
Is it possible to communicate with a sub subprocess with subprocess.Popen?
|
[
"",
"python",
"subprocess",
""
] |
```
Option Explicit On
Option Strict On
Public Class Class1
Dim l As List(Of A)
Public Sub New()
l = New List(Of B)
End Sub
End Class
Public Class A
End Class
Public Class B
Inherits A
End Class<p>
```
I've run into this problem.
I have a list declared of a Generic Type 'A'
I want to define the list as a Generic Type 'B', which is a subclass of 'A'.
Why can't this be done, and how can the same effect be achieved?
|
It's a matter of variance, which C# doesn't support for generics. See [Rick Byer's post on the subject](http://blogs.msdn.com/rmbyers/archive/2005/02/16/375079.aspx).
|
In C# 4.0 (as announced yesterday) we are [half way there](http://blogs.msdn.com/charlie/archive/2008/10/28/linq-farm-covariance-and-contravariance-in-visual-studio-2010.aspx).
|
Create Generic List from a subclass
|
[
"",
"c#",
"vb.net",
"generics",
"reflection",
""
] |
Suppose we have some named enums:
```
enum MyEnum {
FOO,
BAR = 0x50
};
```
What I googled for is a script (any language) that scans all the headers in my project and generates a header with one function per enum.
```
char* enum_to_string(MyEnum t);
```
And a implementation with something like this:
```
char* enum_to_string(MyEnum t){
switch(t){
case FOO:
return "FOO";
case BAR:
return "BAR";
default:
return "INVALID ENUM";
}
}
```
The gotcha is really with typedefed enums, and unnamed C style enums. Does anybody know something for this?
EDIT: The solution should not modify my source, except for the generated functions. The enums are in an API, so using the solutions proposed until now is just not an option.
|
You may want to check out [GCCXML](http://www.gccxml.org/HTML/Index.html).
Running GCCXML on your sample code produces:
```
<GCC_XML>
<Namespace id="_1" name="::" members="_3 " mangled="_Z2::"/>
<Namespace id="_2" name="std" context="_1" members="" mangled="_Z3std"/>
<Enumeration id="_3" name="MyEnum" context="_1" location="f0:1" file="f0" line="1">
<EnumValue name="FOO" init="0"/>
<EnumValue name="BAR" init="80"/>
</Enumeration>
<File id="f0" name="my_enum.h"/>
</GCC_XML>
```
You could use any language you prefer to pull out the Enumeration and EnumValue tags and generate your desired code.
|
X-macros are the best solution. Example:
```
#include <iostream>
enum Colours {
# define X(a) a,
# include "colours.def"
# undef X
ColoursCount
};
char const* const colours_str[] = {
# define X(a) #a,
# include "colours.def"
# undef X
0
};
std::ostream& operator<<(std::ostream& os, enum Colours c)
{
if (c >= ColoursCount || c < 0) return os << "???";
return os << colours_str[c];
}
int main()
{
std::cout << Red << Blue << Green << Cyan << Yellow << Magenta << std::endl;
}
```
colours.def:
```
X(Red)
X(Green)
X(Blue)
X(Cyan)
X(Yellow)
X(Magenta)
```
However, I usually prefer the following method, so that it's possible to tweak the string a bit.
```
#define X(a, b) a,
#define X(a, b) b,
X(Red, "red")
X(Green, "green")
// etc.
```
|
Is there a simple way to convert C++ enum to string?
|
[
"",
"c++",
"string",
"enums",
"scripting",
""
] |
I'm refactoring some PHP code and discovered that certain nested combinations of
```
if () :
```
and
```
if () {
```
generate syntax errors. Not that I would normally mix the two, but I like to do frequent syntax checks as I'm writing code and I kept getting a syntax error because of this.
Example - generates syntax error:
```
if ( $test == 1 ) :
if ( $test2 == 'a' ) {
if ( $test3 == 'A' ) {
} else {
}
}
else :
echo 'test2';
endif;
```
Example - does NOT generate syntax error:
```
if ( $test == 1 ) :
if ( $test2 == 'a' ) :
if ( $test3 == 'A' ) :
else :
endif;
endif;
else :
echo 'test2';
endif;
```
Could someone please explain to me why the first block of code is generating an error?
|
This is a wild guess since I am not familiar with the grammar of PHP. But here goes:
The problem is the second `else`. The parser can't see if this `else` is belonging to the first or the second if (counting from the beginning). In your second example there is an `endif` making the second `if`-block be terminated so there it can do the parse. Perhaps this is the famous 'dangling-else' problem in disguise?
|
i don't know the exact reason why. here's a related [PHP bug post](http://bugs.php.net/bug.php?id=18413) in which a dev basically says, "just don't do it" :). i haven't poured through the PHP source code lately, but if i had to hazard a guess, it's due to not checking for alternative syntax while recursively going through if statements.
|
Mixed syntax for control structures generating syntax errors
|
[
"",
"php",
"syntax",
""
] |
What are the different types of indexes, what are the benefits of each?
I heard of covering and clustered indexes, are there more? Where would you use them?
|
* Unique - Guarantees unique values for the column(or set of columns) included in the index
* Covering - Includes all of the columns that are used in a particular query (or set of queries), allowing the database to use only the index and not actually have to look at the table data to retrieve the results
* Clustered - This is way in which the actual data is ordered on the disk, which means if a query uses the clustered index for looking up the values, it does not have to take the additional step of looking up the actual table row for any data not included in the index.
|
[OdeToCode has a good article covering the basic differences](http://www.odetocode.com/Articles/70.aspx)
As it says in the article:
> Proper indexes are crucial for good
> performance in large databases.
> Sometimes you can make up for a poorly
> written query with a good index, but
> it can be hard to make up for poor
> indexing with even the best queries.
Quite true, too... If you're just starting out with it, I'd focus on clustered and composite indexes, since they'll probably be what you use the most.
|
What are the different types of indexes, what are the benefits of each?
|
[
"",
"sql",
"database",
"database-design",
"indexing",
""
] |
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." (Donald Knuth). My SQL tables are unlikely to contain more than a few thousand rows each (and those are the big ones!). SQL Server Database Engine Tuning Advisor dismisses the amount of data as irrelevant. So I shouldn't even think about putting explicit indexes on these tables. Correct?
|
The value of indexes is in speeding reads. For instance, if you are doing lots of SELECTs based on a range of dates in a date column, it makes sense to put an index on that column. And of course, generally you add indexes on any column you're going to be JOINing on with any significant frequency. The efficiency gain is also related to the ratio of the size of your typical recordsets to the number of records (i.e. grabbing 20/2000 records benefits more from indexing than grabbing 90/100 records). A lookup on an unindexed column is essentially a linear search.
The cost of indexes comes on writes, because every INSERT also requires an internal insert to each column index.
So, the answer depends entirely on your application -- if it's something like a dynamic website where the number of reads can be 100x or 1000x the writes, and you're doing frequent, disparate lookups based on data columns, indexing may well be beneficial. But if writes greatly outnumber reads, then your tuning should focus on speeding those queries.
It takes very little time to identify and benchmark a handful of your app's most frequent operations both with and without indexes on the JOIN/WHERE columns, I suggest you do that. It's also smart to monitor your production app and identify the most expensive, and most frequent queries, and focus your optimization efforts on the intersection of those two sets of queries (which could mean indexes or something totally different, like allocating more or less memory for query or join caches).
|
Knuth's wise words are not applicable to the creation (or not) of indexes, since by adding indexes you are **not** optimising anything directly: you are providing an index that the DBMSs optimiser *may* use to optimise some queries. In fact, you could better argue that deciding *not* to index a small table is premature optimisation, as by doing so you restrict the DBMS optimiser's options!
Different DBMSs will have different guidelines for choosing whether or not to index columns based on various factors including table size, and it is these that should be considered.
What **is** an example of premature optimisation in databases: "denormalising for performance" before any benchmarking has indicated that the normalised database actually has any performance issues.
|
No indexes on small tables?
|
[
"",
"sql",
"sql-server",
"indexing",
"performance",
""
] |
I have heard from people who have switched either way and who swear by the one or the other.
Being a huge Eclipse fan but having not had the time to try out IntelliJ, I am interested in hearing from IntelliJ users who are "ex-Eclipsians" some specific things that you can do with IntelliJ that you can not do with Eclipse.
**Note**: This is not a subjective question nor at all meant to turn into an IDE holy war. ***Please downvote any flamebait answers***.
|
## CTRL-click works anywhere
CTRL-click that brings you to where clicked object is defined works everywhere - not only in Java classes and variables in Java code, but in Spring configuration (you can click on class name, or property, or bean name), in Hibernate (you can click on property name or class, or included resource), you can navigate within one click from Java class to where it is used as Spring or Hibernate bean; clicking on included JSP or JSTL tag also works, ctrl-click on JavaScript variable or function brings you to the place it is defined or shows a menu if there are more than one place, including other .js files and JS code in HTML or JSP files.
## Autocomplete for many languagues
### Hibernate
Autocomplete in HSQL expressions, in Hibernate configuration (including class, property and DB column names), in Spring configuration
```
<property name="propName" ref="<hit CTRL-SPACE>"
```
and it will show you list of those beans which you can inject into that property.
### Java
Very smart autocomplete in Java code:
```
interface Person {
String getName();
String getAddress();
int getAge();
}
//---
Person p;
String name = p.<CTRL-SHIFT-SPACE>
```
and it shows you ONLY *getName()*, *getAddress()* and *toString()* (only they are compatible by type) and *getName()* is first in the list because it has more relevant name. Latest version 8 which is still in EAP has even more smart autocomplete.
```
interface Country{
}
interface Address {
String getStreetAddress();
String getZipCode();
Country getCountry();
}
interface Person {
String getName();
Address getAddress();
int getAge();
}
//---
Person p;
Country c = p.<CTRL-SHIFT-SPACE>
```
and it will silently autocomplete it to
```
Country c = p.getAddress().getCountry();
```
### Javascript
Smart autocomplete in JavaScript.
```
function Person(name,address) {
this.getName = function() { return name };
this.getAddress = function() { return address };
}
Person.prototype.hello = function() {
return "I'm " + this.getName() + " from " + this.get<CTRL-SPACE>;
}
```
and it shows ONLY *getName()* and *getAddress()*, no matter how may get\* methods you have in other JS objects in your project, and ctrl-click on *this.getName()* brings you to where this one is defined, even if there are some other *getName()* functions in your project.
### HTML
Did I mention autocomplete and ctrl-clicking in paths to files, like <script src="", <img src="", etc?
Autocomplete in HTML tag attributes. Autocomplete in style attribute of HTML tags, both attribute names and values. Autocomplete in class attributes as well.
Type <div class="<CTRL-SPACE> and it will show you list of CSS classes defined in your project. Pick one, ctrl-click on it and you will be redirected to where it is defined.
### Easy own language higlighting
Latest version has language injection, so you can declare that you custom JSTL tag usually contains JavaScript and it will highlight JavaScript inside it.
```
<ui:obfuscateJavaScript>function something(){...}</ui:obfuscateJavaScript>
```
## Indexed search across all project.
You can use Find Usages of any Java class or method and it will find where it is used including not only Java classes but Hibernate, Spring, JSP and other places. Rename Method refactoring renames method not only in Java classes but anywhere including comments (it can not be sure if string in comments is really method name so it will ask). And it will find only your method even if there are methods of another class with same name.
Good source control integration (does SVN support changelists? IDEA support them for every source control), ability to create a patch with your changes so you can send your changes to other team member without committing them.
## Improved debugger
When I look at *HashMap* in debugger's watch window, I see logical view - keys and values, last time I did it in Eclipse it was showing entries with hash and next fields - I'm not really debugging *HashMap*, I just want to look at it contents.
## Spring & Hibernate configuration validation
It validates Spring and Hibernate configuration right when you edit it, so I do not need to restart server to know that I misspelled class name, or added constructor parameter so my Spring cfg is invalid.
Last time I tried, I could not run Eclipse on Windows XP x64.
and it will suggest you *person.name* or *person.address*.
Ctrl-click on *person.name* and it will navigate you to *getName()* method of *Person* class.
Type `Pattern.compile("");` put \\ there, hit CTRL-SPACE and see helpful hint about what you can put into your regular expression. You can also use language injection here - define your own method that takes string parameter, declare in IntelliLang options dialog that your parameter is regular expression - and it will give you autocomplete there as well. Needless to say it highlights incorrect regular expressions.
## Other features
There are few features which I'm not sure are present in Eclipse or not. But at least each member of our team who uses Eclipse, also uses some merging tool to merge local changes with changes from source control, usually WinMerge. I never need it - merging in IDEA is enough for me. By 3 clicks I can see list of file versions in source control, by 3 more clicks I can compare previous versions, or previous and current one and possibly merge.
It allows to to specify that I need all .jars inside `WEB-INF\lib` folder, without picking each file separately, so when someone commits new .jar into that folder it picks it up automatically.
Mentioned above is probably 10% of what it does. I do not use Maven, Flex, Swing, EJB and a lot of other stuff, so I can not tell how it helps with them. But it does.
|
There is only one reason I use intellij and not eclipse: *Usability*
Whether it is debugging, refactoring, auto-completion.. Intellij is much easier to use with consistent key bindings, options available where you look for them etc. Feature-wise, it will be tough for intellij to catch up with Eclipse, as the latter has much more plugins available that intellij, and is easily extensible.
|
Things possible in IntelliJ that aren't possible in Eclipse?
|
[
"",
"java",
"eclipse",
"ide",
"intellij-idea",
""
] |
I know that IntelliJ has an option to select all the code in a JSP file, right click, and select "format". This nicely formats all HTML, CSS, scriptlets and JSTL tags in a JSP file.
Can Eclipse do this?
If not, what is the best free Eclipse plugin that does the same?
|
With the Web Tool Plateform plateform (on eclipse.org website), this is very simple : in the JSP editor tab, right click->source->format (or Shift+Ctrl+F)
|
I use the EclipseHTMLEditor from [Project Amateras](http://amateras.sourceforge.jp/). Be sure to set "Amateras JSP Editor" as default editor for file type "\*.jsp" in Window > Preferences > General > Editors > File Associations.
**UPDATE:** As of today, March 27th 2015, Project Amateras seems stale. However [latest releases of WTP](http://www.eclipse.org/webtools/) are much improved and surely worth a try. Thanks to @Vogel612 for the info.
|
What is the best free plugin for Eclipse that allows for formatting/indenting/cleanup of JSP code?
|
[
"",
"java",
"eclipse",
"jsp",
"intellij-idea",
""
] |
Can anybody recommend a good code profiler for C++?
I came across Shiny - any good? <http://sourceforge.net/projects/shinyprofiler/>
|
[Callgrind](http://valgrind.org/info/tools.html) for Unix/Linux
[DevPartner](http://www.compuware.com/products/devpartner/default.htm) for Windows
|
Not C++ specific, but AMD's CodeAnalyst software is free and is feature-packed.
<http://developer.amd.com/cpu/codeanalyst/codeanalystwindows/Pages/default.aspx>
|
C++ Code Profiler
|
[
"",
"c++",
"windows",
"visual-studio",
"profiler",
""
] |
I'm developing a SWT/JFace application using the libraries from Eclipse 3.4.1.
I encounter the following problem on Windows (Vista 32bit) and Ubuntu 8.10 32bit:
I create a menu bar in the createMenuManager method of the JFace ApplicationWindow. I add MenuManagers for file, edit and help.
I then add an ExitAction to the file MenuManager like so:
```
filemenu.add(new ExitAction(this));
```
The ExitAction is defined this way:
```
public class ExitAction extends Action {
final ApplicationWindow window;
public ExitAction(ApplicationWindow w) {
this.window = w;
setText("E&xit");
setToolTipText("Exit the application");
setAccelerator(SWT.MOD1 + 'Q');
}
}
```
Now when my application starts I want be able to press "CTRL+Q" to quit the application. This does however not work. Only AFTER I click on "File" in the menu bar and THEN clicking "CTRL+Q" the application will quit.
I've tried this with different accelerators- same behavior.
It does work however if I create a "MenuItem" instead of an "Action" to contribute to the menu bar.
Is this a SWT bug or do I miss something?
Torsten.
|
Update: There is a duplicate bug of mine which also contains a workaround.
The bug url is: <https://bugs.eclipse.org/bugs/show_bug.cgi?id=243758>
Basically the workaround is to call `create()` on the `ApplicationWindow` and then `getMenuBarManager().updateAll(true);` which will force all menu items to get initialized.
Of course you have to call the above methods after you created the menu items.
|
AFAIK `setAccelerator(.)` does nothing else than adding the appropriate text to your `MenuItem`. You are responsible to register for an `KeyUp` event and react on it.
You can use `Display.addFilter(SWT.KeyUp, myListener)` to register your `Listener` independently of your widgets.
|
Menu item accel key works only after menu item has been shown
|
[
"",
"java",
"swt",
""
] |
In python, if I say
```
print 'h'
```
I get the letter h and a newline. If I say
```
print 'h',
```
I get the letter h and no newline. If I say
```
print 'h',
print 'm',
```
I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?
The print statements are different iterations of the same loop so I can't just use the + operator.
|
```
import sys
sys.stdout.write('h')
sys.stdout.flush()
sys.stdout.write('m')
sys.stdout.flush()
```
You need to call [`sys.stdout.flush()`](https://docs.python.org/library/io.html#io.IOBase.flush) because otherwise it will hold the text in a buffer and you won't see it.
|
In [Python 3](https://docs.python.org/whatsnew/3.0.html#print-is-a-function), use
```
print('h', end='')
```
to suppress the endline terminator, and
```
print('a', 'b', 'c', sep='')
```
to suppress the whitespace separator between items. See [the documentation for `print`](https://docs.python.org/library/functions.html#print)
|
How do I keep Python print from adding newlines or spaces?
|
[
"",
"python",
"printing",
"formatting",
"python-2.x",
""
] |
Given a Stream as input, how do I safely create an XPathNavigator against an XML data source?
The XML data source:
* May possibly contain invalid hexadecimal characters that need to be removed.
* May contain characters that do not match the declared encoding of the document.
As an example, some XML data sources in the cloud will have a declared encoding of *utf-8*, but the actual encoding is *windows-1252* or *ISO 8859-1*, which can cause an invalid character exception to be thrown when creating an XmlReader against the Stream.
From the *StreamReader.CurrentEncoding* property documentation: "The current character encoding used by the current reader. The value can be different after the first call to any Read method of StreamReader, since encoding autodetection is not done until the first call to a Read method." This seems indicate that CurrentEncoding can be checked after the first read, but are we stuck storing this encoding when we need to write out the XML data to a Stream?
I am hoping to find a best practice for safely creating an XPathNavigator/IXPathNavigable instance against an XML data source that will gracefully handle encoding an invalid character issues (in C# preferably).
|
I had a similar issue when some XML fragments were imported into a CRM system using the wrong encoding (there was no encoding stored along with the XML fragments).
In a loop I created a wrapper stream using the current encoding from a list. The encoding was constructed using the DecoderExceptionFallback and EncoderExceptionFallback options (as mentioned by @Doug). If a DecoderFallbackException was thrown during processing the original stream is reset and the next-most-likely encoding is used.
Our encoding list was something like UTF-8, Windows-1252, GB-2312 and US-ASCII. If you fell off the end of the list then the stream was really bad and was rejected/ignored/etc.
EDIT:
I whipped up a quick sample and basic test files (source [here](http://www.devstuff.com/test/Soq255171.zip)). The code doesn't have any heuristics to choose between code pages that both match the same set of bytes, so a Windows-1252 file may be detected as GB2312, and vice-versa, depending on file content, and encoding preference ordering.
|
It's possible to use the [DecoderFallback](http://msdn.microsoft.com/en-us/library/system.text.decoderfallback.aspx) class (and a few related classes) to deal with bad characters, either by skipping them or by doing something else (restarting with a new encoding?).
|
How do I safely create an XPathNavigator against a Stream in C#?
|
[
"",
"c#",
"xml",
"encoding",
"stream",
""
] |
I have the classical table with expandable and collapsible records that if expanded show several subrecords (as new records in the same parent table, not some child div/child table). I am also using tablesorter and absolutely love it.
The problem is that tablesorter isn't keeping expanded child records next to the parent records. It sorts them as if they were top level. So each time the table gets sorted by a column the child rows end up all over the place and not where I want them.
Does anyone know of a good extension to tablesorter or specific configuration that enables tablesorter to keep child rows grouped together with the parent row even after sorting? Or do I have to give up tablesorter in favor of some other API or start the ugly process of writing my own widget? Should I avoid the css-based approach of hiding individual rows of the table to represent collapse rows?
|
If you want to keep tablesorter, there is a mod which I have used for this purpose **[available here](http://www.pengoworks.com/workshop/jquery/tablesorter/tablesorter.htm)**
After including it, you make your second (expandable child) row have the class "expand-child", and tablesorter will know to keep the row paired with its parent (preceding row).
|
Actually, that [mod of tablesorter](http://www.pengoworks.com/workshop/jquery/tablesorter/tablesorter.htm) mentioned by @AdamBellaire was added to [tablesorter v2.0.5](http://tablesorter.com/docs/). I've documented [how to use the `ccsChildRow` option](http://wowmotty.blogspot.com/2011/06/jquery-tablesorter-missing-docs.html#cssChildRow) on my blog.
Also, if you are interested, I have a [fork of tablesorter](http://mottie.github.com/tablesorter/docs/) on [github](https://github.com/Mottie/tablesorter) which has a lot of enhancements and useful widgets :)
|
Getting jQuery tablesorter to work with hidden/grouped table rows
|
[
"",
"javascript",
"jquery",
"tablesorter",
""
] |
Do you know of any tool that would do like Ruby on Rails' Scaffolding (create simple CRUD pages for any particular class to allow quickly populating a database with dummy data), only which used Java classes with Hibernate for database access, and JSP/JSF for the pages?
It is a drag when you are programming one part of an application, but need data that can only be added with another part that is not ready yet, or very cumbersomely by directly inserting it into the DB.
|
[Grails](http://grails.org/) is a very nice Rails-like framework built on top of Spring MVC. For persistence, they use [GORM](http://grails.org/GORM), which is basically an ActiveRecord-like framework built on top of Hibernate. Pretty slick.
If you already have Hibernate entities, they can actually be used immediately in Grails with no additional work.
|
You can try **Telosys Tools**, an Eclipse plugin for
code generation (scaffolding) working from an existing database
with customizable Velocity templates.
It's very simple and easy to use.
The tutorial for code generation with Spring MVC and Spring Data is here : <https://sites.google.com/site/telosystutorial/>
See also : <http://tools.telosys.org/>
Eclipse Marketplace : <http://marketplace.eclipse.org/content/telosys-tools>
|
Hibernate CRUD à la Ruby on Rails' Scaffolding
|
[
"",
"java",
"ruby-on-rails",
"hibernate",
"jsp",
"jsf",
""
] |
What would be the best way to determine if an object equals number zero (0) or string.empty in C#?
**EDIT:** The object can equal any built-in System.Value type or reference type.
Source Code:
```
public void MyMethod(object input1, object input2)
{
bool result = false;
object compare = new object();
if(input != null && input2 != null)
{
if(input1 is IComparable && input2 is IComparable)
{
//do check for zero or string.empty
//if input1 equals to zero or string.empty
result = object.Equals(input2);
//if input1 not equals to zero or string.empty
result = object.Equals(input1) && object.Equals(input2); //yes not valid, but this is what I want to accomplish
}
}
}
```
|
Using Jonathan Holland code sample with a minor modification, here is the solution that worked:
```
static bool IsZeroOrEmpty(object o1)
{
bool Passed = false;
object ZeroValue = 0;
if(o1 != null)
{
if(o1.GetType().IsValueType)
{
Passed = (o1 as System.ValueType).Equals(Convert.ChangeType(ZeroValue, o1.GetType()))
}
else
{
if (o1.GetType() == typeof(String))
{
Passed = o1.Equals(String.Empty);
}
}
}
return Passed;
}
```
|
What's wrong with this?
```
public static bool IsZeroOrEmptyString(object obj)
{
if (obj == null)
return false;
else if (obj.Equals(0) || obj.Equals(""))
return true;
else
return false;
}
```
|
Determine value of object in C#
|
[
"",
"c#",
"casting",
""
] |
Checking the HTML source of a question I see for instance:
```
<a id="comments-link-xxxxx" class="comments-link">add comment</a><noscript> JavaScript is needed to access comments.</noscript>
```
And then in the javascript source:
```
// Setup our click events..
$().ready(function() {
$("a[id^='comments-link-']").click(function() { comments.show($(this).attr("id").substr("comments-link-".length)); });
});
```
It seems that all the user click events are binded this way.
The downsides of this approach are obvious for people browsing the site with no javascript but, what are the advantages of adding events dynamically whith javascript over declaring them directly?
|
* You don't have to type the same string over and over again in the HTML (which if nothing else would increase the number of typos to debug)
* You can hand over the HTML/CSS to a designer who need not have any javascript skills
* You have programmatic control over what callbacks are called and when
* It's more elegant because it fits the conceptual separation between layout and behaviour
* It's easier to modify and refactor
On the last point, imagine if you wanted to add a "show comments" icon somewhere else in the template. It'd be very easy to bind the same callback to the icon.
|
Attaching events via the events API instead of in the mark-up is the core of unobtrusive javascript. You are welcome to read [this wikipedia article](http://en.wikipedia.org/wiki/Unobtrusive_JavaScript) for a complete overview of why unobtrusive javascripting is important.
The same way that you separate styles from mark-up you want to separate scripts from mark-up, including events.
|
Why Stackoverflow binds user actions dynamically with javascript?
|
[
"",
"javascript",
"jquery",
""
] |
I used to work with eclipse for nearly all the languages I need. I'm asked to work on a tool developed in C# and so, I would like to stay in the same familiar environment.
I've found the [improve's plugin](http://www.improve-technologies.com/alpha/esharp/) but its last release is from 2004 and .NET 1.1 which is quite old. Is there a newer plugin to program in C# within eclipse or am I forced to take a look at VS?
|
[Emonic](http://emonic.sourceforge.net/) integrates mono into the eclipse framework, that may be of use.
|
I fear, that there is no good eclipse plug in. Try <http://www.monodevelop.com/Main_Page> or <http://www.icsharpcode.net/OpenSource/SD/>. And the free visual 2008 express editions are worth a look.
|
Looking for up-to-date eclipse plugin for C#
|
[
"",
"c#",
"eclipse",
"eclipse-plugin",
""
] |
I'm absolutely in love with the way GWT does RPC. Is there anything similar for Java SE you have experience with that:
1. Is not spring
2. Doesn't require a Java EE/Servlet container to run the server side
3. Is not RMI that comes with Java SE
|
POJ (Plain Old JSON).
|
Maybe [Jini](http://www.jini.org/ "Jini"). Not Spring- or EJB-related, doesn't run in a container, and you can pick the transport.
|
Suggestion on remoting (rpc, rmi) for Java SE client-server app?
|
[
"",
"java",
"remoting",
""
] |
For the past 2 years-(ish) I've been using [Maven2](http://maven.apache.org) for my build/continuous integration solution. I used [Ant](http://ant.apache.org) a bit before that but really didn't get a lot of experience with it. Now I've taken a new job and the team I'm on now uses Ant.
What I'm wondering about is this:
In Maven we had directory conventions for seperating our java source and files and java test files ([JUnit](http://junit.org) tests). It looked like this:
```
Project-
-src/main/java
-src/test/java
```
This way your tests are separate from your source/production code and won't be built/deployed as such.
Going over the Ant documentation I don't really see any convention for this. Am I missing something? Is there a similar convention in Ant?
|
My experience with ant -- which is our primary build tool for Java source, so make of this what you will -- is that there are no such *formal* conventions. Many source projects I've seen organize things in a similar manner; JBoss uses <module>/src/main for sources, etc... Ant just uses whatever conventions you want, which makes it an ideal tool to integrate into a larger project building framework.
At any rate, the Maven conventions work just fine for Ant, so if you've already got them in place, just re-use the same structures. Not only is it easier for you to keep track of where things are, when you use a familiar structure, but if you ever decide to mavenize the project, you'll already be set.
|
A lot of ANT conventions/best practices are explained in [ANT in Anger](http://ant.apache.org/ant_in_anger.html)
|
Are there any Ant conventions similar to Maven2 conventions?
|
[
"",
"java",
"ant",
"automated-tests",
"conventions",
""
] |
Say i have this PHP code:
```
$FooBar = "a string";
```
i then need a function like this:
```
print_var_name($FooBar);
```
which prints:
```
FooBar
```
Any Ideas how to achieve this? Is this even possible in PHP?
|
You could use [get\_defined\_vars()](http://php.net/get_defined_vars) to find the name of a variable that has the same value as the one you're trying to find the name of. Obviously this will not always work, since different variables often have the same values, but it's the only way I can think of to do this.
Edit: get\_defined\_vars() doesn't seem to be working correctly, it returns 'var' because $var is used in the function itself. $GLOBALS seems to work so I've changed it to that.
```
function print_var_name($var) {
foreach($GLOBALS as $var_name => $value) {
if ($value === $var) {
return $var_name;
}
}
return false;
}
```
Edit: to be clear, there is no good way to do this in PHP, which is probably because you shouldn't have to do it. There are probably better ways of doing what you're trying to do.
|
I couldn't think of a way to do this efficiently either but I came up with this. It works, for the limited uses below.
*shrug*
```
<?php
function varName( $v ) {
$trace = debug_backtrace();
$vLine = file( __FILE__ );
$fLine = $vLine[ $trace[0]['line'] - 1 ];
preg_match( "#\\$(\w+)#", $fLine, $match );
print_r( $match );
}
$foo = "knight";
$bar = array( 1, 2, 3 );
$baz = 12345;
varName( $foo );
varName( $bar );
varName( $baz );
?>
// Returns
Array
(
[0] => $foo
[1] => foo
)
Array
(
[0] => $bar
[1] => bar
)
Array
(
[0] => $baz
[1] => baz
)
```
It works based on the line that called the function, where it finds the argument you passed in. I suppose it could be expanded to work with multiple arguments but, like others have said, if you could explain the situation better, another solution would probably work better.
|
How to get a variable name as a string in PHP?
|
[
"",
"php",
""
] |
I have an asp.net page with a button. This button generates and inserts a user control into the page, so many controls could exist on one page. I need to validate that a certain dynamically generated control inside the generated control exists.
So..Page has 0 to N Control1’s. Each Control 1 can have 0 to N Control2’s. When SaveButton is clicked on Page, I need to make sure there are at least 1 Control2’s inside every Control1.
I’m currently between two options:
• Dynamically insert CustomValidators for each control that is generated, each of which would validate one Control1.
• Do the validation manually (with jQuery), calling a validation function from SaveButton.OnClientClick.
Both are sloppy in their own way – which is why I’m sharing this with you all. Am I missing the easy solution?
Thanks in advance.. (btw – anything up to and including .NET 3.5 SP1 is fair game)
|
Hmm i like the Interface idea suggested by digiguru but i would use the interface on the container Control1 instead of the sub controls as it seems like the more logical place for the code to live. Heres my take on it:
```
public interface IValidatableControl
{
bool IsValidControl();
}
```
then implement this on your Control1
```
public class Control1 : IValidatableControl
{
... Other methods
public bool IsValidControl()
{
foreach(object c in this.Controls)
{
if(c.GetType() == "Control2")
return true;
}
return false;
}
}
```
There are probably better ways to write this but it should give you enough of an idea to get started.
|
If you are adding user controls on the fly, you could make each control implement the same interface with a Validate function. That way you can load the controls into a placeholder in each parent control on the page. When the page is submitted, simply loop through the controls in the placeholder, cast them to the interface class and then call the validate function. I doesn't use custom validators, but you can build up a list of validation errors using the object returned from the validate function, you can render this collection of validation errors whichever way you like.
|
Validating an ASP.NET user control from its parent page
|
[
"",
"c#",
"asp.net",
"validation",
"user-controls",
"custom-controls",
""
] |
Using answers to [this question](https://stackoverflow.com/questions/57522/javascript-array-with-a-mix-of-literals-and-arrays), I have been able to populate a select box based on the selection of another select box. ( [I posted my answer here](https://stackoverflow.com/questions/57522/javascript-array-with-a-mix-of-literals-and-arrays#58062)) Pulling the data from an array structure built server-side, stored in a .js file and referenced in the html page.
Now I would like to add a third select box. If I had 3 sets of data (model, make, options) something like this (pseudo code):
```
cars : [Honda[Accord[Lx, Dx]], [Civic[2dr, Hatchback]],
[Toyota[Camry[Blk, Red]], [Prius[2dr,4dr]]
```
Ex: If Honda were selected, the next select box would have [Accord Civic] and if Accord were selected the next select box would have [Lx Dx]
How can I
1) create an array structure to hold the data? such that
2) I can use the value from one select box to reference the needed values for the next select box
Thanks
**EDIT**
I can create the following, but can't figure out the references in a way that would help populate a select box
```
var cars = [
{"makes" : "Honda",
"models" : [
{'Accord' : ["2dr","4dr"]} ,
{'CRV' : ["2dr","Hatchback"]} ,
{'Pilot': ["base","superDuper"] } ]
},
{"makes" :"Toyota",
"models" : [
{'Prius' : ["green","reallyGreen"]} ,
{'Camry' : ["sporty","square"]} ,
{'Corolla' : ["cheap","superFly"] } ]
} ] ;
alert(cars[0].models[0].Accord[0]); ---> 2dr
```
|
I prefer data structure like this:
```
var carMakers = [
{ name: 'Honda', models: [
{ name: 'Accord', features: ['2dr', '4dr'] },
{ name: 'CRV', features: ['2dr', 'Hatchback'] },
{ name: 'Pilot', features: ['base', 'superDuper'] }
]},
{ name: 'Toyota', models: [
{ name: 'Prius', features: ['green', 'superGreen'] },
{ name: 'Camry', features: ['sporty', 'square'] },
{ name: 'Corolla', features: ['cheap', 'superFly'] }
]}
];
```
Given the three select lists with id's: 'maker', 'model' and 'features' you can manipulate them with this (I believe this is pretty self explanatory):
```
// returns array of elements whose 'prop' property is 'value'
function filterByProperty(arr, prop, value) {
return $.grep(arr, function (item) { return item[prop] == value });
}
// populates select list from array of items given as objects: { name: 'text', value: 'value' }
function populateSelect(el, items) {
el.options.length = 0;
if (items.length > 0)
el.options[0] = new Option('please select', '');
$.each(items, function () {
el.options[el.options.length] = new Option(this.name, this.value);
});
}
// initialization
$(document).ready(function () {
// populating 1st select list
populateSelect($('#maker').get(0), $.map(carMakers, function(maker) { return { name: maker.name, value: maker.name} }));
// populating 2nd select list
$('#maker').bind('change', function() {
var makerName = this.value,
carMaker = filterByProperty(carMakers, 'name', makerName),
models = [];
if (carMaker.length > 0)
models = $.map(carMaker[0].models, function(model) { return { name: model.name, value: makerName + '.' + model.name} });
populateSelect($('#model').get(0), models);
$('#model').trigger('change');
});
// populating 3rd select list
$('#model').bind('change', function () {
var nameAndModel = this.value.split('.'),
features = [];
if (2 == nameAndModel.length) {
var makerName = nameAndModel[0],
carModel = nameAndModel[1],
carMaker = filterByProperty(carMakers, 'name', makerName);
if (carMaker.length > 0) {
var model = filterByProperty(carMaker[0].models, 'name', carModel)
if (model.length > 0)
features = $.map(model[0].features, function(feature) { return { name: feature, value: makerName + '.' + carModel + '.' + feature} })
}
}
populateSelect($('#feature').get(0), features);
})
// alerting value on 3rd select list change
$('#feature').bind('change', function () {
if (this.value.length > 0)
alert(this.value);
})
});
```
|
Thanks to the answer from @Marko Dunic, I was able to build an array (data) structure that can be referenced to populate 3 select boxes. I didn't use the implementation code only because I didn't completely understand it...it works as posted. I will come back to this code later as I learn jQuery.
My code is posted below (obviously, your reference to jQuery may be different)
```
<html><head>
<script language="Javascript" src="javascript/jquery-1.2.6.min.js"></script>
<script type="text/JavaScript">
var cars = [
{ name: 'Honda', models: [
{ name: 'Accord', features: ['2dr', '4dr'] },
{ name: 'CRV', features: ['2dr', 'Hatchback'] },
{ name: 'Pilot', features: ['base', 'superDuper'] }
]},
{ name: 'Toyota', models: [
{ name: 'Prius', features: ['green', 'superGreen'] },
{ name: 'Camry', features: ['sporty', 'square'] },
{ name: 'Corolla', features: ['cheap', 'superFly'] }
]
}
];
$(function() {
var options = '' ;
for (var i = 0; i < cars.length; i++) {
var opt = cars[i].name ;
if (i == 0){ options += '<option selected value="' + opt + '">' + opt + '</option>'; }
else {options += '<option value="' + opt + '">' + opt + '</option>'; }
}
$("#maker").html(options); // populate select box with array
var options = '' ;
for (var i=0; i < cars[0].models.length; i++) {
var opt = cars[0].models[0].name ;
if (i==0){options += '<option selected value="' + opt + '">' + opt + '</option>';}
else {options += '<option value="' + opt + '">' + opt + '</option>';}
}
$("#model").html(options); // populate select box with array
var options = '' ;
for (var i=0; i < cars[0].models[0].features.length; i++) {
var opt = cars[0].models[0].features[i] ;
if (i==0){options += '<option selected value="' + opt + '">' + opt + '</option>';}
else {options += '<option value="' + opt + '">' + opt + '</option>';}
}
$("#feature").html(options); // populate select box with array
$("#maker").bind("click",
function() {
$("#model").children().remove() ; // clear select box
for(var i=0; i<cars.length; i++) {
if (cars[i].name == this.value) {
var options = '' ;
for (var j=0; j < cars[i].models.length; j++) {
var opt= cars[i].models[j].name ;
if (j==0) {options += '<option selected value="' + opt + '">' + opt + '</option>';}
else {options += '<option value="' + opt + '">' + opt + '</option>';}
}
break;
}
}
$("#model").html(options); // populate select box with array
$("#feature").children().remove() ; // clear select box
for(var i=0; i<cars.length; i++) {
for(var j=0; j<cars[i].models.length; j++) {
if(cars[i].models[j].name == $("#model").val()) {
var options = '' ;
for (var k=0; k < cars[i].models[j].features.length; k++) {
var opt = cars[i].models[j].features[k] ;
if (k==0){options += '<option selected value="' + opt + '">' + opt + '</option>';}
else {options += '<option value="' + opt + '">' + opt + '</option>';}
}
break;
}
}
}
$("#feature").html(options); // populate select box with array
});
$("#model").bind("click",
function() {
$("#feature").children().remove() ; // clear select box
for(var i=0; i<cars.length; i++) {
for(var j=0; j<cars[i].models.length; j++) {
if(cars[i].models[j].name == this.value) {
var options = '' ;
for (var k=0; k < cars[i].models[j].features.length; k++) {
var opt = cars[i].models[j].features[k] ;
if (k==0){options += '<option selected value="' + opt + '">' + opt + '</option>';}
else {options += '<option value="' + opt + '">' + opt + '</option>';}
}
break ;
}
}
}
$("#feature").html(options); // populate select box with array
});
});
</script>
</head> <body>
<div id="selection">
<select id="maker"size="10" style="{width=75px}"></select>
<select id="model" size="10" style="{width=75px}"></select>
<select id="feature" size="10"style="{width=75px}"></select>
</div></body></html>
```
|
Using javascript and jquery, to populate related select boxes with array structure
|
[
"",
"javascript",
"jquery",
""
] |
It's easy to get the value of a key from a .NET generic Dictionary:
```
Dictionary<int, string> greek = new Dictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
string secondGreek = greek[2]; // Beta
```
But trying to get the keys given a value is not as straightforward because there could be multiple keys:
```
int[] betaKeys = greek.WhatDoIPutHere("Beta"); // expecting single 2
```
|
Okay, here's the multiple bidirectional version:
```
using System;
using System.Collections.Generic;
using System.Text;
class BiDictionary<TFirst, TSecond>
{
IDictionary<TFirst, IList<TSecond>> firstToSecond = new Dictionary<TFirst, IList<TSecond>>();
IDictionary<TSecond, IList<TFirst>> secondToFirst = new Dictionary<TSecond, IList<TFirst>>();
private static IList<TFirst> EmptyFirstList = new TFirst[0];
private static IList<TSecond> EmptySecondList = new TSecond[0];
public void Add(TFirst first, TSecond second)
{
IList<TFirst> firsts;
IList<TSecond> seconds;
if (!firstToSecond.TryGetValue(first, out seconds))
{
seconds = new List<TSecond>();
firstToSecond[first] = seconds;
}
if (!secondToFirst.TryGetValue(second, out firsts))
{
firsts = new List<TFirst>();
secondToFirst[second] = firsts;
}
seconds.Add(second);
firsts.Add(first);
}
// Note potential ambiguity using indexers (e.g. mapping from int to int)
// Hence the methods as well...
public IList<TSecond> this[TFirst first]
{
get { return GetByFirst(first); }
}
public IList<TFirst> this[TSecond second]
{
get { return GetBySecond(second); }
}
public IList<TSecond> GetByFirst(TFirst first)
{
IList<TSecond> list;
if (!firstToSecond.TryGetValue(first, out list))
{
return EmptySecondList;
}
return new List<TSecond>(list); // Create a copy for sanity
}
public IList<TFirst> GetBySecond(TSecond second)
{
IList<TFirst> list;
if (!secondToFirst.TryGetValue(second, out list))
{
return EmptyFirstList;
}
return new List<TFirst>(list); // Create a copy for sanity
}
}
class Test
{
static void Main()
{
BiDictionary<int, string> greek = new BiDictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
greek.Add(5, "Beta");
ShowEntries(greek, "Alpha");
ShowEntries(greek, "Beta");
ShowEntries(greek, "Gamma");
}
static void ShowEntries(BiDictionary<int, string> dict, string key)
{
IList<int> values = dict[key];
StringBuilder builder = new StringBuilder();
foreach (int value in values)
{
if (builder.Length != 0)
{
builder.Append(", ");
}
builder.Append(value);
}
Console.WriteLine("{0}: [{1}]", key, builder);
}
}
```
|
As everyone else has said, there's no mapping within a dictionary from value to key.
**I've just noticed you wanted to map to from value to multiple keys - I'm leaving this solution here for the single value version, but I'll then add another answer for a multi-entry bidirectional map.**
The normal approach to take here is to have two dictionaries - one mapping one way and one the other. Encapsulate them in a separate class, and work out what you want to do when you have duplicate key or value (e.g. throw an exception, overwrite the existing entry, or ignore the new entry). Personally I'd probably go for throwing an exception - it makes the success behaviour easier to define. Something like this:
```
using System;
using System.Collections.Generic;
class BiDictionary<TFirst, TSecond>
{
IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();
public void Add(TFirst first, TSecond second)
{
if (firstToSecond.ContainsKey(first) ||
secondToFirst.ContainsKey(second))
{
throw new ArgumentException("Duplicate first or second");
}
firstToSecond.Add(first, second);
secondToFirst.Add(second, first);
}
public bool TryGetByFirst(TFirst first, out TSecond second)
{
return firstToSecond.TryGetValue(first, out second);
}
public bool TryGetBySecond(TSecond second, out TFirst first)
{
return secondToFirst.TryGetValue(second, out first);
}
}
class Test
{
static void Main()
{
BiDictionary<int, string> greek = new BiDictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
int x;
greek.TryGetBySecond("Beta", out x);
Console.WriteLine(x);
}
}
```
|
Getting multiple keys of specified value of a generic Dictionary?
|
[
"",
"c#",
".net",
""
] |
```
"foo" instanceof String //=> false
"foo" instanceof Object //=> false
true instanceof Boolean //=> false
true instanceof Object //=> false
false instanceof Boolean //=> false
false instanceof Object //=> false
12.21 instanceof Number //=> false
/foo/ instanceof RegExp //=> true
// the tests against Object really don't make sense
```
Array literals and Object literals match...
```
[0,1] instanceof Array //=> true
{0:1} instanceof Object //=> true
```
Why don't all of them? Or, why don't they all *not*?
And, what are they an instance of, then?
It's the same in FF3, IE7, Opera, and Chrome. So, at least it's consistent.
|
Primitives are a different kind of type than objects created from within Javascript. From the [Mozilla API docs](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/instanceof_Operator):
```
var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral";
color2 instanceof String; // returns false (color2 is not a String object)
```
I can't find any way to construct primitive types with code, perhaps it's not possible. This is probably why people use `typeof "foo" === "string"` instead of `instanceof`.
An easy way to remember things like this is asking yourself "I wonder what would be sane and easy to learn"? Whatever the answer is, Javascript does the other thing.
|
I use:
```
function isString(s) {
return typeof(s) === 'string' || s instanceof String;
}
```
Because in JavaScript strings can be literals or objects.
|
Why does instanceof return false for some literals?
|
[
"",
"javascript",
"literals",
"instanceof",
""
] |
Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/\*nix/Mac)?
|
# C++11
```
#include <thread>
//may return 0 when not able to detect
const auto processor_count = std::thread::hardware_concurrency();
```
Reference: [std::thread::hardware\_concurrency](http://en.cppreference.com/w/cpp/thread/thread/hardware_concurrency)
---
In C++ prior to C++11, there's no portable way. Instead, you'll need to use one or more of the following methods (guarded by appropriate `#ifdef` lines):
* ### Win32
```
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
int numCPU = sysinfo.dwNumberOfProcessors;
```
* ### Linux, Solaris, AIX and Mac OS X >=10.4 (i.e. Tiger onwards)
```
int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
```
* ### FreeBSD, MacOS X, NetBSD, OpenBSD, etc.
```
int mib[4];
int numCPU;
std::size_t len = sizeof(numCPU);
/* set the mib for hw.ncpu */
mib[0] = CTL_HW;
mib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU;
/* get the number of CPUs from the system */
sysctl(mib, 2, &numCPU, &len, NULL, 0);
if (numCPU < 1)
{
mib[1] = HW_NCPU;
sysctl(mib, 2, &numCPU, &len, NULL, 0);
if (numCPU < 1)
numCPU = 1;
}
```
* ### HPUX
```
int numCPU = mpctl(MPC_GETNUMSPUS, NULL, NULL);
```
* ### IRIX
```
int numCPU = sysconf(_SC_NPROC_ONLN);
```
* ### Objective-C (Mac OS X >=10.5 or iOS)
```
NSUInteger a = [[NSProcessInfo processInfo] processorCount];
NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount];
```
|
This functionality is part of the C++11 standard.
```
#include <thread>
unsigned int nthreads = std::thread::hardware_concurrency();
```
For older compilers, you can use the [Boost.Thread](http://www.boost.org/doc/libs/1_46_0/doc/html/thread.html) library.
```
#include <boost/thread.hpp>
unsigned int nthreads = boost::thread::hardware_concurrency();
```
In either case, `hardware_concurrency()` returns the number of threads that the hardware is capable of executing concurrently based on the number of CPU cores and hyper-threading units.
|
Programmatically find the number of cores on a machine
|
[
"",
"c++",
"c",
"multithreading",
"multiplatform",
""
] |
I'm trying to make a page in php that takes rows from a database, displays them, and then give the viewer a chance to upvote or downvote a specific entry. Here is a snippet:
```
echo("<form action=\"vote.php\" method=\"post\"> \n");
echo("<INPUT type=\"hidden\" name=\"idnum\" value=\"".$row[0]."\">");
echo("<INPUT type=\"submit\" name=\"up\" value=\"Upvote.\"> \n");
echo("<INPUT type=\"submit\" name=\"down\" value=\"Downvote\"> ");
echo("<form/>\n");
```
The problem is when I hit a submit button, the value for idnum that gets sent is based on the one farthest down it seems. So my questions is, when a submit button is pressed, are the values for all inputs on a page sent?
|
Your form tag isn't closed properly. You have `<form/>`, but it should be `</form>`.
This makes the entire page a form so it sends all the inputs. With a form that is closed properly though, it will only send the inputs within the form tags that the pressed button was in.
|
While this wouldn't have helped with this particular issue, I would recommend not mixing your markup with your logic wherever possible. This is quite a lot more readable, and quite a lot more editable as well:
```
<form action="vote.php" method="post">
<input type="hidden" name="idnum" value="<?php echo $row[0]; ?>">
<input type="submit" name="up" value="Upvote.">
<input type="submit" name="down" value="Downvote">
</form>
```
|
Are inputs in separate forms sent when a submit button is hit?
|
[
"",
"php",
"html",
""
] |
There are a couple of questions similar to this on stack overflow but not quite the same.
I want to open, or create, a local group on a win xp computer and add members to it, domain, local and well known accounts. I also want to check whether a user is already a member so that I don't add the same account twice, and presumably get an exception.
So far I started using the DirectoryEntry object with the `WinNT://` provider. This is going ok but I'm stuck on how to get a list of members of a group?
Anyone know how to do this? Or provide a better solution than using DirectoryEntry?
|
Okay, it's taken a while, messing around with different solutions but the one that fits best with my original question is given below. I can't get the DirectoryEntry object to access the members of a local group using the 'standard' methods, the only way I could get it to enumerate the members was by using the Invoke method to call the native objects Members method.
```
using(DirectoryEntry groupEntry = new DirectoryEntry("WinNT://./Administrators,group"))
{
foreach(object member in (IEnumerable) groupEntry.Invoke("Members"))
{
using(DirectoryEntry memberEntry = new DirectoryEntry(member))
{
Console.WriteLine(memberEntry.Path);
}
}
}
```
I also used a similar technique to add and remove members from the local group.
Hopefully this helps someone else as well.
Keith.
**EDIT** by Tim: added VB.Net version
```
Public Function MembersOfGroup(ByVal GroupName As String) As List(Of DirectoryEntry)
Dim members As New List(Of DirectoryEntry)
Try
Using search As New DirectoryEntry("WinNT://./" & GroupName & ",group")
For Each member As Object In DirectCast(search.Invoke("Members"), IEnumerable)
Dim memberEntry As New DirectoryEntry(member)
members.Add(memberEntry)
Next
End Using
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Return members
End Function
```
|
Microsoft .NET Framework provides a standard library for working with Active Directory: **[System.DirectoryServices namespace](http://msdn.microsoft.com/en-us/library/ms682458(VS.85).aspx)** in the System.DirectoryServices.dll.
Microsoft recommends using two main classes from the System.DirectoryServices namespace: **DirectoryEntry** and **DirectorySearcher**. In most cases, it is enough to use DirectorySearcher class only.
> *UPDATE: I tested it on my machine - it works. But maybe I've misunderstood
> your question.*
Here is an example from an excellent [CodeProject article](http://www.codeproject.com/KB/system/QueryADwithDotNet.aspx):
## Get a list of users belonging to a particular AD group
```
using System.DirectoryServices;
ArrayList GetADGroupUsers(string groupName)
{
SearchResult result;
DirectorySearcher search = new DirectorySearcher();
search.Filter = String.Format("(cn={0})", groupName);
search.PropertiesToLoad.Add("member");
result = search.FindOne();
ArrayList userNames = new ArrayList();
if (result != null)
{
for (int counter = 0; counter <
result.Properties["member"].Count; counter++)
{
string user = (string)result.Properties["member"][counter];
userNames.Add(user);
}
}
return userNames;
}
```
|
Get a list of members of a WinNT group
|
[
"",
"c#",
".net",
"active-directory",
"active-directory-group",
"windows-security",
""
] |
I am writing a program in Python that will act as a server and accept data from a client, is it a good idea to impose a hard limit as to the amount of data, if so why?
More info:
So certain chat programs limit the amount of text one can send per send (i.e. per time user presses send) so the question comes down to is there a legit reason for this and if yes, what is it?
|
Most likely you've seen code which protects against "extra" incoming data. This is often due to the possibility of buffer overruns, where the extra data being copied into memory overruns the pre-allocated array and overwrites executable code with attacker code. Code written in languages like C typically has a lot of length checking to prevent this type of attack. Functions such as gets, and strcpy are replaced with their safer counterparts like fgets and strncpy which have a length argument to prevent buffer overruns.
If you use a dynamic language like Python, your arrays resize so they won't overflow and clobber other memory, but you still have to be careful about sanitizing foreign data.
Chat programs likely limit the size of a message for reasons such as database field size. If 80% of your incoming messages are 40 characters or less, 90% are 60 characters or less, and 98% are 80 characters or less, why make your message text field allow 10k characters per message?
|
What is your question exactly?
What happens when you do receive on a socket is that the current available data in the socket buffer is immediately returned. If you give receive (or read, I guess), a huge buffer size, such as 40000, it'll likely never return that much data at once. If you give it a tiny buffer size like 100, then it'll return the 100 bytes it has immediately and still have more available. Either way, you're not imposing a limit on how much data the client is sending you.
|
Receive socket size limits good?
|
[
"",
"python",
"sockets",
""
] |
I'm pretty sure one would do this using the os.plock(op) function, but I have no idea how. Also, if there's a better way, I'd be grateful to find out. Code snippets are very welcome.
|
[Subprocess](http://docs.python.org/library/subprocess) replaces os.popen, os.system, os.spawn, popen2 and commands. A [simple example for piping](http://docs.python.org/library/subprocess#replacing-shell-pipe-line) would be:
```
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
```
You could also use a [memory mapped file](http://docs.python.org/library/mmap.html) with the flag=MAP\_SHARED for shared memory between processes.
[multiprocessing](http://docs.python.org/library/multiprocessing.html) abstracts both [pipes](http://docs.python.org/library/multiprocessing.html#exchanging-objects-between-processes) and [shared memory](http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes) and provides a higher level interface. Taken from the Processing documentation:
```
from multiprocessing import Process, Pipe
def f(conn):
conn.send([42, None, 'hello'])
conn.close()
if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
p.start()
print parent_conn.recv() # prints "[42, None, 'hello']"
p.join()
```
|
Take a look at the [multiprocessing](http://docs.python.org/dev/library/multiprocessing.html) module new in python 2.6 (also available for earlier versions a [pyprocessing](http://pyprocessing.berlios.de/)
Here's an example from the docs illustrating passing information using a pipe for instance:
```
from multiprocessing import Process, Pipe
def f(conn):
conn.send([42, None, 'hello'])
conn.close()
if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
p.start()
print parent_conn.recv() # prints "[42, None, 'hello']"
p.join()
```
|
How do you share data between a parent and forked child process in Python?
|
[
"",
"python",
"fork",
"share",
""
] |
I would like to know if it is possible to determine if a function parameter with a default value was passed in Python.
For example, how does dict.pop work?
```
>>> {}.pop('test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'pop(): dictionary is empty'
>>> {}.pop('test',None)
>>> {}.pop('test',3)
3
>>> {}.pop('test',NotImplemented)
NotImplemented
```
How does the pop method determine that the first time a default return value was not passed? Is this something that can only be done in C?
Thanks
|
I guess you mean "keyword argument", when you say "named parameter". `dict.pop()` does not accept keyword argument, so this part of the question is moot.
```
>>> {}.pop('test', d=None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: pop() takes no keyword arguments
```
That said, the way to detect whether an argument was provided is to use the `*args` or `**kwargs` syntax. For example:
```
def foo(first, *rest):
if len(rest) > 1:
raise TypeError("foo() expected at most 2 arguments, got %d"
% (len(rest) + 1))
print 'first =', first
if rest:
print 'second =', rest[0]
```
With some work, and using the `**kwargs` syntax too it is possible to completely emulate the python calling convention, where arguments can be either provided by position or by name, and arguments provided multiple times (by position and name) cause an error.
|
The convention is often to use `arg=None` and use
```
def foo(arg=None):
if arg is None:
arg = "default value"
# other stuff
# ...
```
to check if it was passed or not. Allowing the user to pass `None`, which would be interpreted as if the argument was *not* passed.
|
Determine if a named parameter was passed
|
[
"",
"python",
"default-value",
"named-parameters",
""
] |
I continually get these errors when I try to update tables based on another table. I end up rewriting the query, change the order of joins, change some groupings and then it eventually works, but I just don't quite get it.
What is a 'multi-part identifier'?
When is a 'multi-part identifier' not able to be bound?
What is it being bound to anyway?
In what cases will this error occur?
What are the best ways to prevent it?
The specific error from SQL Server 2005 is:
> The multi-part identifier "..." could not be bound.
Here is an example:
```
SELECT * FROM [MainDB].[dbo].[Company]
WHERE [MainDB].[dbo].[Company].[CompanyName] = 'StackOverflow'
```
The actual error:
> Msg 4104, Level 16, State 1, Line 2 The multi-part identifier
> "MainDB.dbo.Company.CompanyName" could not be bound.
|
A multipart identifier is any description of a field or table that contains multiple parts - for instance MyTable.SomeRow - if it can't be bound that means there's something wrong with it - either you've got a simple typo, or a confusion between table and column. It can also be caused by using reserved words in your table or field names and not surrounding them with [].
It can also be caused by not including all of the required columns in the target table.
Something like [redgate sql prompt](http://www.red-gate.com/products/SQL_Prompt/index.htm) is brilliant for avoiding having to manually type these (it even auto-completes joins based on foreign keys), but isn't free. SQL server 2008 supports intellisense out of the box, although it isn't quite as complete as the redgate version.
|
Actually sometimes when you are updating one table from another table's data, I think one of the common issues that cause this error, is when you use your table abbreviations incorrectly *or when they are not needed*. The correct statement is below:
```
Update Table1
Set SomeField = t2.SomeFieldValue
From Table1 t1
Inner Join Table2 as t2
On t1.ID = t2.ID
```
Notice that **`SomeField`** column from **Table1** doesn't have the `t1` qualifier as **`t1.SomeField`** but is just `SomeField`.
If one tries to update it by specifying **`t1.SomeField`** the statement will return the multi-part error that you have noticed.
|
What is a 'multi-part identifier' and why can't it be bound?
|
[
"",
"sql",
"sql-server",
""
] |
We have a C# service that is deployed to a remote customer system. The application writes a substantial amount of "diagnostic" information to the console (i.e. Console.WriteLine()). The service isn't "doing what it should." How can we capture the console output from the service in another application?
A WinForm version the application can be loaded at the customer location. It, unfortunately, functions correctly.
Update:
We are able to change the change the service, but would prefer not to make major changes at this time.
We are also logging to MSMQ, but only for "important" events. This service does interact with MSMQ for its normal operations. Or, at least, it should. The service doesn't seem to be pulling items from MSMQ when the WinForm version does. So, writing the messages that are going to the console could be problematic.
|
Are you able to change the service code *at all*? If so, using Console.SetOut to write to a file instead would be the most obvious first port of call. Then change to using a proper logging library for the next release :)
|
In general, you should avoid writing diagnostic information directly to Console, the Event Log, MSMQ or elsewhere from your application code. Instead call a logging API, and use configuration to redirect the output wherever you want.
For example, you could replace all the Console.WriteLine by Trace.WriteLine (\*). Then you can redirect output to the console, a file or elsewhere by modifying the application configuration file: for example to output to the console, use a ConsoleTraceListener, something like:
```
<configuration>
<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<add name="configConsoleListener"
type="System.Diagnostics.ConsoleTraceListener" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
```
While debugging, you'll get your output on the console - on the customer site you'd configure it to redirect the trace output to a file, to the event log or similar.
Even better, use a 3rd party logging framework (I'd recommend Log4Net) which will give you more options than System.Diagnostics.Trace.
(\*) Trace.Write/Trace.WriteLine are the same as Debug.Write/Debug.WriteLine, except that the latter are only compiled if the DEBUG symbol is defined. So prefer Trace to Debug if you want the output to be available in Release builds.
|
How to capture console output from a service C#?
|
[
"",
"c#",
"service",
"console",
""
] |
I have a c# form (let's call it MainForm) with a number of custom controls on it. I'd like to have the MainForm.OnClick() method fire anytime someone clicks on the form regardless of whether the click happened on the form or if the click was on one of the custom controls. I'm looking for behavior similar to the KeyPreview feature of forms except for mouse clicks rather than key presses.
|
In the form's ControlAdded event, add a MouseClick handler to the control, with the Address of the form's click event. I haven't tested this, but it might work.
```
Private Sub Example_ControlAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.ControlEventArgs) Handles Me.ControlAdded
AddHandler e.Control.MouseClick, AddressOf Example_MouseClick
End Sub
Private Sub Example_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseClick
MessageBox.Show("Click")
End Sub
```
|
I recommend creating a base form for the other forms in your application to inherit. Add this code to your base form to create a new event called GlobalMouseClickEventHandler:
```
namespace Temp
{
public delegate void GlobalMouseClickEventHander(object sender, MouseEventArgs e);
public partial class TestForm : Form
{
[Category("Action")]
[Description("Fires when any control on the form is clicked.")]
public event GlobalMouseClickEventHander GlobalMouseClick;
public TestForm()
{
InitializeComponent();
BindControlMouseClicks(this);
}
private void BindControlMouseClicks(Control con)
{
con.MouseClick += delegate(object sender, MouseEventArgs e)
{
TriggerMouseClicked(sender, e);
};
// bind to controls already added
foreach (Control i in con.Controls)
{
BindControlMouseClicks(i);
}
// bind to controls added in the future
con.ControlAdded += delegate(object sender, ControlEventArgs e)
{
BindControlMouseClicks(e.Control);
};
}
private void TriggerMouseClicked(object sender, MouseEventArgs e)
{
if (GlobalMouseClick != null)
{
GlobalMouseClick(sender, e);
}
}
}
}
```
This solution will work not only for top-level controls, but also nested controls such as controls placed inside of panels.
|
How do I set a click event for a form?
|
[
"",
"c#",
"winforms",
""
] |
What is the best method for applying drop shadows? I'm working on a site right now where we have a good deal of them, however, I've been fighting to find the best method to do it. The site is pretty animation heavy so shadows need to work well with this.
I tried a jQuery shadow pulgin. The shadows looked good and were easy to use but were slow and didn't work well with any animations (required lots of redrawing, very joggy).
I also tried creating my own jQuery extension that wraps my element in a couple gray divs and then offsets them a little bit to give a shadow effect. This worked well. It's quick and responsive to the animation. However, it makes DOM manipulation/traversal cumbersome since everything is wrapped in these shadow divs.
I know there has to be a better way but this isn't exactly my forte. Thoughts?
|
[ShadedBorder](http://www.ruzee.com/blog/shadedborder/) is a good looking and easy to use Shadow-Library. check it out
|
You don't need to wrap those shadow-divs around the other content, just set them a little askew and place them on a lower z-index !-)
|
What's the best way to apply a drop shadow?
|
[
"",
"javascript",
"jquery",
"css",
"animation",
"user-interface",
""
] |
How do you change the CLASSPATH of a Java process from within the Java process?
---
Before you ask me "Why would you want to do that?" I'll explain it shortly.
> When you have a Clojure REPL running it is common to need more jars in your CLASSPATH to load a [Clojure](http://clojure.org) source file, and I'd like to do it without having to restart Clojure itself (which is not really an option when using it on Slime on Emacs).
That's the reason but I don't want this question tagged as some-weird-language some-weird-editor and be disregarded by the majority of Java developers that may have the answer.
|
Update 2023: as [commented](https://stackoverflow.com/questions/252893/how-do-you-change-the-classpath-within-java#comment135692001_252967) below by [Holger](https://stackoverflow.com/users/2711488/holger)
> The only way to add jar files to the class path working in Java 9 and newer, is through the [Instrumentation API](https://docs.oracle.com/en/java/javase/20/docs/api/java.instrument/java/lang/instrument/Instrumentation.html#appendToSystemClassLoaderSearch(java.util.jar.JarFile)), but it requires a Java Agent.
>
> If you are in control of the launcher/main jar, you can use the [`Launcher-Agent-Class` attribute in the jar file’s manifest](https://docs.oracle.com/en/java/javase/20/docs/api/java.instrument/java/lang/instrument/package-summary.html#manifest-attributes-heading) to start an embedded Agent.
---
Update Q4 2017: as [commented](https://stackoverflow.com/questions/252893/how-do-you-change-the-classpath-within-java/252967#comment82290481_252967) below by [vda8888](https://stackoverflow.com/users/1974520/vda8888), in Java 9, the System [`java.lang.ClassLoader`](https://docs.oracle.com/javase/9/docs/api/java/lang/ClassLoader.html) is no longer a [`java.net.URLClassLoader`](https://docs.oracle.com/javase/9/docs/api/java/net/URLClassLoader.html).
See "[Java 9 Migration Guide: The Seven Most Common Challenges](https://blog.codefx.org/java/java-9-migration-guide/)"
> The class loading strategy that I just described is implemented in a new type and in Java 9 the application class loader is of that type.
> That means it is not a `URLClassLoader` anymore, so the occasional `(URLClassLoader) getClass().getClassLoader()` or `(URLClassLoader) ClassLoader.getSystemClassLoader()` sequences will no longer execute.
[java.lang.ModuleLayer](https://docs.oracle.com/javase/9/docs/api/java/lang/ModuleLayer.html) would be an alternative approach used in order to influence the *modulepath* (instead of the classpath). See for instance "[Java 9 modules - JPMS basics](http://blog.joda.org/2017/04/java-9-modules-jpms-basics.html)".
---
For Java 8 or below:
Some general comments:
you cannot (in a portable way that's guaranteed to work, see below) change the system classpath. Instead, you need to define a new ClassLoader.
ClassLoaders work in a hierarchical manner... so any class that makes a static reference to class X needs to be loaded in the same ClassLoader as X, or in a child ClassLoader. You can NOT use any custom ClassLoader to make code loaded by the system ClassLoader link properly, if it wouldn't have done so before. So you need to arrange for your main application code to be run in the custom ClassLoader in addition to the extra code that you locate.
(That being said, [cracked-all](https://stackoverflow.com/users/188524/cracked-all) mentions in the comments this example of [extending the `URLClassLoader`](http://snippets.dzone.com/posts/show/3574))
And you might consider not writing your own ClassLoader, but just use URLClassLoader instead. Create a URLClassLoader with a url that are *not* in the parent classloaders url's.
```
URL[] url={new URL("file://foo")};
URLClassLoader loader = new URLClassLoader(url);
```
A [more complete solution](http://robertmaldon.blogspot.com/2007/11/dynamically-add-to-eclipse-junit.html) would be:
```
ClassLoader currentThreadClassLoader
= Thread.currentThread().getContextClassLoader();
// Add the conf dir to the classpath
// Chain the current thread classloader
URLClassLoader urlClassLoader
= new URLClassLoader(new URL[]{new File("mtFile").toURL()},
currentThreadClassLoader);
// Replace the thread classloader - assumes
// you have permissions to do so
Thread.currentThread().setContextClassLoader(urlClassLoader);
```
If you assume the JVMs system classloader is a URLClassLoader (which may not be true for all JVMs), you can use reflection as well to actually modify the system classpath... (but that's a hack;)):
```
public void addURL(URL url) throws Exception {
URLClassLoader classLoader
= (URLClassLoader) ClassLoader.getSystemClassLoader();
Class clazz= URLClassLoader.class;
// Use reflection
Method method= clazz.getDeclaredMethod("addURL", new Class[] { URL.class });
method.setAccessible(true);
method.invoke(classLoader, new Object[] { url });
}
addURL(new File("conf").toURL());
// This should work now!
Thread.currentThread().getContextClassLoader().getResourceAsStream("context.xml");
```
|
I don't believe you can - the right thing to do (I believe) is create a new classloader with the new path. Alternatively, you could write your own classloader which allows you to change the classpath (for that loader) dynamically.
|
How do you change the CLASSPATH within Java?
|
[
"",
"java",
"clojure",
"classpath",
""
] |
I have the following intentionally trivial function:
```
void ReplaceSome(ref string text)
{
StringBuilder sb = new StringBuilder(text);
sb[5] = 'a';
text = sb.ToString();
}
```
It appears to be inefficient to convert this to a StringBuilder to index into and replace some of the characters only to copy it back to the ref'd param. Is it possible to index directly into the text param as an L-Value?
Or how else can I improve this?
|
C# strings are "immutable," which means that they can't be modified. If you have a string, and you want a similar but different string, you must create a new string. Using a StringBuilder as you do above is probably as easy a method as any.
|
Armed with Reflector and the decompiled IL - On a pure LOC basis then the StringBuilder approach is definitely the most efficient. Eg tracing the IL calls that StringBuilder makes internally vs the IL calls for String::Remove and String::Insert etc.
I couldn't be bothered testing the memory overhead of each approach, but would imagine it would be in line with reflector results - the StringBuilder approach would be the best.
I think the fact the StringBuilder has a set memory size using the constructor
```
StringBuilder sb = new StringBuilder(text);
```
would help overall too.
Like others have mentioned, it would come down to readability vs efficiency...
|
Indexing into a String in C# as an L-Value
|
[
"",
"c#",
".net",
""
] |
Is there any way I can detect when my page has been set as the user's homepage in their browser?
I'm most interested in something in javascript, but I'd be happy to hear about other approaches as well.
**Edit**: I'm not looking for anything sneaky. I'm wondering if there is anything that is explicitly allowed through the browsers to find out this information.
|
Mozilla/Firefox has a [`window.home()`](https://developer.mozilla.org/En/DOM/Window.home) method which loads the user's home page. This method could be used (in an iframe, maybe) combined with server access logging, to see if the site's home page is instantly requested loaded by the current user.
However, other browsers don't seem to support this javascript method.
|
There isn't likely to be a foolproof method, as that's an intrusion into the privacy of the user.
One thing that comes to mind is checking for a referrer. If the user arrived at your page without following a link, they a) typed the url, b) followed a bookmark, or c) have your page set as their homepage. But that's about the best I can do.
|
How can I tell if my page is set as the user's homepage?
|
[
"",
"javascript",
""
] |
What's a simple/easy way to access the system clock using Java, so that I can calculate the elapsed time of an event?
|
I would avoid using [`System.currentTimeMillis()`](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#currentTimeMillis--) for measuring elapsed time. [`currentTimeMillis()`](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#currentTimeMillis--) returns the 'wall-clock' time, which may change (eg: daylight savings, admin user changing the clock) and skew your interval measurements.
[`System.nanoTime()`](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#nanoTime--), on the other hand, returns the number of nanoseconds since 'some reference point' (eg, JVM start up), and would therefore not be susceptible to system clock changes.
|
This is some sample code.
```
long startTime = System.currentTimeMillis();
// Run some code;
long stopTime = System.currentTimeMillis();
System.out.println("Elapsed time was " + (stopTime - startTime) + " miliseconds.");
```
|
How do I calculate the elapsed time of an event in Java?
|
[
"",
"java",
"time",
"timer",
"clock",
""
] |
I've seen some examples of C++ using template template parameters (that is templates which take templates as parameters) to do policy-based class design. What other uses does this technique have?
|
I think you need to use template template syntax to pass a parameter whose type is a template dependent on another template like this:
```
template <template<class> class H, class S>
void f(const H<S> &value) {
}
```
Here, `H` is a template, but I wanted this function to deal with all specializations of `H`.
**NOTE**: I've been programming c++ for many years and have only needed this once. I find that it is a rarely needed feature (of course handy when you need it!).
I've been trying to think of good examples, and to be honest, most of the time this isn't necessary, but let's contrive an example. Let's pretend that `std::vector` *doesn't* have a `typedef value_type`.
So how would you write a function which can create variables of the right type for the vectors elements? This would work.
```
template <template<class, class> class V, class T, class A>
void f(V<T, A> &v) {
// This can be "typename V<T, A>::value_type",
// but we are pretending we don't have it
T temp = v.back();
v.pop_back();
// Do some work on temp
std::cout << temp << std::endl;
}
```
**NOTE**: `std::vector` has two template parameters, type, and allocator, so we had to accept both of them. Fortunately, because of type deduction, we won't need to write out the exact type explicitly.
which you can use like this:
```
f<std::vector, int>(v); // v is of type std::vector<int> using any allocator
```
or better yet, we can just use:
```
f(v); // everything is deduced, f can deal with a vector of any type!
```
**UPDATE**: Even this contrived example, while illustrative, is no longer an amazing example due to c++11 introducing `auto`. Now the same function can be written as:
```
template <class Cont>
void f(Cont &v) {
auto temp = v.back();
v.pop_back();
// Do some work on temp
std::cout << temp << std::endl;
}
```
which is how I'd prefer to write this type of code.
|
Actually, usecase for template template parameters is rather obvious. Once you learn that C++ stdlib has gaping hole of not defining stream output operators for standard container types, you would proceed to write something like:
```
template<typename T>
static inline std::ostream& operator<<(std::ostream& out, std::list<T> const& v)
{
out << '[';
if (!v.empty()) {
for (typename std::list<T>::const_iterator i = v.begin(); ;) {
out << *i;
if (++i == v.end())
break;
out << ", ";
}
}
out << ']';
return out;
}
```
Then you'd figure out that code for vector is just the same, for forward\_list is the same, actually, even for multitude of map types it's still just the same. Those template classes don't have anything in common except for meta-interface/protocol, and using template template parameter allows to capture the commonality in all of them. Before proceeding to write a template though, it's worth to check a reference to recall that sequence containers accept 2 template arguments - for value type and allocator. While allocator is defaulted, we still should account for its existence in our template operator<<:
```
template<template <typename, typename> class Container, class V, class A>
std::ostream& operator<<(std::ostream& out, Container<V, A> const& v)
...
```
Voila, that will work automagically for all present and future sequence containers adhering to the standard protocol. To add maps to the mix, it would take a peek at reference to note that they accept 4 template params, so we'd need another version of the operator<< above with 4-arg template template param. We'd also see that std:pair tries to be rendered with 2-arg operator<< for sequence types we defined previously, so we would provide a specialization just for std::pair.
Btw, with C+11 which allows variadic templates (and thus should allow variadic template template args), it would be possible to have single operator<< to rule them all. For example:
```
#include <iostream>
#include <vector>
#include <deque>
#include <list>
template<typename T, template<class,class...> class C, class... Args>
std::ostream& operator <<(std::ostream& os, const C<T,Args...>& objs)
{
os << __PRETTY_FUNCTION__ << '\n';
for (auto const& obj : objs)
os << obj << ' ';
return os;
}
int main()
{
std::vector<float> vf { 1.1, 2.2, 3.3, 4.4 };
std::cout << vf << '\n';
std::list<char> lc { 'a', 'b', 'c', 'd' };
std::cout << lc << '\n';
std::deque<int> di { 1, 2, 3, 4 };
std::cout << di << '\n';
return 0;
}
```
**Output**
```
std::ostream &operator<<(std::ostream &, const C<T, Args...> &) [T = float, C = vector, Args = <std::__1::allocator<float>>]
1.1 2.2 3.3 4.4
std::ostream &operator<<(std::ostream &, const C<T, Args...> &) [T = char, C = list, Args = <std::__1::allocator<char>>]
a b c d
std::ostream &operator<<(std::ostream &, const C<T, Args...> &) [T = int, C = deque, Args = <std::__1::allocator<int>>]
1 2 3 4
```
|
What are some uses of template template parameters?
|
[
"",
"c++",
"templates",
"template-templates",
""
] |
If I have the following string:
```
string s = "abcdefghab";
```
Then how do I get a string (or char[]) that has just the characters that are repeated in the original string using C# and LINQ. In my example I want to end up with "ab".
Although not necessary, I was trying to do this in a single line of LINQ and had so far come up with:
```
s.ToCharArray().OrderBy(a => a)...
```
|
```
String text = "dssdfsfadafdsaf";
var repeatedChars = text.ToCharArray().GroupBy(x => x).Where(y => y.Count() > 1).Select(z=>z.Key);
```
|
```
string theString = "abcdefghab";
//C# query syntax
var qry = (from c in theString.ToCharArray()
group c by c into g
where g.Count() > 1
select g.Key);
//C# pure methods syntax
var qry2 = theString.ToCharArray()
.GroupBy(c => c)
.Where(g => g.Count() > 1)
.Select(g => g.Key);
```
|
How do I get an array of repeated characters from a string using LINQ?
|
[
"",
"c#",
"linq",
"algorithm",
""
] |
I have Virtual PC 2007. I am writing a C# program that will run on the Host and Virtual. It needs to communicate both ways.
**What is the best way to do this?**
**Can it be done in a way that does not require changing Virtual settings?**
(the OSs will be XP, Vista, Server 2000 / 2003)
|
[WCF](http://msdn.microsoft.com/en-us/netframework/aa663324.aspx). .NET Remoting without the calls to the suicide prevention hotline.
|
Via TCP. Simple client/server setup.
or
[.NET Remoting](http://msdn.microsoft.com/en-us/library/ms973864.aspx)
|
What is the best way for a process inside a VirtualPc to talk to a process on the host?
|
[
"",
"c#",
"virtual-pc",
""
] |
*[This question is related to but not the same as [this one](https://stackoverflow.com/questions/206106/is-a-safe-way-to-convert-to-bool-in-c).]*
My compiler warns about implicitly converting or casting certain types to bool whereas explicit conversions do not produce a warning:
```
long t = 0;
bool b = false;
b = t; // performance warning: forcing long to bool
b = (bool)t; // performance warning
b = bool(t); // performance warning
b = static_cast<bool>(t); // performance warning
b = t ? true : false; // ok, no warning
b = t != 0; // ok
b = !!t; // ok
```
This is with Visual C++ 2008 but I suspect other compilers may have similar warnings.
So my question is: what is the performance implication of casting/converting to `bool`? Does explicit conversion have better performance in some circumstance (e.g., for certain target architectures or processors)? Does implicit conversion somehow confuse the optimizer?
Microsoft's [explanation](http://msdn.microsoft.com/en-us/library/b6801kcy.aspx) of their warning is not particularly helpful. They imply that there is a good reason but they don't explain it.
|
I was puzzled by this behaviour, until I found this link:
<http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99633>
Apparently, coming from the Microsoft Developer who "owns" this warning:
> *This warning is surprisingly
> helpful, and found a bug in my code
> just yesterday. I think Martin is
> taking "performance warning" out of
> context.*
>
> **It's not about the generated code,
> it's about whether or not the
> programmer has signalled an intent to
> change a value from int to bool**.
> There is a penalty for that, and the
> user has the choice to use "int"
> instead of "bool" consistently (or
> more likely vice versa) to avoid the
> "boolifying" codegen. [...]
>
> **It is an old warning, and may have
> outlived its purpose, but it's
> behaving as designed here.**
So it seems to me the warning is more about style and avoiding some mistakes than anything else.
Hope this will answer your question...
:-p
|
The performance is identical across the board. It involves a couple of instructions on x86, maybe 3 on some other architectures.
On x86 / VC++, they all do
```
cmp DWORD PTR [whatever], 0
setne al
```
GCC generates the same thing, but without the warnings (at any warning-level).
|
What is the performance implication of converting to bool in C++?
|
[
"",
"c++",
"visual-c++",
""
] |
I have a query that has a list of base values and a list of language values. Each value has a key that matches to the other. The base values are stored in one table and the language values in another. My problem is that I need to get all matching base values removed from the QUERY except for one. Then, I export that query into an Excel spreadsheet (I can do this portion fine) and allow the user to edit the language values.
When the user edits and/or inserts new language values, I need to update the database except now writing over any matching values in the database (like those that were removed the first time).
In simplicity, the client pays for translations and if I can generate a sheet that has fewer translations needed (like phrases that reappear often) then they can save money, hence the project to begin with. I realize the downside is that it is not a true linked list, where all matching values all belong to one row in the language table (which would have been easy). Instead, there are multiple values that are identical that need to be updated as described above.
---
Yeah, I'm confused on it which is why it might seem a little vague. Here's a sample:
```
Table 1
Item Description1
Item Description2
Item Description3
Item Description2
Item Description2
Item Description4
Item Description5
Item Description6
Item Description3
Table 2
Item Desc in other Language1
Item Desc in other Language2
Item Desc in other Language3 (blank)
Item Desc in other Language3
Item Desc in other Language4
Item Desc in other Language5
*blank*
```
Desired Result (when queried)
Table 1
Item Description1
Item Description2
Item Description3
Item Description4
Item Description5
Item Description6
```
Table 2
Item Desc in other Language1
Item Desc in other Language2
Item Desc in other Language3 (filled by matching row in Table 2)
Item Desc in other Language4
Item Desc in other Language5
Item Desc in other Language6 (blank, returned as empty string)
```
The user makes their modifications, including inserting data into blank rows (like row 6 for the language) then reuploads:
```
Table 1
Item Description1
Item Description2
Item Description3
Item Description2
Item Description2
Item Description4
Item Description5
Item Description6
Item Description3
Table 2
Item Desc in other Language1
Item Desc in other Language2
Item Desc in other Language3 (now matches row below)
Item Desc in other Language3
Item Desc in other Language4
Item Desc in other Language5
Item Desc in other Language6 (new value entered by user)
```
There is also a resource key that matches each "Item Description" to a single "Item Desc in other Language". The only time they are ever going to see each other is during this translation process, all other times the values may be different, so the resource keys can't simply be changed to all point at one translation permanently.
I should also add, there should be no alteration of the structure of the tables or removing rows of the table.
---
Ok, here's an updated revisal of what I would LIKE the query to do, but obviously does not do since I actually need the values of the joined table:
```
SELECT pe.prodtree_element_name_l, rs.resource_value, pe.prodtree_element_name_l_rk
FROM prodtree_element pe
LEFT JOIN resource_shortstrings rs
ON pe.prodtree_element_name_l_rk = rs.resource_key
WHERE rs.language_id = '5'
AND pe.prodtree_element_name_l <> ''
GROUP BY pe.prodtree_element_name_l
```
|
Hey thanks for that update!
Looking at that and adding it into a previous post I finally came up with this:
```
<cfquery name="getRows" datasource="XXXX">
SELECT pe.prodtree_element_name_l, MAX(rs.resource_value) AS resource_value
FROM prodtree_element pe
LEFT JOIN resource_shortstrings rs
ON pe.prodtree_element_name_l_rk = rs.resource_key
WHERE rs.language_id = '5'
AND pe.prodtree_element_name_l <> ''
GROUP BY prodtree_element_name_l
</cfquery>
```
I realized I didn't need a specific resource\_value, just any that was in there. I also realized I didn't need the resource key at all outside of the query. The update will be updating ALL the matching base values regardless, so I didn't really need the resource key after all, which allowed me to use the GROUP BY.
Took a while, sorry for the poor explanation, but this is it! :) Thanks for all the help.
|
Hrm, still not real clear on what the issue truly is, but let me give it a go.
Tables:
```
BASE_VALUES
------------------
BASE_VALUE_RK
BASE_VALUE_NAME
RESOURCE_VALUES (these are the translations, I'm guessing)
-----------------------
RESOURCE_KEY
RESOURCE_LANGUAGE_ID
RESOURCE_VALUE
```
You want to retrieve one base value, and all corresponding translation values that match that base value, export them to excel, and then re-load them via an update (I think).
SQL to SELECT out data:
```
SELECT bv.BASE_VALUE_RK, rv.RESOURVE_VALUE
FROM BASE_VALUE bv, RESOURCE_VALUE rv
WHERE bv.BASE_VALUE_RK = rv.RESOURCE_KEY
AND rv.resource_language_id = '5'
ORDER BY 1;
```
That'll give you:
```
1234 Foo
1235 Bar
1236 Baz
```
Export that to excel, and get it back with updates:
```
1234 Goo
1235 Car
1236 Spaz
```
You can then say:
```
UPDATE RESOURCE_VALUES
SET RESOURCE_VALUE = value_from_spreadsheet
WHERE RESOURCE_KEY = key_from_spreadsheet
```
I may be way off base on this guy, so let me know and, if you can provide a little more detail, I may be able to score closer to the mark.
Cheers!
|
Matching values in two tables query (SQL and ColdFusion)
|
[
"",
"sql",
"excel",
"coldfusion",
""
] |
I am developing some client side Javascript that is using some JSON web services on a different domain. I have read that some browsers do not allow cross-domain scripting and that I should create a proxy on my local server to serve the data.
Can someone please point me to a simple example of how to do this in ASP.Net?
|
You may be able to avoid a proxy by using a technique like [JSONP](http://remysharp.com/2007/10/08/what-is-jsonp/). Assuming the web service you're talking to supports JSONP (for example, Flickr or Twitter both offer a JSONP API) or you have control over the data the web service sends back, you can send JSON data between domains using a library that features JSONP.
For example, in jQuery, you can make a remote JSON call:
```
jQuery.getJSON("http://www.someothersite.com/webservice?callback=?", function(result)
{
doStuffWithResult(result);
});
```
Because the call is to another domain, jQuery automatically uses some trickery to make a cross domain call. jQuery will automatically replace the ? in the url with a callback function name that the web service can use to format the JSON data being returned.
If you're the one controlling the web service, you can handle the JSONP request by getting the request parameter called "callback" which will be set to the callback function name you need to use. The callback function takes one parameter, which is the JSON data you want to send back. So, if the callback parameter is set to "jsonp2342342", you'll want the web service to respond like this:
```
jsonp2342342({key: value, key2: value});
```
If the web service you're using already supports JSONP, you won't have to worry about doing the formatting yourself.
|
Generally speaking, the proxy runs on your web server - most likely IIS in your case - and 'relays' the requests to another server on a different domain.
Here's an example of one implemented in C# .NET
[Fast, Streaming AJAX proxy](https://www.codeproject.com/articles/25218/fast-scalable-streaming-ajax-proxy-continuously-de)
|
Cross browser scripting proxy
|
[
"",
"asp.net",
"javascript",
"web-services",
"cross-domain",
""
] |
I have two PHP scripts, both using the same session by calling `session_name('MySessID')`.
When the first script calls the second script using curl, the second script hangs when `session_start()` is called.
Why would this happend?
|
I don't totally understand why this happens, but I got it solved.
This [bug](http://bugs.php.net/bug.php?id=44134) describes the same problem I'm having. I have a scripts posting to another script, *both using the same session*, which apparently stalls PHP.
So, before I do the whole curl post script, I call the `session_commit` function, so ending the calling scripts session, and enabling the called script to restart the session.
Whack...
|
From the php manual
<http://php.net/manual/en/function.session-write-close.php>
Session data is usually stored after your script terminated without the need to call session\_write\_close(), **but as session data is locked to prevent concurrent writes only one script may operate on a session at any time**. When using framesets together with sessions you will experience the frames loading one by one due to this locking. You can reduce the time needed to load all the frames by ending the session as soon as all changes to session variables are done.
*So you can not have 2 scripts use the same session att the same time.*
|
Why does session_start cause a timeout when one script calls another script using curl
|
[
"",
"php",
"post",
"curl",
"timeout",
""
] |
**UPDATE:** Thanks to everyone for the responses. I didn't realize document.write() was deprecated. Add a another notch to the learning column. I'll be taking the advice posted here, but leave the original question so that the answers given make sense in context of the original question.
---
I'm in the process of coding some rather long write() arguments and am trying to decide which of the following examples would be the best to follow, considering syntax, readability and performance. Should I
a. Keep them all on one line:
```
<script>
var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)";
document.write("<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>" + someVariable + "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>" + someVariable);
</script>
```
b. Break them up by adding line breaks for somewhat improved readability:
```
<script>
var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)";
document.write("<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>"
+ someVariable
+ "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>"
+ someVariable);
</script>
```
c. Break them up by using multiple variables:
```
<script>
var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)";
var partOne = "<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>";
var partTwo = "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>";
document.write(partOne + someVariable + partTwo + someVariable);
</script>
```
Thanks in advance.
|
My gut reaction is: **don't do that**. (Your example is poor, you should not be writing big chunks of content in your behavior layer.)
Whenever you *have to* do this, either concat:
```
var longVar = 'asdfasdf asdf asdf asdfasdf asdfasdf asdf asdfasdf' +
' fasdf s9d0af asdf asdf0s,dv z-xcfva-sdfmwaert ' +
'qersdfasdfasdfasdfasdf';
document.write(longVar);
```
Or if it gets really long, performance may benefit by using joining an array:
```
var longVar = [
'asdfasdf asdf asdf asdfasdf asdfasdf asdf asdfasdf',
' fasdf s9d0af asdf asdf0s,dv z-xcfva-sdfmwaert ',
'qersdfasdfasdfasdfasdf'
].join('');
document.write(longVar);
```
|
I would write it however is going to be easiest to read and maintain. Then test the performance. If it is too slow try incrementally improving the algorithm until the speed is acceptable.
So ideas to improve the performance:
- ensure script is minified.
- do as much preprocessing on the server and serve the "processed" script.
By using a minification tool (e.g. jsMin) you won't suffer any issues by having white space and line breaks for readability.
|
Which is the best way to handle long write() arguments?
|
[
"",
"javascript",
"readability",
""
] |
I feel that using GetEnumerator() and casting IEnumerator.Current is expensive. Any better suggestions?
I'm open to using a different data structure if it offers similiar capabilities with better performance.
**After thought:**
Would a generic stack be a better idea so that the cast isn't necessary?
|
Have you done any benchmarks, or are they just gut feelings?
If you think that the majority of the processing time is spent looping through stacks you should benchmark it and make sure that that is the case. If it is, you have a few options.
1. Redesign the code so that the looping isn't necessary
2. Find a faster looping construct. (I would recommend generics even though it wouldn't matter that much. Again, do benchmarks).
EDIT:
Examples of looping that might not be necessary are when you try to do lookups in a list or match two lists or similar. If the looping takes a long time, see if it make sense to put the lists into binary trees or hash maps. There could be an initial cost of creating them, but if the code is redesigned you might get that back by having O(1) lookups later on.
|
`Stack<T>` (with foreach) would indeed save the cast, but actually boxing [isn't all *that* bad](https://codeblog.jonskeet.uk/2008/10/08/why-boxing-doesn-t-keep-me-awake-at-nights/) in the grand scheme of things. If you have performance issues, I doubt this is the area where you can add much value. Use a profiler, and focus on real problems - otherwise this is premature.
Note that if you only want to read the data once (i.e. you are happy to consume the stack), then this *may* be quicker (avoids the overhead of an enumerator); YMMV.
```
Stack<T> stack = null;
while (stack.Count > 0)
{
T value = stack.Pop();
// process value
}
```
|
Fastest way to iterate over a stack in c#
|
[
"",
"c#",
"optimization",
"stack",
""
] |
Magento shopping cart is built on the Zend Framework in PHP. This is the first time I've dealt with the Zend framework and I'm having the following difficulty...
I'm creating a custom module that will allow users to upload images whenever they purchase products.
I can overload the addAction() method whenever a user attempts to add a product to their cart. I can also create a custom module which presents the form to the user and accepts the file(s). However I'm not sure how to insert the code to run my module into my overloaded method:
```
<?php
require_once 'Mage/Checkout/controllers/CartController.php';
class Company_SpecialCheckout_Checkout_CartController extends Mage_Checkout_CartController
{
# Overloaded addAction
public function addAction()
{
# when user tries to add to cart, request images from them
# *********
# *** what do i do in here to display a custom block ???? ###
# *** and allow addAction to continue only if successfully validated form input ###
# *********
parent::addAction();
}
}
```
I suspect my difficulties come from my lack of knowledge of the Zend MVC way of doing things. I've studied all the Magento documentation/wikis/forum threads from top to bottom.
|
hey this option is given in newer version of magento 1.3.1 to upload the file from frontend
enjoy
|
I thought I'd move to a new answer as I think I've managed to get it working.
Here's what I did
created the following files;
app/code/local/Company/SpecialCheckout/controllers/Checkout/CartController.php
app/code/local/Company/SpecialCheckout/etc/config.xml
app/etc/modules/Company\_SpecialCheckout.xml
First the controller, which is exactly as you had;
```
<?PHP
require_once 'Mage/Checkout/controllers/CartController.php';
class Company_SpecialCheckout_Checkout_CartController extends Mage_Checkout_CartController {
public function indexAction()
{
die('test');
}
}
```
Then the module configuration
```
<?xml version="1.0"?>
<config>
<modules>
<Company_SpecialCheckout>
<version>0.1.0</version>
</Company_SpecialCheckout>
</modules>
<global>
<rewrite>
<Company_SpecialCheckout_Checkout_Cart>
<from><![CDATA[#^/checkout/cart#]]></from>
<to>/SpecialCheckout/checkout_cart</to>
</Company_SpecialCheckout_Checkout_Cart>
</rewrite>
</global>
<frontend>
<routers>
<Company_SpecialCheckout>
<use>standard</use>
<args>
<module>Company_SpecialCheckout</module>
<frontName>SpecialCheckout</frontName>
</args>
</Company_SpecialCheckout>
</routers>
</frontend>
</config>
```
and then finally the config file in app/etc/modules to make sure the module is picked up.
```
<?xml version="1.0"?>
<config>
<modules>
<Company_SpecialCheckout>
<active>true</active>
<codePool>local</codePool>
</Company_SpecialCheckout>
</modules>
</config>
```
then when you go /checkout/cart you should see 'test'. This is based on details I found [here](http://www.magentocommerce.com/wiki/how_to_overload_a_controller).
Make sure you have the cacheing of config files disabled in the Magento admin.
|
Magento Custom Module. Redirect to another module and return to checkout
|
[
"",
"php",
"magento",
"zend-framework",
"module",
"checkout",
""
] |
This is a simple one. I want to replace a sub-string with another sub-string on client-side using Javascript.
Original string is `'original READ ONLY'`
I want to replace the `'READ ONLY'` with `'READ WRITE'`
Any quick answer please? Possibly with a javascript code snippet...
|
`String.replace()` is regexp-based; if you pass in a string as the first argument, the regexp made from it will not include the **‘g’** (global) flag. This option is essential if you want to replace all occurances of the search string (which is usually what you want).
An alternative **non-regexp** idiom for simple global string replace is:
```
function string_replace(haystack, find, sub) {
return haystack.split(find).join(sub);
}
```
This is preferable where the `find` string may contain characters that have an unwanted special meaning in regexps.
Anyhow, either method is fine for the example in the question.
|
Good [summary](http://www.w3schools.com/jsref/jsref_replace.asp). It is regexp based, if you use regexp notation you can specify the i and g modifiers (case insensitive (i), which will match regardless to case and global (g), which will replace all occurences), if you use string notation it'll get converted to a regex and you wont' be able to specify any modifier.
```
<script type="text/javascript">
var str1="Visit Microsoft!";
var str2 = str1.replace(/microsoft/i, "W3Schools"); //Will work, per the i modifier
var str3 = "original READ ONLY";
var str4 = str3.replace("ONLY", "WRITE"); //Will also work
</script>
```
|
Javascript - how to replace a sub-string?
|
[
"",
"javascript",
"regex",
""
] |
I have a third-party product, a terminal emulator, which provides a DLL that can be linked to a C program to basically automate the driving of this product (send keystrokes, detect what's on the screen and so forth).
I want to drive it from a scripting language (I'm comfortable with Python and slightly less so with Perl) so that we don't have to compile and send out executables to our customers whenever there's a problem found.
We also want the customers to be able to write their own scripts using ours as baselines and they won't entertain the idea of writing and compiling C code.
What's a good way of getting Python/Perl to interface to a Windows DLL. My first thought was to write a server program and have a Python script communicate with it via TCP but there's got to be an easier solution.
|
One way to call C libraries from Python is to use [ctypes](https://docs.python.org/library/ctypes.html):
```
>>> from ctypes import *
>>> windll.user32.MessageBoxA(None, "Hello world", "ctypes", 0);
```
|
In Perl, [Win32::API](http://search.cpan.org/perldoc?Win32::API) is an easy way to some interfacing to DLLs. There is also [Inline::C](http://search.cpan.org/perldoc?Inline::C), if you have access to a compiler and the windows headers.
Perl [XSUB](http://search.cpan.org/perldoc?perlxs)s can also create an interface between Perl and C.
|
How can I call a DLL from a scripting language?
|
[
"",
"python",
"perl",
"dll",
""
] |
Python's IDLE has 'Check Module' (Alt-X) to check the syntax which can be called without needing to run the code. Is there an equivalent way to do this in Emacs instead of running and executing the code?
|
You can [use Pyflakes together with Flymake](https://web.archive.org/web/20090503090851/http://www.plope.org/Members/chrism/flymake-mode) in order to get instant notification when your python code is valid (and avoids a few common pitfalls as well).
|
```
python -m py_compile script.py
```
|
How can I check the syntax of Python code in Emacs without actually executing it?
|
[
"",
"python",
"validation",
"emacs",
"syntax",
""
] |
I am trying the following code:
```
<?php
$link = mysql_connect('localhost', 'root', 'geheim');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$query = "SELECT * FROM Auctions";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach($row as $field=>$value)
{
echo "$field: {$value} <br />";
}
}
mysql_close($link);
?>
```
And get this error:
```
Warning: mysql_fetch_array(): supplied argument is not a
valid MySQL result resource in
C:\Programme\EasyPHP 2.0b1\www\test.php on line 14
```
What am I missing?
|
You haven't selected a database - use [`mysql_select_db()`](http://www.php.net/mysql_select_db)
That would be something like:
```
<?php
$link = mysql_connect('localhost', 'root', 'geheim');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Error selecting database: '. mysql_error());
}
echo 'Using database successfully';
$query = "SELECT * FROM Auctions";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach($row as $field=>$value) {
echo "$field: {$value} <br />";
}
}
mysql_close($link);
?>
```
|
Your MySQL query possibly does not match any rows in the database.
Check the return value of [mysql\_query()](http://nl2.php.net/mysql_query), which returns "resource" on success and "false" on failure.
```
$query = "SELECT * FROM Auctions";
$result = mysql_query($query);
if ($result !== false) {
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach ($row as $field=>$value) {
echo $field . ':' . $value
}
}
} else {
// query returned 0 rows
}
```
As others also suggested, you can use [mysql\_error()](https://www.php.net/manual/en/function.mysql-error.php) to look if the query returns any mySQL errors
|
mysql_fetch_array() returns 'supplied argument is not a valid MySQL result resource'
|
[
"",
"php",
"mysql",
""
] |
Does anyone have a library or JavaScript snippet to validate the check digit of credit cards before the user hits Submit?
|
The [jQuery Validation Plugin](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) has a [method](http://jquery.bassistance.de/api-browser/plugins.html#jQueryvalidatormethodscreditcard) for validating credit card numbers.
There are other specific scripts:
* [JavaScript Credit Card Validation Function](http://www.braemoor.co.uk/software/creditcard.shtml)
* [Credit Card Validation](http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CC70060A01B)
Most of them use the [Luhn algorithm](http://en.wikipedia.org/wiki/Luhn_algorithm).
|
Probably OP doesn't even follow this thread anymore but this may be helpful for someone else:
[http://jquerycreditcardvalidator.com](http://jquerycreditcardvalidator.com/)
It checks the card type, validates its length and checks for mod 10 with Luhn algorithm.
|
Client-side validation of credit cards
|
[
"",
"javascript",
"validation",
"luhn",
""
] |
I'm sure this has been asked before, but I can't find it.
What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework?
I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and dialogs. I am considering moving to PyQt because of the widgets it has (for future expansion), then I realized I could probably just use a browser to do much of the same stuff.
The application currently doesn't require Internet access, though it's a possibility in the future. I was thinking of using [Karrigell](http://karrigell.sourceforge.net/) for the web framework if I go browser-based.
---
**Edit** For clarification, as of right now the application would be browser-based, not web-based. All the information would be stored locally on the client computer; no server calls would need to be made and no Internet access required (it may come later though). It would simply be a browser GUI instead of a wxPython/PyQt GUI. Hope that makes sense.
|
The obvious advantages to browser-based:
* you can present the same UI regardless of platform
* you can upgrade the application easily, and all users have the same version of the app running
* you know the environment that your application will be running in (the server hardware/OS) which makes for easier testing and support compared to the multitude of operating system/hardware configurations that a GUI app will be installed on.
And for GUI based:
* some applications (e.g.: image editing) arguably work better in a native GUI application
* doesn't require network access
Also see my comments on [this question](https://stackoverflow.com/questions/115501/is-ruby-any-good-for-gui-development#115638):
> Cross-platform GUIs are an age-old problem. Qt, GTK, wxWindows, Java AWT, Java Swing, XUL -- they all suffer from the same problem: the resulting GUI doesn't look native on every platform. Worse still, every platform has a slightly different look and **feel**, so even if you were somehow able to get a toolkit that looked native on every platform, you'd have to somehow code your app to feel native on each platform.
>
> It comes down to a decision: do you want to minimise development effort and have a GUI that doesn't look and feel quite right on each platform, or do you want to maximise the user experience? If you choose the second option, you'll need to develop a common backend and a custom UI for each platform. *[edit: or use a web application.]*
Another thought I just had: you also need to consider the kind of data that your application manipulates and where it is stored, and how the users will feel about that. People are obviously okay having their facebook profile data stored on a webserver, but they might feel differently if you're writing a finance application like MYOB and you want to store all their personal financial details on your server. You might be able to get that to work, but it would require a lot of effort to implement the required security and to assure the userbase that their data is safe. In that situation you might decide that the overall effort is lower if you go with a native GUI app.
|
Let's pretend for a moment that the development/deployment/maintenance effort/cost is equal and we look at it from the application user's perspective:
*Which UI is the user going to find more useful?*
in terms of
* Ease of use
* Responsiveness
* Familiar navigation/usage patterns
* Most like other tools/applications in use on the platform (ie, native)
I understand that "useful" is subjective. I personally would never use (as a user, not developer) a web interface again if I could get away with it. I ***hate*** them.
There are some applications that just don't make sense to develop as browser based apps.
From a development perspective
* No two browsers available today render *exactly* the same.
* Even with Ajax, javascript and dynamic, responsive interfaces are non-trivial to implement/debug.
There are many, many standalone GUI applications that are just terrible, no argument. Development/deployment and maintenance for a multi-platform GUI is non-trivial.
Developing good user-interfaces is hard, period.
The reality is that I've made my living over the last 10 years developing mostly web based applications, because they're faster to develop, easier to deploy and provide enough utility that people will use them if they have to.
I don't believe that most users would use a web interface if given an alternative.
IMNSHO
|
Browser-based application or stand-alone GUI app?
|
[
"",
"python",
"user-interface",
"browser",
""
] |
I'm designing some VB based ASP.NET 2.0, and I am trying to make more use of the various ASP tags that visual studio provides, rather than hand writing everything in the code-behind. I want to pass in an outside variable from the Session to identify who the user is for the query.
```
<asp:sqldatasource id="DataStores" runat="server" connectionstring="<%$ ConnectionStrings:MY_CONNECTION %>"
providername="<%$ ConnectionStrings:MY_CONNECTION.ProviderName %>"
selectcommand="SELECT THING1, THING2 FROM DATA_TABLE WHERE (THING2 IN (SELECT THING2 FROM RELATED_DATA_TABLE WHERE (USERNAME = @user)))"
onselecting="Data_Stores_Selecting">
<SelectParameters>
<asp:parameter name="user" defaultvalue ="" />
</SelectParameters>
</asp:sqldatasource>
```
And on my code behind I have:
```
Protected Sub Data_Stores_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles Data_Stores.Selecting
e.Command.Parameters("user").Value = Session("userid")
End Sub
```
Oracle squaks at me with ORA-01036, illegal variable name. Am I declaring the variable wrong in the query?
I thought external variables share the same name with a @ prefixed. from what I understand, this should be placing the value I want into the query when it executes the select.
EDIT: Okay, thanks for the advice so far, first error was corrected, I need to use : and not @ for the variable declaration in the query. Now it generates an ORA-01745 invalid host/bind variable name.
EDIT AGAIN: Okay, looks like user was a reserved word. It works now! Thanks for other points of view on this one. I hadn't thought of that approach.
|
I believe Oracle uses the colon ":", not the at-symbol "@".
---
"user" is probably a reserved word. Change it to "userID", or something similar.
|
You may want to consider using a [SessionParameter](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sessionparameter(VS.80).aspx) instead of just a Parameter and let the SqlDataSource extract the user id directly from the session without any intervention on your part. Also, the example on the page linked above seems to imply that you should use ? instead of @user for parameter replacement for an ODBC connection. I think the parameter replacement would be done by the SqlDataSource and not passed to Oracle, that is it would substitute the actual value of the user id in place of the parameter (properly quoted of course) before sending the query to the database.
```
<SelectParameters>
<SessionParameter Name="userID" SessionField="user" DefaultValue="" />
</SelectParameters>
```
|
ASP.NET : Passing a outside variable into a <asp:sqldatasource> tag ASP.NET 2.0
|
[
"",
"sql",
"vb.net",
"asp.net-2.0",
"selectcommand",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.