Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm trying to get:
```
document.createElement('div') //=> true
{tagName: 'foobar something'} //=> false
```
In my own scripts, I used to just use this since I never needed `tagName` as a property:
```
if (!object.tagName) throw ...;
```
So for the second object, I came up with the following as a quick solution -- which mostly works. ;)
The problem is, it depends on browsers enforcing read-only properties, which not all do.
```
function isDOM(obj) {
var tag = obj.tagName;
try {
obj.tagName = ''; // Read-only for DOM, should throw exception
obj.tagName = tag; // Restore for normal objects
return false;
} catch (e) {
return true;
}
}
```
Is there a good substitute? | This might be of interest:
```
function isElement(obj) {
try {
//Using W3 DOM2 (works for FF, Opera and Chrome)
return obj instanceof HTMLElement;
}
catch(e){
//Browsers not supporting W3 DOM2 don't have HTMLElement and
//an exception is thrown and we end up here. Testing some
//properties that all elements have (works on IE7)
return (typeof obj==="object") &&
(obj.nodeType===1) && (typeof obj.style === "object") &&
(typeof obj.ownerDocument ==="object");
}
}
```
It's part of the [DOM, Level2](http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html).
**Update 2**: This is how I implemented it in my own library:
(the previous code didn't work in Chrome, because Node and HTMLElement are functions instead of the expected object. This code is tested in FF3, IE7, Chrome 1 and Opera 9).
```
//Returns true if it is a DOM node
function isNode(o){
return (
typeof Node === "object" ? o instanceof Node :
o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
);
}
//Returns true if it is a DOM element
function isElement(o){
return (
typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName==="string"
);
}
``` | The [accepted answer](https://stackoverflow.com/a/384380/1204556) is a bit complicated, and does not detect all types of HTML elements. For example, SVG elements are not supported. In contrast, this answer works for HTML as well as SVG, etc.
See it in action here: <https://jsfiddle.net/eLuhbu6r/>
```
function isElement(element) {
return element instanceof Element || element instanceof HTMLDocument;
}
```
Cherry on top: the above code is IE8 compatible. | How do you check if a JavaScript Object is a DOM Object? | [
"",
"javascript",
"dom",
"object",
""
] |
How can I create a local user account using .NET 2.0 and c# and also be able to set the "Password never expires" to never.
I have tried using "Net.exe" using Process.Start and passing its parameters but it seems that the "net user" is unable to set the "Password never expires" to never. | Read this excellent CodeProject article
[**Howto: (Almost) Everything In Active Directory via C#**](http://www.codeproject.com/KB/system/everythingInAD.aspx)
There is a section "Create User Account" and "Dealing with User Passwords".
**UPDATE:**
*To adapt the code for local accounts replace the respective lines with these:*
```
DirectoryEntry localMachine = new DirectoryEntry("WinNT://" +
Environment.MachineName);
DirectoryEntry newUser = localMachine.Children.Add("localuser", "user");
```
*Here starts the original code snippet for domain accounts:*
```
public string CreateUserAccount(string ldapPath, string userName,
string userPassword)
{
string oGUID = string.Empty;
try
{
string connectionPrefix = "LDAP://" + ldapPath;
DirectoryEntry dirEntry = new DirectoryEntry(connectionPrefix);
DirectoryEntry newUser = dirEntry.Children.Add
("CN=" + userName, "user");
newUser.Properties["samAccountName"].Value = userName;
int val = (int)newUser.Properties["userAccountControl"].Value;
newUser.Properties["userAccountControl"].Value = val | 0x10000;
newUser.CommitChanges();
oGUID = newUser.Guid.ToString();
newUser.Invoke("SetPassword", new object[] { userPassword });
newUser.CommitChanges();
dirEntry.Close();
newUser.Close();
}
catch (System.DirectoryServices.DirectoryServicesCOMException E)
{
//DoSomethingwith --> E.Message.ToString();
}
return oGUID;
}
```
> There are some specifics to understand
> when dealing with user passwords and
> boundaries around passwords such as
> forcing a user to change their
> password on the next logon, denying
> the user the right to change their own
> passwords, setting passwords to never
> expire, to when to expire, and these
> tasks can be accomplished using
> UserAccountControl flags that are
> demonstrated in the proceeding
> sections.
>
> Please refer to this great
> [MSDN article: Managing User Passwords](http://msdn.microsoft.com/en-gb/library/ms180915.aspx)
> for examples and documentation
> regarding these features.
```
CONST HEX
------------------------------------------
SCRIPT 0x0001
ACCOUNTDISABLE 0x0002
HOMEDIR_REQUIRED 0x0008
LOCKOUT 0x0010
PASSWD_NOTREQD 0x0020
PASSWD_CANT_CHANGE 0x0040
ENCRYPTED_TEXT_PWD_ALLOWED 0x0080
TEMP_DUPLICATE_ACCOUNT 0x0100
NORMAL_ACCOUNT 0x0200
INTERDOMAIN_TRUST_ACCOUNT 0x0800
WORKSTATION_TRUST_ACCOUNT 0x1000
SERVER_TRUST_ACCOUNT 0x2000
DONT_EXPIRE_PASSWORD 0x10000
MNS_LOGON_ACCOUNT 0x20000
SMARTCARD_REQUIRED 0x40000
TRUSTED_FOR_DELEGATION 0x80000
NOT_DELEGATED 0x100000
USE_DES_KEY_ONLY 0x200000
DONT_REQ_PREAUTH 0x400000
PASSWORD_EXPIRED 0x800000
TRUSTED_TO_AUTH_FOR_DELEGATION 0x1000000
``` | This code will create a local account with the password never expires option set:
```
using System.DirectoryServices;
DirectoryEntry hostMachineDirectory = new DirectoryEntry("WinNT://localhost");
DirectoryEntries entries = hostMachineDirectory.Children;
bool userExists = false;
foreach (DirectoryEntry each in entries)
{
userExists = each.Name.Equals("NewUser",
StringComparison.CurrentCultureIgnoreCase);
if (systemtestUserExists)
break;
}
if (false == userExists)
{
DirectoryEntry obUser = entries.Add("NewUser", "User");
obUser.Properties["FullName"].Add("Local user");
obUser.Invoke("SetPassword", "abcdefg12345@");
obUser.Invoke("Put", new object[] {"UserFlags", 0x10000});
obUser.CommitChanges();
}
```
The 0x10000 flag means PasswordNeverExpires.
I spent a long time figuring out how to create a local user account with the password set not to expire. It seems that when you try to use:
```
int val = (int)newUser.Properties["userAccountControl"].Value;
newUser.Properties["userAccountControl"].Value = val | 0x10000
```
permissions from active directory come into play. If you have active directory permissions everything works fine. If you don't then getting the userAccountControl property will always result in a null value. Trying to set userAccountControl will result in an exception "The directory property cannot be found in the cache".
However after much hunting around I found another property "UserFlags" that needs to be set using Invoke. You can use this to set the flag on a local account. I've tried this code and it worked on windows server 2008.
Hope this helps | Creating local user account c# and .NET 2.0 | [
"",
"c#",
".net",
"account",
""
] |
I'm implementing a sparse matrix with linked lists and it's not fun to manually check for leaks, any thoughts? | The [`valgrind`](http://valgrind.org/) profiler for Unix offers a decent leak detection.
However, this is only one part of a successful approach. The other part is to prevent (i.e. minimize) explicit memory handling. Smart pointers and allocators can help a great deal in preventing memory leaks. Also, *do* use the STL classes: a leak-free linked list implementation is already provided by `std::list`. | **On Windows:**
Compuware BoundChecker (bit costly but very nice)
Visual LeakDetector (free, google it)
**On Linux/Unix:**
Purify | What is the best way to check for memory leaks in c++? | [
"",
"c++",
"memory-leaks",
""
] |
I'm trying to Remote Debugging a Windows Forms Application (C#), but i'm always getting this error:
> *Unable to connect to the Microsoft Visual Studio Remote Debugging Monitor
> named 'XXX. The Visual Studio Remote
> Debugger on the target computer cannot
> connect back to this computer.
> Authentication failed. Please see Help
> for assistance.*
I tried to config according to the MSDN guides but i was not able to make it work.
## My setup:
* **Development Computer** - XP (x86) that
is connected to a domain.
* **Test Computer** - Vista (x86) that is **NOT**
connected to a domain.
* I have network connection between
the machines.
* I created a local user in the **Test
computer** (user1) with the name of my domain
user that I run the Visual Studio (mydomain\user1). setup the same password.
* On The Test Computer i'm running **"msvsmon.exe"** as application (not as services), i'm running it using **"runas"** command with the user that i have created. (user1):
runas /u:user1 msvsmon.exe
Can Someone help me please?
Thanks. | This is how it worked for me:
Remote computer: Microsoft Virtual PC, "IHS\RDM" attached to my corporate domain, logged in as jdoe, administrator account.
Local computer: Attached to local domain, logged in as jdoe, administrator account.
1) remote computer: install rdbgsetup.exe (from Visual Studio 2005\Disk 2\Remote Debugger\x86)
2) Remote computer: RUNAS /user MYDOMAIN\jdoe /netonly msvsmon
3) Remote computer: msvsmon->Tools->permissions add user "MYDOMAIN\jdoe" (I have to do this every time I re-start)
4) local computer: run msvsmon.
5) local computer, msvsmon->Tools->permissions, add object types: "computers", "IHS\RDM"
6) local computer, vs2005->debug->attach to process. Transport: Default, Qualifier: jdoe@RDM
7) Refresh, and voila; a process list! | The problem that I had is that I had 2 users:
```
mydomain\user1
mytestmachine\user1
```
that is not correct (according to Gregg Miskely) i needed to define a local user in my development computer, for example:
```
mydevcomputer\debug
mytestmachine\debug
```
with the same password and run the VS2008 and the Debugging Monitor with this user: | Remote Debugging in Visual Studio (VS2008), Windows Forms Application | [
"",
"c#",
".net",
"visual-studio-2008",
"debugging",
"remote-debugging",
""
] |
In replies to [one of my questions](https://stackoverflow.com/questions/391503/if-condition-continue-or-if-condition-style-preference), I received a number of answers saying that style 2 may perform better than style 1. I don't understand how, since I believe they should emit essentially the same machine instructions (if written in C++). Could you please explain why style 2 might perform better?
I'll rewrite the two styles here for easier reference:
*Style 1*:
```
while (!String.IsNullOrEmpty(msg = reader.readMsg()))
{
RaiseMessageReceived();
if (parseMsg)
{
ParsedMsg parsedMsg = parser.parseMsg(msg);
RaiseMessageParsed();
if (processMsg)
{
process(parsedMsg);
RaiseMessageProcessed();
}
}
}
```
*Style 2:*
```
while (!String.IsNullOrEmpty(msg = reader.readMsg()))
{
RaiseMessageReceived();
if (!parseMsg) continue;
ParsedMsg parsedMsg = parser.parseMsg(msg);
RaiseMessageParsed();
if (!processMsg) continue;
process(parsedMsg);
RaiseMessageProcessed();
}
``` | I had to check this.
Here is my version of the code:
```
using System;
using System.Collections.Generic;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Tester t=new Tester();
t.Method1(new Stack<string>(), new MsgParser(), true, true);
t.Method2(new Stack<string>(), new MsgParser(), true, true);
}
}
class Tester
{
public void Method1(Stack<string> strings, MsgParser parser, bool parseMsg, bool processMsg)
{
string msg;
while (!String.IsNullOrEmpty(msg = strings.Pop()))
{
RaiseMessageReceived();
if (parseMsg)
{
ParsedMsg parsedMsg = parser.ParseMsg(msg);
RaiseMessageParsed();
if (processMsg)
{
process(parsedMsg);
RaiseMessageProcessed();
}
}
}
}
public void Method2(Stack<string> strings, MsgParser parser, bool parseMsg, bool processMsg)
{
string msg;
while (!String.IsNullOrEmpty(msg = strings.Pop()))
{
RaiseMessageReceived();
if (!parseMsg) continue;
ParsedMsg parsedMsg = parser.ParseMsg(msg);
RaiseMessageParsed();
if (!processMsg) continue;
process(parsedMsg);
RaiseMessageProcessed();
}
}
private void RaiseMessageProcessed()
{
Console.WriteLine("Done");
}
private void process(ParsedMsg msg)
{
Console.WriteLine(msg);
}
private void RaiseMessageParsed()
{
Console.WriteLine("Message parsed");
}
private void RaiseMessageReceived()
{
Console.WriteLine("Message received.");
}
}
internal class ParsedMsg
{
}
internal class MsgParser
{
public ParsedMsg ParseMsg(string msg)
{
return new ParsedMsg();
}
}
}
```
I built it with code optimization (default Release configuration), and disassembled the assembly using Reflector.
The result verifies that the two styles are identical:
```
internal class Tester
{
// Methods
public void Method1(Stack<string> strings, MsgParser parser, bool parseMsg, bool processMsg)
{
string msg;
while (!string.IsNullOrEmpty(msg = strings.Pop()))
{
this.RaiseMessageReceived();
if (parseMsg)
{
ParsedMsg parsedMsg = parser.ParseMsg(msg);
this.RaiseMessageParsed();
if (processMsg)
{
this.process(parsedMsg);
this.RaiseMessageProcessed();
}
}
}
}
public void Method2(Stack<string> strings, MsgParser parser, bool parseMsg, bool processMsg)
{
string msg;
while (!string.IsNullOrEmpty(msg = strings.Pop()))
{
this.RaiseMessageReceived();
if (parseMsg)
{
ParsedMsg parsedMsg = parser.ParseMsg(msg);
this.RaiseMessageParsed();
if (processMsg)
{
this.process(parsedMsg);
this.RaiseMessageProcessed();
}
}
}
}
private void process(ParsedMsg msg)
{
Console.WriteLine(msg);
}
private void RaiseMessageParsed()
{
Console.WriteLine("Message parsed");
}
private void RaiseMessageProcessed()
{
Console.WriteLine("Done");
}
private void RaiseMessageReceived()
{
Console.WriteLine("Message received.");
}
}
``` | I think performance would be negligibly different if it's different at all. A compiler may optimze them into the same form anyway.
The only substantive difference is stylistic.
I like style 1 just because the loop has one entry point (per iteration) and one exit point (per iteration) so it's easy to insert debug code at the end of the loop and know it'll get called. It's the same principle behind one entry and exit point on functions (for the same reasons). That being said though too much indenting can be hard to read so continue has its place as well. | Which one of these code samples has better performance? | [
"",
"c#",
"performance",
""
] |
I would like to display tagcloud in my home page. Found this wordpress flash plugin <http://alexisyes.com/tags/wpcumulus> , but for that i needed to setup wordpress. I am wondering whether there is any other standalone plugin similar to wpcumulus which can be configurable.
I don't want to install wordpress but i would like to make use of wpcumulus. Is it possible? If not wpcumulus, could i make use of any other standalone tag clouds.
Just curious, i came across all tag clouds which were implemented in either flash or flex. Can i get the demo link/plugin which has implemented the same in javascript.
Thanks,
~shafi | You could definitely use wpcumulus (I just downloaded it and checked it out). You just have to figure out what data it needs to create a tag cloud.
First, you need to download the swf and add it to your site. You can take a look of an installed version / demo of it to see the proper swf embed html.
Next, you have to figure out how it gets its data. The quickest way I think to do this is to go to a demo of wpcumulus and look at the http requests / responses going on. I use the Live Http Headers plugin for Firefox for this. It will probably look for a xml file that's set in its swf embed code. I'm guessing the xml might look something like this:
```
<?xml version="1.0" encoding="UTF-8"?>
<tags>
<tag name="Books" count="4" />
<tag name="Magazines" count="20" />
<!-- etc... -->
</tags>
```
Now you just need to create an xml file that includes that data. You could either make it a static xml file, or use php or asp.net to create a dynamic page that produces xml. | In other words, I would like to have 'auto-refresh' functionality for the tag cloud. Can it be done? | Tag clouds: Are there any in either flash or javascript | [
"",
"javascript",
"flash",
""
] |
I have an application that resides in a single .py file. I've been able to get pyInstaller to bundle it successfully into an EXE for Windows. The problem is, the application requires a .cfg file that always sits directly beside the application in the same directory.
Normally, I build the path using the following code:
```
import os
config_name = 'myapp.cfg'
config_path = os.path.join(sys.path[0], config_name)
```
However, it seems the sys.path is blank when its called from an EXE generated by pyInstaller. This same behaviour occurs when you run the python interactive command line and try to fetch sys.path[0].
Is there a more concrete way of getting the path of the currently running application so that I can find files that are relative to it? | I found a solution. You need to check if the application is running as a script or as a frozen exe:
```
import os
import sys
config_name = 'myapp.cfg'
# determine if application is a script file or frozen exe
if getattr(sys, 'frozen', False):
application_path = os.path.dirname(sys.executable)
elif __file__:
application_path = os.path.dirname(__file__)
config_path = os.path.join(application_path, config_name)
``` | According to the [documentation](https://pyinstaller.readthedocs.io/en/stable/runtime-information.html) of PyInstaller, the suggested method of recovering application path is as follows:
```
#!/usr/bin/python3
import sys, os
if getattr(sys, 'frozen', False):
# If the application is run as a bundle, the PyInstaller bootloader
# extends the sys module by a flag frozen=True and sets the app
# path into variable _MEIPASS'.
application_path = sys._MEIPASS
else:
application_path = os.path.dirname(os.path.abspath(__file__))
```
Tested for PyInstaller v3.2, but this certainly has been working for earlier versions as well.
Soviut's solution does not work, at least not in general for recent versions of pyInstaller (note that the OP is many years old). For instance, on MacOS, when bundling an application into a one-file-bundle, `sys.executable` points only to the location of the embedded archive, which is *not* the location where the application actually runs after the pyInstaller bootloader has created a temporary application environment. Only `sys._MEIPASS` correctly points to that location. Refer to [this doc-page](https://pyinstaller.readthedocs.io/en/stable/operating-mode.html) for further information on how PyInstaller works. | Determining application path in a Python EXE generated by pyInstaller | [
"",
"python",
"executable",
"relative-path",
"pyinstaller",
""
] |
I'm currently using ReSharper's 30-day trial, and so far I've been impressed with the suggestions it makes. One suggestion puzzles me, however.
When I explicitly define a variable, such as:
```
List<String> lstString = new List<String>();
```
ReSharped adds a little squiggly green line and tells me to:
> Use implicitly type local variable declaration.
If I then follow its suggestion, ReSharper changes the line of code to:
```
var lstString = new List<String>();
```
So, is there some sort of performance gain to be had from changing the `List<String>` to a `var`, or is this merely a peculiarity of ReSharper? I've always been taught that explicitly defining a variable, rather than using a dynamic, is more optimal. | > So, is there some sort of performance gain to be had from changing the List to a var
No but this is not the only valid reason for a refactoring. More importantly, it removes redundance and makes the code shorter without any loss in clarity.
> I've always been taught that explicitly defining a variable, rather than using a dynamic, is more optimal.
You misunderstand what `var` means. This is *not* in any way dynamic, since it produces the same output. It just means that the compiler figures the type for the variable out by itself. It's obviously capable of doing so, since this is the same mechanism used to test for type safety and correctness.
It also removes a completely useless code duplication. For simple types, this might not be much. But consider:
```
SomeNamespace.AndSomeVeryLongTypeName foo = new SomeNamespace.AndSomeVeryLongTypeName();
```
Clearly, in this case doubling the name is not just unnecessary but actually harmful. | Nope. They emit the **exact same IL**.
It's just a matter of style.
`var` has the benefit that makes it easier for you to change the return type of functions without altering other parts of source code. For example change the return type from `IEnumerable<T>` to `List<T>`. However, it might make it easier to introduce bugs. | C# 'var' keyword versus explicitly defined variables | [
"",
"c#",
"performance",
"resharper",
""
] |
If you use an `EnumSet` to store conventional binary values (1,2,4 etc), then when there are less than 64 items, I am led to believe that this is stored as a bit vector and is represented efficiently as a long. Is there a simple way to get the value of this long. I want a quick and simple way to store the contents of the set in either a file or database.
If I was doing this the old way, I'd just use a long, and do the bit twidling myself, despite all the issues of typesafety etc. | As far as I'm aware, this isn't exposed. You could basically rewrite it yourself - have a look at the code for EnumSet to get an idea of the code - but it's a pity there isn't a nicer way of getting at it :( | I don't think this can be done in a generic way. Converting to a long is pretty easy:
```
public static <T extends Enum<T>> long enumSetToLong(EnumSet<T> set)
{
long r = 0;
for(T value : set)
{
r |= 1L << value.ordinal();
}
return r;
}
```
I don't know how you can possibly convert from a long back to EnumSet generically. There's no way (short of reflection) I know of to get at the values array of the enumeration to do the lookup. You'd have to do it on a per-enum basis.
I think serialization is the way to go. Just serializing as a long would be more susceptible to versioning errors, or bugs caused by rearranging the constants in the enum. | Getting the value from an EnumSet in Java | [
"",
"java",
""
] |
I'm using C# on Framework 3.5. I'm looking to quickly group a Generic List<> by two properties. For the sake of this example lets say I have a List of an Order type with properties of CustomerId, ProductId, and ProductCount. How would I get the sum of ProductCounts grouped by CustomerId and ProductId using a lambda expression? | ```
var sums = Orders.GroupBy(x => new { x.CustomerID, x.ProductID })
.Select(group => group.Sum(x => x.ProductCount));
``` | I realize this thread is very old but since I just struggled through this syntax I thought I'd post my additional findings - you can return the sum and the IDs (w/o foreach) in one query like so:
```
var sums = Orders
.GroupBy(x => new { x.CustomerID, x.ProductID })
.Select(group =>new {group.Key, ProductCount = group.Sum(x => x.ProductCount)});
```
The tricky part for me to get it working is that the sum must be aliased, apparently... | C# List<> GroupBy 2 Values | [
"",
"c#",
"linq",
"list",
"ienumerable",
"group-by",
""
] |
I am working on a project to redesign/ redo an application. The problem is that the old application was written in ASP.net 1.0 and the database is pretty large over 100 tables and 300 odd views.The database handles roles and membership in a very shoddy way. It involves a simple workflow too. The app is pain when it comes to maintainence. I have around 3-4 months to redo the software.
The DB design is not to my liking but looking at timeframe migrating data and DB redesign may make the project go off track.
Anyone ran into this situation before?? Any one has any pointers for me as to how to go about this project??
I would love to get the software up to speed with .NET 3.5 . I am not sure if App redesign would be meaningful without considering the DB
Problem with system: 1. Maintainence and scalability issues. 2. Poor DB design specially in case of user management, the app depends heavily on users and roles etc. | Database redesign is a huge effort. If you or someone on your team is not an expert in database design and ETL, you could end up with a worse mess than you have now.
However, is it possible to perhaps fix just the one or two worst parts of the database and thus achieve an improvement overall? Look at the worst performing queries to see what is really wrong (not just from your personal perspective of what you dislike but what really isn't working well now). Maybe something less than a total redesign could give you a major performance boost.
If the reason you dislike the database is that it is not truly relational, it is possible you could compromise by putting in relational tables with new names, moving the data and dropping the old tables, and creating views with the old table names that are structured like the current design. (Do not do without a current datbase backup first!!!!) That way you can start to change code to the new more effective design but the stuff you don't get changed will still work until you get to it. | Is your charge to redesign the database or the entire application? Are you on a solo mission or do you have a decent amount of help? Does your company employ any methodology standards (SDLC processes) or are you a maverick IT department?
Four months sounds very aggressive. You'll need to document the requirements, plan, design, build and test every functional component, convert data from the old system to the new system, and possibly set up new environments for all of these scenarios to take place.
The bottom line is this: spend a decent amount of time estimating the work it would take to go through the entire process. If it's four months, great. I doubt it will be. Once you have a documented, detailed estimate of the effort involved, take this to your boss and explain to him how extreme the four-month time frame really is.
If your main concern is whether or not to redo the database, consider the old idiom that a chain is only as strong as its weakest link. The new application will be written in .NET, but would it really make sense to be sitting on a shotty database with a poor design?
Spend the time *planning* your project, and you'll spend far less time doing the actual development, testing, and re-work that you'd encounter otherwise.
Hope this helps. | Dealing with application redesign | [
"",
"c#",
"asp.net",
"database-design",
""
] |
We mostly tend to following the above best practice.
Have a look at [String vs StringBuilder](https://stackoverflow.com/questions/73883/string-vs-stringbuilder)
But StringBuilder could throw **OutOfMemoryException even when there is sufficient memory available**. It throws OOM exception because it needs "continuous block of memory".
Some links for reference
[StringBuilder OutOfMemoryException](http://bytes.com/groups/net-c/501231-stringbuilder-outofmemory)
and there are many more.....
How many of you faced this problem or aware and what did you do to resolve it?
Is there anything I am missing?
**P.S: I wasn't aware of this.**
I have rephrased the question.
\*\*\* The same thing worked with manual concatenation(I'll verify this and update SO). The other thing that caused me concern was that there is enough memory in the system. That's the reason I raised this question here to check whether any one faced this problem or there was something drastically wrong with the code. | The underyling string you create will also need a contiguous block of memory because it is represented as an array of chars (arrays require contiguous memory) . If the StringBuilder throws an OOM exception you woludn't be able to build the underlying without it.
If creating a string causes an OOM, there is likely a more serious issue in your application.
Edit in response to clarification:
There is a small subset of cases where building a string with a StringBuilder will fail when manual concatenation succeeds. Manual concatenation will use the exact length required in order to combine two strings while a StringBuilder has a different algorithmn for allocating memory. It's more aggressive and will likely allocate more memory than is actually needed for the string.
Using a StringBuilder will also result in a temporary doubling of the memory required since the string will be present in a System.String form and StringBuilder simultaneously for a short time.
But if one way is causing an OOM and the other is not, it still likely points to a more serious issue in your program. | If StringBuilder is going to throw an OutOfMemoryException in your particular situation, then doing manual string concatenation is NOT a better solution; it's much worse. This is exactly the case (creating an extremely, extremely long string) where StringBuilder is supposed to be used. Manual concatenation of a string this large will take many times the memory that creation of a string with StringBuilder would take.
That said, on a modern computer, if your string is *running the computer out of contiguous memory* your design is deeply, deeply flawed. I can't imagine what you could possibly doing that would create a string that large. | StringBuilder for string concatenation throws OutOfMemoryException | [
"",
"c#",
"out-of-memory",
"stringbuilder",
""
] |
Python provides the "\*" operator for unpacking a list of tuples and giving them to a function as arguments, like so:
```
args = [3, 6]
range(*args) # call with arguments unpacked from a list
```
This is equivalent to:
```
range(3, 6)
```
Does anyone know if there is a way to achieve this in PHP? Some googling for variations of "PHP Unpack" hasn't immediately turned up anything.. perhaps it's called something different in PHP? | You can use [`call_user_func_array()`](http://www.php.net/call_user_func_array) to achieve that:
`call_user_func_array("range", $args);` to use your example. | In `php5.6` [Argument unpacking via `...` (splat operator)](http://docs.php.net/manual/en/migration56.new-features.php#migration56.new-features.splat) has been added. Using it, you can get rid of `call_user_func_array()` for this simpler alternative. For example having a function:
```
function add($a, $b){
return $a + $b;
}
```
With your array `$list = [4, 6];` (after php5.5 you can declare arrays in this way).
You can call your function with `...`:
```
echo add(...$list);
``` | unpacking an array of arguments in php | [
"",
"php",
"arguments",
"iterable-unpacking",
""
] |
I have the following classes:
```
public class Person
{
public String FirstName { set; get; }
public String LastName { set; get; }
public Role Role { set; get; }
}
public class Role
{
public String Description { set; get; }
public Double Salary { set; get; }
public Boolean HasBonus { set; get; }
}
```
I want to be able to automatically extract the property value diferences between Person1 and Person2, example as below:
```
public static List<String> DiffObjectsProperties(T a, T b)
{
List<String> differences = new List<String>();
foreach (var p in a.GetType().GetProperties())
{
var v1 = p.GetValue(a, null);
var v2 = b.GetType().GetProperty(p.Name).GetValue(b, null);
/* What happens if property type is a class e.g. Role???
* How do we extract property values of Role?
* Need to come up a better way than using .Namespace != "System"
*/
if (!v1.GetType()
.Namespace
.Equals("System", StringComparison.OrdinalIgnoreCase))
continue;
//add values to differences List
}
return differences;
}
```
How can I extract property values of Role in Person??? | ```
public static List<String> DiffObjectsProperties(object a, object b)
{
Type type = a.GetType();
List<String> differences = new List<String>();
foreach (PropertyInfo p in type.GetProperties())
{
object aValue = p.GetValue(a, null);
object bValue = p.GetValue(b, null);
if (p.PropertyType.IsPrimitive || p.PropertyType == typeof(string))
{
if (!aValue.Equals(bValue))
differences.Add(
String.Format("{0}:{1}!={2}",p.Name, aValue, bValue)
);
}
else
differences.AddRange(DiffObjectsProperties(aValue, bValue));
}
return differences;
}
``` | If the properties aren't value types, why not just call DiffObjectProperties recursively on them and append the result to the current list? Presumably, you'd need to iterate through them and prepend the name of the property in dot-notation so that you could see what is different -- or it may be enough to know that if the list is non-empty the current properties differ. | How to diff Property Values of two objects using GetType GetValue? | [
"",
"c#",
".net",
"reflection",
"object",
"properties",
""
] |
Firstly, I'm a newbie to C# and SharePoint, (less than a month's experience) so apologies if this is an obvious or easy question but I've been trawling the net for a couple of days now with absolutely no success.
I have an xslt file that I have stored in a subdirectory of 'Style Library' from within the new website but how can I access this from within c#?
I've looked at SPSite and SPWeb but neither seems able to do quite what I want.
Any and all help will be gratefully received.
Many thanks
c#newbie | Here is a bit of code to retrieve the list items from a list:
```
SPList list = web.Lists["MyLibrary"];
if (list != null)
{
var results = from SPListItem listItem in list.Items
select new
{
xxx = (string)listItem["FieldName"]),
yyy = (string)listItem["AnotherField"],
zzz = (string)listItem["Field"]
};
}
```
To retrieve a file you could also use this method on SPWeb: [GetFileAsString](http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.getfileasstring.aspx) | without linq:
```
int itemId = getItemId();
SPWeb currentWeb = SPContext.Current.Web;
SPList list = currentWeb.Lists["MyList"];
if ( list != null )
{
SPListItem theItem = list.Items.GetItemById(itemId);
doWork(theItem);
}
```
The SPWeb can be retrieved in numerous ways, using the SPContext will work if the code is called from SharePoint. To get an SPWeb object from a URL you can use SPSite object i.e.
```
using ( SPSite site = new SPSite(urlToWeb) )
{
using (SPWeb web = site.OpenWeb())
{
doWork(web);
}
}
```
the 'using' statement ensures non-managed resources are reclaimed in a timely manner, by calling 'Dispose()' on the relevant objects.
HTH,
jt | Programmatically Accessing SharePoint Style Library from within C# | [
"",
"c#",
"sharepoint",
"spsite",
"spweb",
""
] |
In the external code that I am using there is enum:
```
enum En {VALUE_A, VALUE_B, VALUE_C};
```
In another external code that I am using there are 3 #define directives:
```
#define ValA 5
#define ValB 6
#define ValC 7
```
Many times I have int X which is equal to ValA or ValB or ValC, and I have to cast it to the corresponding value of En (ValA to VALUE\_A, ValB to VALUEB, etc) because some function signature has enum En. And many times I have to do the opposite operation, translate enum En to ValA or ValB or ValC. I cannot change the signatures of these functions, and there are many such functions.
The question is: How to do the translation? Should I create 2 cast operators, which will be used implicitly? Or should I just have 2 translation functions which will be used explicitly:
```
En ToEn(int)
int FromEn(En)
```
Or any other solution? | Since you can't just cast here, I would use a free function, and if there are likely to be other enums that also need converting, try to make it look a little bit like the builtin casts:
```
template<typename T>
T my_enum_convert(int);
template<>
En my_enum_convert<En>(int in) {
switch(in) {
case ValA: return VALUE_A;
case ValB: return VALUE_B;
case ValC: return VALUE_C;
default: throw std::logic_error(__FILE__ ": enum En out of range");
}
}
int my_enum_convert(En in) {
switch(in) {
case VALUE_A: return ValA;
case VALUE_B: return ValB;
case VALUE_C: return ValC;
// no default, so that GCC will warn us if we've forgotten a case
}
}
En enumValue = my_enum_convert<En>(ValA);
int hashDefineValue = my_enum_convert(VALUE_A);
enumValue = my_enum_convert<En>(0); // throws exception
```
Or something like that - might adjust it if issues arise while using it.
The reason I wouldn't use implicit conversion is that there already *is* an implicit conversion from En to int, which gives the wrong answer. Even if you can reliably replace that with something which gives the right answer, the resulting code won't look as though it's doing any conversion. IMO this will hinder anyone who later looks at the code more than typing a call to a conversion routine will hinder you.
If you want converting to int and converting from int to look very different, then you could give the template and the function above different names.
Alternatively, if you want them to look the same (and more like a static\_cast), you could do:
```
template<typename T>
T my_enum_convert(En in) {
switch(in) {
case VALUE_A: return ValA;
case VALUE_B: return ValB;
case VALUE_C: return ValC;
}
}
int hashDefineValue = my_enum_convert<int>(VALUE_A);
```
As written, T must have an implicit conversion from int. If you want to support T that only has an explicit conversion, use "return T(ValA);" instead (or "return static\_cast<T>(ValA);", if you consider that single-arg constructors are C-style casts and hence impermissible). | While implicit casting is more convenient than translation functions it is also less obvious to see what's going on.
An approach being both, convenient and obvious, might be to use your own class with overloaded cast operators.
When casting a custom type into an enum or int it won't be easy to overlook some custom casting.
If creating a class for this is not an option for whatever reason, I would go for the translation functions as readability during maintenance is more important than convenience when writing the code. | enum-int casting: operator or function | [
"",
"c++",
"enums",
"casting",
""
] |
*It is a messy question, hopefully you can figure out what I want :)*
**What is the best way to use Win32 functionality in a Qt Open Source Edition project?**
Currently I have included the necessary Windows SDK libraries and include directories to qmake project file by hand. It works fine on a small scale, but its inconvenient and cumbersome.
So, should I separate the Win32 stuff into a library or is there a sensible way of combining these two? Or have I just overlooked some Qt aspect that simplifies this?
**EDIT**
Removed the syntax stuff, its not really relevant, just annoying. | You could build an interface layer to wrap the Win32 functionality and provide it in a DLL or static library. The DLL would minimize the need for linking directly to the Win32 libraries with your qmake project. It would be more in keeping with the portability of Qt to create generic interfaces like this and then hide the platform specific data in a private implementation. Trolltech has typically employed the [pimpl idiom](http://en.wikipedia.org/wiki/Opaque_pointer) to accomplish such tasks. So, take a look at the Qt source code to see examples (i.e. look for the "d" pointers). | You could use win32 scopes in your .pro file;
```
win32:HEADERS+=mywinheader.h
```
or with .pri (pro include) files to compartmentalize it even more;
```
win32:include( mywinpri.pri )
```
You would typically use this apprpoach with the PIMPL idiom as monjardin describes | Using Win32 API in Qt OSE project | [
"",
"c++",
"windows",
"winapi",
"qt",
"qt4",
""
] |
I am doing some population modeling (for fun, mostly to play with the concepts of Carrying Capacity and the Logistics Function). The model works with multiple planets (about 100,000 of them, right now). When the population reaches carrying capacity on one planet, the inhabitants start branching out to nearby planets, and so on.
Problem: 100,000+ planets can house a LOT of people. More than a C# `Decimal` can handle. Since I'm doing averages and other stuff with these numbers, I need the capability to work with floating points (or I'd just use a BigInt library).
Does anyone know of a BigFloatingPoint class (or whatever) I can use? Google is being very unhelpful today. I could probably write a class that would work well enough, but I'd rather use something pre-existing, if such a thing exists. | Use units of megapeople to achieve more headroom.
Also, Decimal lets you have 100,000 planets each with 100000000000000 times the population of the Earth, if [my arithmetic](http://www.google.co.uk/search?hl=en&rlz=1B5GGGL_enGB302GB302&q=(79228162514264337593543950335+%2F+100000)+%2F+6000000000&btnG=Search&meta=) is right. Are you sure that's not enough? | Even if each planet has 100 billion people, the total is still only 1E16. This is well within the limit of a signed 64 bit integer (2^63 goes to 9,223,372,036,854,775,807 which is almost 1E19...
You could go with a Million Billion people per planet, with 100000 planets before you got close to the limit...
As to fractions and averages and such, can't you convert to a Float or double when you do any such calculations ? | Very, very large C# floating-point numbers | [
"",
"c#",
"math",
"bigdecimal",
""
] |
I'm attempting to code a script that outputs each user and their group on their own line like so:
```
user1 group1
user2 group1
user3 group2
...
user10 group6
```
etc.
I'm writing up a script in python for this but was wondering how SO might do this.
p.s. Take a whack at it in any language but I'd prefer python.
EDIT: I'm working on Linux. Ubuntu 8.10 or CentOS =) | For \*nix, you have the [pwd](http://docs.python.org/2/library/pwd.html) and [grp](http://docs.python.org/2/library/grp.html) modules. You iterate through `pwd.getpwall()` to get all users. You look up their group names with `grp.getgrgid(gid)`.
```
import pwd, grp
for p in pwd.getpwall():
print p[0], grp.getgrgid(p[3])[0]
``` | the `grp` module is your friend. Look at `grp.getgrall()` to get a list of all groups and their members.
**EDIT** example:
```
import grp
groups = grp.getgrall()
for group in groups:
for user in group[3]:
print user, group[0]
``` | Python script to list users and groups | [
"",
"python",
"linux",
"system-administration",
""
] |
I have this sample text, which is retrieved from the class name on an html element:
```
rich-message err-test1 erroractive
rich-message err-test2 erroractive
rich-message erroractive err-test1
err-test2 rich-message erroractive
```
I am trying to match the "test1"/"test2" data in each of these examples. I am currently using the following regex, which matches the "err-test1" type of word. I can't figure out how to limit it to just the data after the hyphen(-).
```
/err-(\S*)/ig
```
Head hurts from banging against this wall. | From what I am reading, your code already works.
**`Regex.exec()` returns an array of results on success.**
The first element in the array (index 0) returns the entire string, after which all `()` enclosed elements are pushed into this array.
```
var string = 'rich-message err-test1 erroractive';
var regex = new RegExp('err-(\S*)', 'ig');
var result = regex.exec(string);
alert(result[0]) --> returns err-test1
alert(result[1]) --> returns test1
``` | You could try 'err-([^ \n\r]\*)' - but are you sure that it is the regex that is the problem? Are you using the whole result, not just the first capture? | Help with regex in javascript | [
"",
"javascript",
"regex",
"classname",
""
] |
This is really stumping me today. I'm sure its not that hard, but I have a System.Reflection.PropertyInfo object. I want to set its value based on the result of a database lookup (think ORM, mapping a column back to a property).
My problem is if the DB returned value is DBNull, I just want to set the property value to its default, the same as calling:
```
value = default(T); // where T is the type of the property.
```
However, the default() method won't compile if you give it a Type, which is what I have:
```
object myObj = ???; // doesn't really matter. some arbitrary class.
PropertyInfo myPropInf = ???; // the reflection data for a property on the myObj object.
myPropInf.SetValue(myObj, default(myPropInf.PropertyType), null);
```
The above doesn't compile. default(Type) is invalid. I also thought about doing:
```
object myObj = ???;
PropertyInfo myPropInf = ???;
myPropInf.SetValue(myObj, Activator.CreateInstance(myPropInf.PropertyType), null);
```
However, if the Type is string, that would assign the value "new String()", but I really want "null", which is what "default(string)" would return.
So what am I missing here?
I suppose a really hacky way would be to create a new instance of myObj's Type and copy the property over, but that just seems stupid...
```
object myObj = ???;
PropertyInfo myPropInf = ???;
var blank = Activator.CreateInstance(myObj.GetType());
object defaultValue = myPropInf.GetValue(blank, null);
myPropInf.SetValue(myObj, defaultValue, null);
```
I'd rather not waste the memory to make a whole new instance, just to get the default for the property though. Seems very wasteful.
Any ideas? | I believe if you just do
```
prop.SetValue(obj,null,null);
```
If it's a valuetype, it'll set it to the default value, if it's a reference type, it'll set it to null. | ```
object defaultValue = type.IsValueType ? Activator.CreateInstance(type) : null;
``` | .NET - Get default value for a reflected PropertyInfo | [
"",
"c#",
".net",
"reflection",
""
] |
How do I copy text to the clipboard (multi-browser)?
Related: *[How does Trello access the user's clipboard?](https://stackoverflow.com/questions/17527870/how-does-trello-access-the-users-clipboard)* | # Overview
There are three primary browser APIs for copying to the clipboard:
1. [Async Clipboard API](https://www.w3.org/TR/clipboard-apis/#async-clipboard-api) `[navigator.clipboard.writeText]`
* Text-focused portion available in [Chrome 66 (March 2018)](https://developers.google.com/web/updates/2018/03/clipboardapi)
* Access is asynchronous and uses [JavaScript Promises](https://developers.google.com/web/fundamentals/primers/promises), can be written so security user prompts (if displayed) don't interrupt the JavaScript in the page.
* Text can be copied to the clipboard directly from a variable.
* Only supported on pages served over HTTPS.
* In Chrome 66 pages inactive tabs can write to the clipboard without a permissions prompt.
2. `document.execCommand('copy')` (***[deprecated](https://developer.mozilla.org/docs/Web/API/Document/execCommand#browser_compatibility)***)
* Most browsers support this as of ~April 2015 (see Browser Support below).
* Access is synchronous, i.e. stops JavaScript in the page until complete including displaying and user interacting with any security prompts.
* Text is read from the DOM and placed on the clipboard.
* During testing ~April 2015 only Internet Explorer was noted as displaying permissions prompts whilst writing to the clipboard.
3. Overriding the copy event
* See Clipboard API documentation on [Overriding the copy event](https://w3c.github.io/clipboard-apis/#override-copy).
* Allows you to modify what appears on the clipboard from any copy event, can include other formats of data other than plain text.
* Not covered here as it doesn't directly answer the question.
# General development notes
Don't expect clipboard related commands to work whilst you are testing code in the console. Generally, the page is required to be active (Async Clipboard API) or requires user interaction (e.g. a user click) to allow (`document.execCommand('copy')`) to access the clipboard see below for more detail.
## **IMPORTANT** (noted here 2020/02/20)
Note that since this post was originally written [deprecation of permissions in cross-origin IFRAMEs](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-permissions-in-cross-origin-iframes) and other [IFRAME "sandboxing"](https://blog.chromium.org/2010/05/security-in-depth-html5s-sandbox.html) prevents the embedded demos "Run code snippet" buttons and "codepen.io example" from working in some browsers (including Chrome and Microsoft Edge).
To develop create your own web page, serve that page over an HTTPS connection to test and develop against.
Here is a test/demo page which demonstrates the code working:
<https://deanmarktaylor.github.io/clipboard-test/>
# Async + Fallback
Due to the level of browser support for the new Async Clipboard API, you will likely want to fall back to the `document.execCommand('copy')` method to get good browser coverage.
Here is a simple example (may not work embedded in this site, read "important" note above):
```
function fallbackCopyTextToClipboard(text) {
var textArea = document.createElement("textarea");
textArea.value = text;
// Avoid scrolling to bottom
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Fallback: Copying text command was ' + msg);
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
}
document.body.removeChild(textArea);
}
function copyTextToClipboard(text) {
if (!navigator.clipboard) {
fallbackCopyTextToClipboard(text);
return;
}
navigator.clipboard.writeText(text).then(function() {
console.log('Async: Copying to clipboard was successful!');
}, function(err) {
console.error('Async: Could not copy text: ', err);
});
}
var copyBobBtn = document.querySelector('.js-copy-bob-btn'),
copyJaneBtn = document.querySelector('.js-copy-jane-btn');
copyBobBtn.addEventListener('click', function(event) {
copyTextToClipboard('Bob');
});
copyJaneBtn.addEventListener('click', function(event) {
copyTextToClipboard('Jane');
});
```
```
<div style="display:inline-block; vertical-align:top;">
<button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
<button class="js-copy-jane-btn">Set clipboard to JANE</button>
</div>
<div style="display:inline-block;">
<textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:
</textarea>
</div>
```
(codepen.io example may not work, read "important" note above)
Note that this snippet is not working well in Stack Overflow's embedded preview you can try it here: <https://codepen.io/DeanMarkTaylor/pen/RMRaJX?editors=1011>
# Async Clipboard API
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API)
* [Chrome 66 announcement post (March 2018)](https://developers.google.com/web/updates/2018/03/clipboardapi)
* Reference [Async Clipboard API](https://www.w3.org/TR/clipboard-apis/#async-clipboard-api) draft documentation
Note that there is an ability to "request permission" and test for access to the clipboard via the permissions API in Chrome 66.
```
var text = "Example text to appear on clipboard";
navigator.clipboard.writeText(text).then(function() {
console.log('Async: Copying to clipboard was successful!');
}, function(err) {
console.error('Async: Could not copy text: ', err);
});
```
# document.execCommand('copy')
The rest of this post goes into the nuances and detail of the `document.execCommand('copy')` API.
## Browser Support
~~The JavaScript [`document.execCommand('copy')`](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand) support has grown, see the links below for browser updates:~~ (***[deprecated](https://developer.mozilla.org/docs/Web/API/Document/execCommand#browser_compatibility)***)
* Internet Explorer 10+ (although [this document](https://msdn.microsoft.com/en-us/library/ms537834(v=vs.85).aspx) indicates some support was there from Internet Explorer 5.5+).
* [Google Chrome 43+ (~April 2015)](https://developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=en)
* [Mozilla Firefox 41+ (shipping ~September 2015)](https://developer.mozilla.org/en-US/Firefox/Releases/41#Interfaces.2FAPIs.2FDOM)
* [Opera 29+ (based on Chromium 42, ~April 2015)](https://dev.opera.com/blog/opera-29/#cut-and-copy-commands)
## Simple Example
(may not work embedded in this site, read "important" note above)
```
var copyTextareaBtn = document.querySelector('.js-textareacopybtn');
copyTextareaBtn.addEventListener('click', function(event) {
var copyTextarea = document.querySelector('.js-copytextarea');
copyTextarea.focus();
copyTextarea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
});
```
```
<p>
<button class="js-textareacopybtn" style="vertical-align:top;">Copy Textarea</button>
<textarea class="js-copytextarea">Hello I'm some text</textarea>
</p>
```
## Complex Example: Copy to clipboard without displaying input
The above simple example works great if there is a `textarea` or `input` element visible on the screen.
In some cases, you might wish to copy text to the clipboard without displaying an `input` / `textarea` element. This is one example of a way to work around this (basically insert an element, copy to clipboard, remove element):
Tested with Google Chrome 44, Firefox 42.0a1, and Internet Explorer 11.0.8600.17814.
(may not work embedded in this site, read "important" note above)
```
function copyTextToClipboard(text) {
var textArea = document.createElement("textarea");
//
// *** This styling is an extra step which is likely not required. ***
//
// Why is it here? To ensure:
// 1. the element is able to have focus and selection.
// 2. if the element was to flash render it has minimal visual impact.
// 3. less flakyness with selection and copying which **might** occur if
// the textarea element is not visible.
//
// The likelihood is the element won't even render, not even a
// flash, so some of these are just precautions. However in
// Internet Explorer the element is visible whilst the popup
// box asking the user for permission for the web page to
// copy to the clipboard.
//
// Place in the top-left corner of screen regardless of scroll position.
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
// Ensure it has a small width and height. Setting to 1px / 1em
// doesn't work as this gives a negative w/h on some browsers.
textArea.style.width = '2em';
textArea.style.height = '2em';
// We don't need padding, reducing the size if it does flash render.
textArea.style.padding = 0;
// Clean up any borders.
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
// Avoid flash of the white box if rendered for any reason.
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
document.body.removeChild(textArea);
}
var copyBobBtn = document.querySelector('.js-copy-bob-btn'),
copyJaneBtn = document.querySelector('.js-copy-jane-btn');
copyBobBtn.addEventListener('click', function(event) {
copyTextToClipboard('Bob');
});
copyJaneBtn.addEventListener('click', function(event) {
copyTextToClipboard('Jane');
});
```
```
<div style="display:inline-block; vertical-align:top;">
<button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
<button class="js-copy-jane-btn">Set clipboard to JANE</button>
</div>
<div style="display:inline-block;">
<textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:
</textarea>
</div>
```
## Additional notes
### Only works if the user takes an action
All `document.execCommand('copy')` calls must take place as a direct result of a user action, e.g. click event handler. This is a measure to prevent messing with the user's clipboard when they don't expect it.
See the [Google Developers post here](https://developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=en) for more info.
### Clipboard API
Note the full Clipboard API draft specification can be found here:
<https://w3c.github.io/clipboard-apis/>
### Is it supported?
* `document.queryCommandSupported('copy')` should return `true` if the command "is supported by the browser".
* and `document.queryCommandEnabled('copy')` return `true` if the `document.execCommand('copy')` will succeed if called now. Checking to ensure the command was called from a user-initiated thread and other requirements are met.
However, as an example of browser compatibility issues, Google Chrome from ~April to ~October 2015 only returned `true` from `document.queryCommandSupported('copy')` if the command was called from a user-initiated thread.
Note compatibility detail below.
### Browser Compatibility Detail
Whilst a simple call to `document.execCommand('copy')` wrapped in a `try`/`catch` block called as a result of a user click will get you the most compatibility use the following has some provisos:
Any call to `document.execCommand`, `document.queryCommandSupported` or `document.queryCommandEnabled` should be wrapped in a `try`/`catch` block.
Different browser implementations and browser versions throw differing types of exceptions when called instead of returning `false`.
Different browser implementations are still in flux and the [Clipboard API](https://w3c.github.io/clipboard-apis/) is still in draft, so remember to do your testing. | Automatic copying to the clipboard may be dangerous, and therefore most browsers (except Internet Explorer) make it very difficult. Personally, I use the following simple trick:
```
function copyToClipboard(text) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
```
The user is presented with the prompt box, where the text to be copied is already selected. Now it's enough to press `Ctrl`+`C` and `Enter` (to close the box) -- and voila!
Now the clipboard copy operation is *safe*, because the user does it manually (but in a pretty straightforward way). Of course, it works in all browsers.
```
<button id="demo" onclick="copyToClipboard(document.getElementById('demo').innerHTML)">This is what I want to copy</button>
<script>
function copyToClipboard(text) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
</script>
``` | How do I copy to the clipboard in JavaScript? | [
"",
"javascript",
"clipboard",
"copy-paste",
""
] |
I actually have two questions regarding the same problem but I think it is better to separate them since I don't think they are related.
Background:
I am writing a Windows Mobile software in VB.NET which among its tasks needs to connect to a mail-server for sending and retrieving e-mails. As a result, I also need a Mime-parser (for decoding and encoding) the e-mails in order to get the attachments. First I thought, I would write a small "hack" to handle this issue (using ordinary string-parsing) but then I saw a project, written in C#, [at CodeProject](http://www.codeproject.com/KB/cs/MIME_De_Encode_in_C_.aspx?fid=209566&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=1202157) which I thought I would implement into my solution. I don't know much about C# so I simply made a class-library out of the classes and used it in my VB.NET-project. This library works very nicely when I am targeting the Net Framework on normal windows-computers however when I was going to make the same library targeting the Compact Net Framework, I ran into troubles. This is natural since the Compact Net Framework has more limits but I actually didn't get that many errors - only two although repeated in various places in the code.
One of the errors is the one cited in the subject of this question i.e. "No overload for method 'GetString' takes '1' arguments". As mentioned above, I don't know much about C# so I converted the class with the error online into VB-NET but still I don't understand much.. Here is the function which gives above indicated error:
```
public virtual string DecodeToString(string s)
{
byte[] b = DecodeToBytes(s);
if(m_charset != null)
{
//ERROR ON THIS LINE
return System.Text.Encoding.GetEncoding(m_charset).GetString(b);
}
else
{
m_charset = System.Text.Encoding.Default.BodyName;
//ERROR ON THIS LINE
return System.Text.Encoding.Default.GetString(b);
}
}
```
If the complete source-code is needed for this class, then I can post it in another message in this thread or you can find it by downloading the code at the web-site mentioned above and by having a look at the class named MimeCode.cs.
Anyone who can help me out? Can I rewrite above function somehow to overcome this problem?
I thank you in advance for your help.
Kind regards and a Happy New Year to all of you.
Rgds,
moster67 | CF .NET requires you to use the signature: Encoding.GetString Method (array[], Int32 index, Int32 count) so try using:
```
...GetString(b, 0, b.Length);
``` | If you look up the Encoding class on MSDN you'll find information about the availability of methods in the compact framework.
<http://msdn.microsoft.com/en-us/library/system.text.encoding.default.aspx>
In your case the System.Text.Encoding.Default property is supported by the .NET Compact Framework 3.5, 2.0, 1.0 so you should be all set.
But here is the thing. MS sometimes drop's of methods from the class implementation, or to be precise overloads.
Looking at the documentation
<http://msdn.microsoft.com/en-us/library/system.text.encoding.getstring.aspx> you can tell by looking at the icons (small images to the left) that while the .NET Compact Framework supports the encoding class, some overloads got removed.
When you pass the byte[] array to the GetString method, it cannot find that overload so you have to add an int offset and int count. | c# - error compiling targeting Compact Net Framework 3.5 - No overload for method 'GetString' takes '1' arguments | [
"",
"c#",
"windows-mobile",
"compact-framework",
"mime",
""
] |
Is there an "easy" way to select either a file OR a folder from the same dialog?
In many apps I create I allow for both files or folders as input.
Until now i always end up creating a switch to toggle between file or folder selection dialogs or stick with drag-and-drop functionality only.
Since this seems such a basic thing i would imagine this has been created before, but googling does not result in much information. So it looks like i would need to start from scratch and create a custom selection Dialog, but I rather not introduce any problems by reinventing the wheel for such a trivial task.
Anybody any tips or existing solutions?
To keep the UI consistent it would be nice if it is possible to extend the OpenFileDialog (or the FolderBrowserDialog). | Technically, it is possible. The shell dialog used by FolderBrowseDialog has the ability to return both files and folders. Unfortunately, that capability isn't exposed in .NET. Not even reflection can poke the required option flag.
To make it work, you'd have to P/Invoke SHBrowseForFolder() with the BIF\_BROWSEINCLUDEFILES flag turned on in BROWSEINFO.ulFlags (value = 0x4000). The P/Invoke is gritty, it is best to copy and paste the code from [another source](http://www.google.com/search?hl=en&q=shbrowseforfolder+structlayout&btnG=Google+Search&aq=f&oq=) or the FolderBrowseDialog class itself with Reflector's help. | Based on the above tips I found some working code that uses the standard Folder Browser dialog at the following location: <http://topic.csdn.net/t/20020703/05/845468.html>
The Class for the extended Folder Browser Dialog
```
Imports System
Imports System.Text
Imports System.Windows.Forms
Imports System.Runtime.InteropServices
Public Class DirectoryDialog
Public Structure BROWSEINFO
Public hWndOwner As IntPtr
Public pIDLRoot As Integer
Public pszDisplayName As String
Public lpszTitle As String
Public ulFlags As Integer
Public lpfnCallback As Integer
Public lParam As Integer
Public iImage As Integer
End Structure
Const MAX_PATH As Integer = 260
Public Enum BrowseForTypes As Integer
Computers = 4096
Directories = 1
FilesAndDirectories = 16384
FileSystemAncestors = 8
End Enum
Declare Function CoTaskMemFree Lib "ole32" Alias "CoTaskMemFree" (ByVal hMem As IntPtr) As Integer
Declare Function lstrcat Lib "kernel32" Alias "lstrcat" (ByVal lpString1 As String, ByVal lpString2 As String) As IntPtr
Declare Function SHBrowseForFolder Lib "shell32" Alias "SHBrowseForFolder" (ByRef lpbi As BROWSEINFO) As IntPtr
Declare Function SHGetPathFromIDList Lib "shell32" Alias "SHGetPathFromIDList" (ByVal pidList As IntPtr, ByVal lpBuffer As StringBuilder) As Integer
Protected Function RunDialog(ByVal hWndOwner As IntPtr) As Boolean
Dim udtBI As BROWSEINFO = New BROWSEINFO()
Dim lpIDList As IntPtr
Dim hTitle As GCHandle = GCHandle.Alloc(Title, GCHandleType.Pinned)
udtBI.hWndOwner = hWndOwner
udtBI.lpszTitle = Title
udtBI.ulFlags = BrowseFor
Dim buffer As StringBuilder = New StringBuilder(MAX_PATH)
buffer.Length = MAX_PATH
udtBI.pszDisplayName = buffer.ToString()
lpIDList = SHBrowseForFolder(udtBI)
hTitle.Free()
If lpIDList.ToInt64() <> 0 Then
If BrowseFor = BrowseForTypes.Computers Then
m_Selected = udtBI.pszDisplayName.Trim()
Else
Dim path As StringBuilder = New StringBuilder(MAX_PATH)
SHGetPathFromIDList(lpIDList, path)
m_Selected = path.ToString()
End If
CoTaskMemFree(lpIDList)
Else
Return False
End If
Return True
End Function
Public Function ShowDialog() As DialogResult
Return ShowDialog(Nothing)
End Function
Public Function ShowDialog(ByVal owner As IWin32Window) As DialogResult
Dim handle As IntPtr
If Not owner Is Nothing Then
handle = owner.Handle
Else
handle = IntPtr.Zero
End If
If RunDialog(handle) Then
Return DialogResult.OK
Else
Return DialogResult.Cancel
End If
End Function
Public Property Title() As String
Get
Return m_Title
End Get
Set(ByVal Value As String)
If Value Is DBNull.Value Then
Throw New ArgumentNullException()
End If
m_Title = Value
End Set
End Property
Public ReadOnly Property Selected() As String
Get
Return m_Selected
End Get
End Property
Public Property BrowseFor() As BrowseForTypes
Get
Return m_BrowseFor
End Get
Set(ByVal Value As BrowseForTypes)
m_BrowseFor = Value
End Set
End Property
Private m_BrowseFor As BrowseForTypes = BrowseForTypes.Directories
Private m_Title As String = ""
Private m_Selected As String = ""
Public Sub New()
End Sub
End Class
```
The code to implement the extended dialog
```
Sub Button1Click(ByVal sender As Object, ByVal e As EventArgs)
Dim frmd As DirectoryDialog = New DirectoryDialog()
' frmd.BrowseFor = DirectoryDialog.BrowseForTypes.Directories
' frmd.BrowseFor = DirectoryDialog.BrowseForTypes.Computers
frmd.BrowseFor = DirectoryDialog.BrowseForTypes.FilesAndDirectories
frmd.Title = "Select a file or a folder"
If frmd.ShowDialog(Me) = DialogResult.OK Then
MsgBox(frmd.Selected)
End If
End Sub
``` | Select either a file or folder from the same dialog in .NET | [
"",
"c#",
".net",
"vb.net",
"winforms",
"openfiledialog",
""
] |
Is there a CRUD generator utility in Java like Scaffolding in Rails? Can be in any framework or even plain servlets. Must generate controllers + views in jsp, not just DAO code... | [Spring Roo](http://www.springsource.org/roo) seems to be exactly what you're looking for: CRUD code generation, spits out pure Java code that can be made tun run entirely independant from the framework. | [Grails](http://grails.org/Scaffolding) has scaffolding. | Is there a CRUD generator utility in Java(any framework) like Scaffolding in Rails? | [
"",
"java",
"ruby-on-rails",
"crud",
"scaffolding",
""
] |
Does the garbage collector clean up web service references or do I need to call dispose on the service reference after I'm finished calling whatever method I call? | Instead of worrying about disposing your web services, you could keep only a single instance of each web service, using a [singleton pattern](http://csharpindepth.com/Articles/General/Singleton.aspx). Web services are stateless, so they can safely be shared between connections and threads on a web server.
Here is an example of a Web Service class you can use to hold references to your web service instances. This singleton is lazy and thread-safe. It is advised that if you make your singletons lazy, they are also kept thread safe by following the same logic. To learn more about how to do this, read the C# In Depth article on [Implementing Singletons](http://csharpindepth.com/Articles/General/Singleton.aspx).
Also keep in mind that you may run into issues with WCF web services. I'd recommend reading up on [WCF's instance management techniques article](http://msdn.microsoft.com/en-us/magazine/cc163590.aspx), specifically the singleton section, for more details.
```
public static class WS
{
private static object sync = new object();
private static MyWebService _MyWebServiceInstance;
public static MyWebService MyWebServiceInstance
{
get
{
if (_MyWebServiceInstance == null)
{
lock (sync)
{
if (_MyWebServiceInstance == null)
{
_MyWebServiceInstance= new MyWebService();
}
}
}
return _MyWebServiceInstance;
}
}
}
```
And then when you need to access your web service, you can do this:
```
WS.MyWebServiceInstance.MyMethod(...)
```
or
```
var ws = WS.MyWebServiceInstance;
ws.MyMethod(...)
```
I've successfully used this pattern on several projects and it has worked well, but as tvanfosson mentions in the comments below, an even better strategy would be to use a DI framework to manage your web service instances. | I think the DataService inherits Dispose from Component. | Do I need to dispose a web service reference in ASP.NET? | [
"",
"c#",
"asp.net",
"web-services",
"dispose",
""
] |
Within my a certain function of a class, I need to use `setInterval` to break up the execution of the code. However, within the `setInterval` function, "this" no longer refers to the class "myObject." How can I access the variable "name" from within the `setInterval` function?
```
function myObject() {
this.name = "the name";
}
myObject.prototype.getName = function() {
return this.name;
}
myObject.prototype.test = function() {
// this works
alert(this.name);
var intervalId = setInterval(function() {
// this does not work
alert(this.name);
clearInterval(intervalId);
},0);
}
``` | ```
myObject.prototype.test = function() {
// this works
alert(this.name);
var oThis = this;
var intervalId = setInterval(function() {
// this does not work
alert(oThis.name);
clearInterval(intervalId);
},0);
}
```
This should work. The anonymous function's "this" is not the same "this" as your myObject's "this." | Here's the prototype bind function
```
Function.prototype.bind = function( obj ) {
var _this = this;
return function() {
return _this.apply( obj, arguments );
}
}
``` | Javascript: How to access a class attribute from a function within one of the class's functions | [
"",
"javascript",
"oop",
"class-design",
""
] |
I know the possibilities of basic leak detection for Win32 using the *crtdbg.h* header, but this header is unavailable in the CE CRT library headers (i'm using the lastest SDK v6.1).
Anyone knows how I can automatically detect leaks in a WinCE/ARMV4I configuration with VC 9.0? I don't want to override new/delete for my class hierarchy, I would prefer ready to use and tested code. | At work (developing WindowsCE based OS + Applications) we have created our own memory manager, roughly based on the [Fluid Studios Memory Manager](http://www.paulnettle.com/pub/FluidStudios/MemoryManagers/Fluid_Studios_Memory_Manager.zip) (the link which I found using SO!). I'm pretty sure with a few simple modifications you could adapt it to use on your platform.
Basically it doesn't override new and delete, but instead uses the preprocessor to add extra reporting to it. Then once the program exits it generates an output file of memory leaks. | You want to use either [AppVerifier](http://msdn.microsoft.com/en-us/library/aa934674.aspx) or [Entrek CodeSnitch](http://entrek.com/products.htm#CodeSnitch). I've had much better luck getting CodeSnitch working in a short period of time. The caveat there is I don't do a whole lot of WinMo - mostly vanilla CE. I believe there are connectivity issues with CodeSnitch and newer WinMo devices (Platman versus Corecon), but I also believe that Entrek either has a beta or a patch that works for it. My recommendation would be to call Entrek (don't email, they're busy so a call will be your quickest route to info) and only if you find that it won't work, then look into AppVerifier. | How to detect leaks under WinCE C/C+ runtime library? | [
"",
"c++",
"windows-mobile",
"memory-leaks",
"windows-ce",
"crtdbg.h",
""
] |
According to FXCop, List should not be exposed in an API object model. Why is this considered bad practice? | I agree with moose-in-the-jungle here: `List<T>` is an unconstrained, bloated object that has a lot of "baggage" in it.
Fortunately the solution is simple: expose `IList<T>` instead.
It exposes a barebones interface that has most all of `List<T>`'s methods (with the exception of things like `AddRange()`) and it doesn't constrain you to the specific `List<T>` type, which allows your API consumers to use their own custom implementers of `IList<T>`.
For even more flexibility, consider exposing some collections to `IEnumerable<T>`, when appropriate. | There are the 2 main reasons:
* List<T> is a rather bloated type with many members not relevant in many scenarios (is too “busy” for public object models).
* The class is unsealed, but not specifically designed to be extended (you cannot override any members) | Why is it considered bad to expose List<T>? | [
"",
"c#",
"fxcop",
""
] |
I'm embedding a Flash ActiveX control in my C++ app (Flash.ocx, Flash10a.ocx, etc depending on your Flash version).
I can load an SWF file by calling LoadMovie(0, filename), but the file needs to physically reside in the disk. How to load the SWF from memory (or resource, or stream)? I'm sure there must be a way, because commercial solutions like **f-in-box**'s feature [Load flash movies from memory directly](http://www.f-in-box.org/dll/#feature_load_movie) also uses Flash ActiveX control. | Appearantly I a going to need to supply details for a vote 'up'.. OK.
The internal flash buffer when first initiailized indicates if a movie is loaded or if the buffer hold properties in the buffer fisrt four bytes.
gUfU -- no movie loaded. properties to follow ....
fUfU -- .. [4bytes] size as integer.
then the UNCOMPRESSED movie or SWF as it were.
Write a IStream class.
fill with above.
save as szFile
```
TFlashStream *fStream = new TFlashStream(szFile);
// QI flash player
```
```
IPersistStreamInit * psStreamInit = 0;
shock->QueryInterface(::IID_IPersistStreamInit,
(LPVOID*)&psStreamInit);
if(psStreamInit)
{
psStreamInit->InitNew();
psStreamInit->Load(fStream);
psStreamInit->Release();
}
delete fStream;
```
Things to note :
When psStreamInit->Load(fStream);
will call IStream::Read looking for the header 'fUfU'.
if the return is correct psStreamInit then calls IStream::Read for the buffer size.
If everthing looks good so far, psStreamInit then reads in 1024 byte chunks until the read is exhausted.
However. for the header and file size.
```
STDMETHOD(Read)(void *pv, ULONG cb, ULONG *pcbRead)
```
pcbRead is invalid. you may want to use something like
IsBadReadPtr
--
Michael | To spare you some typing. It works for me in this way (just works not extensively tested):
```
void flash_load_memory(FlashWidget* w, void* data, ULONG size) {
FlashMemoryStream fStream = FlashMemoryStream(data, size);
IPersistStreamInit* psStreamInit = NULL;
w->mFlashInterface->QueryInterface(IID_IPersistStreamInit,(LPVOID*) &psStreamInit);
if(psStreamInit) {
psStreamInit->InitNew();
psStreamInit->Load((LPSTREAM)&fStream);
psStreamInit->Release();
}
}
class FlashMemoryStream : IStream {
public:
FlashMemoryStream(void* data,ULONG size) {
this->data = data;
this->size = size;
this->pos = 0;
}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, LPVOID* ppv) {
return E_NOTIMPL;
}
ULONG STDMETHODCALLTYPE AddRef() {
return E_NOTIMPL;
}
ULONG STDMETHODCALLTYPE Release() {
return E_NOTIMPL;
}
// IStream methods
STDMETHOD(Read) (void *pv,ULONG cb,ULONG *pcbRead) {
if(pos == 0 && cb == 4) {
memcpy(pv,"fUfU",4);
pos += 4;
return S_OK;
}
else if(pos == 4 && cb == 4) {
memcpy(pv,&size,4);
size += 8;
pos += 4;
return S_OK;
}
else {
if(pos + cb > size) cb = size - pos;
if(cb == 0) return S_FALSE;
memcpy(pv,(char*)data + pos - 8,cb);
if(pcbRead) (*pcbRead) = cb;
pos += cb;
return S_OK;
}
}
STDMETHOD(Write) (void const *pv,ULONG cb,ULONG *pcbWritten) { return E_NOTIMPL; }
STDMETHOD(Seek) (LARGE_INTEGER dlibMove,DWORD dwOrigin,ULARGE_INTEGER *plibNewPosition) { return E_NOTIMPL; }
STDMETHOD(SetSize) (ULARGE_INTEGER libNewSize) { return E_NOTIMPL; }
STDMETHOD(CopyTo) (IStream *pstm,ULARGE_INTEGER cb,ULARGE_INTEGER *pcbRead,ULARGE_INTEGER *pcbWritten) { return E_NOTIMPL; }
STDMETHOD(Commit) (DWORD grfCommitFlags) { return E_NOTIMPL; }
STDMETHOD(Revert) (void) { return E_NOTIMPL; }
STDMETHOD(LockRegion) (ULARGE_INTEGER libOffset,ULARGE_INTEGER cb,DWORD dwLockType) { return E_NOTIMPL; }
STDMETHOD(UnlockRegion) (ULARGE_INTEGER libOffset,ULARGE_INTEGER cb,DWORD dwLockType) { return E_NOTIMPL; }
STDMETHOD(Stat) (STATSTG *pstatstg,DWORD grfStatFlag) { return E_NOTIMPL; }
STDMETHOD(Clone) (IStream **ppstm) { return E_NOTIMPL; }
void* data;
ULONG size;
ULONG pos;
};
``` | Flash ActiveX: How to Load Movie from memory or resource or stream? | [
"",
"c++",
"flash",
"activex",
"ocx",
"shockwave",
""
] |
Is there a built-in function/operator I could use to unpack values from a dictionary and assign it into instance variables?
This is what I intend to do:
```
c = MyClass()
c.foo = 123
c.bar = 123
# c.foo == 123 and c.bar == 123
d = {'bar': 456}
c.update(d)
# c.foo == 123 and c.bar == 456
```
Something akin to dictionary `update()` which load values from another dictionary but for plain object/class instance? | there is also another way of doing it by looping through the items in d. this doesn't have the same assuption that they will get stored in `c.__dict__` which isn't always true.
```
d = {'bar': 456}
for key,value in d.items():
setattr(c,key,value)
```
or you could write a `update` method as part of `MyClass` so that `c.update(d)` works like you expected it to.
```
def update(self,newdata):
for key,value in newdata.items():
setattr(self,key,value)
```
check out the help for setattr
> ```
> setattr(...)
> setattr(object, name, value)
> Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
> ''x.y = v''.
> ``` | Have you tried
```
f.__dict__.update( b )
```
? | Python update object from dictionary | [
"",
"python",
"iterable-unpacking",
""
] |
Many developers seem to be either intimidated or a bit overwhelmed when an application design requires both procedural code and a substantial database. In most cases, "database" means an RDBMS with an SQL interface.
Yet it seems to me that many of the techniques for addressing the "impedance mismatch" between the two paradigms would be much better suited to an ISAM (indexed-sequential access method) toolset, where you can (must) specify tables, indexes, row-naviagation, etc. overtly - exactly the behavior prescribed by the ActiveRecord model, for instance.
In early PC days, dBASE and its progeny were the dominant dbms platforms, and it was an enhanced ISAM. Foxpro continues this lineage quite successfully through to today. MySQL and Informix are two RDBMSs that were at least initially built on top of ISAM implementations, so this approach should be at least equally performant. I get the feeling that many developers who are unhappy with SQL are at least unconsciously yearning for the ISAM approach to be revived, and the database could be more easily viewed as a set of massively efficient linkable hyper-arrays. It seems to me that it could be a really good idea.
Have you ever tried, say, an ORM-to-ISAM implementation? How successfully? If not, do you think it might be worth a try? Are there any toolsets for this model explicitly? | I implemented an ORM-to-isam library back in the 1990s that enjoyed some (very) modest success as shareware. I largely agree with what you say about the virtues of ISAMs and I think it better to use an ISAM when building an ORM layer or product if you are looking only for flexibility and speed.
However, the risk that you take is that you'll lose out on the benefits of the wide range of SQL-related products now on the market. In particular, reporting tools have evolved to be ever more tightly integrated with the most popular SQL packages. While ISAM product vendors in the 1990s provided ODBC drivers to integrate with products like Crystal Reports, it seemed, even then, that the market was trending away from ISAM and that I would be risking obsolescence if I continued using that technology. Thus, I switched to SQL.
One caveat: it has been nearly a decade since I was playing in the ISAM sandbox so I cannot purport to be up on the latest ISAM tools and their solutions to this problem. However, unless I was convinced that I was not going to be trapped without reporting tools support, I would not adopt an ISAM-based ORM regardless of its virtues. And that doesn't even cover the other tools available for SQL-based development! | Maybe Pig Latin is what you want? According to this article
<http://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=693D79B5EFDC0452E1C9A87D1C495D4C?doi=10.1.1.124.5496&rep=rep1&type=pdf> :
> "Besides, many of the people who ana-
> lyze this data are entrenched
> procedural programmers, who find the
> declarative, SQL style to be
> unnatural. The success of the more
> procedural map-reduce programming
> model, and its associated scalable
> implementations on commodity hard-
> ware, is evidence of the above.
> However, the map-reduce paradigm is
> too low-level and rigid, and leads to
> a great deal of custom user code that
> is hard to maintain, and reuse. We
> describe a new language called Pig
> Latin that we have designed to fit in a
> sweet spot between the declarative
> style of SQL, and the low-level,
> procedural style of map-reduce." | Choosing ISAM rather than SQL | [
"",
"sql",
"orm",
"isam",
""
] |
I have a snippet of code that I'm working with to filter rows in a table. It works perfectly in every browser other than Firefox v3.0.x (works fine with 3.1 beta 2). When I run the snippet in Firefox 3.0.x, it says that `children is undefined`. I am using jQuery v1.2.6 also.
Code Snippet:
```
var bodyRows = $("#resultsTable tbody tr");
bodyRows.each(function(n){
if(!filterPattern.test($.trim(this.children[2].innerHTML))){ //errors here
this.style.display = 'none';
}
else {
this.style.display = '';
}
});
```
The code selects all table rows and then loops through them, testing the innerHTML text of the 3rd column. If the RegEx test fails, the row is hidden, else it is displayed.
Has anyone seen this issue and / or know how to get it working?
Thanks
**EDIT:**
Here is the HTML markup for the table. For brevity, I'm only giving 2 record in it though more are populated.
```
<table id="resultsTable" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>First</th>
<th>Last</th>
<th>City</th>
<th>State</th>
<th>Zip</th>
<th>Email</th>
<th> </th>
</tr>
</thead>
<tbody id="resultsBody">
<tr>
<th>James</th>
<th>Eggers</th>
<th>SomeCity</th>
<th>IA</th>
<th>55555</th>
<th>email@email.com</th>
<th> </th>
</tr>
<tr>
<th>John</th>
<th>Doe</th>
<th>SomeCity</th>
<th>KY</th>
<th>88888</th>
<th>email2@email.com</th>
<th> </th>
</tr>
</tbody>
</table>
``` | Why not use jQuery to traverse the DOM elements instead.
```
var bodyRows = $("#resultsTable tbody tr");
bodyRows.each(function(){
var thirdCell = $(this).find('td').eq(2);
if(!filterPattern.test($.trim(thirdCell.html()))){
this.style.display = 'none';
} else {
this.style.display = '';
}
});
```
You could also use '`.text()`' if you just want the text without any possible markup to be returned.
The property `children` is an IE only DOM property which no other browser has (to my knowledge). Firefox uses the standard property `childNodes` for accessing children. The problem with `childNodes` is that it considers whitespace and text to be a node (or at least Firebug says so) which makes it (in my opinion) very difficult to deal with. If you have a JavaScript API, you should take advantage of it so that you don't have to deal with the differences between browsers' DOM traversal techniques. | ```
if(!filterPattern.test($.trim(this.children[2].innerHTML)))
```
When an 'each' callback is invoked by jQuery, 'this' is a direct browser DOM node, not a jQuery object.
Confusion occurs because jQuery offers a 'children' method on its DOM wrappers, and IE offers a non-standard 'children' collection on its native DOM nodes, but the two interfaces are almost totally incompatible.
So use $(this).children()[2] or similar for the jQuery version, or this.getElementsByTagName('td')[2] for the standard DOM version.
(Assuming you meant to make the table data elements 'td' rather than 'th', which you probably did. Also you probably want to grab the raw text of the cell rather than the innerHTML version which may have characters escaped in unexpected ways.) | jQuery each tr.children is undefined in Firefox 3.0 | [
"",
"javascript",
"jquery",
"firefox-3",
""
] |
I am trying to create a sidebar for a site that will allow a user to select an item from a drop down menu and show an RSS Feed. The feed will change depending on which item is selected from the list. I am not sure how to acomplish this, but my first thought was to use z-index and show/hide layers. I have one layer and the menu set up, but it will not allow me to change the feed displayed when a different menu item is selected. Does anyone know how I can acomplish this?
I have a live preview up of what I have gotten done so far. It's located on the site, [CHUD](http://www.chud.com/articles/templates/chud/new_sidebarhome.php), | you have two options:
1. pre-load all the rss feeds (i'm assuming your `<ul>`'s in your example page are the HTML output of your RSS feeds?), hide them all when your document loads, and then reveal them as selected
2. use AJAX to dynamically grab the selected feed information as your select box changes.
here's a quick example of a javascript and jQuery version of doing the former:
html:
```
<select id="showRss">
<option name="feed1">Feed 1</option>
<option name="feed2">Feed 2</option>
</select>
<div id="rssContainer">
<ul id="feed1">
<li>feed item 1</li>
<li>...</li>
</ul>
<ul id="feed2">
<li>feed item 2</li>
<li>...</li>
</ul>
<!-- etc... -->
</div>
```
javascript:
```
var rss = document.getElementById('rssContainer'); // main container
var nodes = rss.getElementsByTagName('ul'); // collection of ul nodes
var select = document.getElementById('showRss'); // your select box
function hideAll() { // hide all ul's
for (i = 0; i < nodes.length; ++i) {
nodes[i].style.display = 'none';
}
}
select.onchange = function() { // use the 'name' of each
hideAll(); // option as the id of the ul
var e = this[this.selectedIndex].getAttribute('name');
var show = document.getElementById(e); // to show when selected
show.style.display = 'block';
}
hideAll();
```
jQuery:
```
$('#showRss').change(function() {
$('#rssContainer ul').hide('slow'); // added a bit of animation
var e = '#' + $(':selected', $(this)).attr('name');
$(e).show('slow'); // while we change the feed
});
$('#rssContainer ul').hide();
```
to do option 2, your `onchange` function would handle the AJAX loading. if you're not that familiar with AJAX, and have a few feeds, option 1 is probably the easiest. (again, i'm assuming you have already parsed out your RSS as HTML, as that's another topic altogether). | This uses jQuery and jFeed plugin to replace the contents of a DIV based on a dropdown selection.
```
// load first feed on document load
$(document).ready(
function() {
load_feed( $('select#feedSelect')[0], 'feedDiv' ) ); // pick first
}
);
function load_feed( ctl, contentArea ) // load based on select
{
var content = $('#' + contentArea )[0]; //pick first
content.html( 'Loading feed, please wait...' );
var feedUrl = ctl.options[ctl.selectedIndex].value;
$.getFeed( { url: feedUrl,
function(feed) {
content.html( '' );
content.append( '<h1>' + feed.title + '</h1>' );
feed.items.each(
function(i,item) {
content.append( '<h2><a href="'
+ item.link
+ '">'
+ feed.title
+ '</a></h2>' );
content.append( '<p>' + feed.description + '</p>' );
}
);
}
});
}
```
HTML
```
<div>
<select id=feedSelect onchange="load_feed(this,'feedDiv');" >
<option value='url-to-first-feed' text='First Feed' selected=true />
<option value='url-to-second-feed' text='Second Feed' />
...
</select>
<div id='feedDiv'>
</div>
</div>
``` | Creating a Drop Down Menu That Changes Page Content Using Show/Hide Layers and Z-Index | [
"",
"javascript",
"z-index",
"data-layers",
"drop-down-menu",
""
] |
Say I have a Python function that returns multiple values in a tuple:
```
def func():
return 1, 2
```
Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this:
```
x, temp = func()
``` | One common convention is to use a "\_" as a variable name for the elements of the tuple you wish to ignore. For instance:
```
def f():
return 1, 2, 3
_, _, x = f()
``` | You can use `x = func()[0]` to return the first value, `x = func()[1]` to return the second, and so on.
If you want to get multiple values at a time, use something like `x, y = func()[2:4]`. | Ignore python multiple return value | [
"",
"python",
"function",
"tuples",
""
] |
I'm working on a project for the .net platform and would like to support multiple database types. I would like to keep the DDL under source control in a generic format then convert it to database specific DDL for deployment.
So I'm looking for utilities that will convert generic DDL into database specific DDL. Ideally it would support MSSQL 05/08, MySQL, Oracle, Postgres, & DB2 out of the box.
Here are the tools that I've found so far:
1. [XML to DDL](http://xml2ddl.berlios.de/)
* No built in support for MSSQL.
2. [DdlUtils](http://db.apache.org/ddlutils/)
* No command line utility. Must be called from java or ant scripts.
3. [ActiveRecord::Migration](http://api.rubyonrails.org/classes/ActiveRecord/Migration.html)
* No support for foreign keys
* Not sure how to integrate with .net project.
Does anyone have experience with those I've mentioned or know of others? | The only one that I know of that has support for SQL Server is [SQLFairy](http://sqlfairy.sourceforge.net/). It's written in Perl and is pretty feature rich. XML2DDL is pretty good too, but if it doesn't support your DBMS of choice it's not really viable. | NHibernate's [SchemaExport tool](http://hibernate.org/hib_docs/nhibernate/html/toolsetguide.html) can generate an appropriate DDL from the OR mappings for any of NHibernate's supported DBMS dialects. However, as others have implied, if you're working at that level you're really restricted to the rather thin common denominator between DBMSes. | Best database independent SQL DDL utility? | [
"",
".net",
"sql",
"version-control",
"ddl",
""
] |
When I try to set the `z` variable in the code below, I get this compile time error:
> Operator '\*' cannot be applied to operands of type 'double' and 'decimal'
```
decimal x = 1, y = 2, z;
// There are two ways I set the z variable:
z = (x*y)*(.8 * 1.732050808m);
z = (1000 * x)/(y * 1.732050808m)* .8;
```
Why is that, and how do I solve it? | Be sure to use `.8m` instead of `.8`. | You didn't say which line it was, but I'm betting on these two:
```
z = (x*y)*(.8 * 1.732050808m);
```
And:
```
z = (1000 * x)/(y * 1.732050808m)* .8;
```
Note that your .8 does not have the 'm' qualifier. Every other place I see you did supply that. | Why am I getting a compile error when multiplying a decimal by a literal value? | [
"",
"c#",
"decimal",
""
] |
I'm currently using the ModelStateDictionary in asp.net mvc to hold validation errors and pass then back to the user. Being able to check if the whole model is valid with ModelState.IsValid is particularly. However, a current application I'm working on has a need to be able to report warnings. These aren't as critical so the form content can still be saved, but they should be shown to the user so that action can be optionally taken.
I've been looking through the framework to see if there are any obvious place to extend it to allow me to do this. I'm thinking that another dictionary with warnings in and a subclass of model error called model warning. I'm not sure how I'd get the framework to use my new container classes in the view etc. though, I still want all of the existing error stuff to work.
If anyone has tried anything similar or has any thoughts I'd appreciate their input.
Update:
I've got as far as extending the ViewDataDictionary to add some warnings
```
public class AetherViewDataDictionary : ViewDataDictionary
{
public AetherViewDataDictionary()
{
ModelStateWarning = new ModelStateDictionary();
}
public AetherViewDataDictionary(object model) : base(model)
{
ModelStateWarning = new ModelStateDictionary();
}
public AetherViewDataDictionary(ViewDataDictionary viewDataDictionary) : base(viewDataDictionary)
{
ModelStateWarning = new ModelStateDictionary();
}
public ModelStateDictionary ModelStateWarning { get; private set; }
}
```
The problem that I'm having now is that when I get to my view code, this is just for debug I'm losing the fact that its my new type, so when I try to cast it back and get access to my new dictionary I have no joy.
```
public partial class Index : ViewPage<PageViewData>
{
protected override void SetViewData(ViewDataDictionary viewData)
{
base.SetViewData(viewData);
}
}
```
It sets it correctly here, but when I check the type its gone.
Edit:
This turned out to be a dumb way of doing things, see answer below. | So the route that I was headed down before turned out to be a bad idea, there just isn't enough access in the framework to get at the bits that you need. At least not without reinventing the wheel a few times.
I decided to head down the route of extending the ModelState class to add a warnings collection to it:
```
public class AetherModelState : ModelState
{
public AetherModelState() { }
public AetherModelState(ModelState state)
{
this.AttemptedValue = state.AttemptedValue;
foreach (var error in state.Errors)
this.Errors.Add(error);
}
private ModelErrorCollection _warnings = new ModelErrorCollection();
public ModelErrorCollection Warnings { get { return this._warnings; } }
}
```
In order to be able to easily add warnings in the same way that you would errors I created some extension methods for the ModelStateDictionary:
```
public static class ModelStateDictionaryExtensions
{
public static void AddModelWarning(this ModelStateDictionary msd, string key, Exception exception)
{
GetModelStateForKey(key, msd).Warnings.Add(exception);
}
public static void AddModelWarning(this ModelStateDictionary msd, string key, string errorMessage)
{
GetModelStateForKey(key, msd).Warnings.Add(errorMessage);
}
private static AetherModelState GetModelStateForKey(string key, ModelStateDictionary msd)
{
ModelState state;
if (string.IsNullOrEmpty(key))
throw new ArgumentException("key");
if (!msd.TryGetValue(key, out state))
{
msd[key] = state = new AetherModelState();
}
if (!(state is AetherModelState))
{
msd.Remove(key);
msd[key] = state = new AetherModelState(state);
}
return state as AetherModelState;
}
public static bool HasWarnings(this ModelStateDictionary msd)
{
return msd.Values.Any<ModelState>(delegate(ModelState modelState)
{
var aState = modelState as AetherModelState;
if (aState == null) return true;
return (aState.Warnings.Count == 0);
});
}
}
```
The GetModelStateForKey code is ropey but you should be able to see where I'm headed with this. The next thing to do is to write some extension methods that allow me to display the warnings along with the errors | Why not simply add a list of warnings, or a dictionary, to the ViewData and then display them in your view?
e.g.
```
ViewData[ "warnings" ] = new[] { "You need to snarfle your aardvark" } ;
``` | Model Warnings in ASP.NET MVC | [
"",
"c#",
"asp.net-mvc",
"model",
""
] |
Does any one know of a control that i can use with a ASP.Net gridview that provides the functionality of the ASP.Net Ajax Control PagingBulletedList. I want to provide the users with a easier way to access the data in the grid.
It should ideally work in the same way paging for the grid works except that it should show all the data for the selected option i.e. if the letter a is selected all items that begin with a are shown to the user.
I would prefer not to have to re develop something like this as i am sure it exists, i just have no idea what would you call it.
Thanks in advance. | Unfortunatly there is nothing already buildt for this. To build your own you will have to create your own [PagerTemplate](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.pagertemplate.aspx).
There is something similiar with code in it in this [tutorial](http://www.highoncoding.com/Articles/209_GridView%20Alphabet%20Paging.aspx). This tutorial migh help you well to achieve what you require. I would have done it differently with PagerTemplate instead of GridView Footer as show.
So basically to create the paging bar it would have give :
```
<asp:UpdatePanel runat="server" ID="UpdatePanel">
<asp:GridView runat="server" ID="GridView">
<PagerTemplate>
<asp:LinkButton runat="server" Text="A" Command="A" />
-
<asp:LinkButton runat="server" Text="B" Command="B" />
-
<asp:LinkButton runat="server" Text="C" Command="C" />
-
<asp:LinkButton runat="server" Text="D" Command="D" />
-
<asp:LinkButton runat="server" Text="E" Command="E" />
<%-- Continue at will... --%>
</PagerTemplate>
</asp:GridView>
</asp:UpdatePanel>
```
Then you catch in the code behind the command and re create a new Datasource with only the data for the letter you need. You have to understand that GridView is bind to a Datasource that can't be manipulated. So when you initially show it, the datasource provider will only send the data with letter A. When you will click F then you will request you data provider to retreive only the information with Letter F and reassign the data to gridview : GridView.Datasource = mynewdata
Hope this helps | it's ugly, but just have a paged datagrid, with a single cell that has a separate ul/li .. they'll line up together, and give you the functionality you want. Otherwise you may have to roll your own. | ASP.Net PagingBulletedList Extender For ASP.Net GridView | [
"",
"c#",
"asp.net",
""
] |
I've often seen people use Perl data structures in lieu of configuration files; i.e. a lone file containing only:
```
%config = (
'color' => 'red',
'numbers' => [5, 8],
qr/^spam/ => 'eggs'
);
```
What's the best way to convert the contents of these files into Python-equivalent data structures, using pure Python? For the time being we can assume that there are no real expressions to evaluate, only structured data. | Not sure what the use case is. Here's my assumption: you're going to do a one-time conversion from Perl to Python.
Perl has this
```
%config = (
'color' => 'red',
'numbers' => [5, 8],
qr/^spam/ => 'eggs'
);
```
In Python, it would be
```
config = {
'color' : 'red',
'numbers' : [5, 8],
re.compile( "^spam" ) : 'eggs'
}
```
So, I'm guessing it's a bunch of RE's to replace
* `%variable = (` with `variable = {`
* `);` with `}`
* `variable => value` with `variable : value`
* `qr/.../ =>` with `re.compile( r"..." ) : value`
However, Python's built-in `dict` doesn't do anything unusual with a regex as a hash key. For that, you'd have to write your own subclass of `dict`, and override `__getitem__` to check REGEX keys separately.
```
class PerlLikeDict( dict ):
pattern_type= type(re.compile(""))
def __getitem__( self, key ):
if key in self:
return super( PerlLikeDict, self ).__getitem__( key )
for k in self:
if type(k) == self.pattern_type:
if k.match(key):
return self[k]
raise KeyError( "key %r not found" % ( key, ) )
```
Here's the example of using a Perl-like dict.
```
>>> pat= re.compile( "hi" )
>>> a = { pat : 'eggs' } # native dict, no features.
>>> x=PerlLikeDict( a )
>>> x['b']= 'c'
>>> x
{<_sre.SRE_Pattern object at 0x75250>: 'eggs', 'b': 'c'}
>>> x['b']
'c'
>>> x['ji']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 10, in __getitem__
KeyError: "key 'ji' not found"
>>> x['hi']
'eggs'
``` | Is using pure Python a requirement? If not, you can load it in Perl and convert it to YAML or JSON. Then use PyYAML or something similar to load them in Python. | How can I read Perl data structures from Python? | [
"",
"python",
"perl",
"configuration",
"data-structures",
""
] |
I would like to build a regexp in Java that would be passed in a FilenameFilter to filter the files in a dir.
The problem is that I can't get the hang of the regexp "mind model" :)
This is the regexp that I came up with to select the files that I would like to exclude
((ABC|XYZ))+\w\*Test.xml
What I would like to do is to select all the files that end with Test.xml but do not start with ABC or XYZ.
Could you please add any resources that could help me in my battle with regexps.
Thanks
The following resource explains a lot of things about regexp [regular-expressions.info](http://www.regular-expressions.info/refadv.html) | > What I would like to do is to select
> all the files that end with `Test.xml`
> but do not start with `ABC` or `XYZ`.
Either you match all your files with this regex:
```
^(?:(?:...)(?<!ABC|XYZ).*?)?Test\.xml$
```
or you do the opposite, and take every file that does *not* match:
```
^(?:ABC|XYZ).*?Test\.xml$
```
Personally, I find the second alternative much simpler.
```
ABC_foo_Test.xml // #2 matches
XYZ_foo_Test.xml // #2 matches
ABCTest.xml // #2 matches
XYZTest.xml // #2 matches
DEF_foo_Test.xml // #1 matches
DEFTest.xml // #1 matches
Test.xml // #1 matches
``` | This stuff is easier, faster and more readable without regexes.
```
if (str.endsWith("Test.xml") && !str.startsWith("ABC"))
``` | Java regexp for file filtering | [
"",
"java",
"regex",
""
] |
I've got the following two tables (in MySQL):
```
Phone_book
+----+------+--------------+
| id | name | phone_number |
+----+------+--------------+
| 1 | John | 111111111111 |
+----+------+--------------+
| 2 | Jane | 222222222222 |
+----+------+--------------+
Call
+----+------+--------------+
| id | date | phone_number |
+----+------+--------------+
| 1 | 0945 | 111111111111 |
+----+------+--------------+
| 2 | 0950 | 222222222222 |
+----+------+--------------+
| 3 | 1045 | 333333333333 |
+----+------+--------------+
```
How do I find out which calls were made by people whose `phone_number` is not in the `Phone_book`? The desired output would be:
```
Call
+----+------+--------------+
| id | date | phone_number |
+----+------+--------------+
| 3 | 1045 | 333333333333 |
+----+------+--------------+
``` | There's several different ways of doing this, with varying efficiency, depending on how good your query optimiser is, and the relative size of your two tables:
This is the shortest statement, and may be quickest if your phone book is very short:
```
SELECT *
FROM Call
WHERE phone_number NOT IN (SELECT phone_number FROM Phone_book)
```
alternatively (thanks to [Alterlife](https://stackoverflow.com/users/36848/alterlife))
```
SELECT *
FROM Call
WHERE NOT EXISTS
(SELECT *
FROM Phone_book
WHERE Phone_book.phone_number = Call.phone_number)
```
or (thanks to WOPR)
```
SELECT *
FROM Call
LEFT OUTER JOIN Phone_Book
ON (Call.phone_number = Phone_book.phone_number)
WHERE Phone_book.phone_number IS NULL
```
(ignoring that, as others have said, it's normally best to select just the columns you want, not '`*`') | ```
SELECT Call.ID, Call.date, Call.phone_number
FROM Call
LEFT OUTER JOIN Phone_Book
ON (Call.phone_number=Phone_book.phone_number)
WHERE Phone_book.phone_number IS NULL
```
Should remove the subquery, allowing the query optimiser to work its magic.
Also, avoid "SELECT \*" because it can break your code if someone alters the underlying tables or views (and it's inefficient). | Find records from one table which don't exist in another | [
"",
"sql",
"mysql",
""
] |
Not that I'm trying to prevent 'View Source' or anything silly like that, but I'm making some custom context menus for certain elements.
EDIT: response to answers: I've tried this:
```
<a id="moo" href=''> </a>
<script type="text/javascript">
var moo = document.getElementById('moo');
function handler(event) {
event = event || window.event;
if (event.stopPropagation)
event.stopPropagation();
event.cancelBubble = true;
return false;
}
moo.innerHTML = 'right-click here';
moo.onclick = handler;
moo.onmousedown = handler;
moo.onmouseup = handler;
</script>
``` | Capture the `onContextMenu` event, and return false in the event handler.
You can also capture the click event and check which mouse button fired the event with `event.button`, in some browsers anyway. | If you don't care about alerting the user with a message every time they try to right click, try adding this to your body tag
```
<body oncontextmenu="return false;">
```
This will block all access to the context menu (not just from the right mouse button but from the keyboard as well)
However, there really is no point adding a right click disabler. Anyone with basic browser knowledge can view the source and extract the information they need. | How to disable right-click context-menu in JavaScript | [
"",
"javascript",
"contextmenu",
""
] |
Can anyone give me an idea how can we *show* or embed a YouTube video if we just have the URL or the Embed code? | You have to ask users to store the 11 character code from the youtube video.
For e.g. <http://www.youtube.com/watch?v=Ahg6qcgoay4>
The eleven character code is : Ahg6qcgoay4
You then take this code and place it in your database. Then wherever you want to place the youtube video in your page, load the character from the database and put the following code:-
e.g. for Ahg6qcgoay4 it will be :
```
<object width="425" height="350" data="http://www.youtube.com/v/Ahg6qcgoay4" type="application/x-shockwave-flash"><param name="src" value="http://www.youtube.com/v/Ahg6qcgoay4" /></object>
``` | Do not store the embed code in your database -- YouTube may change the embed code and URL parameters from time to time. For example the `<object>` embed code has been retired in favor of `<iframe>` embed code. You should parse out the video id from the URL/embed code (using regular expressions, URL parsing functions or HTML parser) and store it. Then display it using whatever mechanism currently offered by YouTube API.
A naive PHP example for extracting the video id is as follows:
```
<?php
preg_match(
'/[\\?\\&]v=([^\\?\\&]+)/',
'http://www.youtube.com/watch?v=OzHvVoUGTOM&feature=channel',
$matches
);
// $matches[1] should contain the youtube id
?>
```
I suggest that you look at these articles to figure out what to do with these ids:
* [Embed YouTube Videos, Playlists and More with IFrame Embeds](http://salman-w.blogspot.com/2012/07/youtube-iframe-embeds-video-playlist-and-html5.html)
To create your own YouTube video player:
* [YouTube Embedded Player Parameters](https://developers.google.com/youtube/player_parameters)
* [YouTube JavaScript Player API Reference](https://developers.google.com/youtube/js_api_reference) | How to embed YouTube videos in PHP? | [
"",
"php",
"html",
"video",
"youtube",
"youtube-api",
""
] |
```
public class CovariantTest {
public A getObj() {
return new A();
}
public static void main(String[] args) {
CovariantTest c = new SubCovariantTest();
System.out.println(c.getObj().x);
}
}
class SubCovariantTest extends CovariantTest {
public B getObj() {
return new B();
}
}
class A {
int x = 5;
}
class B extends A {
int x = 6;
}
```
The above code prints 5 when compiled and run. It uses the covariant return for the over-ridden method.
Why does it prints 5 instead of 6, as it executes the over ridden method getObj in class SubCovariantTest.
Can some one throw some light on this. Thanks. | This is because in Java member variables don't override, they *shadow* (unlike methods). Both A and B have a variable x. Since c is *declared* to be of type CovarientTest, the return of getObj() is implicitly an A, not B, so you get A's x, not B's x. | Java **doesn't override fields** (aka. attributes or member variables). Instead they [shadow over](http://leepoint.net/notes-java/data/variables/60shadow-variables.html) each other. If you run the program through the debugger, you'll find two `x` variables in any object that is of type `B`.
Here is an explanation on what is happening. The program first retrieves something that is implicitly of type `A` and then call for the `x` that is assumed to come from `A`. Even though it is clearly a subtype, in your example an object of type `B` is created through `SubCovariantTest`, it still assumes you return something in getObj() that is implicitly typed A. Since Java cannot override fields, the test will call `A.x` and not `B.x`.
```
CovariantTest c = new SubCovariantTest();
// c is assumed the type of CovariantTest as it is
// implicitly declared
System.out.println(c.getObj().x);
// In this method chain the following happens:
// c.getObj() will return object of type B
// BUT will assume it is an A
// c.getObj().x will return the x from A
// since in this context the compiler assumes
// it is an A and make the call to A.x
```
It seems like a mindboggling gotcha because methods are always overridden in Java (in comparison to C++ and C# in which they are not). You usually won't run into this problem because Java code convention tells you to never access fields directly. Instead make sure that fields are always accessed through *accessor methods*, i.e. *getters*:
```
class A {
private int x = 5;
public int getX() { // <-- This is a typical accessor method
return x;
}
}
class B extends A {
private int x = 6;
@override
public int getX() {
// will be called instead even though B is implied to be A
// @override is optional because methods in Java are always virtual
// thus are always overridden
return x;
}
}
```
Code to get this working is the following:
```
c.getObj().getX();
// Will now call getX() in B and return the x that is defined in B's context.
``` | Java Covariants | [
"",
"java",
""
] |
I have a numerical field called `category_id` in my table. I want to do something like this.
```
$ids=implode(',',$id_array);
$sql="SELECT * FROM myTbl WHERE IN(category_id,'$ids')";
```
Which should output something like:
```
SELECT * FROM myTbl WHERE IN(category_id,'1,2,3,4,5,6');
```
Is this possible and am I using the right syntax for this? Is there a better way to do this? | From where do you get the id array? If it's from the database you should consider doing it all there:
```
SELECT * FROM myTbl WHERE c_id IN (SELECT c_id FROM yourTable WHERE ...);
``` | Almost, but not quite - here is one way it could work
```
$ids="'".implode("','",$id_array)."'";
$sql="SELECT * FROM myTbl WHERE category_id IN($ids)";
```
Which should output something like:
```
SELECT * FROM myTbl WHERE category_id IN('1', '2', '3', '4', '5', '6');
```
Note that since the field is numeric, the quotes are unnecessary but it's a useful code idiom building lists of quoted strings. In your case you could simplify to
```
$ids=implode(',',$id_array);
```
*(I'm assuming the array isn't empty, the array elements are santized etc for clarity!)* | Best query syntax for nested tables? | [
"",
"sql",
"mysql",
""
] |
I'm trying to create proper header files which don't include too many other files to keep them clean and to speed up compile time.
I encountered two problems while doing this:
1. Forward declaration on base classes doesn't work.
```
class B;
class A : public B
{
// ...
}
```
2. Forward declaration on STD classes doesn't work.
```
namespace std
{
class string;
}
class A
{
string aStringToTest;
}
```
How do I solve these problems? | The first problem you can't solve.
The second problem is not anything to do with standard library classes. It's because you declare an instance of the class as a member of your own class.
Both problems are due to the requirement that the compiler must be able to find out the total size of a class from its definition.
However, the compiler can work out the size of a pointer to a class, even if it doesn't yet have the full definition of it. So a possible solution in such cases is to have a pointer (or reference) member in the consuming class.
Not much help in the base class case, because you won't get an 'is a' relationship.
Nor is it worth doing for something like `std::string`. Firstly, it's supposed to be a convenient wrapper around a character buffer, to save you from doing memory management on something so simple. If you then hold a pointer to it, just to avoid including the header, you're probably taking a good idea too far.
Secondly (as pointed out in a comment), `std::string` is a typedef to `std::basic_string<char>`. So you need to forward declare (and then use) that instead, by which time things are getting very obscure and hard to read, which is another kind of cost. Is it really worth it? | As answered before by Earwicker, you can not use forward declarations in any of those cases as the compiler needs to know the size of the class.
You can only use a forward declaration in a set of operations:
* declaring functions that take the forward declared class as parameters or returns it
* declaring member pointers or references to the forward declared class
* declaring static variables of the forward declared type in the class definition
You cannot use it to
* declare a member attribute of the given type (compiler requires size)
* define or create an object of the type or delete it
* call any static or member method of the class or access any member or static attribute
(did I forget any?)
Take into account that declaring an `auto_ptr` is not the same as declaring a raw pointer, since the `auto_ptr` instantiation will try to delete the pointer when it goes out of scope and deleting requires the complete declaration of the type. If you use an `auto_ptr` in to hold a forward declared type you will have to provide a destructor (even if empty) and define it after the full class declaration has been seen.
There are also some other subtleties. When you forward declare a class, you are telling the compiler that it will be a class. This means that it cannot be an `enum` or a `typedef` into another type. That is the problem you are getting when you try to forward declare `std::string`, as it is a typedef of a specific instantiation of a template:
```
typedef basic_string<char> string; // aproximate
```
To forward declare string you would need to forward declare the `basic_string` template and then create the `typedef`. The problem is that the standard does not state the number of parameters that `basic_string` template takes, it just states that if it takes more than one parameter, there rest of the parameters must have a default type so that the expression above compiles. This means that there is no standard way for forward declaring the template.
If, on the other hand you want to forward declare a non-standard template (non STL, that is) you can do it for as long as you do know the number of parameters:
```
template <typename T, typename U> class Test; // correct
//template <typename T> class Test; // incorrect even if U has a default type
template <typename T, typename U = int> class Test {
// ...
};
```
At the end, the advice that was given to you by Roddy: forward declare as much as you can, but assume that some things must be included. | Forward Declaration of a Base Class | [
"",
"c++",
"class",
"forward-declaration",
""
] |
> **Possible Duplicate:**
> [What static analysis tools are available for C#?](https://stackoverflow.com/questions/38635/what-static-analysis-tools-are-available-for-c)
Guys, I'm looking for an open source or free source code analysis tool for C#. The tool should be able to generate metrics from the source code such as cyclomatic complexity, number of lines, number of commented lines, SEI maintainability etc.
Does anyone know of any such tool? | There are many plugins for reflector (which is also free):
[Reflector Add-Ins](http://www.codeplex.com/reflectoraddins)
I believe the CodeMetrics plugin does what you need | NDepend will give you a vast number of stats for your code:
<http://codebetter.com/blogs/patricksmacchia/archive/2008/11/25/composing-code-metrics-values.aspx>
There is a free 'Trial' version which contains fewer features than the Professional product, but which is free to use for Open Source and Academic development. The Trial version on the download page gets updated with a new version before the previous one runs out:
<http://www.ndepend.com/NDependDownload.aspx> | Source code analysis tools for C# | [
"",
"c#",
""
] |
> Possible duplicate
> [Debug Visual Studio Release in .NET](https://stackoverflow.com/questions/90871/debug-vs-release-in-net)
What is the difference between Debug and Release in Visual Studio? | The most important thing is that in Debug mode there are no optimizations, while in Release mode there are optimizations. This is important because the compiler is very advanced and can do some pretty tricky low-level improving of your code. As a result some lines of your code might get left without any instructions at all, or some might get all mixed up. Step-by-step debugging would be impossible. Also, local variables are often optimized in mysterious ways, so Watches and QuickWatches often don't work because the variable is "optimized away". And there are multitudes of other optimizations too. Try debugging optimized .NET code sometime and you'll see.
Another key difference is that because of this the default Release settings don't bother with generating extensive debug symbol information. That's the .PDB file you might have noticed and it allows the debugger to figure out which assembly instructions corresspond to which line of code, etc. | "Debug" and "Release" are actually just two labels for a whole slew of settings that can affect your build and debugging.
In "Debug" mode you usually have the following:
* Program Debug Database files, which allow you to follow the execution of the program quite closely in the source during run-time.
* All optimizations turned off, which allows you to inspect the value of variables and trace into functions that might otherwise have been optimized away or in-lined
* A \_DEBUG preprocessor definition that allows you to write code that acts differently in debug mode compared to release, for example to instrument ASSERTs that should only be used while debugging
* Linking to libraries that have also been compiled with debugging options on, which are usually not deployed to actual customers (for reasons of size and security)
In "Release" mode optimizations are turned on (though there are multiple options available) and the \_DEBUG preprocessor definition is not defined. Usually you will still want to generate the PDB files though, because it's highly useful to be able to "debug" in release mode when things are running faster. | What is the difference between Debug and Release in Visual Studio? | [
"",
"c#",
".net",
"visual-studio",
""
] |
What are good online resources to learn Python, *quickly*, for some who can code decently in other languages?
edit: It'll help if you could explain why you think that resource is useful. | [Dive into python](http://diveintopython.net/toc/index.html)
I have gone over it in a weekend or so and it was enough to learn almost all the idioms of the language and get the feeling of what is "the Python way" :-) | Not sure if you already considered that, but [documentation at the official site](http://docs.python.org/3.0/) is very good. In particular, [Tutorial](http://docs.python.org/3.0/tutorial/index.html) lets you start quickly | Resources for moving to Python | [
"",
"python",
""
] |
Are Swing applications really used nowadays? I don't find a place where they are used. Is it okay to skip the AWT and Swing package (I learned a bit of the basics though)? | If you are writing for the web exclusively, you can probably skip Swing, but otherwise you're absolutely going to run into it. I've never worked on a non-trivial Java app without a Swing GUI.
Also, Swing is one of the better APIs to use. If you use most others, you are going to find them more difficult to use and/or platform incompatible. (If anyone reading this is aware of exceptions to this, please leave comments, I haven't looked for a while and am kind of curious if anything better has become available)
Other JVM languages like JRuby and Jython are often used because of their access to Swing. | You may checkout [Swing Sightings](http://java.sun.com/products/jfc/tsc/sightings/).
This website is hosted by SUN and it is dedicated to sw projects that use Swing.
There are a lot of projects using Swing ...
<http://java.sun.com/products/jfc/tsc/sightings/> | Where are Swing applications used? | [
"",
"java",
"swing",
""
] |
I’ve run into a limitation in the cURL bindings for PHP. It appears there is no easy way to send the same multiple values for the same key for postfields. Most of the workarounds I have come across for this have involved creating the URL encoded post fields by hand tag=foo&tag=bar&tag=baz) instead of using the associative array version of CURLOPT\_POSTFIELDS.
It seems like a pretty common thing to need to support so I feel like I must have missed something. Is this really the only way to handle multiple values for the same key?
While this workaround might be considered workable (if not really annoying), my main problem is that I need to be able to do multiple values for the same key and also support file upload. As far as I can tell, file upload more or less requires to use the associate arravy version of CURLOPT\_POSTFIELDS. So I feel like I am stuck.
I have [posted](http://curl.haxx.se/mail/curlphp-2008-12/0009.html) about this problem in more detail on the cURL PHP mailing list in the hopes that someone there has some ideas about this.
Suggestions or hints on where I can look for more information on this are greatly appreciated! | I ended up writing my own function to build a custom CURLOPT\_POSTFIELDS string with multipart/form-data. What a pain.
```
function curl_setopt_custom_postfields($ch, $postfields, $headers = null) {
// $postfields is an assoc array.
// Creates a boundary.
// Reads each postfields, detects which are @files, and which values are arrays
// and dumps them into a new array (not an assoc array) so each key can exist
// multiple times.
// Sets content-length, content-type and sets CURLOPT_POSTFIELDS with the
// generated body.
}
```
I was able to use this method like this:
```
curl_setopt_custom_postfields($ch, array(
'file' => '@/path/to/file',
'tag' => array('a', 'b', 'c'),
));
```
I am not certain of CURLOPT\_HTTPHEADER stacks, so since this method calls it, I made certain that the function would allow for the user to specify additonal headers if needed.
I have the full code available [in this blog post](http://not-invented-here.com/2009/01/01/multiple-values-for-the-same-key-and-file-uploads-using-curl-and-php-solution/). | If you use `tag[]` rather than `tag` for the name, [PHP will generate an array](http://www.php.net/manual/en/faq.html.php#faq.html.arrays) for you, in other words, rather than
```
tag=foo&tag=bar&tag=baz
```
You need
```
tag[]=foo&tag[]=bar&tag[]=baz
```
Note that when urlencoded for transmission this should become
```
tag%5B%5D=foo&tag%5B%5D=bar&tag%5B%5D=baz
``` | Mixing multiple values for the same key and file uploads using cURL and PHP | [
"",
"php",
"curl",
""
] |
I am trying to create an ActiveRecord object via a JSON request. However the controller fails to set the variables passed in the parameters in the newly created object. As an example, a person object has two fields: firstname and lastname.
The JSON generated by the JSON.stringify function of the JSON.org library produces:
```
{"firstname" : "Joe" , "lastname" : "Bloggs"}
```
However the controller expects the JSON to be in the form:
```
{ "Person" : {"firstname" : "Joe" , "lastname" : "Bloggs"} }
```
I am aware that in the normal course of events (for HTTP requests) the
parameters for the request are nested under the class name of the model
being created.
The create action in the controller is:
```
def create
@person = Person.new(params[:person])
respond_to do |format|
if @person.save
flash[:notice] = 'Person was successfully created.'
format.html { redirect_to(@person) }
format.xml { render :xml => @person, :status => :created, :location => @person }
format.json { render :json => @person, :status => :created, :location => @person }
else
format.html { render :action => "new" }
format.xml { render :xml => @person.errors, :status => :unprocessable_entity }
format.json { render :json => @person.errors, :status => :unprocessable_entity }
end
end
end
```
What would be the neatest way for the controller to process the JSON
requests as generated? Or alternatively how do you generate "correct"
JSON from Javascript objects for passing to your controllers?
TIA,
Adam | If you are just passing a hash of all of the person parameters (rather than a nested-hash with "person" as the key) then you should just be able to do `@person = Person.new(params)`. | As for ActiveRecord 3.0.7, you can just add
```
self.include_root_in_json = false
```
to your model (person.rb) to get rid from root ({ "Person" :") part. | Rails controller does not accept JSON? | [
"",
"javascript",
"ruby-on-rails",
"json",
""
] |
You can initialize an array like this:
```
int [ ] arr = { 1, 2, 3, 4, 5 };
```
but `List<T>` doesn't allow this:
```
List<int> list = { 1, 2, 3, 4, 5 };
```
What's the reason behind this?
After all both allow this:
```
int [ ] arr = new int [ ] { 1, 2, 3, 4, 5 };
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
```
Also why it's not possible to do this with a `LinkedList<T>`?:
```
LinkedList<int> ll = new LinkedList<int>() { 1, 2, 3 };
```
**Update**
Thanks guys. Just saw the replies. I wanted to pick several answers but it didn't let me so.
Why does the LinkedList has an Add method though explicit implementation? Will this likely be fixed? Because problems like this will just snowball into bigger ones when they are overlooked, right? | Your first sample is the standard language syntax for initializing an array of integers. The left-hand value evaluates to int[]. In the second sample you are attempting to assign an int[] to a List<int>. The assignment operator doesn't support this as they are different types. A List<int> is **not** an array of type int. As you say, though, there is a constructor for List<int> that does take an int[] as an argument and the new syntactic sugar added in C# 3.0 allows you the convenience of using { } to add members to the collection defined by the default constructor.
As @Patrik says, this won't work for LinkedList because it doesn't define the Add() method as part of its interface (there is an explicit implementation of ICollection.Add) so the syntactic sugar won't work.
There is an easy work-around for LinkedList, however.
```
public class LinkedListWithInit<T> : LinkedList<T>
{
public void Add( T item )
{
((ICollection<T>)this).Add(item);
}
}
LinkedList<int> list = new LinkedListWithInit<int> { 1, 2, 3, 4, 5 };
``` | Here is what the **C# 3.0 Language Spec** has to say on the subject:
> The following is an example of an
> object creation expression that
> includes a collection initializer:
>
> ```
> List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
> ```
>
> The collection object to which a
> collection initializer is applied must
> be of a type that implements
> System.Collections.IEnumerable or a
> compile-time error occurs. For each
> specified element in order, the
> collection initializer invokes an Add
> method on the target object with the
> expression list of the element
> initializer as argument list, applying
> normal overload resolution for each
> invocation. Thus, the collection
> object must contain an applicable Add
> method for each element initializer.
That makes sense when you think about it. The compiler makes sure you are working on an enumerable type that implements an Add function (through which it does the initialization). | Collection initialization | [
"",
"c#",
".net",
""
] |
I'm in a ASP.NET project where I need to give several parameters to the administrator that is going to install the website, like:
```
AllowUserToChangePanelLayout
AllowUserToDeleteCompany
```
etc...
My question is, will be a good thing to add this into the web.config file, using my own configSession or add as a profile varibles? or should I create a XML file for this?
What do you do and what are the cons and favs?
I originally thought about web.config but I then realized that I should mess up with Website configurations and my own web app configuration and that I should create a different file, them I read [this post](http://www.aspcode.net/Your-own-configuration-setting-section-in-webconfig.aspx) and now I'm on this place... should I do this or that? | I usually use Settings - available via the project properties - Settings. These can be edited and saved in code, and I write a form / web page to edit them.
If you want to use the XML configuration, there's an attribute called file that reads external files.
You could have a web.config file and a someothername.config file. The someothername.config would have settings like:
```
<appSettings>
<add key="ConnString" value="my conn string" />
<add key="MaxUsers" value="50" />
</appSettings>
```
And the web.config would have
```
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings file="ExternalWeb.config">
<add key="MyKey" value="MyValue" />
</appSettings>
</configuration>
```
See [DevX](http://www.devx.com/vb2themax/Tip/18880) for the example I stole. | just to let you guys know that I did what [configurator](https://stackoverflow.com/users/9536/configurator) recommended but with a twist.
instead of asking all the time (that I need) for
```
System.Configuration.ConfigurationManager.AppSettings["myKey"];
```
I just created a static class that would pull this values with what we call by Strongly typed values (so you don't need to remember all the values)
the **mySettings** class
```
public static class mySettings
{
public enum SettingsType
{ UserPermitions, WebService, Alerts }
public enum SectionType
{ AllowChangeLayout, AllowUserDelete, MaximumReturnsFromSearch, MaximumOnBatch, SendTo }
public static String GetSettings(SettingsType type, SectionType section)
{
return
ConfigurationManager.AppSettings[
String.Format("{0}_{1}",
Enum.Parse(typeof(SettingsType), type.ToString()).ToString(),
Enum.Parse(typeof(SectionType), section.ToString()).ToString())
];
}
}
```
the **web.config** appSettings part
```
<configuration>
<appSettings file="myApp.config">
<add key="UserPermitions_AllowChangeLayout" value="" />
<add key="UserPermitions_AllowUserDelete" value="" />
<add key="WebService_MaximumReturnsFromSearch" value="" />
<add key="Alerts_SendTo" value="" />
<add key="Alerts_MaximumOnBatch" value="" />
</appSettings>
</configuration>
```
the entire **myApp.config** file
```
<?xml version="1.0" encoding="utf-8" ?>
<!--
###
### This file serves the propose of a quick configuration.
### Administrator can either change this values directly or use the
### Settings tab in the application.
###
-->
<appSettings>
<!-- *** User Access Configuration *** -->
<!-- Allow user to change the panels layout {1: Yes} {0: No} -->
<add key="UserPermitions_AllowChangeLayout" value="1" />
<!-- Allow user to delete a company fro monitoring -->
<add key="UserPermitions_AllowUserDelete" value="1" />
<!-- *** Web Service configuration *** -->
<!-- Maximum responses from the search service -->
<add key="WebService_MaximumReturnsFromSearch" value="10" />
<!-- *** Allerts configuration *** -->
<!-- Send the alerts to the email writeen below -->
<add key="Alerts_SendTo" value="bruno.in.dk@gmail.com" />
<!-- Send an alert when user import more than the number bellow -->
<add key="Alerts_MaximumOnBatch" value="10" />
</appSettings>
```
So, now I call like this:
```
p.value = mySettings.GetSettings(
mySettings.SettingsType.WebService,
mySettings.SectionType.MaximumReturnsFromSearch);
```
Hope that helps someone with the same problem :) | create your own settings in xml | [
"",
"c#",
"asp.net",
"configuration-files",
""
] |
I have a web service that needs different settings for different environments (debug, test, prod). What's the easiest way to setup separate config files for these different environments? Everything I find on the web tells me how to use configuration manager to retrieve settings, but not how to find particular settings based on the current build configuration. | I find having several config files for each environment works well. ie:
* config\local.endpoints.xml
* config\ dev.endpoints.xml
* config\ test.endpoints.xml
* config\ staging.endpoints.xml
* config\ prod.endpoints.xml
I then link to a "master" version of this using the built in configSource attribute within the web.config or app.config such as
```
<appSettings configSource="config\endpoints.xml"/>
```
I would then use the build process or deploy process to copy the the correct configuration for the environment down to the name that the web.config is expecting.
Each environment is clearly labelled and controlled, without the need of messy placeholders. | One way would be to maintain 3 different configuration files and choose them via MSBuild when deploying.
```
<Choose>
<When Condition="$(BuildEnvironment) == 'debug'">
<PropertyGroup>
<ConfigFile>debug.config</ConfigFile>
</PropertyGroup>
</When>
<When Condition="$(BuildEnvironment) == 'test'">
<PropertyGroup>
<ConfigFile>test.config</ConfigFile>
</PropertyGroup>
</When>
<When Condition="$(BuildEnvironment) == 'prod'">
<PropertyGroup>
<ConfigFile>prod.config</ConfigFile>
</PropertyGroup>
</When>
</Choose>
```
By utilizing an MSBuild task you can rename and push the specific configuration file to the proper location.
Still somewhat cumbersome, this has the added advantage of moving towards a [one step build](http://www.joelonsoftware.com/articles/fog0000000043.html). | How do you set up solution configuration specific config files? | [
"",
"c#",
"visual-studio",
"web-services",
""
] |
What's the simplest, most standard, and/or most efficient way to split a List into two sub-Lists in Java? It's OK to mutate the original List, so no copying should be necessary. The method signature could be
```
/** Split a list into two sublists. The original list will be modified to
* have size i and will contain exactly the same elements at indices 0
* through i-1 as it had originally; the returned list will have size
* len-i (where len is the size of the original list before the call)
* and will have the same elements at indices 0 through len-(i+1) as
* the original list had at indices i through len-1.
*/
<T> List<T> split(List<T> list, int i);
```
[EDIT] `List.subList` returns a view on the original list, which becomes invalid if the original is modified. So `split` can't use `subList` unless it also dispenses with the original reference (or, as in Marc Novakowski's answer, uses `subList` but immediately copies the result). | Quick semi-pseudo code:
```
List sub=one.subList(...);
List two=new XxxList(sub);
sub.clear(); // since sub is backed by one, this removes all sub-list items from one
```
That uses standard List implementation methods and avoids all the running around in loops. The clear() method is also going to use the internal `removeRange()` for most lists and be much more efficient. | You can use common utilities, like Guava library:
```
import com.google.common.collect.Lists;
import com.google.common.math.IntMath;
import java.math.RoundingMode;
int partitionSize = IntMath.divide(list.size(), 2, RoundingMode.UP);
List<List<T>> partitions = Lists.partition(list, partitionSize);
```
The result is a list of two lists - not quite by your spec, but you can easily adapt, if needed. | Java: split a List into two sub-Lists? | [
"",
"java",
"list",
""
] |
I have a large-ish Oracle table containing rows representing units of work, with columns for start time and end time in addition to other meta-data.
I need to generate usage graphs from this data, given some arbitrary filtering criteria and a reporting time period. E.g., show me a graph of all of Alice's jobs for the 24-hour period starting last Tuesday at 7:00am. Each DB row will stack vertically in the graph.
I could do this in a high-level language by querying all potentially relevant rows, time slicing each one into 1-minute buckets, and graphing the result. But is there an efficient way to do this time slicing in SQL? Or is there an existing Oracle technology that does this?
Thanks! | In terms of getting the data out, you can use 'group by' and '[truncate](http://www.techonthenet.com/oracle/functions/trunc_date.php)' to slice the data into 1 minute intervals. eg:
```
SELECT user_name, truncate(event_time, 'YYYYMMDD HH24MI'), count(*)
FROM job_table
WHERE event_time > TO_DATE( some start date time)
AND user_name IN ( list of users to query )
GROUP BY user_name, truncate(event_time, 'YYYYMMDD HH24MI')
```
This will give you results like below (assuming there are 20 rows for alice between 8.00 and 8.01 and 40 rows between 8.01 and 8.02):
```
Alice 2008-12-16 08:00 20
Alice 2008-12-16 08:01 40
``` | Your best bet is to have a table (a temporary one generated on the fly would be fine if the time-slice is dynamic) and then join against that. | Time slicing in Oracle/SQL | [
"",
"sql",
"oracle",
"optimization",
"reporting",
"graphing",
""
] |
By default the BinaryWriter class writes int values with the low bits on the left (e.g. (int)6 becomes 06 00 00 00 when the resulting file is viewed in a hex editor). I need the low bits on the right (e.g. 00 00 00 06).
How do I achieve this?
EDIT: Thanks strager for giving me the name for what I was looking for. I've edited the title and tags to make it easier to find. | Jon Skeet has an EndianBitConverter [here](http://www.pobox.com/~skeet/csharp/miscutil/) that should do the job. Just use big/little endian as desired. Alternatively, just shift the data a few times ;-p
```
int i = 6;
byte[] raw = new byte[4] {
(byte)(i >> 24), (byte)(i >> 16),
(byte)(i >> 8), (byte)(i)};
``` | Not really a built in way but you can use this: [EndianBit\*](http://www.yoda.arachsys.com/csharp/miscutil/). Thanks to Jon Skeet :P | How do I write ints out to a text file with the low bits on the right side (Bigendian) | [
"",
"c#",
"endianness",
""
] |
I understand that the @ symbol can be used before a string literal to change how the compiler parses the string. But what does it mean when a variable name is prefixed with the @ symbol? | The @ symbol allows you to use reserved word. For example:
```
int @class = 15;
```
The above works, when the below wouldn't:
```
int class = 15;
``` | The @ symbol serves 2 purposes in C#:
Firstly, it allows you to use a reserved keyword as a variable like this:
```
int @int = 15;
```
The second option lets you specify a string without having to escape any characters. For instance the '\' character is an escape character so typically you would need to do this:
```
var myString = "c:\\myfolder\\myfile.txt"
```
alternatively you can do this:
```
var myString = @"c:\myFolder\myfile.txt"
``` | What does the @ symbol before a variable name mean in C#? | [
"",
"c#",
"variables",
"naming",
"specifications",
"reserved-words",
""
] |
My Java UI unexpectly terminated and dumped an `hs_err_pid` file. The file says "The crash happened outside the Java Virtual Machine in native code." JNA is the only native code we use. Does anyone know of any know issues or bugs with any JNA version that might cause this. I've included some of the contents from the error file below.
```
An unexpected error has been detected by Java Runtime Environment:
EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x6d02bcbd, pid=312, tid=3616
Java VM: Java HotSpot(TM) Client VM (11.0-b16 mixed mode, sharing windows-x86)<br>
Problematic frame:
C [awt.dll+0x2bcbd]
If you would like to submit a bug report, please visit:
http://java.sun.com/webapps/bugreport/crash.jsp
The crash happened outside the Java Virtual Machine in native code.
See problematic frame for where to report the bug.
Current thread (0x02acf000): JavaThread "AWT-Windows" daemon [_thread_in_native, id=3616, stack(0x02eb0000,0x02f00000)]
siginfo: ExceptionCode=0xc0000005, writing address 0xe2789280
Registers:
EAX=0x234f099c, EBX=0x00001400, ECX=0x00000100, EDX=0xe2789280
ESP=0x02eff4a4, EBP=0x00000400, ESI=0x234f099c, EDI=0xe2789280
EIP=0x6d02bcbd, EFLAGS=0x00010206
Top of Stack: (sp=0x02eff4a4)
0x02eff4a4: 02eff500 00000100 02eff584 00000100
0x02eff4b4: 6d0a5697 00000400 00000400 00000100
0x02eff4c4: 00000100 02eff700 02eff500 00000000
0x02eff4d4: 00000000 00000100 041ac3a0 00000100
0x02eff4e4: 00182620 00000400 e2789280 00000000
0x02eff4f4: 00000000 00000100 00000100 00000000
0x02eff504: 00000000 00000100 00000100 00000000
0x02eff514: 00000000 00000004 00000400 00000000
Instructions: (pc=0x6d02bcbd)
0x6d02bcad: 00 00 00 8b 4c 24 14 8b e9 c1 e9 02 8b f0 8b fa
0x6d02bcbd: f3 a5 8b cd 83 e1 03 f3 a4 8b 74 24 18 8b 4c 24
Stack: [0x02eb0000,0x02f00000], sp=0x02eff4a4, free space=317k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C [awt.dll+0x2bcbd]
[error occurred during error reporting (printing native stack), id 0xc0000005]
Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j sun.awt.windows.WToolkit.eventLoop()V+0
j sun.awt.windows.WToolkit.run()V+69
j java.lang.Thread.run()V+11
v ~StubRoutines::call_stub
``` | I just hit that very same bug, it's apppearantly a bug in the new Direct3d accelerated Java2d functionality with 1.6.0\_11 that happens with machines with low video ram.
If you start your app with -Dsun.java2d.d3d=false it should work again.
The sun bug tracking this is the following: <https://bugs.java.com/bugdatabase/view_bug?bug_id=6788497> | Just because the only bit of native code you knowingly use is JNI/whatever doesn't mean a crash like yours is related to it in location or in time. There's all sorts of native support used silently in any given JVM/execution, and I was at one time getting bizarre crashes caused in the end by corruption that had happened much earlier and by the JVM itself.
In my case I was finding exciting bugs in the threading of concurrent GC on my shiny new multi-CPU (Niagara) box, that was leaving all sorts of bombs waiting to go off, and I had *no* non-JDK native code in my app at all.
When Sun's GC team fixed their bug (and very kindly supplied me with a test bootleg VM) my issues evaporated (well, after a round or two, natch).
Rgds
Damon | JNA causing EXCEPTION_ACCESS_VIOLATION? | [
"",
"java",
"java-native-interface",
"awt",
"jna",
""
] |
I have an application that I'm trying to debug a crash in. However, it is difficult to detect the problem for a few reasons:
* The crash happens at shutdown, meaning the offending code isn't on the stack
* The crash only happens in release builds, meaning symbols aren't available
By crash, I mean the following exception:
```
0xC0000005: Access violation reading location 0x00000000.
```
**What strategy would you use to diagnose this problem?**
What I have done so far is remove as much code from my program until I get the bare minimum that will cause the crash. It seems to be happening in code that is statically linked to the project, so that doesn't help, either. | You can make the symbol files even for the release build. Do that, run your program, attach the debugger, close it, and see the cause of the crash in the debugger. | You seem to have something reading a null pointer - never good.
I'm not sure what platform you are on. Under Linux, you could consider using `valgrind`.
What is different about your release builds from your debug builds apart from the presence or absence of the debug information?
Can you built the statically linked code with debugging information in it? Can you obtain a debug build of the statically linked code? | How to diagnose Access Violation on application exit | [
"",
"c++",
"wtl",
""
] |
I'm trying to use a dll, namely libcurl, with my program, but, it's not linking. Libcurl comes with .h files that I can include (takes care of dllimport), but then I guess I must specify which dll to actually use when linking somehow... How do I do that? I'm compiling with Borland C++ builder, but I really want to know how these things work in general...
EDIT:
This is the code (straight c/p from curl homepage)
```
bool FTPGetFile::ConnectToFTP(string ftpServer){
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "curl.haxx.se");
res = curl_easy_perform(curl);
return true;
}else{
return false;
}
}
```
And here are the errors:
```
[Linker Error] Error: Unresolved external '_curl_easy_init' referenced from C:\PROJECTS\PC\TOOLBOX\DEBUG_BUILD\FTPGETFILE.OBJ
[Linker Error] Error: Unresolved external '_curl_easy_setopt' referenced from C:\PROJECTS\PC\TOOLBOX\DEBUG_BUILD\FTPGETFILE.OBJ
[Linker Error] Error: Unresolved external '_curl_easy_perform' referenced from C:\PROJECTS\PC\TOOLBOX\DEBUG_BUILD\FTPGETFILE.OBJ
```
EDIT 2: As per suggestion from joe\_muc I have made the lib files with the implib tool and included them in the linker path. I still get the same errors. | As mentioned, you will need the static .lib file that goes with the .dll which you run
through implib and add the result lib file to your project.
If you have done that then:
* You may need to use the stdcall calling convention.
You didn't mention which version of Builder you are using, but
it is usually under Project options - Advanced compiler - Calling convention.
* You may need to enable MFC compatibility option.
* It could be a name mangling issue (Project options - C++ compatiblity options).
* Or generation underscores
* Or advanced linker options "Case\_insensitive-link" on or off
libcurl appears to be C code; but if it is C++, note that Microsoft and Borland classes are generally not compatible. There are supposed to be tricks to get them to work, but it is a real mess to deal with and I have never had success. C coded DLLs should work. | There should be a program called IMPLIB.EXE in the bin or app directory for builder. Run that against the dll to create a .lib file.
[IMPLIB.EXE, the Import Library Tool for Win32](https://docwiki.embarcadero.com/RADStudio/Alexandria/en/IMPLIB.EXE,_the_Import_Library_Tool_for_Win32) | Use a dll from a c++ program. (borland c++ builder and in general) | [
"",
"c++",
"dll",
"c++builder",
"dllimport",
""
] |
I hope it is correct term-wise to say that components in a GUI is like JButton, JPanel, JTextField, all that good stuff.
I want to create a text field that takes in an integer. Then a submit button can be pressed and based on the integer that was inputted, create that many textfields in a popup window or whatever.
I have no clue, could someone get me started in the right direction?
The trouble I'm having is that I have no clue how to create a for loop to create the GUI components. I mean if I have a for loop and do something like:
```
print("JTextField num1 = new JTextField()");
```
then in a for loop it will only create 1 text field when I want many. How do I generically create variables of JTextFields?
Thanks for your help... | Use an appropriate LayoutManager (e.g. GridLayout) to create and add your textfields.
```
for (i = 0; i < numberOfTextFields; i++) {
JTextField textField = new JTextField();
container.add(textField);
/* also store textField somewhere else. */
}
``` | Try something like this:
```
List<JTextField> nums = new ArrayList<JTextField>();
JTextField tempField;
for (int i = 0; i < 10; i++) {
tempField = new JTextField();
jPanel1.add(tempField); // Assuming all JTextFields are on a JPanel
nums.add(tempField);
}
```
Don't forget to set a proper layout manager for the container. (jPanel1 in this case) | Java GUI Creating Components | [
"",
"java",
"user-interface",
"jbutton",
"jtextfield",
""
] |
What C++ HTTP frameworks are available that will help in adding HTTP/SOAP serving support to an application? | Well, gSOAP of course. :)
<http://www.cs.fsu.edu/~engelen/soap.html> | You could also look at:
<http://pocoproject.org/> | What C++ HTTP frameworks are available? | [
"",
"c++",
"frameworks",
""
] |
I have a .NET assembly which I have exposed to COM via a tlb file, and an installer which registers the tlb. I have manually checked that the installer works correctly and that COM clients can access the library. So far, so good...
However, I am trying to put together some automated system tests which check that the installer is working correctly. As part of that I have automated the installation on a VM, and I now want to make some calls to the installed COM library to verify that it is working correctly. I originally thought about writing some tests in VB6, but I already have a large suite of tests written in C#, which reference the .NET assembly. I was hoping that I could change these to reference the .tlb, but I get an error when I try this within VS2008:
The ActiveX type library 'blah.tlb' was exported from a .NET assembly and cannot be added as a reference.
Is there any way I can fool VS2008 into allowing me to add this reference, perhaps by editing the tlb file?
Googling hasn't come up with any solutions. All I've found is a Microsoft Connect article stating that this is "By Design": <http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=120882> | The Closest I've gotten to a solution is something like the following:
```
using System;
class ComClass
{
public bool CallFunction(arg1, arg2)
{
Type ComType;
object ComObject;
ComType = Type.GetTypeFromProgID("Registered.ComClass");
// Create an instance of your COM Registered Object.
ComObject = Activator.CreateInstance(ComType);
object[] args = new object[2];
args[0] = arg1;
args[1] = arg2;
// Call the Method and cast return to whatever it should be.
return (bool)ComType.InvokeMember("MethodToCall", BindingFlags.InvokeMethod, null, ComObject, args))
}
}
```
It's not very pretty, but I think gets the point across. You could of course put the ComObject instantiation into a constructor and wrap the rest of the calls to the object, but probably not necessary for test code. | You should be able to create a wrapper class to your installed COM component using TLBImp then run your tests against that. You'll basically be writing a .Net assembly, installing that to COM then testing against the wrapper class so your tests will be routed as if it was called by a COM component | Is it possible to test a COM-exposed assembly from .NET? | [
"",
"c#",
"visual-studio",
"com",
"interop",
"com-interop",
""
] |
I have a single spool mbox file that was created with evolution, containing a selection of emails that I wish to print. My problem is that the emails are not placed into the mbox file chronologically. I would like to know the best way to place order the files from first to last using bash, perl or python. I would like to oder by received for files addressed to me, and sent for files sent by me. Would it perhaps be easier to use maildir files or such?
The emails currently exist in the format:
```
From x@blah.com Fri Aug 12 09:34:09 2005
Message-ID: <42FBEE81.9090701@blah.com>
Date: Fri, 12 Aug 2005 09:34:09 +0900
From: me <x@blah.com>
User-Agent: Mozilla Thunderbird 1.0.6 (Windows/20050716)
X-Accept-Language: en-us, en
MIME-Version: 1.0
To: someone <someone@hotmail.com>
Subject: Re: (no subject)
References: <BAY101-F9353854000A4758A7E2CCA9BD0@phx.gbl>
In-Reply-To: <BAY101-F9353854000A4758A7E2CCA9BD0@phx.gbl>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 8bit
Status: RO
X-Status:
X-Keywords:
X-UID: 371
X-Evolution-Source: imap://x+blah.com@blah.com/
X-Evolution: 00000002-0010
Hey
the actual content of the email
someone wrote:
> lines of quotedtext
```
I am wondering if there is a way to use this information to easily reorganize the file, perhaps with perl or such. | This is how you could do it in python:
```
#!/usr/bin/python2.5
from email.utils import parsedate
import mailbox
def extract_date(email):
date = email.get('Date')
return parsedate(date)
the_mailbox = mailbox.mbox('/path/to/mbox')
sorted_mails = sorted(the_mailbox, key=extract_date)
the_mailbox.update(enumerate(sorted_mails))
the_mailbox.flush()
``` | Python solution wont work if mail messages was imported into mbox using Thunderbird's ImportExportTools addon.
There are a bug: messages shall prefix with 'from' line in format:
```
From - Tue Apr 27 19:42:22 2010
```
but ImportExportTools prefix with such 'from' line:
```
From - Sat May 01 2010 15:07:31 GMT+0400 (Russian Daylight Time)
```
So there are two errors:
1. sequence 'time year' broken into
'year time'
2. extra trash with GMT
info along with time zone name
Since Python's mailbox.py/UnixMailbox has hardcoded regexp for 'from' line matching, some of messages can't parsed.
I wrote the error message to the author, but there are many mistakenly imported messages :(. | How can I reorder an mbox file chronologically? | [
"",
"python",
"email",
"sorting",
"mbox",
""
] |
I'm aiming to create a set of objects, each of which has a unique identifier. If an object already exists with that identifier, I want to use the existing object. Otherwise I want to create a new one. I'm trying not to use the word Singleton, because I know it's a dirty word here...
I can use a factory method:
```
// A map of existing nodes, for getInstance.
private static Map<String, MyClass> directory = new HashMap<String, MyClass>();
public static MyClass getInstance(String name) {
MyClass node = directory.get(name);
if(node == null) {
node == new MyClass(name);
}
return node;
}
```
Or equally, I could have a separate MyClassFactory method.
But I had intended to subclass MyClass:
```
public class MySubClass extends MyClass;
```
If I do no more, and invoke MySubClass.getInstance():
```
MyClass subclassObj = MySubClass.getInstance("new name");
```
... then subclassObj will be a plain MyClass, not a MySubClass.
Yet overriding getInstance() in every subclass seems hacky.
Is there a neat solution I'm missing?
---
That's the generalised version of the question. More specifics, since the answerers asked for them.
The program is for generating a directed graph of dependencies between nodes representing pieces of software. Subclasses include Java programs, Web Services, Stored SQL procedures, message-driven triggers, etc.
So each class "is-a" element in this network, and has methods to navigate and modify dependency relationships with other nodes. The difference between the subclasses will be the implementation of the `populate()` method used to set up the object from the appropriate source.
Let's say the node named 'login.java' learns that it has a dependency on 'checkpasswd.sqlpl':
```
this.addDependency( NodeFactory.getInstance("checkpasswd.sqlpl"));
```
The issue is that the checkpasswd.sqlpl object may or may not already exist at this time. | The static method is defined on the parent class, and it's called statically as well. So, there's no way of knowing in the method that you've called it on the subclass. The java compiler probably even resolves the call statically to a call to the parent class.
So you will need to either reimplement the static method in your child classes as you propose, or make them not static so you can inheritance (on a hierarchy of factory **objects**, not classes), or pass a parameter to signify the type you want to create.
Check out the EnumSet.noneOf() method. It has a similar issue as you do, and it solves it by passing the java.lang.Class method. You could use newInstance on the class. But personally, I'd just use factory objects rather than classes with static methods. | Have you looked into Guice? Not sure if it would solve your problem exactly, but it acts as a generic factory and dependency injection container, and eliminates non-type safe String keys. | Polymorphic factory / getInstance() in Java | [
"",
"java",
"design-patterns",
"polymorphism",
"factory",
""
] |
I'm trying to make a graph in Rails, for example the avg sales amount per day for each day in a given date range
Say I have a products\_sold model which has a "sales\_price" float attribute. But if a specific day has no sales (e.g none in the model/db), I want to return simply 0.
What's the best way in MySQL/Rails to get this done? I know I can do something like this:
(*This SQL query might be the completely wrong way to get what I'm wanting too*)
```
SELECT avg(sales_price) AS avg, DATE_FORMAT(created_at, '%m-%d-%Y') AS date
FROM products_sold WHERE merchant_id = 1 GROUP BY date;
```
And get results like this:
```
| avg | date |
23 01-03-2009
50 01-05-2009
34 01-07-2009
... ...
```
What I'd like to get is this:
```
| avg | date |
23 01-03-2009
0 01-04-2009
50 01-05-2009
0 01-06-2009
34 01-07-2009
0 01-08-2009
... ...
```
Can I do this with SQL or will I have to post-process the results to find what dates in the daterange aren't in the SQL result set? Perhaps I need some sub-selects or IF statements?
Thanks for any help everyone. | Is there a reason (other than the date one already mentioned) why you wouldn't use the built-in group function capabilities in ActiveRecord? You seem to be concerned about "post-processing", which I don't think is really something to worry about.
You're in Rails, so you should probably be looking for a Rails solution first[1]. My first thought would be to do something like
```
Product.average(:sales_price, :group => "DATE(created_at)", :conditions => ["merchant_id=?", 1])
```
which ActiveRecord turned into pretty much the SQL you described. Assuming there's a declared `has_many` association between Merchant and Product, then you'd probably be better using that, so something like:
```
ave_prices = Merchant.find(1).products.average(:sales_price, :group => "DATE(created_at)")
```
*(I'm hoping that your description of the model as "products\_sold" is some kind of transcription error, btw - if not, you're somewhat off-message with your class naming!)*
After all that, you're back where you started, but you got there in a more conventional Rails way (and Rails really values conventions!). Now we need to fill in the gaps.
I'll assume you know your date range, let's say it's defined as all dates from `from_date` to `to_date`.
```
date_aves = (from_date..to_date).map{|dt| [dt, 0]}
```
That builds the complete list of dates as an array. We don't need the dates where we got an average:
```
ave_price_dates = ave_prices.collect{|ave_price| ave_price[0]} # build an array of dates
date_aves.delete_if { |dt| ave_price.dates.index(dt[0]) } # remove zero entries for dates retrieved from DB
date_aves.concat(ave_prices) # add the query results
date_aves.sort_by{|ave| ave[0] } # sort by date
```
That lot looks a bit cluttered to me: I think it could be terser and cleaner. I'd investigate building a Hash or Struct rather than staying in arrays.
---
[1] I'm not saying don't use SQL - situations do occur where ActiveRecord can't generate the most efficient query and you fall back on `find_by_sql`. That's fine, it's supposed to be like that, but I think you should try to use it only as a last resort. | For any such query, you will need to find a mechanism to generate a table with one row for each date that you want to report on. Then you will do an outer join of that table with the data table you are analyzing. You may also have to play with NVL or COALESCE to convert nulls into zeroes.
The hard part is working out how to generate the (temporary) table that contains the list of dates for the range you need to analyze. That is DBMS-specific.
Your idea of mapping date/time values to a single date is spot on, though. You'd need to pull a similar trick - mapping all the dates to an ISO 8601 date format like 2009-W01 for week 01 - if you wanted to analyze weekly sales.
Also, you would do better to map your DATE format to 2009-01-08 notation because then you can sort in date order using a plain character sort. | Best way in MySQL or Rails to get AVG per day within a specific date range | [
"",
"sql",
"mysql",
"ruby-on-rails",
"ruby",
"static-analysis",
""
] |
Is it possible to use JavaScript to open an HTML select to show its option list? | Unfortunately there's a simple answer to this question, and it's "No" | I had this problem...and found a workable solution.
I didn't want the select box to show until the user clicked on some plain HTML. So I overlayed the select element with `opacity=.01`. Upon clicking, I changed it back to `opacity=100`. This allowed me to hide the select, and when the user clicked the text the select appeared with the options showing. | Is it possible to use JS to open an HTML select to show its option list? | [
"",
"javascript",
"html-select",
""
] |
I have been investigating for some time now a way to prevent my user from accidently entering a data directory of my application.
My application uses a folder to store a structured project. The folder internal structure is critic and should not be messed up. I would like my user to see this folder as a whole and not be able to open it (like a Mac bundle).
Is there a way to do that on Windows?
**Edit from current answers**
Of course I am not trying to prevent my users from accessing their data, just protecting them from accidentally destroying the data integrity. So encryption or password protection are not needed.
Thank you all for your .Net answers but unfortunately, this is mainly a C++ project without any dependency to the .Net framework.
The data I am mentioning are not light, they are acquired images from an electronic microscope. These data can be huge (~100 MiB to ~1 GiB) so loading everything in memory is not an option. These are huge images so the storage must provide a way to read the data incrementally by accessing one file at a time without loading the whole archive in memory.
Besides, the application is mainly legacy with some components we are not even responsible of. A solution that allows me to keep the current IO code is preferable.
Shell Extension looks interesting, I will investigate the solution further.
LarryF, can you elaborate on Filter Driver or DefineDOSDevice ? I am not familiar with these concepts. | Looks like some [Windows ports of FUSE](http://sourceforge.net/apps/mediawiki/fuse/index.php?title=OperatingSystems#Windows) are starting to appear. I think this would be the best solution since it would allow me to keep the legacy code (which is quite large) untouched. | Inside, or outside of your program?
There are ways, but none of them easy. You are probably going to be looking at a Filter Driver on the file system. | Windows Explorer directory as bundle | [
"",
"c++",
"windows",
"directory",
"bundle",
"windows-shell",
""
] |
We have 2 applications that run under JBoss. I am looking for a way to reduce the overhead of the server. The main app runs under Tomcat. The other app is made up of MBeans. Is there a way to run MBeans under Tomcat?
Alternative suggestions are appreciated. | MBeans are a part of the JMX specification which is included in the JRE. It should be possible to run MBeans under Tomcat. Tomcat 5 or later provides an MBean server. | You can use the following JVM arguments to startup Tomcat with MBean enabled
```
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=4444 (could be anything)
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false
``` | Can an MBean be run under Tomcat? | [
"",
"java",
"tomcat",
"jboss",
"mbeans",
""
] |
> **Possible Duplicate:**
> [LINQ equivalent of foreach for IEnumerable<T>](https://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerablet)
The linq extension methods for ienumerable are very handy ... but not that useful if all you want to do is apply some computation to each item in the enumeration without returning anything. So I was wondering if perhaps I was just missing the right method, or if it truly doesn't exist as I'd rather use a built-in version if it's available ... but I haven't found one :-)
I could have sworn there was a .ForEach method somewhere, but I have yet to find it. In the meantime, I did write my own version in case it's useful for anyone else:
```
using System.Collections;
using System.Collections.Generic;
public delegate void Function<T>(T item);
public delegate void Function(object item);
public static class EnumerableExtensions
{
public static void For(this IEnumerable enumerable, Function func)
{
foreach (object item in enumerable)
{
func(item);
}
}
public static void For<T>(this IEnumerable<T> enumerable, Function<T> func)
{
foreach (T item in enumerable)
{
func(item);
}
}
}
```
usage is:
`myEnumerable.For<MyClass>(delegate(MyClass item) { item.Count++; });` | Shedding a little more light on why:
LINQ is functional in nature. It is used to query data and return results. A LINQ query shouldn't be altering the state of the application (with some exceptions like caching). Because foreach doesn't return any results, it doesn't have many uses that don't involve altering the state of something besides what you are passing in to it. And if you need a Foreach() extension method, it *is* easy to roll your own.
If, on the other hand, what you want is to take input and call a function on each item that returns a result, LINQ provides a way through its select method.
For example, the following code calls a function delegate on every item in a list, returning true if that item is positive:
```
static void Main(string[] args)
{
IEnumerable<int> list = new List<int>() { -5, 3, -2, 1, 2, -7 };
IEnumerable<bool> isPositiveList = list.Select<int, bool>(i => i > 0);
foreach (bool isPositive in isPositiveList)
{
Console.WriteLine(isPositive);
}
Console.ReadKey();
}
``` | Actually, the Reactive Extensions framework from Microsoft Research did add this functionality.
In the `System.Interactive` assembly they've included a `Run()` and a `Do()` extensions to `IEnumerable<T>`.
**Do(action)** will execute the action on each element and yield it back. This is useful for adding logging to a linq query for example:
```
var res = GetRandomNumbers(100).Take(10)
.Do(x => Console.WriteLine("Source -> {0}", x))
.Where(x => x % 2 == 0)
.Do(x => Console.WriteLine("Where -> {0}", x))
.OrderBy(x => x)
.Do(x => Console.WriteLine("OrderBy -> {0}", x))
.Select(x => x + 1)
.Do(x => Console.WriteLine("Select -> {0}", x));
```
This will result in:
```
Source -> 96
Where -> 96
Source -> 25
Source -> 8
Where -> 8
Source -> 79
Source -> 25
Source -> 3
Source -> 36
Where -> 36
Source -> 51
Source -> 53
Source -> 81
OrderBy -> 8
Select -> 9
9
OrderBy -> 36
Select -> 37
37
OrderBy -> 96
Select -> 97
97
```
**Run(action)** is like a foreach loop, which means its folding the sequence which executing the action.
You can read more about it here: <http://community.bartdesmet.net/blogs/bart/archive/2009/12/26/more-linq-with-system-interactive-the-ultimate-imperative.aspx>
The Rx framework can be found here: <http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx> | Existing LINQ extension method similar to Parallel.For? | [
"",
"c#",
"linq",
"extension-methods",
"iteration",
""
] |
I need to be able to see if a form input in PHP is numeric. If it is not numeric, the website should redirect. I have tried is\_numeric() but it does not seem to work.
Code examples will be nice.
I am developing a shopping cart that accepts an integer value for the quantity. I am trying this:
```
if(!is_numeric($quantity)){
//redirect($data['referurl']."/badinput");
echo "is not numeric";
}
``` | ```
if(!is_numeric($quantity == 0)){
//redirect($data['referurl']."/badinput");
echo "is not numeric";
```
What you have here are two nested conditions.
Let's say $quantity is 1.
The first condition evaluates 1 == 0 and returns FALSE.
The second condition checks if FALSE is numeric and returns FALSE because FALSE is not numeric.
just write:
```
if (!is_numeric($quantity))
{
echo 'is not numeric';
}
``` | You should probably explain what you mean by "numeric" - integral, floating point, exponential notation etc? [`is_numeric()`](http://www.php.net/manual/en/function.is-numeric.php) will accept all of these.
If you want to check that a string contains nothing other than digits, then you could use a regular expression, e.g.
```
/^\d+$/
```
If you're going to use the actual value as if it were an integer, you'll probably want to pass it through [`intval()`](http://www.php.net/manual/en/function.intval.php) anyway, which will return `0` if the value cannot be parsed - if `0` is a valid value, then you'll probably have to handle that in some way, maybe by constraining the lower range of the value. | How can I check if form input is numeric in PHP? | [
"",
"php",
"validation",
"numeric",
""
] |
I have a friend who likes to use metaclasses, and regularly offers them as a solution.
I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.
Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.
So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.
I will start:
> Sometimes when using a third-party
> library it is useful to be able to
> mutate the class in a certain way.
(This is the only case I can think of, and it's not concrete) | I have a class that handles non-interactive plotting, as a frontend to Matplotlib. However, on occasion one wants to do interactive plotting. With only a couple functions I found that I was able to increment the figure count, call draw manually, etc, but I needed to do these before and after every plotting call. So to create both an interactive plotting wrapper and an offscreen plotting wrapper, I found it was more efficient to do this via metaclasses, wrapping the appropriate methods, than to do something like:
```
class PlottingInteractive:
add_slice = wrap_pylab_newplot(add_slice)
```
This method doesn't keep up with API changes and so on, but one that iterates over the class attributes in `__init__` before re-setting the class attributes is more efficient and keeps things up to date:
```
class _Interactify(type):
def __init__(cls, name, bases, d):
super(_Interactify, cls).__init__(name, bases, d)
for base in bases:
for attrname in dir(base):
if attrname in d: continue # If overridden, don't reset
attr = getattr(cls, attrname)
if type(attr) == types.MethodType:
if attrname.startswith("add_"):
setattr(cls, attrname, wrap_pylab_newplot(attr))
elif attrname.startswith("set_"):
setattr(cls, attrname, wrap_pylab_show(attr))
```
Of course, there might be better ways to do this, but I've found this to be effective. Of course, this could also be done in `__new__` or `__init__`, but this was the solution I found the most straightforward. | I was asked the same question recently, and came up with several answers. I hope it's OK to revive this thread, as I wanted to elaborate on a few of the use cases mentioned, and add a few new ones.
Most metaclasses I've seen do one of two things:
1. Registration (adding a class to a data structure):
```
models = {}
class ModelMetaclass(type):
def __new__(meta, name, bases, attrs):
models[name] = cls = type.__new__(meta, name, bases, attrs)
return cls
class Model(object):
__metaclass__ = ModelMetaclass
```
Whenever you subclass `Model`, your class is registered in the `models` dictionary:
```
>>> class A(Model):
... pass
...
>>> class B(A):
... pass
...
>>> models
{'A': <__main__.A class at 0x...>,
'B': <__main__.B class at 0x...>}
```
This can also be done with class decorators:
```
models = {}
def model(cls):
models[cls.__name__] = cls
return cls
@model
class A(object):
pass
```
Or with an explicit registration function:
```
models = {}
def register_model(cls):
models[cls.__name__] = cls
class A(object):
pass
register_model(A)
```
Actually, this is pretty much the same: you mention class decorators unfavorably, but it's really nothing more than syntactic sugar for a function invocation on a class, so there's no magic about it.
Anyway, the advantage of metaclasses in this case is inheritance, as they work for any subclasses, whereas the other solutions only work for subclasses explicitly decorated or registered.
```
>>> class B(A):
... pass
...
>>> models
{'A': <__main__.A class at 0x...> # No B :(
```
2. Refactoring (modifying class attributes or adding new ones):
```
class ModelMetaclass(type):
def __new__(meta, name, bases, attrs):
fields = {}
for key, value in attrs.items():
if isinstance(value, Field):
value.name = '%s.%s' % (name, key)
fields[key] = value
for base in bases:
if hasattr(base, '_fields'):
fields.update(base._fields)
attrs['_fields'] = fields
return type.__new__(meta, name, bases, attrs)
class Model(object):
__metaclass__ = ModelMetaclass
```
Whenever you subclass `Model` and define some `Field` attributes, they are injected with their names (for more informative error messages, for example), and grouped into a `_fields` dictionary (for easy iteration, without having to look through all the class attributes and all its base classes' attributes every time):
```
>>> class A(Model):
... foo = Integer()
...
>>> class B(A):
... bar = String()
...
>>> B._fields
{'foo': Integer('A.foo'), 'bar': String('B.bar')}
```
Again, this can be done (without inheritance) with a class decorator:
```
def model(cls):
fields = {}
for key, value in vars(cls).items():
if isinstance(value, Field):
value.name = '%s.%s' % (cls.__name__, key)
fields[key] = value
for base in cls.__bases__:
if hasattr(base, '_fields'):
fields.update(base._fields)
cls._fields = fields
return cls
@model
class A(object):
foo = Integer()
class B(A):
bar = String()
# B.bar has no name :(
# B._fields is {'foo': Integer('A.foo')} :(
```
Or explicitly:
```
class A(object):
foo = Integer('A.foo')
_fields = {'foo': foo} # Don't forget all the base classes' fields, too!
```
Although, on the contrary to your advocacy for readable and maintainable non-meta programming, this is much more cumbersome, redundant and error prone:
```
class B(A):
bar = String()
# vs.
class B(A):
bar = String('bar')
_fields = {'B.bar': bar, 'A.foo': A.foo}
```
Having considered the most common and concrete use cases, the only cases where you absolutely HAVE to use metaclasses are when you want to modify the class name or list of base classes, because once defined, these parameters are baked into the class, and no decorator or function can unbake them.
```
class Metaclass(type):
def __new__(meta, name, bases, attrs):
return type.__new__(meta, 'foo', (int,), attrs)
class Baseclass(object):
__metaclass__ = Metaclass
class A(Baseclass):
pass
class B(A):
pass
print A.__name__ # foo
print B.__name__ # foo
print issubclass(B, A) # False
print issubclass(B, int) # True
```
This may be useful in frameworks for issuing warnings whenever classes with similar names or incomplete inheritance trees are defined, but I can't think of a reason beside trolling to actually change these values. Maybe David Beazley can.
Anyway, in Python 3, metaclasses also have the `__prepare__` method, which lets you evaluate the class body into a mapping other than a `dict`, thus supporting ordered attributes, overloaded attributes, and other wicked cool stuff:
```
import collections
class Metaclass(type):
@classmethod
def __prepare__(meta, name, bases, **kwds):
return collections.OrderedDict()
def __new__(meta, name, bases, attrs, **kwds):
print(list(attrs))
# Do more stuff...
class A(metaclass=Metaclass):
x = 1
y = 2
# prints ['x', 'y'] rather than ['y', 'x']
```
```
class ListDict(dict):
def __setitem__(self, key, value):
self.setdefault(key, []).append(value)
class Metaclass(type):
@classmethod
def __prepare__(meta, name, bases, **kwds):
return ListDict()
def __new__(meta, name, bases, attrs, **kwds):
print(attrs['foo'])
# Do more stuff...
class A(metaclass=Metaclass):
def foo(self):
pass
def foo(self, x):
pass
# prints [<function foo at 0x...>, <function foo at 0x...>] rather than <function foo at 0x...>
```
You might argue ordered attributes can be achieved with creation counters, and overloading can be simulated with default arguments:
```
import itertools
class Attribute(object):
_counter = itertools.count()
def __init__(self):
self._count = Attribute._counter.next()
class A(object):
x = Attribute()
y = Attribute()
A._order = sorted([(k, v) for k, v in vars(A).items() if isinstance(v, Attribute)],
key = lambda (k, v): v._count)
```
```
class A(object):
def _foo0(self):
pass
def _foo1(self, x):
pass
def foo(self, x=None):
if x is None:
return self._foo0()
else:
return self._foo1(x)
```
Besides being much more ugly, it's also less flexible: what if you want ordered literal attributes, like integers and strings? What if `None` is a valid value for `x`?
Here's a creative way to solve the first problem:
```
import sys
class Builder(object):
def __call__(self, cls):
cls._order = self.frame.f_code.co_names
return cls
def ordered():
builder = Builder()
def trace(frame, event, arg):
builder.frame = frame
sys.settrace(None)
sys.settrace(trace)
return builder
@ordered()
class A(object):
x = 1
y = 'foo'
print A._order # ['x', 'y']
```
And here's a creative way to solve the second one:
```
_undefined = object()
class A(object):
def _foo0(self):
pass
def _foo1(self, x):
pass
def foo(self, x=_undefined):
if x is _undefined:
return self._foo0()
else:
return self._foo1(x)
```
But this is much, MUCH voodoo-er than a simple metaclass (especially the first one, which really melts your brain). My point is, you look at metaclasses as unfamiliar and counter-intuitive, but you can also look at them as the next step of evolution in programming languages: you just have to adjust your mindset. After all, you could probably do everything in C, including defining a struct with function pointers and passing it as the first argument to its functions. A person seeing C++ for the first time might say, "what is this magic? Why is the compiler implicitly passing `this` to methods, but not to regular and static functions? It's better to be explicit and verbose about your arguments". But then, object-oriented programming is much more powerful once you get it; and so is this, uh... quasi-aspect-oriented programming, I guess. And once you understand metaclasses, they're actually very simple, so why not use them when convenient?
And finally, metaclasses are rad, and programming should be fun. Using standard programming constructs and design patterns all the time is boring and uninspiring, and hinders your imagination. Live a little! Here's a metametaclass, just for you.
```
class MetaMetaclass(type):
def __new__(meta, name, bases, attrs):
def __new__(meta, name, bases, attrs):
cls = type.__new__(meta, name, bases, attrs)
cls._label = 'Made in %s' % meta.__name__
return cls
attrs['__new__'] = __new__
return type.__new__(meta, name, bases, attrs)
class China(type):
__metaclass__ = MetaMetaclass
class Taiwan(type):
__metaclass__ = MetaMetaclass
class A(object):
__metaclass__ = China
class B(object):
__metaclass__ = Taiwan
print A._label # Made in China
print B._label # Made in Taiwan
```
# Edit
This is a pretty old question, but it's still getting upvotes, so I thought I'd add a link to a more comprehensive answer. If you'd like to read more about metaclasses and their uses, I've just published an article about it [here](https://medium.com/@dan.gittik/metaphysics-2036b38fa711). | What are some (concrete) use-cases for metaclasses? | [
"",
"python",
"metaclass",
""
] |
I am retrieving three different sets of data (or what should be "unique" rows). In total, I expect 3 different unique sets of rows because I have to complete different operations on each set of data. I am, however, retrieving more rows than there are in total in the table, meaning that I must be retrieving duplicate rows somewhere. Here is an example of my three sets of queries:
```
SELECT DISTINCT t1.*
FROM table1 t1
INNER JOIN table2 t2
ON t2.ID = t1.ID
AND t2.NAME = t1.NAME
AND t2.ADDRESS <> t1.ADDRESS
SELECT DISTINCT t1.*
FROM table1 t1
INNER JOIN table2 t2
ON t2.ID = t1.ID
AND t2.NAME <> t1.NAME
AND t2.ADDRESS <> t1.ADDRESS
SELECT DISTINCT t1.*
FROM table1 t1
INNER JOIN table2 t2
ON t2.ID <> t1.ID
AND t2.NAME = t1.NAME
AND t2.ADDRESS <> t1.ADDRESS
```
As you can see, I am selecting (in order of queries)
* Set of data where the id AND name match
* Set of data where the id matches but the name does NOT
* Set of data where the id does not match but name DOES
I am retrieving MORE rows than exist in T1 when adding up the number of results returned from all three queries which I don't think is logically possible, plus this means I must be duplicating rows (if it is logically possible) somewhere which prevents me from executing different commands against each set (since a row would have another command executed on it).
Can someone find where I'm going wrong here? | Consider if Name is not unique. If you have the following data:
```
Table 1 Table 2
ID Name Address ID Name Address
0 Jim Smith 1111 A St 0 Jim Smith 2222 A St
1 Jim Smith 2222 B St 1 Jim Smith 3333 C St
```
Then Query 1 gives you:
```
0 Jim Smith 1111 A St
1 Jim Smith 2222 B St
```
Because rows 1 & 2 in Table 1 match rows 1 & 2, respectively in Table 2.
Query 2 gives you nothing.
Query 3 gives you
```
0 Jim Smith 1111 A St
1 Jim Smith 2222 B St
```
Because row 1 in Table 1 matches row 2 in Table 2 and row 2 in Table 1 matches row 1 in Table 2. Thus you get 4 rows out of Table 1 when there are only 2 rows in it. | Are you sure that NAME and ID are unique in both tables?
If not, you could have a situation, for example, where table 1 has this:
NAME: Fred
ID: 1
and table2 has this:
NAME: Fred
ID: 1
NAME: Fred
ID: 2
In this case, the record in table1 will be returned by two of your queries: ID and NAME both match, and NAME matches but ID doesn't.
You might be able to narrow down the problem by intersecting each combination of two queries to find out what the duplicates are, e.g.:
```
SELECT DISTINCT t1.*
FROM table1 t1
INNER JOIN table2 t2
ON t2.ID = t1.ID
AND t2.NAME = t1.NAME
AND t2.ADDRESS <> t1.ADDRESS
INTERSECT
SELECT DISTINCT t1.*
FROM table1 t1
INNER JOIN table2 t2
ON t2.ID = t1.ID
AND t2.NAME <> t1.NAME
AND t2.ADDRESS <> t1.ADDRESS
``` | Query three non-bisecting sets of data | [
"",
"sql",
"sql-server",
""
] |
Is there a managed API to retrieve an application's install date using the Product GUID?
Thanks.
Scott | The "proper" way to get to that information is to use ::MsiGetProductInfo(). PInvoke should be trivial. | Thanks Rob! I've added a complete C# example below.
```
[DllImport("msi.dll", CharSet = CharSet.Unicode)]
static extern Int32 MsiGetProductInfo(string product, string property, [Out] StringBuilder valueBuf, ref Int32 len);
static void Main(string[] args)
{
Int32 len = 512;
var builder = new StringBuilder(len);
MsiGetProductInfo("{0db93d2f-a9e7-417f-9425-5e61e82c0868}", "InstallDate", builder, ref len);
var installDate = DateTime.ParseExact(builder.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture);
Console.WriteLine(installDate);
}
``` | Get install date from managed code | [
"",
"c#",
"wix",
"windows-installer",
""
] |
Hey everyone, I'm working on a PHP application that needs to parse a .tpl file with HTML in it and I'm making it so that the HTML can have variables and basic if statements in it. An if statement look something like this:
`
```
<!--if({VERSION} == 2)-->
Hello World
<!--endif -->
```
To parse that, I've tried using `preg_replace` with no luck. The pattern that I tried was
`/<!--if\(([^\]*)\)-->([^<]*)<!--endif-->/e`
which gets replaced with
`if($1) { echo "$2"; }`
Any ideas as to why this won't work and what I can do to get it up and running? | I think you meant to do this:
```
'/<!--if\(([^)]*)\)-->([^<]*)<!--endif-->/'
```
Your regex has only one character class in it:
```
[^\]*)\)-->([^<]
```
Here's what's happening:
* The first closing square bracket is escaped by the backslash, so it's matched literally.
* The parentheses that were supposed close the first capturing group and open the second one are also taken literally; it isn't necessary to escape parens inside a character class.
* The first hyphen *is* taken as a metacharacter; it forms the range [)\*+,-]
* The second opening square bracket is taken as a literal square bracket because it's inside a character class.
* The second caret is taken as a literal caret because it's not the first character in the class.
So, after removing the duplicates and sorting the characters into their ASCII order, your character class is equivalent to this:
```
[^()*+,\-<>\[\]^]
```
And the parentheses outside the character class are still balanced, so the regex compiles, but it doesn't even come close to matching what you wanted it to. | You have a space between `endif` and `-->` but your regular expression doesn't allow this.
Incidentally, this seems horribly insecure... Is there any reason you're not using a pre-built templating engine like Smarty? | Template ifs using regex | [
"",
"php",
"regex",
""
] |
I have a `JPanel` subclass on which I add buttons, labels, tables, etc. To show on screen it I use `JFrame`:
```
MainPanel mainPanel = new MainPanel(); //JPanel subclass
JFrame mainFrame = new JFrame();
mainFrame.setTitle("main window title");
mainFrame.getContentPane().add(mainPanel);
mainFrame.setLocation(100, 100);
mainFrame.pack();
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
```
But when I size the window, size of panel don't change. How to make size of panel to be the same as the size of window even if it was resized? | You can set a layout manager like BorderLayout and then define more specifically, where your panel should go:
```
MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);
```
This puts the panel into the center area of the frame and lets it grow automatically when resizing the frame. | You need to set a layout manager for the JFrame to use - This deals with how components are positioned. A useful one is the BorderLayout manager.
Simply adding the following line of code should fix your problems:
```
mainFrame.setLayout(new BorderLayout());
```
(Do this before adding components to the JFrame) | Automatically size JPanel inside JFrame | [
"",
"java",
"swing",
"size",
"jframe",
"jpanel",
""
] |
There is a particular website I must use for work which is absolutely heinous and despised by all who must use it. In particular, the site's Javascript is fundamentally broken and works only in IE, which pretty much makes it the only site I must use outside my preferred browsers.
So, to the question. If I could '***patch***' the javascript after loading the website in such a fashion as to '*do the right thing*', I could then use the website without IE.
( *Just to cut out some of the superfluous answers: I have already tried masking both browsers as IE, which has no effect because the issue is with the javascript, not browser detection on the server.* )
I would prefer solutions which are for Opera, though I'm not opposed to Firefox answers. Also, I would rather not have to view the site though a proxy, though I will entertain such answers. | For Opera, you want [User JavaScript](http://www.opera.com/browser/tutorials/userjs/). Similar to Greasemonkey, but built-in to Opera. Built to be used for exactly the sort of situation you're in: fixing sites that are broken in Opera... | For Firefox, you could use the [Greasemonkey](https://addons.mozilla.org/en-US/firefox/addon/748) addon to do this. | How can I patch client side javascript on a website after loading it in Opera or Firefox? | [
"",
"javascript",
"firefox",
"opera",
""
] |
Even though I've been a developer for awhile I've been lucky enough to have avoided doing much work with XML. So now I've got a project where I've got to interact with some web services, and would like to use some kind of Object-to-XML Mapping solution.
The only one I'm aware of is JAXB. Is that the best to go with? Are there any other recommendations?
One catch - I'm stuck using Java 1.4, so I can't do anything with annotations. | If you're calling a web-service with a WSDL, JAXB is absolutely the best option. Take a look at wsimport, and you're be up and running in 10 minutes.
I don't think JAXB 2.0 will be possible on Java 1.4. You may need to use Axis instead:
```
java -cp axis-1.4.jar;commons-logging-1.1.jar;commons-discovery-0.2.jar;jaxrpc-1.1.jar;saaj-1.1.jar;wsdl4j-1.4.jar;activation-1.1.jar;mail-1.4.jar org.apache.axis.wsdl.WSDL2Java http://someurl?WSDL
```
This will generate similar stubs to JAXB.
If you don't have a WSDL or XSD, you can always [generate one](http://bitkickers.blogspot.com/2008/12/using-jaxb-without-schema.html). | **JAXB is the best choice:**
* [Public API included in Java SE 6](http://download.oracle.com/javase/6/docs/api/javax/xml/bind/package-summary.html)
* Binding layer for JAX-WS (Web Services)
* Binding layer for JAX-RS (Rest)
* [Can preserve XML Infoset](http://bdoughan.blogspot.com/2010/09/jaxb-xml-infoset-preservation.html)
* Multiple implementations: [Metro](http://jaxb.java.net/), [MOXy](http://www.eclipse.org/eclipselink/moxy.php), [JaxMe](http://ws.apache.org/jaxme/), etc
**[EclipseLink JAXB (MOXy)](http://www.eclipse.org/eclipselink/moxy.php) is the best implementation:**
MOXy is a JAXB implementation with Extensions
MOXy has an external configuration file (based on JAXB annotations with extensions):
* <http://bdoughan.blogspot.com/2010/12/extending-jaxb-representing-annotations.html>
* <http://wiki.eclipse.org/EclipseLink/Examples/MOXy/EclipseLink-OXM.XML>
Has XPath based mapping, for deep mapping:
* <http://bdoughan.blogspot.com/2010/07/xpath-based-mapping.html>
* <http://bdoughan.blogspot.com/2011/03/map-to-element-based-on-attribute-value.html>
* <http://bdoughan.blogspot.com/2010/09/xpath-based-mapping-geocode-example.html>
Designed to handle ORM mapped objects, including support for bidirectional relationships:
* <http://wiki.eclipse.org/EclipseLink/Examples/MOXy/JPA>
* <http://bdoughan.blogspot.com/2010/07/jpa-entities-to-xml-bidirectional.html> | What is the best Java OXM library? | [
"",
"java",
"oxm",
""
] |
Is there any reason to prefer a `CharBuffer` to a `char[]` in the following:
```
CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);
while( in.read(buf) >= 0 ) {
out.append( buf.flip() );
buf.clear();
}
```
vs.
```
char[] buf = new char[DEFAULT_BUFFER_SIZE];
int n;
while( (n = in.read(buf)) >= 0 ) {
out.write( buf, 0, n );
}
```
(where `in` is a `Reader` and `out` in a `Writer`)? | No, there's really no reason to prefer a `CharBuffer` in this case.
In general, though, `CharBuffer` (and `ByteBuffer`) can really simplify APIs and encourage correct processing. If you were designing a public API, it's definitely worth considering a buffer-oriented API. | I wanted to mini-benchmark this comparison.
Below is the class I have written.
The thing is I can't believe that the CharBuffer performed so badly. What have I got wrong?
*EDIT: Since the 11th comment below I have edited the code and the output time, better performance all round but still a significant difference in times. I also tried out2.append((CharBuffer)buff.flip()) option mentioned in the comments but it was much slower than the write option used in the code below.*
Results: (time in ms)
char[] : 3411
CharBuffer: 5653
```
public class CharBufferScratchBox
{
public static void main(String[] args) throws Exception
{
// Some Setup Stuff
String smallString =
"1111111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
stringBuilder.append(smallString);
}
String string = stringBuilder.toString();
int DEFAULT_BUFFER_SIZE = 1000;
int ITTERATIONS = 10000;
// char[]
StringReader in1 = null;
StringWriter out1 = null;
Date start = new Date();
for (int i = 0; i < ITTERATIONS; i++)
{
in1 = new StringReader(string);
out1 = new StringWriter(string.length());
char[] buf = new char[DEFAULT_BUFFER_SIZE];
int n;
while ((n = in1.read(buf)) >= 0)
{
out1.write(
buf,
0,
n);
}
}
Date done = new Date();
System.out.println("char[] : " + (done.getTime() - start.getTime()));
// CharBuffer
StringReader in2 = null;
StringWriter out2 = null;
start = new Date();
CharBuffer buff = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);
for (int i = 0; i < ITTERATIONS; i++)
{
in2 = new StringReader(string);
out2 = new StringWriter(string.length());
int n;
while ((n = in2.read(buff)) >= 0)
{
out2.write(
buff.array(),
0,
n);
buff.clear();
}
}
done = new Date();
System.out.println("CharBuffer: " + (done.getTime() - start.getTime()));
}
}
``` | CharBuffer vs. char[] | [
"",
"java",
"io",
"buffer",
""
] |
Say I have a package "mylibrary".
I want to make "mylibrary.config" available for import, either as a dynamically created module, or a module imported from an entirely different place that would then basically be "mounted" inside the "mylibrary" namespace.
I.e., I do:
```
import sys, types
sys.modules['mylibrary.config'] = types.ModuleType('config')
```
Given that setup:
```
>>> import mylibrary.config # -> works
>>> from mylibrary import config
<type 'exceptions.ImportError'>: cannot import name config
```
Even stranger:
```
>>> import mylibrary.config as X
<type 'exceptions.ImportError'>: cannot import name config
```
So it seems that using the direct import works, the other forms do not. Is it possible to make those work as well? | You need to monkey-patch the module not only into sys.modules, but also into its parent module:
```
>>> import sys,types,xml
>>> xml.config = sys.modules['xml.config'] = types.ModuleType('xml.config')
>>> import xml.config
>>> from xml import config
>>> from xml import config as x
>>> x
<module 'xml.config' (built-in)>
``` | As well as the following:
```
import sys, types
config = types.ModuleType('config')
sys.modules['mylibrary.config'] = config
```
You also need to do:
```
import mylibrary
mylibrary.config = config
``` | Making a virtual package available via sys.modules | [
"",
"python",
"import",
"module",
""
] |
I'm writing a C# wrapper for a third-party native library, which we have as a DLL. I would like to be able to distribute a single DLL for the new assembly. Is it possible for me to embed the win32 DLL in my .NET DLL, and still make calls into it using P/Invoke? If so, how? | I've never done it but I know of an opensource project that does this. They embed the native SQLite3 code into the managed SQLite assembly using their own tool called [mergebin](http://www.koushikdutta.com/2008/09/day-6-mergebin-combine-your-unmanaged.html).
Go and take a look at the [SQLite project for .NET by PHX](http://sqlite.phxsoftware.com/) and grab the source and you can see how it's done. | Should work, if the native dll does not have any dependencies.
You can compile the dll in as embedded resource, than access the stream from inside your code, serialize it to the temporary folder and use it from there.
Too much to post example code here, but the way is not to complicated. | Can I embed a win32 DLL in a .NET assembly, and make calls into it using P/Invoke? | [
"",
"c#",
".net",
"pinvoke",
""
] |
In Java, what are the performance and resource implications of using
```
System.currentTimeMillis()
```
vs.
```
new Date()
```
vs.
```
Calendar.getInstance().getTime()
```
As I understand it, `System.currentTimeMillis()` is the most efficient. However, in most applications, that long value would need to be converted to a Date or some similar object to do anything meaningful to humans. | `System.currentTimeMillis()` is obviously the most **efficient** since it does not even create an object, but `new Date()` is really just a thin wrapper about a long, so it is not far behind. `Calendar`, on the other hand, is relatively slow and very complex, since it has to deal with the considerably complexity and all the oddities that are inherent to dates and times (leap years, daylight savings, timezones, etc.).
It's generally a good idea to deal only with long timestamps or `Date` objects within your application, and only use `Calendar` when you actually need to perform date/time calculations, or to format dates for displaying them to the user. If you have to do a lot of this, using [Joda Time](http://joda-time.sourceforge.net/) is probably a good idea, for the cleaner interface and better performance. | Looking at the JDK, innermost constructor for `Calendar.getInstance()` has this:
```
public GregorianCalendar(TimeZone zone, Locale aLocale) {
super(zone, aLocale);
gdate = (BaseCalendar.Date) gcal.newCalendarDate(zone);
setTimeInMillis(System.currentTimeMillis());
}
```
so it already automatically does what you suggest. Date's default constructor holds this:
```
public Date() {
this(System.currentTimeMillis());
}
```
So there really isn't need to get system time specifically unless you want to do some math with it before creating your Calendar/Date object with it. Also I do have to recommend [joda-time](http://joda-time.sourceforge.net/) to use as replacement for Java's own calendar/date classes if your purpose is to work with date calculations a lot. | System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime() | [
"",
"java",
"performance",
"date",
"time",
"calendar",
""
] |
I have some code that prints out databse values into a repeater control on an asp.net page. However, some of the values returned are null/blank - and this makes the result look ugly when there are blank spaces.
How do you do conditional logic in asp.net controls i.e. print out a value if one exists, else just go to next value.
I should also add - that I want the markup to be conditional also, as if there is no value I dont want a
tag either.
Here is a snippet of code below just to show the type of values I am getting back from my database. (It is common for **Address 2** not to have a value at all).
```
<div id="results">
<asp:Repeater ID="repeaterResults" runat="server">
<ItemTemplate>
Company: <strong><%#Eval("CompanyName") %></strong><br />
Contact Name: <strong><%#Eval("ContactName") %></strong><br />
Address: <strong><%#Eval("Address1")%></strong><br />
<strong><%#Eval("Address2")%></strong><br />..................
```
Many thanks | It's going to be a pretty subjective one this as it completely depends on where and how you like to handle null / blank values, and indeed which one of those two you are dealing with.
For example, some like to handle nulls at the database level, some like to code default values in the business logic layer and others like to handle default / blank values at the UI - not to mention the plethora of options in between.
Either way my personal choice would be to make sure you display that no data was available for that field at the UI level to avoid confusion. At worst something along the lines of:
```
<strong><% If (Eval("Address2").Length > 0) Then %><%#Eval("Address2")%><% Else %>No data available for Address 2<% End If %></strong><br />
```
That way at least the user knows that no data is available, rather than not knowing if there has been some system / administrative error.
Hope that helps :) | I suggest wrapping each key/value pair into custom control with 2 properties. This control will display itself only if value is not empty:
```
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ShowPair.ascx.cs" Inherits="MyWA.ShowPair" %>
<% if (!string.IsNullOrEmpty(Value))
{ %>
<%=Key %> : <%=Value %>
<% } %>
```
And then put controls into repeater template:
```
<asp:Repeater runat='server' ID="repeater1">
<ItemTemplate>
<cst:ShowPair Key="Company Name:" Value="<%#((Company)Container.DataItem).CompanyName %>" runat="server"/>
<cst:ShowPair Key="Contact Name:" Value="<%#((Company)Container.DataItem).ContactName %>" runat="server" />
<cst:ShowPair Key="Address 1:" Value="<%#((Company)Container.DataItem).Address1 %>" runat="server" />
</ItemTemplate>
</asp:Repeater>
``` | Conditional Logic in ASP.net page | [
"",
"c#",
"asp.net",
"conditional-statements",
""
] |
In which cases, except development, would you prefer XAMPP over a complete installation and configuration of Linux, Apache, MySQL, and PHP? | Other than development, the only other time I use it is for demos - it's nice being able to take a "solution on a stick" to a customer.
I'd never consider it for a live/public site though. | I would say that XAMPP would be preferred over a complete manual install, whenever one is not confident enough, skilled enough, experienced enough, or educated enough to properly install, the OS, HTTP server, database server, and language system with all the mainstream security and stability aspects in mind, and compensated for.
Although I recognize that XAMPP is not perfect, it is, in 99% of cases, much better than anyone without proper knowledge could accomplish. | When to prefer XAMPP over a complete installation of Linux, Apache, MySQL, and PHP | [
"",
"php",
"mysql",
"linux",
"apache",
"xampp",
""
] |
Can I call a remote webservice from a Stored Procedure and use the values that areretuned? | If you're using SQL 2005/2008, you could do this from a CLR stored procedure if you have the ability to install and run these. For more info:
<http://msdn.microsoft.com/en-us/library/ms190790.aspx> | Service Broker might provide the sort of functionality you're looking for here. | Webservice From SQL | [
"",
"sql",
"web-services",
"t-sql",
""
] |
I'm using an API that requires me to pass a function pointer as a callback. I'm trying to use this API from my class but I'm getting compilation errors.
Here is what I did from my constructor:
```
m_cRedundencyManager->Init(this->RedundencyManagerCallBack);
```
This doesn't compile - I get the following error:
> Error 8 error C3867: 'CLoggersInfra::RedundencyManagerCallBack': function call missing argument list; use '&CLoggersInfra::RedundencyManagerCallBack' to create a pointer to member
I tried the suggestion to use `&CLoggersInfra::RedundencyManagerCallBack` - didn't work for me.
Any suggestions/explanation for this??
I'm using VS2008.
Thanks!! | That doesn't work because a member function pointer cannot be handled like a normal function pointer, because it expects a "this" object argument.
Instead you can pass a static member function as follows, which are like normal non-member functions in this regard:
```
m_cRedundencyManager->Init(&CLoggersInfra::Callback, this);
```
The function can be defined as follows
```
static void Callback(int other_arg, void * this_pointer) {
CLoggersInfra * self = static_cast<CLoggersInfra*>(this_pointer);
self->RedundencyManagerCallBack(other_arg);
}
``` | This is a simple question but the answer is surprisingly complex. The short answer is you can do what you're trying to do with `std::bind1st` or `boost::bind`. The longer answer is below.
The compiler is correct to suggest you use `&CLoggersInfra::RedundencyManagerCallBack`. First, if `RedundencyManagerCallBack` is a member function, the function itself doesn't belong to any particular instance of the class `CLoggersInfra`. It belongs to the class itself. If you've ever called a static class function before, you may have noticed you use the same `SomeClass::SomeMemberFunction` syntax. Since the function itself is 'static' in the sense that it belongs to the class rather than a particular instance, you use the same syntax. The '&' is necessary because technically speaking you don't pass functions directly -- functions are not real objects in C++. Instead you're technically passing the memory address for the function, that is, a pointer to where the function's instructions begin in memory. The consequence is the same though, you're effectively 'passing a function' as a parameter.
But that's only half the problem in this instance. As I said, `RedundencyManagerCallBack` the function doesn't 'belong' to any particular instance. But it sounds like you want to pass it as a callback with a particular instance in mind. To understand how to do this you need to understand what member functions really are: regular not-defined-in-any-class functions with an extra hidden parameter.
For example:
```
class A {
public:
A() : data(0) {}
void foo(int addToData) { this->data += addToData; }
int data;
};
...
A an_a_object;
an_a_object.foo(5);
A::foo(&an_a_object, 5); // This is the same as the line above!
std::cout << an_a_object.data; // Prints 10!
```
How many parameters does `A::foo` take? Normally we would say 1. But under the hood, foo really takes 2. Looking at A::foo's definition, it needs a specific instance of A in order for the 'this' pointer to be meaningful (the compiler needs to know what 'this' is). The way you usually specify what you want 'this' to be is through the syntax `MyObject.MyMemberFunction()`. But this is just syntactic sugar for passing the address of `MyObject` as the first parameter to `MyMemberFunction`. Similarly, when we declare member functions inside class definitions we don't put 'this' in the parameter list, but this is just a gift from the language designers to save typing. Instead you have to specify that a member function is static to opt out of it automatically getting the extra 'this' parameter. If the C++ compiler translated the above example to C code (the original C++ compiler actually worked that way), it would probably write something like this:
```
struct A {
int data;
};
void a_init(A* to_init)
{
to_init->data = 0;
}
void a_foo(A* this, int addToData)
{
this->data += addToData;
}
...
A an_a_object;
a_init(0); // Before constructor call was implicit
a_foo(&an_a_object, 5); // Used to be an_a_object.foo(5);
```
Returning to your example, there is now an obvious problem. 'Init' wants a pointer to a function that takes one parameter. But `&CLoggersInfra::RedundencyManagerCallBack` is a pointer to a function that takes two parameters, it's normal parameter and the secret 'this' parameter. That's why you're still getting a compiler error (as a side note: If you've ever used Python, this kind of confusion is why a 'self' parameter is required for all member functions).
The verbose way to handle this is to create a special object that holds a pointer to the instance you want and has a member function called something like 'run' or 'execute' (or overloads the '()' operator) that takes the parameters for the member function, and simply calls the member function with those parameters on the stored instance. But this would require you to change 'Init' to take your special object rather than a raw function pointer, and it sounds like Init is someone else's code. And making a special class for every time this problem comes up will lead to code bloat.
So now, finally, the good solution, `boost::bind` and `boost::function`, the documentation for each you can find here:
[boost::bind docs](http://www.boost.org/doc/libs/1_37_0/libs/bind/bind.html),
[boost::function docs](http://www.boost.org/doc/libs/1_37_0/doc/html/function/tutorial.html)
`boost::bind` will let you take a function, and a parameter to that function, and make a new function where that parameter is 'locked' in place. So if I have a function that adds two integers, I can use `boost::bind` to make a new function where one of the parameters is locked to say 5. This new function will only take one integer parameter, and will always add 5 specifically to it. Using this technique, you can 'lock in' the hidden 'this' parameter to be a particular class instance, and generate a new function that only takes one parameter, just like you want (note that the hidden parameter is always the *first* parameter, and the normal parameters come in order after it). Look at the `boost::bind` docs for examples, they even specifically discuss using it for member functions. Technically there is a standard function called `[std::bind1st][3]` that you could use as well, but `boost::bind` is more general.
Of course, there's just one more catch. `boost::bind` will make a nice boost::function for you, but this is still technically not a raw function pointer like Init probably wants. Thankfully, boost provides a way to convert boost::function's to raw pointers, as documented on StackOverflow [here](https://stackoverflow.com/questions/282372/demote-boostfunction-to-a-plain-function-pointer). How it implements this is beyond the scope of this answer, though it's interesting too.
Don't worry if this seems ludicrously hard -- your question intersects several of C++'s darker corners, and `boost::bind` is incredibly useful once you learn it.
C++11 update: Instead of `boost::bind` you can now use a lambda function that captures 'this'. This is basically having the compiler generate the same thing for you. | How can I pass a class member function as a callback? | [
"",
"c++",
"callback",
"function-pointers",
"c++03",
""
] |
How to know, in Python, that the directory you are in is inside a symbolic link ?
I have a directory **/tmp/foo/kiwi**
I create a symlink **/tmp/bar** pointing to **/tmp/foo**
I enter into **/tmp/bar/kiwi**
the linux command **pwd** tells me I'm in **/tmp/bar/kiwi**, which is correct.
The python command prompt tells me I'm in **/tmp/foo/kiwi**:
```
Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.getcwd()
'/tmp/foo/kiwi'
```
Is there a way, in Python, to get the directory I'm really in ? | If you don't find anything else, you can use
```
os.getenv("PWD")
```
It's not really a portable python method, but works on POSIX systems. It gets the value of the `PWD` environment variable, which is set by the `cd` command (if you don't use `cd -P`) to the path name you navigated into (see `man cd`) before running the python script. That variable is not altered by python, of course. So if you `os.chdir` somewhere else, that variable will retain its value.
Anyway, as a side node, `/tmp/foo/kiwi` *is* the directory you are in. I'm not sure whether anything apart from the shell knows that you've really navigated through another path into that place, actually :) | If your symlink is set up in the way you state, then `/tmp/foo/kiwi` is the directory that you're really in. `/tmp/bar/kiwi` is just another way to get to the same place.
Note that the shell command `pwd -P` will give you the physical path of the current directory. In your case, the shell is remembering that you got where you are through the `bar` symlink, so it tell you that you are in `/tmp/bar/kiwi`. | How to know when you are in a symbolic link | [
"",
"python",
""
] |
Using the Java version of Lucene, how would you find out the number of documents in an index? | IndexReader contains the methods you need, in particular, numDocs
<http://lucene.apache.org/core/3_6_0/api/all/org/apache/lucene/index/IndexReader.html#numDocs()> | The official documentation:
<http://lucene.apache.org/java/2_4_0/api/org/apache/lucene/index/IndexReader.html#numDocs()> | Finding the number of documents in a Lucene index | [
"",
"java",
"lucene",
""
] |
```
private HashMap<DataObject, HashSet> AllDataObjects;
...
/** Returns all DataObject elements that are NOT in the specified set. */
private DataObject[] invert( HashSet<DataObject> set )
{
HashSet<DataObject> keys = (HashSet) AllDataObjects.keySet();
keys = (HashSet) keys.clone();
keys.removeAll( set );
return (DataObject[]) keys.toArray();
}
```
Note that I don't want to alter `AllDataObjects` through this process. I casted the set of `AllDataObjects`' keys (which are the `DataObject`s I want the `set` parameter to subtract from) into a HashSet to use clone, which supposedly returns a shallow copy that I can then remove `set` from without affecting `AllDataObjects`.
Does this look right to you? | Create a new set and give the one to be cloned as an argument. This avoids casting and so you don't lose generics.
```
private DataObject[] invert( Set<DataObject> set ){
Set<DataObject> keys = new HashSet<DataObject>(AllDataObjects.keySet());
keys.removeAll( set );
return keys.toArray(new DataObject[]{});
}
```
It's also worth noting that you should use Set rather than HashSet for the parameter so as to not overly burden your clients. | Knowing that these sets were populated by a relational query, I would suggest that you at least trade off writing a better SQL query to get what you want rather than doing it in memory. There are several reasons why. First, most relational databases are optimized to do this more efficiently than your code will. Second, you're letting the server where the relational database is running do more of the work that it was intended for. Third, if the size of the sets become large you'll be unnecessarily burdening the middle tier by having to bring back the results, allocate memory for them, and then throw away the unwanted results. | Cloning and subtracting sets - does this work? | [
"",
"java",
"collections",
"clone",
"set",
"subtraction",
""
] |
I'm looking for a consistent way to structure my use of formatting strings throughout a large web application, and I'm looking for recommendations or best practices on which way to go.
Up until now I've had a static class that does some common formatting e.g.
Formatting.FormatCurrency
Formatting.FormatBookingReference
I'm not convinced that this is the way to go though, I'd prefer to use the standard way of formatting strings within .NET directly and use:
amount.ToString("c")
reference.ToString("000000")
Id use IFormattable and ICustomFormatter for some of our more complicated data structures, but I'm struggling what to do about the more simple existing objects that we need to format (in this case Int32 but also DateTime).
Do I simply define constants for "c" and "000000" and use them consistently around the whole web app or is there a more standard way to do it? | One option is to use a helper class with extension methods like
```
public static class MyWebAppExtensions
{
public static string FormatCurrency(this decimal d)
{
return d.ToString("c");
}
}
```
Then anywhere you have a decimal value you do
```
Decimal d = 100.25;
string s = d.FormatCurrency();
``` | I agree with GeekyMonkey's suggestion, with one alteration:
Formatting is an implementation detail. I would suggest `ToCurrencyString` to keep with the To\* convention and its intent. | Formatting strings in C# consistently throughout a large web application | [
"",
"c#",
".net",
"asp.net",
"architecture",
"formatting",
""
] |
These are some questions for any developer whose made the jump from Java to .Net:
If you could go back to the start of your switched, what would you do to make the transition easier?
Any books you would recommend?
How is .Net compared to Java EE? Anything that totally bugs you?
And the most important, do you regret making the jump? | I did several years of C/C++ development in between Java and .NET, so my experience may be a bit different.
I found the move from Java to C# very easy. The languages are very similar and much of the framework works in similar ways. I loved Java, but I don't think I will be going back. I think the biggest differences for me are the tools. Visual Studio is a great product on makes coding a pleasure. Add in a refactoring addon for VS like [Resharper](http://www.jetbrains.com/resharper/) and you probably won't look back.
Depending on the type of development you do, I would avoid WPF at first and stick to WinForms (or WebForms vs Silverlight) as you will be more at home there coming from Java. Move to WPF or Silverlight once you start feeling comfortable as there is a lot to learn with these frameworks.
You will also find that many of the OpenSource libraries you may have used in the past have been ported to .NET, so that may help you hit the ground running.
The best book in my opinion is [Professional C# 2008](https://rads.stackoverflow.com/amzn/click/com/0470191376) by Wrox Press. As a Java programmer, you won't have too many problems with the language, you will need the most help with the framework. This book will be very helpful there. | Get a decent refactoring plugin for VS, because you will miss all the nice refactorings of your Java-IDE. | From Java to .Net | [
"",
"java",
".net",
""
] |
I need to check to see if a variable contains anything OTHER than `a-z`, `A-Z`, `0-9` and the `.` character (full stop). | ```
if (preg_match('/[^A-Z\d.]/i', $var))
print $var;
``` | There are two ways of doing it.
Tell whether the variable contains any one character *not* in the allowed ranges. This is achieved by using a negative character class [^...]:
```
preg_match('/[^a-zA-Z0-9\.]/', $your_variable);
```
Th other alternative is to make sure that every character in the string *is* in the allowed range:
```
!preg_match('/^[a-zA-Z0-9\.]*$/', $your_variable);
``` | Check if string only contains alphanumeric and dot characters | [
"",
"php",
"regex",
"validation",
"alphanumeric",
"whitelist",
""
] |
**Hi All,**
It's clear wehn I change any control and then posts back the SaveViewState method saves the changes and apply them agian after postback, see the folowing code notice that server-side-code put in a scrispt in my code liske this <% %>
```
switch (myQuestion.QuestionType)
{
case 0:
{
rdlistAnswers.Items.Clear();
foreach (sting item in myCollection)
{
ListItem i = new ListItem();
i.Value = item;
i.Text = item;
rdlistAnswers.Items.Add(i);
}
**//the folowing line of code is not a comment, it's a tag for asp control
//but I commeted it due to editing requirements**
//<asp:RadioButtonList ID="rdlistAnswers" runat="server"</asp:RadioButtonList>
break;
}
case 1:
{
cblistAnswers.Items.Clear();
foreach (sting item in myCollection)
{
ListItem i = new ListItem();
i.Value = item;
i.Text = item;
cblistAnswers.Items.Add(i);
}
<asp:CheckBoxList ID="cblistAnswers" runat="server" </asp:CheckBoxList>
}
}
```
**Now** I Can see my list fileed but when I select an item and push next button the SelectedItem property of the list remains null, **what's the reason??** | **Thanks All**
I found the reason, the code script placed in .aspx file is called "code render block", its executed during the render phase and after save view state phase so the changes done by this kind of code **just renderd but not saved**, as simple as that. | try to do rdlistAnswers.Databind() and cblistAnswers.Databind() after the foreach. | I Can't see my dynamically generated RadioButtonList or CheckBoxList items after postback | [
"",
"c#",
".net",
"asp.net",
""
] |
I'm looking for a kind of array data-type that can easily have items added, without a performance hit.
* System.**Array** - `Redim Preserve` copies entire RAM from old to new, as slow as amount of existing elements
* System.Collections.**ArrayList** - good enough?
* System.Collections.**IList** - good enough? | Just to summarize a few data structures:
**System.Collections.ArrayList**: untyped data structures are obsolete. Use List(of t) instead.
**System.Collections.Generic.List(of t)**: this represents a resizable array. This data structure uses an internal array behind the scenes. Adding items to List is O(1) as long as the underlying array hasn't been filled, otherwise its O(n+1) to resize the internal array and copy the elements over.
```
List<int> nums = new List<int>(3); // creates a resizable array
// which can hold 3 elements
nums.Add(1);
// adds item in O(1). nums.Capacity = 3, nums.Count = 1
nums.Add(2);
// adds item in O(1). nums.Capacity = 3, nums.Count = 3
nums.Add(3);
// adds item in O(1). nums.Capacity = 3, nums.Count = 3
nums.Add(4);
// adds item in O(n). Lists doubles the size of our internal array, so
// nums.Capacity = 6, nums.count = 4
```
Adding items is only efficient when adding to the back of the list. Inserting in the middle forces the array to shift all items forward, which is an O(n) operation. Deleting items is also O(n), since the array needs to shift items backward.
**System.Collections.Generic.LinkedList(of t)**: if you don't need random or indexed access to items in your list, for example you only plan to add items and iterate from first to last, then a LinkedList is your friend. Inserts and removals are O(1), lookup is O(n). | You should use the Generic List<> ([System.Collections.Generic.List](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx)) for this. It operates in [constant amortized time](https://stackoverflow.com/questions/200384/constant-amortized-time).
It also shares the following features with Arrays.
* Fast random access (you can access any element in the list in O(1))
* It's quick to loop over
* Slow to insert and remove objects in the start or middle (since it has to do a copy of the entire listbelieve)
If you need quick insertions and deletions in the beginning or end, use either linked-list or queues | Array that can be resized fast | [
"",
"c#",
"arrays",
"resize",
"performance",
"arraylist",
""
] |
I built a Winform app several months ago that schedules appointments for repair techs. I'd like to update the app by adding a map for the customer's address on the customer form, and then print that map on the report the techs take when they leave the office.
I've been looking around but I haven't found a good solution for this yet.
I currently have an address for the customer. What I'd like to do is submit the address to one of the popular online map sites and get a minimap of the locale. I can *almost* do this with Google maps using their embedded link feature. I can get the following HTML after adding an address to their website:
```
<iframe width="300" height="300" frameborder="0" scrolling="no"
marginheight="0" marginwidth="0"
src="http://maps.google.com/maps?hl=en&ie=UTF8&t=h&g=1193+Presque+Isle+Dr,+Port+Charlotte,+FL+33952&s=AARTsJqsWtjYwJ7ucpVS6UU2EInkRk6JLA&ll=27.012108,-82.087955&spn=0.005735,0.006437&z=16&output=embed">
</iframe>
```
My first plan was to simply parse this HTML and insert whichever customer's address was needed in place this address, then show the result in a browser object on the form. However, if I change the address in the above iframe Google gives me a "Your client does not have permission to get URL ..." message.
I have no preference on which map service I ultimately use, the important thing is that the solution can't have an associated expenses and its usable from Windows forms.
Anyone got an ideas/recommendations/resources on how to tackle this?
**Results**:
I ended up using the control found [here](http://www.codeplex.com/VEarthControl). I find it an "okay" solution... it's tedious to get working as the code does not work as-is. I'm pretty stunned to find that none of the popular map APIs support winforms. | Both Google Maps and Live Maps have a public api.
Since you are doing winforms I'd probably use live maps.
<http://dev.live.com/VirtualEarth/>
There are a few examples on CodePlex.
<http://codeplex.com/Project/ProjectDirectory.aspx?TagName=Virtual%20Earth> | There is [some example code](http://www.koushikdutta.com/2008/07/virtual-earth-and-google-maps-tiled-map.html) for developing a map viewer control (NB: I doubt this is strictly within their licence)
Otherwise, depending on your budget, you could use the [MapPoint ActiveX control](http://msdn.microsoft.com/en-us/cc905749.aspx) | Display a map in a Windows Form app | [
"",
"c#",
"winforms",
"maps",
""
] |
The `()` seems silly. is there a better way?
For example:
`ExternalId.IfNotNullDo(() => ExternalId = ExternalId.Trim());` | Sort of! There is a new idiom in town, that is nice and may help you in some cases. It is not fully what you want, but sometimes I think you will like it.
Since underscore ("\_") is a valid C# identifier, it is becoming a common idiom to use it as a parameter name to a lambda in cases where you plan to ignore the parameter anyway. If other coders are aware of the idiom, they will know immediately that the parameter is irrelevant.
For example:
```
ExternalId.IfNotNullDo( _ => ExternalId=ExternalId.Trim());
```
Easy to type, conveys your intent, and easier on the eyes as well.
Of course, if you're passing your lambda to something that expects an expression tree, this may not work, because now you're passing a one-parameter lambda instead of a no-parameter lambda.
But for many cases, it is a nice solution. | For a lambda, no: you need `() =>`
Is it for a delegate or an expression? For delegates, another option is `delegate {...}`. This may or may not be desirable, depending on the scenario. It is more keys, certainly...
In some cases (not this one) you can use a target method directly - i.e.
```
ExternalId.IfNotNullDo(SomeMethod);
``` | Is there a better way to express a parameterless lambda than () =>? | [
"",
"c#",
"lambda",
""
] |
What are some good end to end CPU profilers that exist for Java?
Quick list of things I'm looking for:
1. Offline profiling - No user interaction or GUI required during program execution. Dumping the profile data to a file and then requiring viewing afterwards with a GUI is fine, I just don't want to have to babysit it as the job runs
2. End to End recording - Profiler should be able to start recording immediately after entering the main call for a J2SE application. It should stop recording immediately before the JVM exits.
3. Call graph generation - After profiling, it'd be nice to turn the data into a visual call graph.
Google has a nice profiler for C/C++ - <http://google-perftools.googlecode.com/svn/trunk/doc/cpuprofile.html>
If the Java equivalent of this exists, it'd be exactly what I'm looking for.
I'm not including HProf in my list of prospective profilers because it performs badly compared to other commercial profilers I've looked at when you use accurate CPU call profiling (Usually done via Byte Code Injection, which is slow, but HProf appears at least an order of magnitude slower than other profilers, and when a single sampling profile run takes 1-2 hours, waiting more than a day for the same run is unacceptable) | My favorite, by far, is [JProfiler](http://www.ej-technologies.com/products/jprofiler/overview.html). I didn't realize it until just now (because I always use the interactive profiling GUI), but it does in fact support offline profiling, exactly like you described.
A few other cool features:
* It profiles all your SQL statements, so you can see which DB queries are slowing you down.
* It keeps track of which methods (in which classes & packages) are allocating the most memory, for which types of objects & arrays, and the longevity of those objects. So, if you're leaking memory, it's easy to track down which types of class instances are outliving their usefullness, and to find the methods where those objects were originally allocated (and who's holding the references that are keeping the objects alive).
* You can keep track of the VM growth, monitoring the frequency of GC full collections, and determining how many objects (of which type) were freed during each collection cycle.
* And of course, you get a hierarchical breakdown of all method invocations, with the number of calls and mean execution time (exclusive or inclusive) of the whole call stack. You can also view this hierarchy from the perspective of "worst bottleneck" functions, ordered either by execution time or memory allocation.
For me, JProfiler is one of the most important tools in my development process (second only to Eclipse).
---
Also: there's a [free 10-day trial](http://www.ej-technologies.com/download/jprofiler/trial.php). Download it and check it out. And, btw, I'm not affiliated with the company or anything. I've just been a happy customer for the last five or six years. | I am not familiar with offline profiling. Isn't it what [hprof](http://java.sun.com/developer/technicalArticles/Programming/HPROF.html) is for?. Otherwise I've had very good experience with [YourKit profiler](http://www.yourkit.com/). | Looking for recommendations for end-to-end Java CPU Profilers | [
"",
"java",
"profiling",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.