Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I read in the MS documentation that assigning a 64-bit value on a 32-bit Intel computer is not an atomic operation; that is, the operation is not thread safe. This means that if two people simultaneously assign a value to a static `Int64` field, the final value of the field cannot be predicted.
Three part question:
* Is this really true?
* Is this something I would worry about in the real world?
* If my application is multi-threaded do I really need to surround all my `Int64` assignments with locking code? | This is not about every variable you encounter. If some variable is used as a shared state or something (including, but not limited to *some* `static` fields), you should take care of this issue. It's completely non-issue for local variables that are not hoisted as a consequence of being closed over in a closure or an iterator transformation and are used by a single function (and thus, a single thread) at a time. | Even if the writes *were* atomic, chances are you would still need to take out a lock whenever you accessed the variable. If you didn't do that, you'd at least have to make the variable `volatile` to make sure that all threads saw the new value the next time they read the variable (which is almost always what you want). That lets you do atomic, volatile sets - but as soon as you want to do anything more interesting, such as adding 5 to it, you'd be back to locking.
Lock free programming is very, very hard to get right. You need to know *exactly* what you're doing, and keep the complexity to as small a piece of code as possible. Personally, I rarely even try to attempt it other than for very well known patterns such as using a static initializer to initialize a collection and then reading from the collection without locking.
Using the [`Interlocked`](http://msdn.microsoft.com/en-us/library/system.threading.interlocked.aspx) class can help in some situations, but it's almost always a lot easier to just take out a lock. Uncontested locks are "pretty cheap" (admittedly they get expensive with more cores, but so does everything) - don't mess around with lock-free code until you've got good evidence that it's actually going to make a significant difference. | Under C# is Int64 use on a 32 bit processor dangerous | [
"",
"c#",
".net",
"thread-safety",
"int64",
""
] |
I have an ASP .NET website that hosts a Java applet. The Java applet requires version 1.6 Update 11 of the Java runtime.
How can I detect that a client has the appropriate runtime installed so that I can display an informative message if they do not?
Thanks,
Carl.
**EDIT:** The solution must be platform independant. | This page describes how to and lists some plugins that will allow you to detect Java with JavaScript: <http://www.pinlady.net/PluginDetect/JavaDetect.htm>
Other than that, try out this snippet as well:
```
if (navigator.javaEnabled()) {
//Java is enabled
}
``` | The link below details on the deployment tips for java apps.
<http://java.sun.com/javase/6/docs/technotes/guides/jweb/deployment_advice.html>
Quoting from the link
> Deployment Toolkit
> To avoid browser compatibility issues, the Deployment Toolkit ([deployJava.js](http://java.com/js/deployJava.js)) provides JavaScript functions that automatically generate HTML required to deploy applets and Java Web Start applications. Developers should invoke these functions to deploy their solutions in a consistent fashion across various browsers. | How can I detect the Java runtime installed on a client from an ASP .NET website? | [
"",
"java",
"asp.net",
"applet",
"version-detection",
""
] |
When I'm creating temp tables I get an error message telling me that the temp table already exists. The temp table is unique to the session so it seems my connection isn't closing properly and I think it may have something to do with a return statement I have in my using statement.
I have the following code:
```
using (IDbConnection connection = dbConnectionHandler.CreateConnection())
{
connection.Open();
CreateATempTable();
PopulateTempTable();
DataSet ds = CallStoredProcThatUsesTempTable();
return ds;
}
```
I use this sort of code in several places to create a temp table with the same name.
Unfortunately, I'm getting the following error: `There is already an object named '#MyTempTable' in the database`.
Now, I know that the temp table is unique to the session and so once the session is closed it should disappear.
There are three things that I believe might cause this...
1. I need to call connection.Close()
2. I need to place the return statement outside my using statement
3. I need to drop the temp table I created prior to returning
Does anyone know which one it is? or if its something I haven't thought of? | I'm guessing here but check your database connection pooling settings. Try turning pooling off and see if it helps.
Usually, when you close/dispose connection on the .NET libraries level, real database server connection is not closed. It is just returned to connection pool inside data provider and will be reused when program asks for another connection with the same parameters and credentials. I don't think database session is reset in any way before being returned to the pool, except for open transactions and maybe some basic parameters. More expensive objects, like temporary tables, are left alone.
You can turn pooling off (very inefficient). Or you can check temporary table existence before trying to create it and delete its content if it exists. Or you can drop temporary table before closing connection. | I am pretty sure that connection.Dispose() (and thus connection.Close() as well) will be called.
You can verify that easily enough by doing 1) and 2) and checking that the problem still exists. The solution is probably 3) and the explanation would be Connection pooling. | Can a return statement prevent a using statement from closing a connection to a database? | [
"",
"c#",
"using-statement",
"dbconnection",
"temp-tables",
""
] |
I am trying to add and remove events from a timer and I have the following code:
```
Timer myTimer = new Timer(); // Windows.Forms Timer
public void addEvent(MyDelegate ev)
{
myTimer.Tick += new EventHandler(ev);
}
public void removeEvent(MyDelegate ev)
{
myTimer.Tick -= new EventHandler(ev);
}
```
I don't know If Im doing anything stupid in trying to add and remove delegates in this fashion, I am able to add delegates and get them to fire as expected. However, when I attempt to remove the events, they continue to fire on Timers Tick.
Can anyone see anything obviously wrong? | I believe that this code:
```
myTimer.Tick -= new EventHandler(ev);
```
creates a new EventHandler object. It will never remove an existing EventHandler. To get the functionality you want, you should be passing in EventHandlers, not MyDelegates, to the add and remove methods:
```
Timer myTimer = new Timer(); // Windows.Forms Timer
public void addEvent(EventHandler ev)
{
myTimer.Tick += ev;
}
public void removeEvent(EventHandler ev)
{
myTimer.Tick -= ev;
}
```
The calling code will have to keep track of the EventHandlers added, so that it can pass in the same EventHandler object when it is time to unsubscribe. | The initial code works fine, as long as the `MyDelegate` '`ev`' passed into `addEvent` and `removeEvent` is the same object instance (For example, if there is a class-level `MyDelegate` field that contains the instance or if you follow the advice of several others here and keep the `MyDelegate` object(s) in a Dictionary).
I suspect the problem is that the code calling `addEvent` and `removeEvent` is passing new `MyDelegate` instances pointing to some handler method, like so:
```
addEvent(new MyDelegate(this.HandlerMethod));
// ... do some stuff
removeEvent(new MyDelegate(this.HandlerMethod));
```
In which case `addEvent` and `removeEvent` are creating `EventHandler` delegates which point to different method addresses even though those delegates in turn are pointing to the same method (`this.HandlerMethod`). This is because the `EventHandler` delegates that `add` and `remove` create point to the `MyDelegate.Invoke()` method on different `MyDelegate` instances rather than directly to the address of `this.HandlerMethod`. | C# adding and removing events from a timer | [
"",
"c#",
"event-handling",
""
] |
I read [this question](https://stackoverflow.com/questions/580984/how-do-you-get-the-object-reference-of-an-object-in-java-when-tostring-and-hash) and thought that would easily be solved (not that it isn't solvable without) if one could write:
```
@Override
public String toString() {
return super.super.toString();
}
```
I'm not sure if it is useful in many cases, but I wonder *why* it isn't and if something like this exists in other languages.
What do you guys think?
**EDIT:**
To clarify: yes I know, that's impossible in Java and I don't really miss it. This is nothing I expected to work and was surprised getting a compiler error. I just had the idea and like to discuss it. | It violates encapsulation. You shouldn't be able to bypass the parent class's behaviour. It makes sense to sometimes be able to bypass your *own* class's behaviour (particularly from within the same method) but not your parent's. For example, suppose we have a base "collection of items", a subclass representing "a collection of red items" and a subclass of that representing "a collection of big red items". It makes sense to have:
```
public class Items
{
public void add(Item item) { ... }
}
public class RedItems extends Items
{
@Override
public void add(Item item)
{
if (!item.isRed())
{
throw new NotRedItemException();
}
super.add(item);
}
}
public class BigRedItems extends RedItems
{
@Override
public void add(Item item)
{
if (!item.isBig())
{
throw new NotBigItemException();
}
super.add(item);
}
}
```
That's fine - RedItems can always be confident that the items it contains are all red. Now suppose we *were* able to call super.super.add():
```
public class NaughtyItems extends RedItems
{
@Override
public void add(Item item)
{
// I don't care if it's red or not. Take that, RedItems!
super.super.add(item);
}
}
```
Now we could add whatever we like, and the invariant in `RedItems` is broken.
Does that make sense? | I think Jon Skeet has the correct answer. I'd just like to add that you *can* access shadowed variables from superclasses of superclasses by casting `this`:
```
interface I { int x = 0; }
class T1 implements I { int x = 1; }
class T2 extends T1 { int x = 2; }
class T3 extends T2 {
int x = 3;
void test() {
System.out.println("x=\t\t" + x);
System.out.println("super.x=\t\t" + super.x);
System.out.println("((T2)this).x=\t" + ((T2)this).x);
System.out.println("((T1)this).x=\t" + ((T1)this).x);
System.out.println("((I)this).x=\t" + ((I)this).x);
}
}
class Test {
public static void main(String[] args) {
new T3().test();
}
}
```
which produces the output:
```
x= 3
super.x= 2
((T2)this).x= 2
((T1)this).x= 1
((I)this).x= 0
```
(example from the [JLS](https://docs.oracle.com/javase/specs/jls/se10/html/jls-15.html#jls-15.11.2))
However, this doesn't work for method calls because method calls are determined based on the runtime type of the object. | Why is super.super.method(); not allowed in Java? | [
"",
"java",
"superclass",
""
] |
The JUnit view in Eclipse seems to order the tests randomly. How can I order them by class name? | As Gary said in the comments:
> it would be nice if Unit Runner could
> be told to go ahead and order them by
> class name. Hmm, maybe I should look
> into the source code...
I did look but there's no hint of a functionality to sort these names. I would suggest a change request to the JUnit plugin, but I don't think, that there are lot of people using this thing, so: DIY.
I would like to see the solution if you modify the plugin code. | One thing that one might do is using the schema of JUnit 3.x. We used a test suite that was called AllTests where you add the tests to it in a specific order. And for every package we got another AllTests. Giving those test suites a name being the same as the package enables one to easily build a hierarchy that should be valued by the junit plugin.
I really dislike how it is even presenting the test methods inside the Junit viewer. It should be in the very same order as they are specified in the TestCase class. I order those methods in the way of importance and features. So the upmost failing method is to correct first and then the more special one in the later part of the test case.
That is really annoying that the test runner is scrambling those. I will take a look at it myself and if I find a solution I will update this answer.
Update:
My problem with the ordering of method names within a TestCase is related to this one:
<https://bugs.java.com/bugdatabase/view_bug?bug_id=7023180> (Thanks Oracle!).
So in the end oracle changed the ordering of the methods within a class.getMethods or class.getDeclaredMethods call. Now the methods are random and can change between different runs of the JVM. It seams to be related to optimizations of compare or even is an attempt to compress method name - who knows... .
So whats left. First one can use: @FixMethodOrder (from [javacodegeeks.com](http://www.javacodegeeks.com/2013/01/junit-test-method-ordering.html)):
> 1. @FixMethodOrder(MethodSorters.DEFAULT) – deterministic order based on an internal comparator
> 2. @FixMethodOrder(MethodSorters.NAME\_ASCENDING) – ascending order of method names
> 3. @FixMethodOrder(MethodSorters.JVM) – pre 4.11 way of depending on reflection based order
Well that is stupid but explains why people start using test1TestName schema.
**Update2**:
I use ASM since Javassist also produces random sorted methods on getMethods(). They use Maps internally. With ASM I just use a Visitor.
```
package org.junit.runners.model;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import com.flirtbox.ioc.OrderTest;
/**
* @author Martin Kersten
*/
public class TestClassUtil {
public static class MyClassVisitor extends ClassVisitor {
private final List<String> names;
public MyClassVisitor(List<String> names) {
super(Opcodes.ASM4);
this.names = names;
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc,
String signature, String[] exceptions) {
names.add(name);
return super.visitMethod(access, name, desc, signature, exceptions);
}
}
private static List<String> getMethodNamesInCorrectOrder(Class<?> clazz) throws IOException {
InputStream in = OrderTest.class.getResourceAsStream("/" + clazz.getName().replace('.', '/') + ".class");
ClassReader classReader=new ClassReader(in);
List<String> methodNames = new ArrayList<>();
classReader.accept(new MyClassVisitor(methodNames), 0);
return methodNames;
}
public static void sort(Class<?> fClass, List<FrameworkMethod> list) {
try {
final List<String> names = getMethodNamesInCorrectOrder(fClass);
Collections.sort(list, new Comparator<FrameworkMethod>() {
@Override
public int compare(FrameworkMethod methodA, FrameworkMethod methodB) {
int indexA = names.indexOf(methodA.getName());
int indexB = names.indexOf(methodB.getName());
if(indexA == -1)
indexA = names.size();
if(indexB == -1)
indexB = names.size();
return indexA - indexB;
}
});
} catch (IOException e) {
throw new RuntimeException("Could not optain the method names of " + fClass.getName() + " in correct order", e);
}
}
}
```
Just put this in your src/test/java folder in the package org.junit.runners.model. Now copy the org.junit.runners.model.TestClass of the junit 4.5 lib to the same package and alter its constructor by adding the sorting routine.
```
public TestClass(Class<?> klass) {
fClass= klass;
if (klass != null && klass.getConstructors().length > 1)
throw new IllegalArgumentException(
"Test class can only have one constructor");
for (Class<?> eachClass : getSuperClasses(fClass))
for (Method eachMethod : eachClass.getDeclaredMethods())
addToAnnotationLists(new FrameworkMethod(eachMethod));
//New Part
for(List<FrameworkMethod> list : fMethodsForAnnotations.values()) {
TestClassUtil.sort(fClass, list);
}
//Remove once you have verified the class is really picked up
System.out.println("New TestClass for " + klass.getName());
}
```
Here you go. Now you have nicely sorted methods in the order they are declared within the java file. If you wonder the class path is usually set that way that everything in your src (target or bin) folder is considered first by the classloader. So while defining the very same package and the same class you can 'override' every class / interface in any library you use. Thats the trick!
**Update3**
I was able to get a tree view of every package and every class in the right order to.
* The idea is to subclass ParentRunner and then add all classes to it that you identify as being public and having methods annotated with test.
* Add a getName() method returning only the package name of the class your suite runner is representing (so you see the tree as a package tree without the suite's class name).
* Inspect subdirectories if you find a certain suite class (I use AllTests for all suite classes).
* If you do not find a suite class in a subdirectory check all of its subdirectories, this way you dont miss a package containing tests if the parent directory is not containing a suite.
That was it. The suite class I add everywhere is:
`@RunWith(MySuiteRunner.class) public class AllTests { }`
That's it. It should you give enough to start and extend on this one. The suite runner is only using reflection but I sort the test classes and suits of the subdirectories alphabetically and suits of subdirectories (which represent the packages they are in) are sorted upmost. | Ordering unit tests in Eclipse's JUnit view | [
"",
"java",
"eclipse",
"junit",
""
] |
How do I detect the width of a user's window with Javascript and account for their scrollbar? (I need the width of the screen INSIDE of the scrollbar). Here's what I have...it seems to work in multiple browsers...except that it doesn't account for the scrollbars..
```
function browserWidth() {
var myWidth = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
} else if( document.documentElement && document.documentElement.clientWidth ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
} else if( document.body && document.body.clientWidth ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
}
return myWidth;
}
```
any ideas? i need it to work in all browsers;) | You will find the big summary of what properties are supported on what browsers [on this page on quirksmode.org](http://www.quirksmode.org/dom/w3c_cssom.html).
Your best bet is probably to grab an element in the page (using document.body where supported, or document.getElementById or whatever), walk its offsetParent chain to find the topmost element, then examine that element's clientWidth and clientHeight. | A (markedly nasty) workaround if you're only interested in the width is to create a 1px x 100% div and use its offsetWidth. Works on IE>=7, FF, Chrome, Safari and Opera (I've not tried IE6, as we're working to a you're-lucky-it-works-at-all-so-don't-complain-about-rendering-oddities policy thereabouts these days). I hang the div off document.body with attributes `{ position: 'absolute', top: '-1px', left: 0, width: '100%', height: '1px' }`, creating it the first time it's needed.
Works if you can stomach it. | detect window width and compensate for scrollbars - Javascript | [
"",
"javascript",
"screen",
"width",
""
] |
I have an image gallery that is created using a repeater control. The repeater gets bound inside my code behind file to a table that contains various image paths.
The images in my repeater are populated like this
```
<img src='<%# Eval("PicturePath")' %>' height='200px' width='150px'/>
```
(or something along those lines, I don't recall the exact syntax)
The problem is sometimes the images themselves are massive so the load times are a little ridiculous. And populating a 150x200px image definitely should not require a 3MB file.
Is there a way I can not only change the image dimensions, but shrink the file size down as well?
Thanks! | I would recommend creating a handler that can resize images for you on the fly and encode them in whatever format you like.. kind of like a thumbnail generator. This will cost CPU on the server but you can cache images and severely reduce bandwidth costs ETC. Let me see if I can find the link to a good article I read on something similar.
You can look at [this article](http://dotnetslackers.com/articles/aspnet/Generating-Image-Thumbnails-in-ASP-NET.aspx) it isn't the one I had read but it has some info about how you can go about implementing this. | You're looking for the [GetThumbnailImage method](http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx) of the Image class. You will either want to generate the thumbnail images ahead of time or create the image the first time it is accessed and save it to disk for later use (so first access would be slow but subsequent requests would be quick). | Dynamically reducing image dimension as well as image size in C# | [
"",
"c#",
"asp.net",
"image-scaling",
""
] |
I've got a window that I handle WM\_NCLBUTTONUP messages, in order to handle clicks on custom buttons in the caption bar. This works great when the window is maximised, but when it's not, the WM\_NCLBUTTONUP message never arrives! I do get a WM\_NCLBUTTONDOWN message though. Strangely WM\_NCLBUTTONUP does arrive if I click on the right of the menu bar, but anywhere along the caption bar / window frame, the message never arrives.
After a while of debugging I discovered that if I set a breakpoint on CMainFrame::OnNcLButtonDown(), clicked the caption bar, but keep the mouse button held down, let the debugger break in the function, hit F5 to continue debugging, then release the mouse button - magically WM\_NCLBUTTONUP is sent!!
My question is two-fold, (1) what the hell is going on? (2) how do I get around this "problem".
I also note that there are several other people on the internet who have the same issue (a quick Google reveals lots of other people with the same issue, but no solution).
**Edit**
Thanks for the first two replies, I've tried calling ReleaseCapture in NCLButtonDown, but it has no effect (in fact, it returns NULL, indicating a capture is not in place). I can only assume that the base class (def window proc) functionality may set a capture. I shall investigate on Monday... | I've had this same problem. The issue is indeed that a left button click on the window caption starts a drag, and thus mouse capture, which prevents WM\_NCLBUTTONUP from arriving.
The solution is to override WM\_NCHITTEST:
```
LRESULT CALLBACK WndProc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
switch (nMsg)
{
...
case WM_NCHITTEST:
Point p(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam);
ScreenToClient(p);
if (myButtonRect.Contains(p))
{
return HTBORDER;
}
break;
}
return DefWindowProc(hWnd, nMsg, wParam, lParam);
}
```
So essentially you inform Windows that the area occupied by your button is not part of the window caption, but a non-specific part of the non-client area (HTBORDER).
Footnote: If you have called SetCapture() and not yet called ReleaseCapture() when you expect the WM\_NCLBUTTONDOWN message to come in, it won't arrive even with the above change. This can be irritating since it's normal to capture the mouse during interaction with such custom buttons so that you can cancel the click/highlight if the mouse leaves the window. However, as an alternative to using capture, you might consider SetTimer()/KillTimer() with a short (eg. 100 ms) interval, which won't cause WM\_NCLBUTTONUP messages to vanish. | A wild guess - some code is capturing the mouse, probably to facilitate the window move when you grab the title. That would explain also why breaking in the debugger would cause the message to show up - the debugger interaction is clearing the mouse capture.
I would suggest you run Spy++ on that window and it's children and try to figure out who gets the button up message.
As to how to fix it - can't help you there without looking at the actual code. You'll have to figure out who the culprit is and look at their code. | The curious problem of the missing WM_NCLBUTTONUP message when a window isn't maximised | [
"",
"c++",
"winapi",
"mfc",
""
] |
Trying to compile a sample http class with the SDK, and getting some strange link errors... I am sure its something to do with a missing option, or directory...
I am no expert in c++ as you can see, but looking for any assistance.
I included my sample class. I also did install the Windows SDK. If you need any other information about my setups or anything, please ask. I'd prefer someone point me to a working WinHttp SDK sample project.
```
//START OF utils.cpp
#pragma once
#include "stdafx.h"
class http
{
public:
http();
~http();
std::string getText();
};
//END OF utils.cpp
```
---
```
//START OF utils.cpp
#include "stdafx.h"
#include "utils.h"
http::http()
{
}
http::~http()
{
}
std::string http::getText()
{
DWORD dwSize = 0;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer;
BOOL bResults = FALSE;
HINTERNET hSession = NULL,
hConnect = NULL,
hRequest = NULL;
// Use WinHttpOpen to obtain a session handle.
hSession = WinHttpOpen( L"WinHTTP Example/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0 );
// Specify an HTTP server.
if( hSession )
hConnect = WinHttpConnect( hSession, L"www.microsoft.com",
INTERNET_DEFAULT_HTTPS_PORT, 0 );
// Create an HTTP request handle.
if( hConnect )
hRequest = WinHttpOpenRequest( hConnect, L"GET", NULL,
NULL, WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_SECURE );
// Send a request.
if( hRequest )
bResults = WinHttpSendRequest( hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS, 0,
WINHTTP_NO_REQUEST_DATA, 0,
0, 0 );
// End the request.
if( bResults )
bResults = WinHttpReceiveResponse( hRequest, NULL );
// Keep checking for data until there is nothing left.
if( bResults )
{
do
{
// Check for available data.
dwSize = 0;
if( !WinHttpQueryDataAvailable( hRequest, &dwSize ) )
printf( "Error %u in WinHttpQueryDataAvailable.\n",
GetLastError( ) );
// Allocate space for the buffer.
pszOutBuffer = new char[dwSize+1];
if( !pszOutBuffer )
{
printf( "Out of memory\n" );
dwSize=0;
}
else
{
// Read the data.
ZeroMemory( pszOutBuffer, dwSize+1 );
if( !WinHttpReadData( hRequest, (LPVOID)pszOutBuffer,
dwSize, &dwDownloaded ) )
printf( "Error %u in WinHttpReadData.\n", GetLastError( ) );
else
printf( "%s", pszOutBuffer );
// Free the memory allocated to the buffer.
delete [] pszOutBuffer;
}
} while( dwSize > 0 );
}
// Report any errors.
if( !bResults )
printf( "Error %d has occurred.\n", GetLastError( ) );
// Close any open handles.
if( hRequest ) WinHttpCloseHandle( hRequest );
if( hConnect ) WinHttpCloseHandle( hConnect );
if( hSession ) WinHttpCloseHandle( hSession );
return "";
}
//END OF utils.cpp
```
---
```
1>------ Build started: Project: winagent, Configuration: Debug Win32 ------
1>Compiling...
1>utils.cpp
1>Linking...
1> Creating library C:\winagent\Debug\winagent.lib and object C:\winagent\Debug\winagent.exp
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpCloseHandle@4 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText@http@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpReadData@16 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText@http@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpQueryDataAvailable@8 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText@http@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpReceiveResponse@8 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText@http@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpSendRequest@28 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText@http@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpOpenRequest@28 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText@http@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpConnect@16 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText@http@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpOpen@20 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText@http@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>C:\winagent\Debug\winagent.exe : fatal error LNK1120: 8 unresolved externals
1>Build log was saved at "file://c:\winagent\Debug\BuildLog.htm"
1>winagent - 9 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
``` | If you check the MSDN reference for the WinHttp\* functions you will see that you need to link with the library Winhttp.lib.
Open the project settings, select the linker options then 'input' and add WinHttp.lib to the 'Additional Dependencies' list.
Or you could put
```
#pragma comment(lib, "winhttp.lib")
```
(as previously mentioned) in your source code. | You need to link to winhttp.lib
Change the project settings or add this line to your .cpp file
```
#pragma comment(lib, "winhttp")
``` | C++ Compile problem with WinHttp/Windows SDK | [
"",
"c++",
"sdk",
""
] |
Sometimes I will be at a breakpoint in my code and I want to view the contents of a `DataTable` variable (or a `DataTable` in a `DataSet`). The quick watch doesn't give you a very clear view of the contents. How can I view them easily? | The Visual Studio debugger comes with four standard visualizers. These are the text, HTML, and XML visualizers, all of which work on string objects, and the dataset visualizer, which works for DataSet, DataView, and DataTable objects.
To use it, break into your code, mouse over your DataSet, expand the quick watch, view the Tables, expand that, then view Table[0] (for example). You will see something like {Table1} in the quick watch, but notice that there is also a **magnifying glass icon**. Click on that icon and your DataTable will open up in a grid view.
[](https://i.stack.imgur.com/rJnyo.png) | To beautify adinas's debugger output I made some simple formattings:
```
public void DebugTable(DataTable table)
{
Debug.WriteLine("--- DebugTable(" + table.TableName + ") ---");
int zeilen = table.Rows.Count;
int spalten = table.Columns.Count;
// Header
for (int i = 0; i < table.Columns.Count; i++)
{
string s = table.Columns[i].ToString();
Debug.Write(String.Format("{0,-20} | ", s));
}
Debug.Write(Environment.NewLine);
for (int i = 0; i < table.Columns.Count; i++)
{
Debug.Write("---------------------|-");
}
Debug.Write(Environment.NewLine);
// Data
for (int i = 0; i < zeilen; i++)
{
DataRow row = table.Rows[i];
//Debug.WriteLine("{0} {1} ", row[0], row[1]);
for (int j = 0; j < spalten; j++)
{
string s = row[j].ToString();
if (s.Length > 20) s = s.Substring(0, 17) + "...";
Debug.Write(String.Format("{0,-20} | ", s));
}
Debug.Write(Environment.NewLine);
}
for (int i = 0; i < table.Columns.Count; i++)
{
Debug.Write("---------------------|-");
}
Debug.Write(Environment.NewLine);
}
```
Best of this solution: **You don't need Visual Studio**!
Here my example output:
```
SELECT PackKurz, PackName, PackGewicht FROM verpackungen
PackKurz | PackName | PackGewicht |
---------------------|----------------------|----------------------|-
BB205 | BigBag 205 kg | 205 |
BB300 | BigBag 300 kg | 300 |
BB365 | BigBag 365 kg | 365 |
CO | Container, Alteru... | |
EP | Palette | |
IBC | Chemikaliengefäß ... | |
lose | nicht verpackungs... | 0 |
---------------------|----------------------|----------------------|-
``` | How can I easily view the contents of a datatable or dataview in the immediate window | [
"",
"c#",
".net",
"asp.net",
"visual-studio",
""
] |
I'm using the ICSharpcode text editor, and I am looking for a way to do Word Wrap in it. Is there any documentation for this other than the source code? My only documentation so far has been the [Code Project article](http://www.codeproject.com/KB/edit/TextEditorControl.aspx), and the source code for [Kaxaml](http://www.codeplex.com/Kaxaml/SourceControl/ListDownloadableCommits.aspx). Most importantly, how does one turn WordWrap on in the editor? Second, is there any documentation that I am missing for the editor? | The `ICSharpCode.TextEditor` does not support word wrapping yet. It will support it in SharpDevelop 4. See [this forum post](http://community.icsharpcode.net/forums/p/8879/24725.aspx#24725), among [others](http://community.icsharpcode.net/search/SearchResults.aspx?q=word+wrap&o=Relevance). You can download SharpDevelop 4 Alpha from their [build server](http://build.sharpdevelop.net/BuildArtefacts/).
In order to implement support for word wrapping yourself, you're gonna have to jump through a lot of hoops. And these hoops will all be on fire. If you ***really*** need this, in SharpDevelop 3, a good place to look for the code to word-wrap is [DeveloperFusion](http://www.developerfusion.co.uk/show/4646/) as Jon T suggested. | Word wrapping is very hard to get right and still have the renderer fast. | Word Wrap in ICSharpcode TextEditor | [
"",
"c#",
"text-editor",
"icsharpcode",
""
] |
So I'm learning C++. I've got my "C++ Programming Language" and "Effective C++" out and I'm running through Project Euler. Problem 1...dunzo. Problem 2...not so much. I'm working in VS2008 on a Win32 Console App.
Whats the Sum of all even terms of the Fibonacci Sequence under 4 million?
It wasn't working so I cut down to a test case of 100...
Here's what I wrote...
```
// Problem2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Project Euler Problem 2:\n\n";
cout << "Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:\n\n";
cout << "1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\n\n";
cout << "Find the sum of all the even-valued terms in the sequence which do not exceed four million.\n\n";
cout << "Answer: " << Solve();
}
double Solve() {
int FibIndex = 0;
double result = 0.0;
double currentFib = GenerateNthFibonacciNumber(FibIndex);
while (currentFib < 100.0){
cout << currentFib << " " << (int)currentFib << " " << (int)currentFib % 2 << "\n";
if ((int)currentFib % 2 == 0){
result += currentFib;
cout<<(int)currentFib;
}
currentFib = GenerateNthFibonacciNumber(++FibIndex);
}
return result;
}
double GenerateNthFibonacciNumber(const int n){
//This generates the nth Fibonacci Number using Binet's Formula
const double PHI = (1.0 + sqrt(5.0)) / 2.0;
return ((pow(PHI,n)-pow(-1.0/PHI,n)) / sqrt(5.0));
}
```
And here's the output...
> Project Euler Problem 2:
>
> Each new term in the Fibonacci
> sequence is generated by adding the
> previous two terms. By starting with 1
> and 2, the first 10 terms will be:
>
> 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
>
> Find the sum of all the even-valued
> terms in the sequence which do not
> exceed four million.
>
> 0 0 0
> 1 1 1
> 1 1 1
> 2 2
> 0
> 3 3 1
> 5 5 1
> 8 8 0
> 13
> 13 1
> 21 21 1
> 34 34 0
> 55 54
> 0
> 89 89 1
> Answer: 99
So I have three columns of debug code...the number returned from the generate function, (int)generatedNumber, and (int)generatedNumber % 2
So on the 11th term we have
55,54,0
Why does (int)55 = 54? | Casting to `int` truncates the number - same as if you'd called `floor(currentFib)`. So even if `currentFib` is `54.999999`... (a number so close to 55 that it will be rounded up when printed), `(int)currentFib` will produce 54. | Due to floating point rounding, that 55 row is computing something like 54.99999.
Casting double to int truncates the .99999 right off.
On my machine, printing a column displaying `(currentFib-(int)currentFib)` shows errors on the order of 1.42109e-14. So it's more like 0.999999999999986. | Why does (int)55 == 54 in C++? | [
"",
"c++",
"fibonacci",
""
] |
I make my `boost::signal`s public because I'm lazy.
```
class Button {
public:
signal<void()> clicked;
};
int main() {
Button btn;
btn.clicked.connect(handleClick);
}
```
... rather than encapsulating with a `Button::OnClicked(boost::function<void()>)`.
Is this going to come back and bite me? | It depends.
It has bitten me before when I wanted to add some special logic each time an object connected to another object's signals. This is the most likely case to bite you.
Also, it can make it difficult to keep track of exactly when other objects are connecting to any given object.
I would say hide the connections behind a function to be on the safe side.
I usually use a macro to do the vanilla function definition.
```
#define SIGNAL(slot,name) connection name(function<slot> func) { return _##name##.connect(func);}
```
And then in a class definition:
```
SIGNAL(void(),clicked)
```
This assumes you follow the convention of naming the signal '\_clicked' but you can substitute any convention. It generally keeps the interface cleaner for all of your classes. When you want to add special connection logic you can, without changing all of the other objects that use the signal.
**EDIT**
One instance was when the signal object was actually moved to a delegate implementation inside another class, but it still made sense for objects to connect through the original class. This broke all of the places that tried to connect to it. If they had been using function accessors to connect, it would have been as simple as changing the function to look up the signal in the delegate. But as it was it broke all the users of the original class.
Or, when I wanted to log each time something connected to a specific signal. This was just for debugging purposes, but it can be very helpful if you suspect something wonky is going on like cycles in your signal connections. | I've stumbled across a good reason *not* to do this.
We are looking at using a third party library that exposes boost::signals on an external interface. This library depends on a version of boost with a set of compiler definitions that are binary-incompatible with the standard Visual Studio compiler definitions that we use in our project. Whenever we attempt to call the third-party-library's signal.connect, things die.
The solution for us is either to:
1. Recompile all of our source and dependent libraries with the boost version provided by them.
2. Wrap the boost signals and hide the implementation
Something to consider, at least! | Public boost::signal object | [
"",
"c++",
"boost-signals",
"public-fields",
""
] |
I would like to use the .Net Regex.Split method to split this input string into an array. **It must split on whitespace unless it is enclosed in a quote.**
Input:
Here is "my string" it has "six matches"
Expected output:
1. Here
2. is
3. my string
4. it
5. has
6. six matches
What pattern do I need? Also do I need to specify any RegexOptions? | No options required
Regex:
```
\w+|"[\w\s]*"
```
C#:
```
Regex regex = new Regex(@"\w+|""[\w\s]*""");
```
**Or if you need to exclude " characters:**
```
Regex
.Matches(input, @"(?<match>\w+)|\""(?<match>[\w\s]*)""")
.Cast<Match>()
.Select(m => m.Groups["match"].Value)
.ToList()
.ForEach(s => Console.WriteLine(s));
``` | Lieven's solution gets most of the way there, and as he states in his comments it's just a matter of changing the ending to Bartek's solution. The end result is the following working regEx:
```
(?<=")\w[\w\s]*(?=")|\w+|"[\w\s]*"
```
Input: Here is "my string" it has "six matches"
Output:
1. Here
2. is
3. "my string"
4. it
5. has
6. "six matches"
Unfortunately it's including the quotes. If you instead use the following:
```
(("((?<token>.*?)(?<!\\)")|(?<token>[\w]+))(\s)*)
```
And explicitly capture the "token" matches as follows:
```
RegexOptions options = RegexOptions.None;
Regex regex = new Regex( @"((""((?<token>.*?)(?<!\\)"")|(?<token>[\w]+))(\s)*)", options );
string input = @" Here is ""my string"" it has "" six matches"" ";
var result = (from Match m in regex.Matches( input )
where m.Groups[ "token" ].Success
select m.Groups[ "token" ].Value).ToList();
for ( int i = 0; i < result.Count(); i++ )
{
Debug.WriteLine( string.Format( "Token[{0}]: '{1}'", i, result[ i ] ) );
}
```
Debug output:
```
Token[0]: 'Here'
Token[1]: 'is'
Token[2]: 'my string'
Token[3]: 'it'
Token[4]: 'has'
Token[5]: ' six matches'
``` | Regular Expression to split on spaces unless in quotes | [
"",
"c#",
".net",
"regex",
""
] |
We're developing a .NET app that must make up to tens of thousands of small webservice calls to a 3rd party webservice. We would prefer a more 'chunky' call, but the 3rd party does not support it. We've designed the client to use a configurable number of worker threads, and through testing have code that is fairly well optimized for one multicore machine. However, we still want to improve the speed, and are looking at spreading the work accross multiple machines. We're well versed in typical client/server/database apps, but new to designing for multiple machines. So, a few questions related to that:
* Is there any other client-side optimization, besides multithreading, that we should look at that could improve speed of a http request/response? (I should note this is a non-standard webservice, so is implemented using WebClient, not a WCF or SOAP client)
* Our current thinking is to use WCF to publish chunks of work to MSMQ, and run clients on one or more machines to pull work off of the queue. We have experience with WCF + MSMQ, but want to be sure we're not missing better options. Are there other, better ways to do this today?
* I've seen some 3rd party tools like DigiPede and Microsoft's HPC offerings, but these seem like overkill. Any experience with those products or reasons we should consider them over roll-our-own? | Sounds like your goal is to execute all these web service calls as quickly as you can, and get the results tabulated. Given that, your greatest efficiency control is going to be through scaling the number of concurrent requests you can make.
Be sure to look at your [client-side connection limits](http://msdn.microsoft.com/en-us/library/system.net.servicepoint.connectionlimit.aspx). By default, I think the system default is 2 connections. I haven't tried this myself, but by upping the number of connections with this property, you should theoretically see a multiplier effect in terms of generating more requests by generating more connections from a single machine. There's [more info](http://social.microsoft.com/forums/en-US/netfxnetcom/thread/1f863f20-09f9-49a5-8eee-17a89b591007) on MS forums.
The MSMQ option works well. I'm running that configuration myself. ActiveMQ is also a fine solution, but MSMQ is already on the server.
You have a good starting point. Get that in operation, then move on to performance and throughput. | At CodeMash this year, Wesley Faler did an interesting presentation on this sort of problem. His solution was to store "jobs" in a DB, then use clients to pull down work and mark status when complete.
He then pushed the whole infrastructure up to Amazon's EC2.
[Here's his slides from the presentation](http://docs.google.com/Present?docid=dc6tbhk6_0cngb9zkw) - they should give you the basic idea:
I've done something similar w/ multiple PC's locally - the basics of managing the workload were similar to Faler's approach. | What is the best way scale out work to multiple machines? | [
"",
"c#",
"performance",
"scaling",
""
] |
Working on Maths problems, I'm very fond of LINQ to Data.
I would like to know if LINQ is smart enough to avoid a cast like .ToArray() when the IEnumerable I work with is already an array.
See example below:
```
/// <summary> Transforms an array of timeSeries into one ModelData. </summary>
public static ModelData ToModelData(this IEnumerable<TimeSerieInfo> timeSeries)
{
var seriesArray = timeSeries as TimeSerieInfo[];
return null != seriesArray ?
new ModelData(seriesArray) :
new ModelData(timeSeries.ToArray());
}
```
Does LINQ avoid the transformation to an array when the `IEnumerable<TimeSerieInfo> timeSeries` is already an array?
Thank you for help. | LINQ creates a copy of the array, *and this is the correct behaviour* IMO. It would be highly confusing if calling `ToArray()` and then modifying the returned array *sometimes* modified the original collection and *sometimes* didn't. | I suspect that it will do what you ask and create a new array. Could you not change your constructor of `ModelData` to take an `IEnumerable` instead? | LINQ to Data : Clever Type Recognition | [
"",
"c#",
"linq",
"types",
"casting",
""
] |
Is is possible to create silverlight content in C# using Visual Studio 2005 Professional or Visual Studio 2008 Express Edition? I can't find an answer on Microsoft's web site. Thanks for any help! | Yes if the express edition is [Visual Web Developer 2008 Express Edition](http://www.microsoft.com/express/vwd/). Here is a quote from [this blog post](http://weblogs.asp.net/scottgu/archive/2008/11/16/update-on-silverlight-2-and-a-glimpse-of-silverlight-3.aspx) from the guy who runs the development team for Silverlight at Microsoft:
> Developers can use either VS 2008 or
> the free Visual Web Developer 2008
> Express to open and edit Silverlight 2
> projects, and get a powerful
> code-focused .NET development
> environment. | I belive you can with 2008 express.
Make sure you install SP1 to 2008 then install everything else from [here](http://silverlight.net/GetStarted/) (it has the SP1 download as well) | Silverlight and VS 2005 or VS 2008 Express Edition | [
"",
"c#",
"visual-studio",
"silverlight",
"silverlight-2.0",
""
] |
How can I remove all HTML from a string in Python? For example, how can I turn:
```
blah blah <a href="blah">link</a>
```
into
```
blah blah link
```
Thanks! | You can use a regular expression to remove all the tags:
```
>>> import re
>>> s = 'blah blah <a href="blah">link</a>'
>>> re.sub('<[^>]*>', '', s)
'blah blah link'
``` | When your regular expression solution hits a wall, try this super easy (and reliable) [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) program.
```
from BeautifulSoup import BeautifulSoup
html = "<a> Keep me </a>"
soup = BeautifulSoup(html)
text_parts = soup.findAll(text=True)
text = ''.join(text_parts)
``` | Python HTML removal | [
"",
"python",
"string",
""
] |
In my [earlier question](https://stackoverflow.com/questions/553974/why-does-int55-54-in-c) I was printing a `double` using `cout` that got rounded when I wasn't expecting it. How can I make `cout` print a `double` using full precision? | In C++20 you can use [`std::format`](https://en.cppreference.com/w/cpp/utility/format) to do this:
```
std::cout << std::format("{}", std::numbers::pi_v<double>);
```
Output (assuming [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754) `double`):
```
3.141592653589793
```
The default floating-point format is the shortest decimal representation with a round-trip guarantee. The advantage of this method compared to the `setprecision` I/O manipulator is that it doesn't print unnecessary digits and is not affected by global state (see [this blog post](https://vitaut.net/posts/2023/printing-double/) for more details).
In the meantime you can use [the {fmt} library](https://github.com/fmtlib/fmt), `std::format` is based on. {fmt} also provides the `print` function that makes this even easier and more efficient ([godbolt](https://godbolt.org/z/ej48Wa)):
```
fmt::print("{}", M_PI);
```
The question doesn’t actually define what it means by "full precision". Normally it is understood as the precision enough for a round trip through decimal but there is another possible but unlikely interpretation of [the maximum number of (significant) decimal digits](https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/). For IEEE 754 double the latter is 767 digits.
**Disclaimer**: I'm the author of {fmt} and C++20 `std::format`. | Use [`std::setprecision`](http://en.cppreference.com/w/cpp/io/manip/setprecision):
```
#include <iomanip>
std::cout << std::setprecision (15) << 3.14159265358979 << std::endl;
``` | How do I print a double value with full precision using cout? | [
"",
"c++",
"floating-point",
"precision",
"iostream",
"cout",
""
] |
I'm using SQL Server 2005.
Our application almost never deletes without it being a logical delete and therefore we have no need for cascading deletes.
In fact, its quite a comfort knowing that the foreign key contraints give us some protection against an accidental delete statement.
However, very occasionally I need to delete a top level table and all of its children. At the moment I do this with multiple DELETE statements in the write order and it becomes a very large, complex and impossible to keep up to date script.
I'm wondering if there is a way of automatically turning cascading deletes on for all foreign keys in the database, performing my top level delete, and then turning them all back on again? | For another question here, [I wrote a script](https://stackoverflow.com/questions/485581/generate-delete-statement-from-foreign-key-relationships-in-sql-2008/485760#485760) which should generate the deletes automatically. | How about writing pair of scripts -- one you manually run when you're about to delete records that enables the on delete cascade appropriately for the constraints, and then have another one other that you run once finished deleting to disable them and get things back to normal? | Temporary enabling of ON DELETE CASCADE | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
We have an application that behaves really badly in IE6, the application relies heavily on javascript and most of the activity happens in one page.
In IE6, it seems that memory keeps piling up and never gets cleared even when you navigate to a different site!
Since there's not so little code running within the browser, I'm looking for an external tool that will shed some light on the memory consumption of the application so that we can focus our optimization efforts. | One of the best tools I've found is IE Sieve, Memory Leak detector for Internet Explorer which is an improved version of drip - <http://home.wanadoo.nl/jsrosman/> | Well, IE6 is fundamentally broken, this shouldn't come as a surprise to any web developer.
Is the browser still so widely used among your users that this is a problem?
Anyway, I know IE6 leaks memory whenever you use cyclic references in Javascript. Its garbage collector is too broken to handle these, so they never get freed. | Javascript Memory profiling - IE6 | [
"",
"javascript",
"ajax",
"memory-leaks",
"internet-explorer-6",
""
] |
I need to perform a simple grep and other manipulations on large files in Java. I am not that familiar with the Java NIO utilities, but I am assuming that is what I need to use. What resources or helpful tips do you have for reading/writing large files. Also, I am working on a SWT application and need to display parts of that data within a text area on a GUI. | `java.io.RandomAccessFile` uses long for file-pointer offset so should be able to cope. However, you should read a chunk at a time otherwise overheads will be high. `FileInputStream` works similarly.
Java NIO shouldn't be too difficult. You don't need to mess around with `Selector`s or similar. In fact, prior to JDK7 you can't select with files. However, avoid mapping files. There is no unmap, so if you try to do it lots you'll run out of address space on 32-bit systems, or run into other problems (NIO does attempt to call GC, but it's a bit of a hack). | If all you are doing is reading the entire file a chunk at a time, with no special processing, then nio and `java.io.RandomAccessFile` are probably overkill. Just read and process the content of the file a block at a time. Ensure that you use a `BufferedInputStream` or `BufferedReader`.
If you have to read the entire file to do what you are doing, and you read only one file at a time, then you will gain little benefit from nio. | What are some tips for processing large files in Java | [
"",
"java",
"nio",
"large-files",
""
] |
How do I format my output in C++ streams to print fixed width left-aligned tables? Something like
```
printf("%-14.3f%-14.3f\n", 12345.12345, 12345.12345);
```
poducing
```
12345.123 12345.123
``` | Include the standard header [`<iomanip>`](http://www.cplusplus.com/query/search.cgi?q=iomanip) and go crazy. Specifically, the `setw` manipulator sets the output width. `setfill` sets the filling character. | ```
std::cout << std::setiosflags(std::ios::fixed)
<< std::setprecision(3)
<< std::setw(18)
<< std::left
<< 12345.123;
``` | Table layout using std::cout | [
"",
"c++",
"formatting",
"stream",
"iostream",
""
] |
Sometimes we encounter an SWT composite that absolutely refuses to lay itself out correctly. Often we encounter this when we have called dispose on a composite, and then replaced it with another; although it does not seem to be strictly limited to this case.
When we run into this problem, about 50 % of the time, we can call `pack()` and `layout()` on the offending composite, and all will be well. About 50 % of the time, though, we have to do this:
```
Point p = c.getSize();
c.setSize(p.x+1, p.y+1);
c.setSize(p);
```
We've had this happen with just about every combination of layout managers and such.
I wish I had a nice, simple, reproducible case, but I don't. I'm hoping that someone will recognize this problem and say: "Well, duh, you're missing xyz...." | Looks to me like the **layout's cache is outdated and needs to be refreshed**.
Layouts in SWT support caches, and will usually cache preferred sizes of the Controls, or whatever they like to cache:
```
public abstract class Layout {
protected abstract Point computeSize (Composite composite, int wHint, int hHint, boolean flushCache);
protected boolean flushCache (Control control) {...}
protected abstract void layout (Composite composite, boolean flushCache);
}
```
I'm relatively new to SWT programming (former Swing programmer), but encountered similar situations in which the layout wasn't properly updated. I was usually able to resolve them using the *other* layout methods that will also cause the layout to flush its cache:
```
layout(boolean changed)
layout(boolean changed, boolean allChildren)
``` | In the meantime I learned a little more about SWT's shortcomings when changing or resizing parts of the control hierarchy at runtime. `ScrolledComposite`s and `ExpandBar`s need also to be updated explicitly when the should adapt their minimal or preferred content sizes.
I wrote a little helper method that revalidates the layout of a control hierarchy for a control that has changed:
```
public static void revalidateLayout (Control control) {
Control c = control;
do {
if (c instanceof ExpandBar) {
ExpandBar expandBar = (ExpandBar) c;
for (ExpandItem expandItem : expandBar.getItems()) {
expandItem
.setHeight(expandItem.getControl().computeSize(expandBar.getSize().x, SWT.DEFAULT, true).y);
}
}
c = c.getParent();
} while (c != null && c.getParent() != null && !(c instanceof ScrolledComposite));
if (c instanceof ScrolledComposite) {
ScrolledComposite scrolledComposite = (ScrolledComposite) c;
if (scrolledComposite.getExpandHorizontal() || scrolledComposite.getExpandVertical()) {
scrolledComposite
.setMinSize(scrolledComposite.getContent().computeSize(SWT.DEFAULT, SWT.DEFAULT, true));
} else {
scrolledComposite.getContent().pack(true);
}
}
if (c instanceof Composite) {
Composite composite = (Composite) c;
composite.layout(true, true);
}
}
``` | Why does an SWT Composite sometimes require a call to resize() to layout correctly? | [
"",
"java",
"swt",
""
] |
Are there existing JARs available to convert from JSON to XML? | Not a Java, but **a pure XSLT 2.0 implementation**:
Have a look at the [**`f:json-document()`**](http://fxsl.cvs.sourceforge.net/viewvc/fxsl/fxsl-xslt2/f/func-json-document.xsl?view=markup&sortby=date) from the [**FXSL 2.x library**](http://fxsl.sf.net).
Using this function it is extremely easy to incorporate JSon and use it just as... XML.
For example, one can just write the following XPath expression:
```
f:json-document($vstrParam)/Students/*[sex = 'Female']
```
and **get all children of `Students` with `sex = 'Female'`**
**Here is the complete example:**
```
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:f="http://fxsl.sf.net/"
exclude-result-prefixes="f xs"
>
<xsl:import href="../f/func-json-document.xsl"/>
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:variable name="vstrParam" as="xs:string">
{
"teacher":{
"name":
"Mr Borat",
"age":
"35",
"Nationality":
"Kazakhstan"
},
"Class":{
"Semester":
"Summer",
"Room":
null,
"Subject":
"Politics",
"Notes":
"We're happy, you happy?"
},
"Students":
{
"Smith":
{"First Name":"Mary","sex":"Female"},
"Brown":
{"First Name":"John","sex":"Male"},
"Jackson":
{"First Name":"Jackie","sex":"Female"}
}
,
"Grades":
{
"Test":
[
{"grade":"A","points":68,"grade":"B","points":25,"grade":"C","points":15},
{"grade":"C","points":2, "grade":"B","points":29, "grade":"A","points":55},
{"grade":"C","points":2, "grade":"A","points":72, "grade":"A","points":65}
]
}
}
</xsl:variable>
<xsl:template match="/">
<xsl:sequence select=
"f:json-document($vstrParam)/Students/*[sex = 'Female']"/>
</xsl:template>
</xsl:stylesheet>
```
**When the above transformation is applied on any XML document (ignored), the correct result is produced**:
```
<Smith>
<First_Name>Mary</First_Name>
<sex>Female</sex>
</Smith>
<Jackson>
<First_Name>Jackie</First_Name>
<sex>Female</sex>
</Jackson>
``` | You can create a [JSONObject](https://github.com/stleary/JSON-java/blob/master/JSONObject.java), and then convert it to XML using the [XML class](https://github.com/stleary/JSON-java/blob/master/XML.java) in the org.json namespace
Wrapping the json string in the object is as easy as passing it in its constructor
```
JSONObject o = new JSONObject(jsonString);
```
Then you can get it in XML format using the XML class, like so:
```
String xml = org.json.XML.toString(o);
``` | Java implementation of JSON to XML conversion | [
"",
"java",
"xml",
"json",
"translation",
""
] |
Looking for a way to pass an associative array to a method. I'm looking to rewrite an Actionscript tween package in C# but running into trouble with "associative" arrays/objects. Normally in Actionscript I might do something like:
```
public function tween(obj:DisplayObject, params:Object = null):void {
if (params.ease != null) {
//do something
}
//...
}
```
And this could be called like:
```
tween(this, {ease:'out', duration:15});
```
I'm looking for a way to do the same in C#. So far, I've gathered my options to be:
a) creating a class or struct to define the possible param keys and types and pass that
b) pass the parameters as generic type
```
tween(frameworkElement, new {ease = 'out', duration = 15});
```
assuming
```
public static void tween(FrameworkElement target, object parameters);
```
and figure out some way to use that in the tween function (I'm not sure how to separate the key=value's given that object. any ideas?)
c) create a `Dictionary<string, object>` to pass the parameters into the tween function
Any other ideas or sample code? I'm new to C#.
**Edit**
Took me all day to figure this out:
"Anonymous types cannot be shared across assembly boundaries. The compiler ensures that there is at most one anonymous type for a given sequence of property name/type pairs within each assembly. To pass structures between assemblies you will need to properly define them." | **EDIT**: This is basically the mechanism that HtmlHelper extensions use in ASP.NET MVC. It's not original with me.
---
I'd favor a hybrid approach that has two different signatures. Note: I haven't tried this and there may be a conflict between the two signatures so you may have to give the second method a slightly different name to allow the compiler to choose between them, but I don't think so.
```
public static void tween( FrameworkElement target, object parameters )
{
return tween( target, new ParameterDictionary( parameters ) );
}
public static void tween( FrameworkElement target,
ParameterDictionary values )
{
if (values.ContainsKey( "ease" ))
{
....
}
}
```
Then you have a ParameterDictionary class that uses reflection on the anonymous type and sets up the dictionary.
```
public class ParameterDictionary : Dictionary<string,object>
{
public ParameterDictionary( object parameters )
{
if (parameters != null)
{
foreach (PropertyInfo info in parameters.GetType()
.GetProperties())
{
object value = info.GetValue(parameters,null);
this.Add(info.Name,value);
}
}
}
}
```
This gives you both ease of use and ease of consumption -- the "ugly" reflection stuff is wrapped up in the single constructor for the dictionary rather than in your method. And, of course, the dictionary can be used over and over for similar purposes with the reflection code only written once. | I'm a fan of option (b) myself - passing an anonymous type and parsing out the values using reflection.
I've seen others achieve the same thing using lambda expressions. The calling syntax would be:
```
tween(frameworkElement, ease => "out", duration => 15);
```
And the declaration would be something along the lines of:
```
public static void tween(FrameworkElement target, params Expression<Func<object>>[] parameters) { ... }
```
The idea is that you can take a variable number of "functions which return object". You then parse the name of the parameter out of each [Expression<TDelegate>](http://msdn.microsoft.com/en-us/library/bb335710.aspx), and invoke each one to get its value.
I don't think this is any better than reflecting over an anonymous type, but it's another approach to consider.
**Update**
I have actually written about the idea of passing associative arrays as dictionaries on my blog, [here](http://www.madprops.org/blog/named-parameters-in-c-4-0/) and [here](http://msdn.microsoft.com/en-us/library/bb335710.aspx). | Concise Method for Passing Associative Arrays to Method | [
"",
"c#",
"silverlight",
"associative-array",
"parameter-passing",
""
] |
I have an HTML page with some textual spans marked up something like this:
```
...
<span id="T2" class="Protein">p50</span>
...
<span id="T3" class="Protein">p65</span>
...
<span id="T34" ids="T2 T3" class="Positive_regulation">recruitment</span>
...
```
I.e. each span has an ID and refers to zero or more spans via their IDs.
I would like to visualize these references as arrows.
Two questions:
* How can I map an ID of a span to the screen coordinates of the rendering of the span?
* How do I draw arrows going from one rendering to another?
The solution should work in Firefox, working in other browsers is a plus but not really necessary. The solution could use jQuery, or some other lightweight JavaScript library. | You have a couple options: [svg](http://developer.mozilla.org/en/SVG/Tutorial/Getting_Started) or [canvas](http://developer.mozilla.org/en/Canvas_tutorial).
From the looks of it you don't need these arrows to have any particular mathematical form, you just need them to go between elements.
Try [WireIt](http://neyric.github.io/wireit/). Have a look at this [WireIt Demo](http://neyric.github.io/wireit/sandbox/presentation.html) (*which has been deprecated*). It uses a `canvas` tag for each individual wire between the floating dialog `div`s, then sizes and positions each `canvas` element to give the appearance of a connecting line at just the right spot. You may have to implement an additional rotating arrowhead, unless you don't mind the arrows coming in to each element at the same angle.
**Edit**: [the demo has been deprecated](https://github.com/neyric/wireit/commit/73fab603636490e68ce9e82ef05e9d99086e675c).
**Edit**: Ignore this answer, [*@Phil H* nailed it](https://stackoverflow.com/questions/554167/drawing-arrows-on-an-html-page-to-visualize-semantic-links-between-textual-spans#623770) | This captured my interest for long enough to produce a little test. The code is below.

It lists all the spans on the page (might want to restrict that to just those with ids starting with T if that is suitable), and uses the 'ids' attribute to build the list of links. Using a canvas element behind the spans, it draws arc arrows alternately above and below the spans for each source span.
```
<script>
function generateNodeSet() {
var spans = document.getElementsByTagName("span");
var retarr = [];
for(var i=0;i<spans.length; i++) {
retarr[retarr.length] = spans[i].id;
}
return retarr;
}
function generateLinks(nodeIds) {
var retarr = [];
for(var i=0; i<nodeIds.length; i++) {
var id = nodeIds[i];
var span = document.getElementById(id);
var atts = span.attributes;
var ids_str = false;
if((atts.getNamedItem) && (atts.getNamedItem('ids'))) {
ids_str = atts.getNamedItem('ids').value;
}
if(ids_str) {
retarr[id] = ids_str.split(" ");
}
}
return retarr;
}
// degrees to radians, because most people think in degrees
function degToRad(angle_degrees) {
return angle_degrees/180*Math.PI;
}
// draw a horizontal arc
// ctx: canvas context;
// inax: first x point
// inbx: second x point
// y: y value of start and end
// alpha_degrees: (tangential) angle of start and end
// upside: true for arc above y, false for arc below y.
function drawHorizArc(ctx, inax, inbx, y, alpha_degrees, upside)
{
var alpha = degToRad(alpha_degrees);
var startangle = (upside ? ((3.0/2.0)*Math.PI + alpha) : ((1.0/2.0)*Math.PI - alpha));
var endangle = (upside ? ((3.0/2.0)*Math.PI - alpha) : ((1.0/2.0)*Math.PI + alpha));
var ax=Math.min(inax,inbx);
var bx=Math.max(inax,inbx);
// tan(alpha) = o/a = ((bx-ax)/2) / o
// o = ((bx-ax)/2/tan(alpha))
// centre of circle is (bx+ax)/2, y-o
var circleyoffset = ((bx-ax)/2)/Math.tan(alpha);
var circlex = (ax+bx)/2.0;
var circley = y + (upside ? 1 : -1) * circleyoffset;
var radius = Math.sqrt(Math.pow(circlex-ax,2) + Math.pow(circley-y,2));
ctx.beginPath();
if(upside) {
ctx.moveTo(bx,y);
ctx.arc(circlex,circley,radius,startangle,endangle,1);
} else {
ctx.moveTo(bx,y);
ctx.arc(circlex,circley,radius,startangle,endangle,0);
}
ctx.stroke();
}
// draw the head of an arrow (not the main line)
// ctx: canvas context
// x,y: coords of arrow point
// angle_from_north_clockwise: angle of the line of the arrow from horizontal
// upside: true=above the horizontal, false=below
// barb_angle: angle between barb and line of the arrow
// filled: fill the triangle? (true or false)
function drawArrowHead(ctx, x, y, angle_from_horizontal_degrees, upside, //mandatory
barb_length, barb_angle_degrees, filled) { //optional
(barb_length==undefined) && (barb_length=13);
(barb_angle_degrees==undefined) && (barb_angle_degrees = 20);
(filled==undefined) && (filled=true);
var alpha_degrees = (upside ? -1 : 1) * angle_from_horizontal_degrees;
//first point is end of one barb
var plus = degToRad(alpha_degrees - barb_angle_degrees);
a = x + (barb_length * Math.cos(plus));
b = y + (barb_length * Math.sin(plus));
//final point is end of the second barb
var minus = degToRad(alpha_degrees + barb_angle_degrees);
c = x + (barb_length * Math.cos(minus));
d = y + (barb_length * Math.sin(minus));
ctx.beginPath();
ctx.moveTo(a,b);
ctx.lineTo(x,y);
ctx.lineTo(c,d);
if(filled) {
ctx.fill();
} else {
ctx.stroke();
}
return true;
}
// draw a horizontal arcing arrow
// ctx: canvas context
// inax: start x value
// inbx: end x value
// y: y value
// alpha_degrees: angle of ends to horizontal (30=shallow, >90=silly)
function drawHorizArcArrow(ctx, inax, inbx, y, //mandatory
alpha_degrees, upside, barb_length) { //optional
(alpha_degrees==undefined) && (alpha_degrees=45);
(upside==undefined) && (upside=true);
drawHorizArc(ctx, inax, inbx, y, alpha_degrees, upside);
if(inax>inbx) {
drawArrowHead(ctx, inbx, y, alpha_degrees*0.9, upside, barb_length);
} else {
drawArrowHead(ctx, inbx, y, (180-alpha_degrees*0.9), upside, barb_length);
}
return true;
}
function drawArrow(ctx,fromelem,toelem, //mandatory
above, angle) { //optional
(above==undefined) && (above = true);
(angle==undefined) && (angle = 45); //degrees
midfrom = fromelem.offsetLeft + (fromelem.offsetWidth / 2) - left - tofromseparation/2;
midto = toelem.offsetLeft + ( toelem.offsetWidth / 2) - left + tofromseparation/2;
//var y = above ? (fromelem.offsetTop - top) : (fromelem.offsetTop + fromelem.offsetHeight - top);
var y = fromelem.offsetTop + (above ? 0 : fromelem.offsetHeight) - canvasTop;
drawHorizArcArrow(ctx, midfrom, midto, y, angle, above);
}
var canvasTop = 0;
function draw() {
var canvasdiv = document.getElementById("canvas");
var spanboxdiv = document.getElementById("spanbox");
var ctx = canvasdiv.getContext("2d");
nodeset = generateNodeSet();
linkset = generateLinks(nodeset);
tofromseparation = 20;
left = canvasdiv.offsetLeft - spanboxdiv.offsetLeft;
canvasTop = canvasdiv.offsetTop - spanboxdiv.offsetTop;
for(var key in linkset) {
for (var i=0; i<linkset[key].length; i++) {
fromid = key;
toid = linkset[key][i];
var above = (i%2==1);
drawArrow(ctx,document.getElementById(fromid),document.getElementById(toid),above);
}
}
}
</script>
```
And you just need a call somewhere to the draw() function:
```
<body onload="draw();">
```
Then a canvas behind the set of spans.
```
<canvas style='border:1px solid red' id="canvas" width="800" height="7em"></canvas><br />
<div id="spanbox" style='float:left; position:absolute; top:75px; left:50px'>
<span id="T2">p50</span>
...
<span id="T3">p65</span>
...
<span id="T34" ids="T2 T3">recruitment</span>
</div>
```
Future modifications, as far as I can see:
* Flattening the top of longer arrows
* Refactoring to be able to draw non-horizontal arrows: add a new canvas for each?
* Use a better routine to get the total offsets of the canvas and span elements.
[Edit Dec 2011: Fixed, thanks @Palo]
*(Old -now broken- link to demo: <http://www.things.org.uk/examples/arrowtest.html>)*
Hope that's as useful as it was fun. | Drawing arrows on an HTML page to visualize semantic links between textual spans | [
"",
"javascript",
"html",
"visualization",
""
] |
If you had a DBA who was responsible for deploying databases in a live environment, what would you choose to give him? A database creation script or a backup which he could restore onto an existing database? What kinds of advantages/disadvantages are there? (We're using MSSQL2000 and MSSQL2005) | While I agree with John's first deployment suggestion of using a database backup, I prefer the idea of at least having the script available for review to allow for checking for coding standards, performance evaluation, etc.
If you're looking to turnkey something that has already been reviewed, then the backup/restore is a perfect option for the first deployment, even more so if there is configuration data that has been "staged" in that database. This help to avoid lengthy or complex insert statements.
Its a given that releases beyond the first are going to be scripted. In our environment we require release notes to specify the server, instance, and path to the scripts. The scripts should be provided in numeric order, separated into folders by target database, with a second set of rollback scripts. We even require that each script has a USE statement at the top so we don't have to worry about creating new objects in the master database! ;) | I prefer a script for deployments, they are much less intrusive. A restore will overwrite the whole database, data and all, which probably is not a good idea on your production enviroment.. | Database deployment: script or backup | [
"",
"sql",
"sql-server",
"deployment",
""
] |
I know it's not supported, and I know it's not even a terribly good idea. But, I want to have a WCF client inside a SQL Table Valued Function.
I've (seemingly) registered the correct assemblies, but when running my client - I get a WCF error:
```
Msg 6522, Level 16, State 1, Line 1
System.ServiceModel.CommunicationObjectFaultedException:
The communication object, System.ServiceModel.ChannelFactory`1[MyProxy.IMyService],
cannot be used for communication because it is in the Faulted state.
```
A test outside of Sql Server seems to work - and I don't even see the WCF client trying to make a TCP connection.
Not sure if this is a WCF or SQL CLR issue, as I'm new to both.....
Edit: I understand that the required System.ServiceModel and it's umpteen assemblies are outside of the vetted Sql CLR list. However,
> "Unsupported libraries can still be called from your managed stored procedures, triggers, user-defined functions, user-defined types, and user-defined aggregates. The unsupported library must first be registered in the SQL Server database, using the CREATE ASSEMBLY statement, before it can be used in your code. Any unsupported library that is registered and run on the server should be reviewed and tested for security and reliability." | This article might help you find out what the true underlying exception is and to see how fatal it is:
> [http://jdconley.com/blog/archive/2007/08/22/wcfclientwrapper.aspx](http://web.archive.org/web/20101230161606/http://www.jdconley.com/blog/archive/2007/08/22/wcfclientwrapper.aspx) (archive.org copy)
As [David correctly says](https://stackoverflow.com/questions/489748/wcf-client-inside-sql-clr#489850), the SQL CLR has support for a limited subset of .NET assemblies:
> [SQL 2005 Supported .NET Framework Libraries](http://msdn.microsoft.com/en-us/library/ms403279(SQL.90).aspx)
> [SQL 2005 CLR Integration Programming Model Restrictions](http://msdn.microsoft.com/en-us/library/ms403273(SQL.90).aspx)
>
> [SQL 2008 Supported .NET Framework Libraries](http://msdn.microsoft.com/en-us/library/ms403279.aspx)
> [SQL 2008 CLR Integration Programming Model Restrictions](http://msdn.microsoft.com/en-us/library/ms403273.aspx)
`System.Web.Services` is supported if the end point is a WSDL service so that might help you get out of a hole? Or you could always use a web service as a proxy to whatever non-webservice WCF endpoint you're trying to talk to. | I don't quite get it, but [Kev's pointer](https://stackoverflow.com/questions/489748/wcf-client-inside-sql-clr/489881#489881) finally led me to a working state. The WCF client wrapper gives you the *actual* exception - instead of the CommunicationObjectFaultedException the VS2008 proxy gives you (how has this not been fixed?).
That exception was a FileLoadException, complaining about System.ServiceModel:
> Assembly in host store has a different signature than assembly in GAC. (Exception from HRESULT: 0x80131050) See Microsoft Knowledge Base article 949080 for more information.
Of course, [KB 949080](http://support.microsoft.com/kb/949080) was no help, since it still refers to SQL 2005 (as an aside, I've noticed a lot of the SQL 2008 error messages and such still refer to 2005 - you'd think they could've at least replaced the text in the error messages) and deals with problems after updating the .NET FX - which hadn't happened.
That did make me think of 32-bit and 64-bit differences, though. My SQL 2008 server is x64 on Server 2008 x64 - and, as such, has both a C:\Windows\Microsoft.NET\Framework and a Framework64 folder. Since SQL Server is a 64 bit process, and my assembly would be hosted in process - I loaded the assemblies from the Framework64 folder, and System.IdentityModel and System.IdentityModel.Selectors from Program Files, as opposed to Program Files (x86).
So, I tried the x86 assemblies - but trying to load System.Web gives the rather cryptic error:
> Assembly 'System.Web' references assembly 'system.web, version=2.0.0.0, culture=neutral, publickeytoken=b03f5f7f11d50a3a.', which is not present in the current database.
Well, yeah...I guess System.Web probably does reference System.Web. Turns out, StackOverflow [already has an answer](https://stackoverflow.com/questions/400099/deploying-wcf-client-assembly-in-sql2005/403837#40383) to this problem. Though it doesn't make much sense, it looks like you need to load the Framework64 version of System.Web, and the regular Framework versions of everything else.
Unfortunately, trying that solution gave me back the dreaded WCF catch all CommunicationObjectFaultedException. Annoyed by the stupidity of WCF and IDisposable, I did away with the using and Dispose call, so that I could - you know - actually *see* the correct exception:
```
var p = new MyServiceClient(new CustomBinding(b), new EndpointAddress(uri));
var result = p.Execute(); // Don't Dispose proxy or you'll lose the actual exception.
try {
return result.Values;
} finally {
if (p.State != CommunicationState.Closed) {
if (p.State != CommunicationState.Faulted) {
p.Close();
} else {
p.Abort();
}
}
}
```
I then ended up with yet another FileLoadException, this time on System.Runtime.Serialization again pointing me to the useless KB 949080.
Figuring this was yet another case of x64 weirdness, I decided that if I was going to load the Framework assemblies, I should probably also load the Program Files (x86) System.IdentityModel assemblies.
And - what do you know...it actually worked. IntPtr.Size at runtime was 8 bytes...so I was being loaded as x64. Marking my assembly as x64 (or x86) would fail to deploy - it only worked with AnyCPU. Running corflags on the assemblies loaded showed no differences between the bitness of the x86 or x64 versions, so I *really* don't know what the problem is. But, the following CREATE ASSEMBLIES worked:
```
create assembly [System.Web]
from 'C:\Windows\Microsoft.NET\Framework64\v2.0.50727\System.Web.dll'
with permission_set = UNSAFE
create assembly [System.Messaging]
from 'C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Messaging.dll'
with permission_set = UNSAFE
create assembly [SMDiagnostics]
from 'C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\SMDiagnostics.dll'
with permission_set = UNSAFE
CREATE ASSEMBLY [System.IdentityModel]
from 'C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0\System.IdentityModel.dll'
with permission_set = UNSAFE
CREATE ASSEMBLY [System.IdentityModel.Selectors]
from 'C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0\System.IdentityModel.Selectors.dll'
with permission_set = UNSAFE
CREATE ASSEMBLY [Microsoft.Transactions.Bridge]
from 'C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\Microsoft.Transactions.Bridge.dll'
with permission_set = UNSAFE
```
And then deploying my user assembly as AnyCPU. YMMV may on an x86 version of Sql Server.
Boy - I'm really starting to get annoyed at the not quite ready for prime timeness of some of this stuff. I'm almost missing the simple days of C. | WCF Client Inside SQL CLR | [
"",
".net",
"sql",
"wcf",
"sqlclr",
""
] |
What more can I do to optimize this query?
```
SELECT * FROM
(SELECT `item`.itemID, COUNT(`votes`.itemID) AS `votes`,
`item`.title, `item`.itemTypeID, `item`.
submitDate, `item`.deleted, `item`.ItemCat,
`item`.counter, `item`.userID, `users`.name,
TIMESTAMPDIFF(minute,`submitDate`,NOW()) AS 'timeMin' ,
`myItems`.userID as userIDFav, `myItems`.deleted as myDeleted
FROM (votes `votes` RIGHT OUTER JOIN item `item`
ON (`votes`.itemID = `item`.itemID))
INNER JOIN
users `users`
ON (`users`.userID = `item`.userID)
LEFT OUTER JOIN
myItems `myItems`
ON (`myItems`.itemID = `item`.itemID)
WHERE (`item`.deleted = 0)
GROUP BY `item`.itemID,
`votes`.itemID,
`item`.title,
`item`.itemTypeID,
`item`.submitDate,
`item`.deleted,
`item`.ItemCat,
`item`.counter,
`item`.userID,
`users`.name,
`myItems`.deleted,
`myItems`.userID
ORDER BY `item`.itemID DESC) as myTable
where myTable.userIDFav = 3 or myTable.userIDFav is null
limit 0, 20
```
I'm using MySQL
Thanks | Of course, as @theomega said, look at the execution plan.
But I'd also suggest to try and "clean up" your statement. (I don't know which one is faster - that depends on your table sizes.) Usually, I'd try to start with a clean statement and start optimizing from there. But typically, a clean statement makes it easier for the optimizer to come up with a good execution plan.
So here are some observations about your statement that might make things slow:
* a couple of outer joins (makes it hard for the optimzer to figure out an index to use)
* a group by
* a lot of columns to group by
As far as I understand your SQL, this statement should do most of what yours is doing:
```
SELECT `item`.itemID, `item`.title, `item`.itemTypeID, `item`.
submitDate, `item`.deleted, `item`.ItemCat,
`item`.counter, `item`.userID, `users`.name,
TIMESTAMPDIFF(minute,`submitDate`,NOW()) AS 'timeMin'
FROM (item `item` INNER JOIN users `users`
ON (`users`.userID = `item`.userID)
```
WHERE
Of course, this misses the info from the tables you outer joined, I'd suggest to try to add the required columns via a subselect:
```
SELECT `item`.itemID,
(SELECT count (itemID)
FROM votes v
WHERE v.itemID = 'item'.itemID) as 'votes', <etc.>
```
This way, you can get rid of one outer join and the group by. The outer join is replaced by the subselect, so there is a trade-off which may be bad for the "cleaner" statement.
Depending on the cardinality between item and myItems, you can do the same or you'd have to stick with the outer join (but no need to reintroduce the group by).
Hope this helps. | **What does the analyzer say for this query?** Without knowledge about how many rows there are in the table you cant tell any optimization. So run the analyzer and you'll see what parts costs what. | optimize SQL query | [
"",
"sql",
"mysql",
"optimization",
"left-join",
"inner-join",
""
] |
I decided to put some effort in building a web browser from scratch. **What are the common functions, architectures, and features of modern web browsers** that I should know before getting started?
Any recommendations are highly appreciated! | Well break it down into pieces. What is a Web browser? What does it do? It:
* **Fetches external content.** So you need a HTTP library or (not recommended) write this yourself. There's a lot of complexity/subtlety to the HTTP protocol eg handling of expires headers, different versions (although it's mostly 1.1 these days), etc;
* **Handles different content types.** Theres a Windos registry for this kind of thing that you can piggyback. I'm talking interpreting content based on MIME type here;
* **Parses HTML and XML**: to create a DOM (Document Object Model);
* **Parses and applies CSS**: this entails understanding all the properties, all the units of measure and all the ways values can be specified (eg "border: 1px solid black" vs the separate border-width, etc properties);
* **Implements the W3C visual model** (and this is the real kicker); and
* **Has a Javascript engine**.
And that's basically a Web browser in a nutshell. Now some of these tasks are incredibly complex. Even the easy sounding ones can be hard. Take fetching external content. You need to deal with use cases like:
* How many concurrent connections to use?
* Error reporting to the user;
* Proxies;
* User options;
* etc.
The reason I and others are colletively raising our eyebrows is the rendering engine is hard (and, as someone noted, man years have gone into their development). The major rendering engines around are:
* **Trident:** developed by Microsoft for Internet Explorer;
* **Gecko:** used in Firefox;
* **Webkit:** used in Safari and Chrome 0-27;
* **KHTML:** used in the KDE desktop environment. Webkit forked from KHTML some years ago;
* **Elektra:** used in Opera 4-6;
* **Presto:** used in Opera 7-12;
* **Blink:** used in Chrome 28+, Opera 15+, webkit fork;
The top three have to be considered the major rendering engines used today.
Javascript engines are also hard. There are several of these that tend to be tied to the particular rendering engine:
* **SpiderMonkey:** used in Gecko/Firefox;
* **TraceMonkey:** will replace SpiderMonkey in Firefox 3.1 and introduces JIT (just-in-time) compilation;
* **KJS:** used by Konqueror, tied to KHTML;
* **JScript:** the Javascript engine of Trident, used in Internet Explorer;
* **JavascriptCore:** used in Webkit by the Safari browser;
* **SquirrelFish:** will be used in Webkit and adds JIT like TraceMonkey;
* **V8:** Google's Javascript engine used in Chrome and Opera;
* Opera (12.X and less) also used its own.
And of course there's all the user interface stuff: navigation between pages, page history, clearing temporary files, typing in a URL, autocompleting URLs and so on.
That is a **lot** of work. | Sounds like a really interesting project, but it will require you to invest an enormous effort.
It's no easy thing, but from an academic point of view, you could learn **so much** from it.
Some resources that you could check:
* [HTMLayout.NET](https://terrainformatica.com/a-homepage-section/htmlayout/): fast, lightweight and embeddable HTML/CSS renderer and layout manager component.
* [GeckoFX](https://code.google.com/archive/p/geckofx): Windows Forms control that embeds the Mozilla Gecko browser control in any Windows Forms Application.
* [SwiftDotNet](https://code.google.com/archive/p/swiftdotnet): A Browser based on Webkit in C#
* [Gecko DotNetEmbed](https://mxr.mozilla.org/seamonkey/source/embedding/wrappers/DotNETEmbed/)
* [Gecko#](https://www.mono-project.com/GeckoSharp/)
* [Rendering a web page - step by step](https://friendlybit.com/css/rendering-a-web-page-step-by-step/)
But seeing it from a *realistic* point of view, the huge effort needed to code it from scratch reminded me this comic:
[](http://www.geekherocomic.com/2009/02/25/coding-overkill/)
(source: [geekherocomic.com](http://www.geekherocomic.com/comics/2009-02-25-coding-overkill.png))
Good Luck :-) | How to get started building a web browser? | [
"",
"c#",
"browser",
""
] |
I want to write a PHP application that is going to do some checks first, to ensure an optimal and secure environment. I'm sure I alone can not think of everything, so what am I missing?
* Ensure MySQL username/password can SELECT, INSERT etc
* Update PHP timezone
* Check for register\_globals and warn if enabled
* Ensure /install is deleted
* If no config file make one
* Ensure config file doesn't have write permissions
* Erase cache folder contents if over 50mb or so
* Make sure GD and PDO are installed and working
Please answer with any more ideas or if any of the above aern't a good idea. I probably realise the cache folder thing should be a cron job that runs every week or so. | Have you checked [PHPSecInfo](http://phpsec.org/projects/phpsecinfo/index.html)? It is going to do some really [important PHP security-related configuration tests](http://phpsec.org/projects/phpsecinfo/tests/) you should be aware of. | Adding to your database user check - check that they don't have permission for dangerous things you don't need - such as DROP.
Something you could check in installation could be to prompt the user to upload application logic above the webroot. This is completely off the cuff, but you could check if the current directory is the document root, and then whether you (the script) can access one level above. I know most shared hosting don't provide this (I'm with a host that does fortunately) but I think it should be taken advantage wherever possible. Otherwise, check that blank index.html/php files have been placed in 'inaccessible' directories to prevent file listing. | What are some precautions a LAMP application should undertake on initialisation? | [
"",
"php",
"security",
""
] |
I've used Spring before (and like it), but thought I'd take a look at [Guice](http://code.google.com/p/google-guice/).
Is there a way to initialize something like maps or lists into beans using Guice?
For instance, I've done the following before in Spring to inject a list of items I want to process into some bean.
```
<property name="FilesToProcess">
<list>
<value>file1.xml</value>
<value>file2.xml</value>
</list>
</property>
```
How can I do this in Guice? | Guice2 has MultiBindings and MapBindings, which should work for you.
<https://github.com/google/guice/wiki/Multibindings>
Updated:
After looking at this again, it seems that you may be asking how you can inject runtime values into Guice, perhaps as arbitrary objects.
Guice is very focused around doing everything as typesafe code, so it doesn't lend itself
naturally to this. What I've done to provide input to Guice is to create an XML schema and use jaxb to suck this in and inject the resulting objects.
There is a Names.bindProperties method for binding regular old properties into Guice
constants.
There is also some level of integration with Spring, so you may want to look at this as
well. | I agree with Dave Stenglein for runtime values.
There are frameworks like [Obix](http://obix-framework.sourceforge.net/) that are specialized in the configuration. I like Guice for *code injection*, but they are better for that *configuration injection*. | Can Guice initialize beans? | [
"",
"java",
"dependency-injection",
"inversion-of-control",
"guice",
""
] |
### Duplicate of: [round() for float in C++](https://stackoverflow.com/questions/485525/round-for-float-in-c)
---
I'm using VS2008 and I've included math.h but I still can't find a round function. Does it exist?
I'm seeing a bunch of "add 0.5 and cast to int" solutions on google. Is that the best practice? | You may use C++11's [`std::round()`](http://en.cppreference.com/w/cpp/numeric/math/round).
If you are still stuck with older standards, you may use [`std::floor()`](http://en.cppreference.com/w/cpp/numeric/math/floor), which always rounds to the lower number, and [`std::ceil()`](http://en.cppreference.com/w/cpp/numeric/math/ceil), which always rounds to the higher number.
To get the normal rounding behaviour, you would indeed use `floor(i + 0.5)`.
This way will give you problems with negative numbers, a workaround for that problem is by using ceil() for negative numbers:
```
double round(double number)
{
return number < 0.0 ? ceil(number - 0.5) : floor(number + 0.5);
}
```
Another, cleaner, but more resource-intensive, way is to make use of a stringstream and the input-/output-manipulators:
```
#include <iostream>
#include <sstream>
double round(double val, int precision)
{
std::stringstream s;
s << std::setprecision(precision) << std::setiosflags(std::ios_base::fixed) << val;
s >> val;
return val;
}
```
Only use the second approach if you are not low on resources and/or need to have control over the precision. | Using `floor(num + 0.5)` won't work for negative numbers. In that case you need to use `ceil(num - 0.5)`.
```
double roundToNearest(double num) {
return (num > 0.0) ? floor(num + 0.5) : ceil(num - 0.5);
}
``` | Where is Round() in C++? | [
"",
"c++",
"rounding",
""
] |
```
public enum aa{ a1=1,a2=2,a3=6,...,a100=203}
```
How to get value like this
```
string att=GetFromDatabase("attribute"); //this return a1 or a2 ...
Enum.GetValue(att);
``` | Solution
```
string name = GetFromDatabase("attribute");
Enum.Parse(typeof(aa),name);
``` | Something like this should do the trick:
```
aa attEnum = (aa)Enum.Parse(typeof(aa), att);
```
Go to <http://msdn.microsoft.com/en-us/library/system.enum.parse.aspx> for more details. | How to get enum value by keyname | [
"",
"c#",
""
] |
I have the following code:
```
typedef void VOID;
int f(void);
int g(VOID);
```
which compiles just fine in C (using gcc 4.3.2 on Fedora 10). The same code compiled as C++ gives me the following error:
```
void.c:3: error: ‘<anonymous>’ has incomplete type
void.c:3: error: invalid use of ‘VOID’
```
Now, this is something in external library and I would like the owner to fix that problem. So I have a question - does C++ standard forbids this construct? Could you give me a pointer/citation? The only thing I can recall is that function declaration with (void) to signal empty parameter list is deprecated in C++, but I don't understand why typedefed VOID does not work. | Yes, as far as i know the second declaration is invalid in C++ and C89, but it is valid in C99.
From The C99 draft, TC2 (`6.7.5.3/10`):
> The special case of an unnamed parameter of type void as the only item in the list
> specifies that the function has no parameters.
It's explicitly talking about the type "void", not the keyword.
From The C++ Standard, `8.3.5/2`:
> If the parameter-declaration-clause is empty, the function takes no arguments. The parameter list `(void)` is equivalent to the empty parameter list.
That it means the actual keyword with "void", and not the general type "void" can also be seen from one of the cases where template argument deduction fails (`14.8.2/2`):
> * Attempting to create a function type in which a parameter has a type of void.
It's put clear by others, notable in one core language issue report [here](http://anubis.dkuug.dk/jtc1/sc22/wg21/docs/cwg_closed.html#18) and some GCC bugreports linked to by other answers.
---
To recap, your GCC is right but earlier GCC versions were wrong. Thus that code might have been successfully compiled with it earlier. You should fix your code, so that it uses "void" for both functions, then it will compile also with other compilers (comeau also rejects the second declaration with that "VOID"). | gcc bugs. Edit: since it wasn't clear enough, what I meant was gcc 4.3.2 was compiling it due to bugs. See [#32364](http://gcc.gnu.org/bugzilla/show_bug.cgi?id=32364) and [#9278](http://gcc.gnu.org/bugzilla/show_bug.cgi?id=9278). | void, VOID, C and C++ | [
"",
"c++",
"c",
"standards",
""
] |
This would appear to imply "no". Which is unfortunate.
```
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class,
AllowMultiple = true, Inherited = true)]
public class CustomDescriptionAttribute : Attribute
{
public string Description { get; private set; }
public CustomDescriptionAttribute(string description)
{
Description = description;
}
}
[CustomDescription("IProjectController")]
public interface IProjectController
{
void Create(string projectName);
}
internal class ProjectController : IProjectController
{
public void Create(string projectName)
{
}
}
[TestFixture]
public class CustomDescriptionAttributeTests
{
[Test]
public void ProjectController_ShouldHaveCustomDescriptionAttribute()
{
Type type = typeof(ProjectController);
object[] attributes = type.GetCustomAttributes(
typeof(CustomDescriptionAttribute),
true);
// NUnit.Framework.AssertionException: Expected: 1 But was: 0
Assert.AreEqual(1, attributes.Length);
}
}
```
Can a class inherit attributes from an interface? Or am I barking up the wrong tree here? | No. Whenever implementing an interface or overriding members in a derived class, you need to re-declare the attributes.
If you only care about ComponentModel (not direct reflection), there is a way ([`[AttributeProvider]`](http://msdn.microsoft.com/en-us/library/system.componentmodel.attributeproviderattribute.aspx)) of suggesting attributes from an existing type (to avoid duplication), but it is only valid for property and indexer usage.
As an example:
```
using System;
using System.ComponentModel;
class Foo {
[AttributeProvider(typeof(IListSource))]
public object Bar { get; set; }
static void Main() {
var bar = TypeDescriptor.GetProperties(typeof(Foo))["Bar"];
foreach (Attribute attrib in bar.Attributes) {
Console.WriteLine(attrib);
}
}
}
```
outputs:
```
System.SerializableAttribute
System.ComponentModel.AttributeProviderAttribute
System.ComponentModel.EditorAttribute
System.Runtime.InteropServices.ComVisibleAttribute
System.Runtime.InteropServices.ClassInterfaceAttribute
System.ComponentModel.TypeConverterAttribute
System.ComponentModel.MergablePropertyAttribute
``` | You can define a useful extension method ...
```
Type type = typeof(ProjectController);
var attributes = type.GetCustomAttributes<CustomDescriptionAttribute>( true );
```
Here is the extension method:
```
/// <summary>Searches and returns attributes. The inheritance chain is not used to find the attributes.</summary>
/// <typeparam name="T">The type of attribute to search for.</typeparam>
/// <param name="type">The type which is searched for the attributes.</param>
/// <returns>Returns all attributes.</returns>
public static T[] GetCustomAttributes<T>( this Type type ) where T : Attribute
{
return GetCustomAttributes( type, typeof( T ), false ).Select( arg => (T)arg ).ToArray();
}
/// <summary>Searches and returns attributes.</summary>
/// <typeparam name="T">The type of attribute to search for.</typeparam>
/// <param name="type">The type which is searched for the attributes.</param>
/// <param name="inherit">Specifies whether to search this member's inheritance chain to find the attributes. Interfaces will be searched, too.</param>
/// <returns>Returns all attributes.</returns>
public static T[] GetCustomAttributes<T>( this Type type, bool inherit ) where T : Attribute
{
return GetCustomAttributes( type, typeof( T ), inherit ).Select( arg => (T)arg ).ToArray();
}
/// <summary>Private helper for searching attributes.</summary>
/// <param name="type">The type which is searched for the attribute.</param>
/// <param name="attributeType">The type of attribute to search for.</param>
/// <param name="inherit">Specifies whether to search this member's inheritance chain to find the attribute. Interfaces will be searched, too.</param>
/// <returns>An array that contains all the custom attributes, or an array with zero elements if no attributes are defined.</returns>
private static object[] GetCustomAttributes( Type type, Type attributeType, bool inherit )
{
if( !inherit )
{
return type.GetCustomAttributes( attributeType, false );
}
var attributeCollection = new Collection<object>();
var baseType = type;
do
{
baseType.GetCustomAttributes( attributeType, true ).Apply( attributeCollection.Add );
baseType = baseType.BaseType;
}
while( baseType != null );
foreach( var interfaceType in type.GetInterfaces() )
{
GetCustomAttributes( interfaceType, attributeType, true ).Apply( attributeCollection.Add );
}
var attributeArray = new object[attributeCollection.Count];
attributeCollection.CopyTo( attributeArray, 0 );
return attributeArray;
}
/// <summary>Applies a function to every element of the list.</summary>
private static void Apply<T>( this IEnumerable<T> enumerable, Action<T> function )
{
foreach( var item in enumerable )
{
function.Invoke( item );
}
}
```
**Update:**
Here is a shorter version as proposed by SimonD in a comment:
```
private static IEnumerable<T> GetCustomAttributesIncludingBaseInterfaces<T>(this Type type)
{
var attributeType = typeof(T);
return type.GetCustomAttributes(attributeType, true)
.Union(type.GetInterfaces().SelectMany(interfaceType =>
interfaceType.GetCustomAttributes(attributeType, true)))
.Cast<T>();
}
``` | Can a C# class inherit attributes from its interface? | [
"",
"c#",
"attributes",
""
] |
I have a string buffer of about 2000 characters and need to check the buffer if it contains a specific string.
Will do the check in a ASP.NET 2.0 webapp for every webrequest.
Does anyone know if the [String.Contains method](http://msdn.microsoft.com/en-us/library/dy85x1sa(VS.80).aspx) performs better than [String.IndexOf method](http://msdn.microsoft.com/en-us/library/system.string.indexof(VS.80).aspx)?
```
// 2000 characters in s1, search token in s2
string s1 = "Many characters. The quick brown fox jumps over the lazy dog";
string s2 = "fox";
bool b;
b = s1.Contains(s2);
int i;
i = s1.IndexOf(s2);
```
[Fun fact](http://www.cl.cam.ac.uk/~mgk25/ucs/examples/quickbrown.txt) | `Contains` calls `IndexOf`:
```
public bool Contains(string value)
{
return (this.IndexOf(value, StringComparison.Ordinal) >= 0);
}
```
Which calls `CompareInfo.IndexOf`, which ultimately uses a CLR implementation.
If you want to see how strings are compared in the CLR [this will show you](https://github.com/gbarnett/shared-source-cli-2.0/blob/master/clr/src/vm/comstring.cpp) (look for *CaseInsensitiveCompHelper*).
`IndexOf(string)` has no options and `Contains()`uses an Ordinal compare (a byte-by-byte comparison rather than trying to perform a smart compare, for example, e with é).
So `IndexOf` will be marginally faster (in theory) as `IndexOf` goes straight to a string search using FindNLSString from kernel32.dll (the power of reflector!).
**Updated for .NET 4.0** - *IndexOf no longer uses Ordinal Comparison and so Contains can be faster. See comment below.* | Contains(s2) is many times (in my computer 10 times) faster than IndexOf(s2) because Contains uses StringComparison.Ordinal that is faster than the culture sensitive search that IndexOf does by default (but that may change in .net 4.0 <http://davesbox.com/archive/2008/11/12/breaking-changes-to-the-string-class.aspx>).
Contains has exactly the same performance as IndexOf(s2,StringComparison.Ordinal) >= 0 in my tests but it's shorter and makes your intent clear. | Is String.Contains() faster than String.IndexOf()? | [
"",
"c#",
".net",
"asp.net",
"performance",
"string",
""
] |
I'm starting my 2nd class in C# programming through Kaplan online school. I have some limited interaction with the professor and the class online, but nothing like in an actual school. I'm about to go through "Modern Software Development Using C#.NET" by Richard Wiener. It seems the book as a extremely heavy focus on UML (which I don't even really know what that is right now!)
You experinced Csharpers.... any tips to keep in mind as I go through this to keep in perspective how the modern software engineer works outside the classroom?
Any perspectives to share as I start understanding UML and intermediate C# programming? | Some companies will use UML everywhere. Some use it nowhere. I'm not a big fan myself - I prefer ad-hoc diagrams and plenty of other communication (notes on the diagram, actual *talking* etc).
The good thing about an ad-hoc approach is that you can leave it as vague as you like or make it really detailed. The bad thing about it is you can't generate any code from it - but I've never really liked generating code from UML. (Others swear by it, mind.)
You certainly don't *need* to know UML to learn C#. | UML would come very close to the end of the list of things that gave me insight into the complex world of programming. I find it very distracting when trying to design something, and too time consuming for real system descriptions. I have always thought it is important and tried to start my project with UML diagram, but it wasn't ever worth it. | Starting Intermediate Level C# Class, with heavy focus on UML... Your best tips or experinced advice? | [
"",
"c#",
""
] |
I've inherited a PHP application that has "versions" of pages (viewacct.php, viewacct2.php, viewacct\_rcw.php, etc). I want to discover which of these pages are called from other pages in the application and which are not. Is there a tool available that will help with that? | Using whatever tools you would like (Find/Grep/Sed on Linux, I use Visual Studio on windows), it is just a matter of crawling your source tree for references of the filenames in each file. | Similar to FlySwat's answer: any good text editor or IDE with multi-file search should be able to help you find the orphan pages. On Mac OS X I would suggest TextWrangler(free), TextMate($), or BBEdit($$). I've had good success with each of these tools, but your mileage may vary. | Find PHP Orphan Page | [
"",
"php",
""
] |
I cannot close one of my forms programmatically. Can someone help me?
Here's the code:
```
private void WriteCheck_Load(object sender, EventArgs e) {
SelectBankAccountDialog sbad = new SelectBankAccountDialog();
DialogResult result = sbad.ShowDialog();
if (result == DialogResult.Cancel) {
this.Close();
} else {
MessageBox.Show(result.ToString());
}
MessageBox.Show(sbad.bankaccountID.ToString());
}
``` | As configurator mentioned (in comments), the form must be shown before it can be closed, so, instead of the *Load* event, you should be doing this in the *Shown* event instead.
If you don't want the form visible for the Dialog box, I guess you can wrap the event code in a Visible = false;
In summary, the basic code would be
```
private void WriteCheck_Shown(object sender, EventArgs e)
{
Visible = false;
SelectBankAccountDialog sbad = new SelectBankAccountDialog();
DialogResult result = sbad.ShowDialog();
if (result == DialogResult.Cancel) {
this.Close();
} else {
MessageBox.Show(result.ToString());
}
MessageBox.Show(sbad.bankaccountID.ToString());
Visible = true;
}
``` | By calling `Form.Close()`, the form should close, but not until all waiting events have been processed. You also still have a chance to cancel the form closing in the `FormClosing` event.
First, you'll probably want to `return` after your call to `this.Close()`. If it still doesn't close, step through your code and see what is happening. You may have to set and check a "forciblyClose" flag and return from any other processing methods before it'll actually close. | Why can I not close a form in C#? | [
"",
"c#",
".net",
"winforms",
""
] |
I like how Java has a Map where you can define the types of each entry in the map, for example `<String, Integer>`.
What I'm looking for is a type of collection where each element in the collection is a pair of values. Each value in the pair can have its own type (like the String and Integer example above), which is defined at declaration time.
The collection will maintain its given order and will not treat one of the values as a unique key (as in a map).
Essentially I want to be able to define an ARRAY of type `<String,Integer>` or any other 2 types.
I realize that I can make a class with nothing but the 2 variables in it, but that seems overly verbose.
I also realize that I could use a 2D array, but because of the different types I need to use, I'd have to make them arrays of OBJECT, and then I'd have to cast all the time.
I only need to store pairs in the collection, so I only need two values per entry. Does something like this exist without going the class route? Thanks! | The Pair class is one of those "gimme" generics examples that is easy enough to write on your own. For example, off the top of my head:
```
public class Pair<L,R> {
private final L left;
private final R right;
public Pair(L left, R right) {
assert left != null;
assert right != null;
this.left = left;
this.right = right;
}
public L getLeft() { return left; }
public R getRight() { return right; }
@Override
public int hashCode() { return left.hashCode() ^ right.hashCode(); }
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) return false;
Pair pairo = (Pair) o;
return this.left.equals(pairo.getLeft()) &&
this.right.equals(pairo.getRight());
}
}
```
And yes, this exists in multiple places on the Net, with varying degrees of completeness and feature. (My example above is intended to be immutable.) | ## [AbstractMap.SimpleEntry](https://docs.oracle.com/javase/7/docs/api/java/util/AbstractMap.SimpleEntry.html)
Easy you are looking for this:
```
java.util.List<java.util.Map.Entry<String,Integer>> pairList= new java.util.ArrayList<>();
```
How can you fill it?
```
java.util.Map.Entry<String,Integer> pair1=new java.util.AbstractMap.SimpleEntry<>("Not Unique key1",1);
java.util.Map.Entry<String,Integer> pair2=new java.util.AbstractMap.SimpleEntry<>("Not Unique key2",2);
pairList.add(pair1);
pairList.add(pair2);
```
This simplifies to:
```
Entry<String,Integer> pair1=new SimpleEntry<>("Not Unique key1",1);
Entry<String,Integer> pair2=new SimpleEntry<>("Not Unique key2",2);
pairList.add(pair1);
pairList.add(pair2);
```
And, with the help of a `createEntry` method, can further reduce the verbosity to:
```
pairList.add(createEntry("Not Unique key1", 1));
pairList.add(createEntry("Not Unique key2", 2));
```
Since `ArrayList` isn't final, it can be subclassed to expose an `of` method (and the aforementioned `createEntry` method), resulting in the syntactically terse:
```
TupleList<java.util.Map.Entry<String,Integer>> pair = new TupleList<>();
pair.of("Not Unique key1", 1);
pair.of("Not Unique key2", 2);
``` | A Java collection of value pairs? (tuples?) | [
"",
"java",
""
] |
I would like to write a program that will find bus stop times and update my personal webpage accordingly.
If I were to do this manually I would
1. Visit www.calgarytransit.com
2. Enter a stop number. ie) 9510
3. Click the button "next bus"
The results may look like the following:
> 10:16p Route 154
> 10:46p Route 154
> 11:32p Route 154
Once I've grabbed the time and routes then I will update my webpage accordingly.
I have no idea where to start. I know diddly squat about web programming but can write some C and Python. What are some topics/libraries I could look into? | [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/documentation.html#Quick%20Start) is a Python library designed for parsing web pages. Between it and [urllib2](http://docs.python.org/library/urllib2.html) ([urllib.request](http://docs.python.org/py3k/library/urllib.request) in Python 3) you should be able to figure out what you need. | What you're asking about is called "web scraping." I'm sure if you google around you'll find some stuff, but the core notion is that you want to open a connection to the website, slurp in the HTML, parse it and identify the chunks you want.
The [Python Wiki](http://wiki.python.org/moin/WebProgramming) has a good lot of stuff on this. | Grabbing text from a webpage | [
"",
"python",
"c",
"text",
"html",
""
] |
I know I should spend more time researching this and having a go before asking the question but I've got just 2 weeks to build a site with a portal style homepage (much like [http://www.bbc.co.uk](http://www.bc.co.uk)).
I'm fairly good with jQuery and have played with jQuery UI draggables in the past but I was wondering if there were any tutorials or best practice examples of how to build a portal with multiple drop zones and the ability to remember which "portlets" have been dragged into which dropzones in some kind of state object.
I would need to be able to save the state object to the back-end using a $ajax() call and somehow reorganise the portlets when the user logs back in to the site, presumably by sending a JSON state object from the back-end.
Just some ideas of where to start would be useful. Thanks | I've been thinking about something similar recently. The best method I could come up with was to have several 'zones' on the page where items would be placed. In my case these were 3 columns. I gave each an identifier and used an Ajax call every time a block was moved to a different position to update the new position of that block.
For example, a sample database table:
```
tbl.blocks:
userid | blockid | column | placement
1 | 2 | 1 | 3
```
Where column is a simple column identifier and placement is the placement within that column. I used a query at page load that loaded the blocks in order of placement, and then wrote them in. `blockid` refers to a table of blocks.
Here's a tutorial I found that looks relevant: <http://aymanh.com/drag-drop-portal-interface-with-scriptaculous> | One suggestion that I have is to use the generated ordering information on the backend to build the page with the items in the correct locations initially rather than rely on javascript to reorder them on page load. This will reduce the chances of having the display morph before the user's eyes from the default to their chosen ordering. It also allows the page to render correctly even with javascript turned off, although they will lose their ability to reorder things obviously.
I think you're spot on with using AJAX to communicate back ordering changes to the server. The only other way you might do this is by having an "edit" mode that allows the user to make the changes, then "save" to get out of edit mode. The save would post back the current orderings. I prefer the AJAX way since you'll need Javascript to handle the drag-n-drop anyway. | How to build a portal page with saveable state in jquery UI? | [
"",
"javascript",
"jquery",
"jquery-ui",
"drag-and-drop",
""
] |
If you want to use global functions and variable dynamically you can use:
```
window[functionName](window[varName]);
```
Is it possible to do the same thing for variables in the local scope?
This code works correctly but currently uses eval and I'm trying to think of how else to do it.
```
var test = function(){
//this = window
var a, b, c; //private variables
var prop = function(name, def){
//this = window
eval(name+ ' = ' + (def.toSource() || undefined) + ';');
return function(value){
//this = test object
if ( !value) {
return eval('(' + name + ')');
}
eval(name + ' = value;')
return this;
};
};
return {
a:prop('a', 1),
b:prop('b', 2),
c:prop('c', 3),
d:function(){
//to show that they are accessible via to methods
return [a,b,c];
}
};
}();
>>>test
Object
>>>test.prop
undefined
>>>test.a
function()
>>>test.a()
1 //returns the default
>>>test.a(123)
Object //returns the object
>>>test.a()
123 //returns the changed private variable
>>>test.d()
[123,2,3]
``` | No, like [crescentfresh](https://stackoverflow.com/users/45433/crescentfresh) said. Below you find an example of how to implement without eval, but with an internal private object.
```
var test = function () {
var prv={ };
function prop(name, def) {
prv[name] = def;
return function(value) {
// if (!value) is true for 'undefined', 'null', '0', NaN, '' (empty string) and false.
// I assume you wanted undefined. If you also want null add: || value===null
// Another way is to check arguments.length to get how many parameters was
// given to this function when it was called.
if (typeof value === "undefined"){
//check if hasOwnProperty so you don't unexpected results from
//the objects prototype.
return Object.prototype.hasOwnProperty.call(prv,name) ? prv[name] : undefined;
}
prv[name]=value;
return this;
}
};
return pub = {
a:prop('a', 1),
b:prop('b', 2),
c:prop('c', 3),
d:function(){
//to show that they are accessible via two methods
//This is a case where 'with' could be used since it only reads from the object.
return [prv.a,prv.b,prv.c];
}
};
}();
``` | To answer your question, no, there is no way to do dynamic variable lookup in a local scope without using `eval()`.
The best alternative is to make your "scope" just a regular object [literal] (ie, `"{}"`), and stick your data in there. | How can I access local scope dynamically in javascript? | [
"",
"javascript",
"scope",
""
] |
I tend to use eclipse's "Open Call Hierarchy" function a lot, to trace where method calls are going in larger Java projects. I get irritated by Threads, as the call hierarchy shows the callers of the `Thread.run()` method as various internal Java threading functions, rather than the `Thread.start()` call which effectively led to the thread being run.
Is there any way to make Eclipse show the Thread.start calls as the parent of `Thread.run()` methods. Perhaps a plugin to do this? | Thanks for your response Jamesh.
With the first two points you made, you say that (in both anonymous and non-anonymous Runnables)it would be useful to look at the call hierarchy of the Runnable's constructor - yes, I agree! This is usually what I end up doing. But it usually means frequent switching between the two hierarchies, only one of which can be shown at a time. I would like to avoid this by retaining one hierarchy.
There is no direct call hierarchy between the Runnable constructor and the call to run(), so it seems to me that it would be inappropriate to extend the call hierarchy by adding the constructor as a "caller" of run(). However, calls to start() or to add the thread to an Executor (or perhaps run() calls within the executor) might be appropriate to show in the call hierarchy.
I really was just wondering if there was an existing solution to this which I was unable to find. I guess I'll just have to make an attempt at a plugin myself if I want it enough.
I tried out the implementors plugin. It is useful, but not for this particular problem!
I also tried out nWire. It has a lot of features which I haven't had time to explore fully, but I couldn't find a way to do what I'm looking for here. | Interesting question.
You are welcome to check out [nWire](http://www.nwiresoftware.com/). It's a new tool for exploring all the associations of your code in one dynamic view. Very convenient and simple to use. It combines the callers and implementors (and all other associations) together. Would love to have your feedback on it. | Call hierarchy of Thread.run() in Eclipse | [
"",
"java",
"eclipse",
"multithreading",
"eclipse-plugin",
""
] |
I have a working login form in an asp.net application. Standard stuff with a username and password text box and a button to process the login. Works fine.
I have a new requirement to allow the user to input the username and password from a separate plain html page that is not a part of my asp.net application. I plan on achieving this using standard html - form, input, submit button etc. The form action will be the URL of my asp.net login page and its method will be POST.
What I want to do in the C# code behind page of the asp.net login form, presumably in the Page\_Load event, is to check if the request for the page contains a username and password value being passed in. If it does then I need to read those values and process the login as if someone had clicked the login button on the asp.net page. If not then I will display the login form as usual.
How do I check for the existence of, and read, the username and password values in the request for my page. | Read the Request.Form NameValueCollection and process your logic accordingly:
```
NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
userName = nvc["txtUserName"];
}
if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
password = nvc["txtPassword"];
}
//Process login
CheckLogin(userName, password);
```
... where "txtUserName" and "txtPassword" are the **Names** of the controls on the posting page. | ```
if (!string.IsNullOrEmpty(Request.Form["username"])) { ... }
```
username is the name of the input on the submitting page. The password can be obtained the same way. If its not null or empty, it exists, then log in the user (I don't recall the exact steps for ASP.NET Membership, assuming that's what you're using). | Read Post Data submitted to ASP.Net Form | [
"",
"c#",
"asp.net",
"post",
""
] |
In a `WebBrowser` control, how do I remove `HtmlElement` objects? There are no methods in the `HtmlElement` class to accomplish this. As a workaround, I can create a "dummy" `HtmlElement` (without inserting it into the `HtmlDocument`), into which I then insert (via `AppendChild`) the `HtmlElement` objects to be removed. This feels like a hack. Is there a better way to do this?
P.S. I want to retain the `HtmlElement` in memory to be used later, not simply destroy it (which is what setting its parent's `innerHtml` to an empty string would do) | Look at this WebControl Heritance, with loads of feature: <http://www.codeproject.com/KB/miscctrl/csEXWB.aspx>
You could add a remove method to del element by id.
Hope this helps | You can delete the element by setting its outerhtml to an empty string.
elem.OuterHtml = ""
I hope this is what you were looking for.
gm | Removing HtmlElement objects programmatically using C# | [
"",
"c#",
"browser",
"webbrowser-control",
"dom",
""
] |
I am programming a list of recent network messages communicated to/from a client. Basically I just want a list that stores up to X number of my message objects. Once the list reaches the desired size, the oldest (first) item in the list should be removed. The collection needs to maintain its order, and all I will need to do is
1. iterate through it,
2. add an item to the end, and
3. remove an item from the beginning, if #2 makes it too long.
What is the most efficient structure/array/collection/method for doing this? Thanks! | You want to use a [Queue](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Queue.html). | I don't think LILO is the real term...but you're looking for a FIFO Queue | Most efficient collection for this kind of LILO? | [
"",
"java",
"data-structures",
""
] |
Please include the nanos, otherwise it would be trivial:
```
long diff = Math.abs(t1.getTime () - t2.getTime ());
```
[EDIT] I want the most precise result, so no doubles; only integer/long arithmetic. Also, the result must be positive. Pseudo code:
```
Timestamp result = abs (t1 - t2);
```
Examples:
```
t1 = (time=1001, nanos=1000000), t2 = (time=999, nanos=999000000)
-> diff = (time=2, nanos=2000000)
```
Yes, milliseconds in java.sql.Timestamp are duplicated in the time and the nanos par, so 1001 milliseconds means 1 second (1000) and 1 milli which is in the `time` part and the `nanos` part because 1 millisecond = 1000000 nanoseconds). This is much more devious than it looks.
I suggest not to post an answer without actually testing the code or having a working code sample ready :) | After one hour and various unit tests, I came up with this solution:
```
public static Timestamp diff (java.util.Date t1, java.util.Date t2)
{
// Make sure the result is always > 0
if (t1.compareTo (t2) < 0)
{
java.util.Date tmp = t1;
t1 = t2;
t2 = tmp;
}
// Timestamps mix milli and nanoseconds in the API, so we have to separate the two
long diffSeconds = (t1.getTime () / 1000) - (t2.getTime () / 1000);
// For normals dates, we have millisecond precision
int nano1 = ((int) t1.getTime () % 1000) * 1000000;
// If the parameter is a Timestamp, we have additional precision in nanoseconds
if (t1 instanceof Timestamp)
nano1 = ((Timestamp)t1).getNanos ();
int nano2 = ((int) t2.getTime () % 1000) * 1000000;
if (t2 instanceof Timestamp)
nano2 = ((Timestamp)t2).getNanos ();
int diffNanos = nano1 - nano2;
if (diffNanos < 0)
{
// Borrow one second
diffSeconds --;
diffNanos += 1000000000;
}
// mix nanos and millis again
Timestamp result = new Timestamp ((diffSeconds * 1000) + (diffNanos / 1000000));
// setNanos() with a value of in the millisecond range doesn't affect the value of the time field
// while milliseconds in the time field will modify nanos! Damn, this API is a *mess*
result.setNanos (diffNanos);
return result;
}
```
Unit tests:
```
Timestamp t1 = new Timestamp (0);
Timestamp t3 = new Timestamp (999);
Timestamp t4 = new Timestamp (5001);
// Careful here; internally, Java has set nanos already!
t4.setNanos (t4.getNanos () + 1);
// Show what a mess this API is...
// Yes, the milliseconds show up in *both* fields! Isn't that fun?
assertEquals (999, t3.getTime ());
assertEquals (999000000, t3.getNanos ());
// This looks weird but t4 contains 5 seconds, 1 milli, 1 nano.
// The lone milli is in both results ...
assertEquals (5001, t4.getTime ());
assertEquals (1000001, t4.getNanos ());
diff = DBUtil.diff (t1, t4);
assertEquals (5001, diff.getTime ());
assertEquals (1000001, diff.getNanos ());
diff = DBUtil.diff (t4, t3);
assertEquals (4002, diff.getTime ());
assertEquals (2000001, diff.getNanos ());
``` | I use this method to get difference between 2 `java.sql.Timestmap`
```
/**
* Get a diff between two timestamps.
*
* @param oldTs The older timestamp
* @param newTs The newer timestamp
* @param timeUnit The unit in which you want the diff
* @return The diff value, in the provided time unit.
*/
public static long getDateDiff(Timestamp oldTs, Timestamp newTs, TimeUnit timeUnit) {
long diffInMS = newTs.getTime() - oldTs.getTime();
return timeUnit.convert(diffInMS, TimeUnit.MILLISECONDS);
}
// Examples:
// long diffMinutes = getDateDiff(oldTs, newTs, TimeUnit.MINUTES);
// long diffHours = getDateDiff(oldTs, newTs, TimeUnit.HOURS);
``` | How to calculate the difference between two Java java.sql.Timestamps? | [
"",
"java",
"timestamp",
""
] |
I have a service application written in C# and under certain circumstances, I would like it to terminate itself. This would happen after the service has been running for a while, so this would not be happening in the OnStart() event.
Everything that I have read so far suggests that the only safe way to terminate a service is through the Service Control Manager. My service runs as Local Service and does not have the rights to start or stop services, so I can't access the SCM from the service itself. Is there another way to self-terminate while still playing by the rules of the SCM? | Try [`ServiceBase.Stop()`](http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.stop.aspx). | If you want to terminate the service instead of stopping it (perhaps because the service has caught an otherwise unhandled exception) you can use `Environment.Exit(1)` (use another exit code if you want).
Windows will discover that the service has terminated unexpectedly. If the service has been configured to recover the recovery procedure will be used which includes options for restarting the service, running a program or restarting the computer. | Can a service written in .NET self-terminate? | [
"",
"c#",
"windows-services",
""
] |
We have an external .js file that we want to include in a number of different pages. The file contains code for sorting a table on the client-side, and uses the ▲ and ▼ characters in the script to indicate which column is sorted and in which direction.
The script was originally written for an ASP.Net page to offload some sorting work from the server to client (prevent sorting postbacks when javascript is enabled). In that case, the encoding is pretty much always UTF-8 and it works great in that context.
However, we also have a number of older Classic ASP pages where we want to include the script. For these pages the encoding is more of a hodgepodge depending on who wrote the page when and what tool they were using (notepad, vs6, vs2005, other html helper). Often no encoding is specified in the page so it's up to the browser to pick, but there's really no hard rule for it that I can see.
The problem is that if a different (non-UTF8) encoding is used the ▼ and ▲ characters won't show up correctly. I tried using html entities instead, but couldn't get them to work well from the javascript.
How can I make the script adjust for the various potential encodings so that the "special" characters always show up correctly? Are there different characters I could be using, or a trick I missed to make the html entities work from javascript?
Here is the snippet where the characters are used:
```
// get sort direction, arrow
var dir = 1;
if (self.innerHTML.indexOf(" ▲") > -1)
dir = -1;
var arrow = (dir == 1)?" ▲":" ▼";
// SORT -- function that actually sorts- not relevant to the question
if (!SimpleTableSort(t.id, self.cellIndex, dir, sortType)) return;
//remove all arrows
for (var c = 0,cl=t.rows[0].cells.length;c<cl;c+=1)
{
var cell = t.rows[0].cells[c];
cell.innerHTML = cell.innerHTML.replace(" ▲", "").replace(" ▼", "");
}
// set new arrow
self.innerHTML += arrow;
```
For the curious, the code points I ended up using with the accepted answer were \u25B4 and \u25BC. | You want Javascript Unicode escapes i.e. "\uxxxx", where "xxxx" is the Unicode code point for the character. I believe "\u25B2" and "\u25BC" are the two you need. | The encoding of the JavaScript file depends on the encoding of the HTML page, where it is embedded. If you have a UTF-8 JavaScript file and a ISO-8859-1 HTML page the JavaScript is interpreted as ISO-8859-1.
If you load the JavaScript from as a external file you could specify the encoding of the JavaScript:
```
<script type="text/javascript" charset="UTF-8" src="externalJS.js"></script>
```
Anyway the best option is to save all files related to a webproject in one encoding, UTF-8 recommended. | Javascript encoding question | [
"",
"javascript",
"html",
"encoding",
""
] |
My application reads an Excel file using VSTO and adds the read data to a `StringDictionary`. It adds only data that are numbers with a few digits (1000 1000,2 1000,34 - comma is a delimiter in Russian standards).
What is better to check if the current string is an appropriate number?
```
object data, string key; // data had read
try
{
Convert.ToDouble(regionData, CultureInfo.CurrentCulture);
dic.Add(key, regionData.ToString());
}
catch (InvalidCastException)
{
// is not a number
}
```
or
```
double d;
string str = data.ToString();
if (Double.TryParse(str, out d)) // if done, then is a number
{
dic.Add(key, str);
}
```
I have to use `StringDictionary` instead of `Dictionary<string, double>` because of the following parsing algorithm issues.
My questions: Which way is faster? Which is safer?
And is it better to call `Convert.ToDouble(object)` or `Convert.ToDouble(string)` ? | I did a quick non-scientific test in Release mode. I used two inputs: "2.34523" and "badinput" into both methods and iterated 1,000,000 times.
Valid input:
```
Double.TryParse = 646ms
Convert.ToDouble = 662 ms
```
Not much different, as expected. For all intents and purposes, for valid input, these are the same.
Invalid input:
```
Double.TryParse = 612ms
Convert.ToDouble = ..
```
Well.. it was running for a long time. I reran the entire thing using 1,000 iterations and `Convert.ToDouble` with bad input took 8.3 seconds. Averaging it out, it would take over 2 hours. I don't care how basic the test is, in the invalid input case, `Convert.ToDouble`'s exception raising will ruin your performance.
So, here's another vote for `TryParse` with some numbers to back it up. | To start with, I'd use `double.Parse` rather than `Convert.ToDouble` in the first place.
As to whether you should use `Parse` or `TryParse`: can you proceed if there's bad input data, or is that a really exceptional condition? If it's exceptional, use `Parse` and let it blow up if the input is bad. If it's expected and can be cleanly handled, use `TryParse`. | Double.TryParse or Convert.ToDouble - which is faster and safer? | [
"",
"c#",
".net",
"parsing",
"double",
""
] |
What are most important things you know about templates: hidden features, common mistakes, best and most useful practices, tips...**common mistakes/oversight/assumptions**
I am starting to implement most of my library/API using templates and would like to collect most common patterns, tips, etc., found in practice.
Let me formalize the question: What is the most important thing you've learned about templates?
Please try to provide examples -- it would be easier to understand, as opposed to convoluted and overly dry descriptions
Thanks | From **"Exceptional C++ style", Item 7:** function overload resolution happens *before* templates specialization. Do not mix overloaded function and specializations of template functions, or you are in for a nasty surprise at which function actually gets called.
```
template<class T> void f(T t) { ... } // (a)
template<class T> void f(T *t) { ... } // (b)
template<> void f<int*>(int *t) { ... } // (c)
...
int *pi; f(pi); // (b) is called, not (c)!
```
On top of **Item 7**:
Worse yet, if you omit the type in template specialization, a *different* function template might get specialized depending on the order of definition and as a result a specialized function may or may not be called.
Case 1:
```
template<class T> void f(T t) { ... } // (a)
template<class T> void f(T *t) { ... } // (b)
template<> void f(int *t) { ... } // (c) - specializes (b)
...
int *pi; f(pi); // (c) is called
```
Case 2:
```
template<class T> void f(T t) { ... } // (a)
template<> void f(int *t) { ... } // (c) - specializes (a)
template<class T> void f(T *t) { ... } // (b)
...
int *pi; f(pi); // (b) is called
``` | This may not be popular, but I think it needs to be said.
Templates are complicated.
They are awesomely powerful, but use them wisely. Don't go too crazy, don't have too many template arguments... Don't have too many specializations... Remember, other programmers have to read this too.
And most of all, stay away from template metaprogramming... | Most important things about C++ templates… lesson learned | [
"",
"c++",
"templates",
""
] |
I want to access the full model of users with their roles in my SOAP app. For example, I might want to know the role of a user called "Fred."
How do I reach into some sort of global JAAS registry and do (pseudocode) *globalRegistry.getUser("Fred").getPrincipals()*? (Note that in JAAS, a role is represented by a *Principal*.)
I know how to get the *Principal* of the *Subject* from the *LoginContext*, but that has two problems.
1. It is only at the moment of login, and I'd prefer not to code the aforementioned registry and store the *Subject* and *Principal* objects myself, as they are already stored by the appserver.
2. Preferably, I want to be able to access this information even when Fred is not the current user.
I am using Jetty, but I presume that these behaviors are standard to JAAS. | We use a ThreadLocal variable to reference the current user as has been authenticated at the system entrypoint (a servlet or ejb in our case). This allows 'global' access to the current user. This is not directly tied to JAAS or any other security protocol, but can be initialized from them.
EDIT: The return from the ThreadLocal is the Subject for the current user.
Accessing other users would typically be done via some type of admin module. | A pattern i have seen is:
```
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
Set<Principal> principals = subject.getPrincipals();
```
Essentially, this finds the subject currently associated with the current thread, and asks for its principals.
One example of the use of this is in [Apache Jackrabbit](http://jackrabbit.apache.org/)'s [RepositoryImpl](http://svn.apache.org/viewvc/jackrabbit/trunk/jackrabbit-core/src/main/java/org/apache/jackrabbit/core/RepositoryImpl.java?view=markup). It's in the `extendAuthentication` method, whose job is to determine what Jackrabbit rights the current thread has when creating a new session (i think).
However, i should note that this may not necessarily actually work, at least in J2EE contexts. I'm using this code under JBoss AS7, and it doesn't find a subject. That might just be a bug, though. | How do I access JAAS roles at arbitrary point in the code? | [
"",
"java",
"security",
"jaas",
"role",
"security-roles",
""
] |
This is a follow up to my last question [Open a window if the window does not already exist](https://stackoverflow.com/questions/528671/javascript-window-open-only-if-the-window-does-not-already-exist)
Essentially, I am now keeping a list of all the window references that have been opened by a page, and only allowing them to be opened if they are not already open. Then a potential problem struck me - it is of course possible for a user to shut down the original window, and open it again, thus losing the list of window references.
Is it possible to loop through the windows open in a browser, checking for a particular URL?
Edit:
After a lot of helpful comments here (and on the other question), here is the final code for the application launcher. Essentially, it tries to get the location of the open window with the appropriate name. If that causes an exception (because of a privacy issue), then the application is judged to have been loaded. If it is "about:blank", then it is a new window. This works on Firefox, IE7 and Google Chrome. It feels dirty...
```
var g_urlarray = [];
Array.prototype.has = function(value) {
var i;
for (var i in this) {
if (i === value) {
return true;
}
}
return false;
};
function launchApplication(l_url, l_windowName)
{
var l_width = screen.availWidth;
var l_height = screen.availHeight;
var winRef;
var l_params = 'status=1' +
',resizable=1' +
',scrollbars=1' +
',width=' + l_width +
',height=' + l_height +
',left=0' +
',top=0';
if (g_urlarray.has(l_url)) {
winRef = g_urlarray[l_url];
}
if (winRef == null || winRef.closed) {
winRef = window.open('', l_windowName, l_params);
var l_openNew = 0;
try {
if (winRef.location == 'about:blank') {
l_openNew = 1;
}
}
catch (e) {
l_openNew = 0;
}
if (l_openNew === 1)
{
winRef.location = l_url;
winRef.moveTo(0,0);
winRef.resizeTo(l_width, l_height);
}
g_urlarray[l_url] = winRef;
}
}
``` | > @annakata (and even if you stored them, you wouldn't have permission to close them any more)
Not true. If you have the name of the window, you can use window.open to reestablish a link to the window even if the opener was closed and reopened. For example:
```
<script>
function winOpen(url){
return window.open(url,getWinName(url));
}
function winClose(url){
var win = window.open("",getWinName(url));
win.close();
}
function getWinName(url){
return "win" + url.replace(/[^A-Za-z0-9\-\_]*/g,"");
}
</script>
<a href="#" onclick="winOpen('http://google.com');return false;">Click me first</a>, close and open this window, then
<a href="#" onclick="winClose('http://google.com');return false;">click me to close the other window</a>
``` | No, this would be a security/privacy issue.
---
Since others have brought up the ownership/cookie state storage: this only works if you are also the same document which opened the window, i.e. in the scenario where the user shuts the window down and reopens then these references are indeed lost (and even if you stored them, you wouldn't have permission to close them any more) | How can I check for an open URL in another window? | [
"",
"javascript",
"windows",
"popup",
""
] |
I'm new to python. I've studied C and I noticed that that the C structure (struct) seemed to have the same task as "class" in python. So what is, conceptually, the difference? | Aside from numerous technical differences between how they're implemented, they serve roughly the same purpose: the organization of data.
The big difference is that in Python (and other object oriented languages such as C++, Java, or C#), a class can also have functions associated with it that operate only on the instance of the class, whereas in C, a function that wishes to operate on a struct must accept the structure as a parameter in some way, usually by pointer.
I won't delve into the technical differences between the two, as they are fairly significant, but I suggest you look into the concept of [Object Oriented Programming](http://en.wikipedia.org/wiki/Object-oriented_programming). | Structs encapsulate data.
Classes encapsulate behavior and data. | Difference between class (Python) and struct (C) | [
"",
"python",
"c",
""
] |
I am appending p tags to a div as I process a json request and would liek to style it according to what is in the request.
```
$(document).ready(function() {
function populatePage() {
var numberOfEntries = 0;
var total = 0;
var retrieveVal = "http://www.reddit.com/" + $("#addressBox").val() + ".json";
$("#redditbox").children().remove();
$.getJSON(retrieveVal, function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
ups = this.data.ups;
downs = this.data.downs;
total += (ups - downs);
numberOfEntries += 1;
$("#redditbox").append("<p>" + ups + ":" + downs + " <a href=\"" + url + "\">" + title + "</a><p>");
$("#redditbox :last-child").css('font-size', ups%20); //This is the line in question
});
$("#titlebox h1").append(total/numberOfEntries);
});
}
populatePage()
$(".button").click(function() {
populatePage();
});
});
```
Unfortunately things are not quite working out as planned. The styling at the line in question is applying to every child of the div, not just the one that happens to be appended at the time, so they all end up the same size, not sized dependent on their numbers.
how can I apply a style to the p tags as they are appended ot the div?
Edit: Thanks Fortes and Veggerby both worked, but i went with Fortes in the end because I did. | You can use JQuery's `appendTo` instead of `append`. For your example:
```
$("<p>" + ups + ":" + downs + " <a href=\"" + url + "\">" + title + "</a><p>")
.css('font-size', ups%20)
.appendTo('#redditbox');
```
Here are the docs for appendTo: <http://docs.jquery.com/Manipulation/appendTo> | Replace:
```
$("#redditbox").append("<p>" + ups + ":" + downs + " <a href=\"" + url + "\">" + title + "</a><p>");
```
with
```
var p = $("<p>" + ups + ":" + downs + " <a href=\"" + url + "\">" + title + "</a><p>");
$("p", p).css('font-size', ups%20)
$("#redditbox").append(p);
```
Can probably be condensed even further.
Edit:
Condensed like:
```
$("#redditbox").append(
$("<p></p>").css('font-size', ups%20).append(ups + ":" + downs + " <a href=\"" + url + "\">" + title + "</a>")
);
``` | JQuery: get a child as you append it | [
"",
"javascript",
"jquery",
""
] |
Guys, would you describe a few things about c++ building blocks, on unix.
I want to create an application that links against static libs and dynamic libs (.so).
**Question 1:** *How do I create static library using gcc/g++ ?How do I make my app link against it.*
**Question 2:** *How to specify it in the makefile, linking against static and dynamic libs, assuming that both libraries have header files*
Summary: I have been using makefiles and libraries for years, written by someone else. Thus every time I modified it, I simply cut-and-pasted things around, without really understanding it. Now I want to get down to the ground and understand the building/linking/Creating Makfile process in-depth.
*What is a good book describing these concepts in intimate details?*
Thanks | Static libraries are usually *archived* with the `ar` command. Once you build all of the object files (preferably with the `-fPIC` switch on GCC), you can run `ar` like so:
```
ar -rs archivename.a list.o of.o objects.o
```
The `man` page describes the options.
Dynamic libraries are built usually with the `-shared` switch to `gcc` or `ld` and the output file name with a `.so` extension.
Autotools handles this with the `libtool` program. I'm not familiar with its use.
Linking against these libraries can be done either by listing the libraries with the `-l` (ell) switch (such as `-lX` to link to `libX.so`) or by specifying them directly with absolute paths (such as adding `/usr/lib/libX.so` to your command). Static libraries are linked by specifying `-static` before `-l` or the appropriate absolute path to the `.a` archive. | Bare bones Makefile for creating a static library consisting of the code in foo.cpp, bar.cpp:
```
PROJECT = library.a
OBJECTS = foo.o bar.o
CFLAGS = -Wall -pedantic
all: $(PROJECT)
.cpp.o:
g++ -c $(CFLAGS) $<
$(PROJECT): $(OBJECTS)
libtool -o $(PROJECT) -static $(OBJECTS)
```
Bare bones Makefile for an app baz.cpp that static links to library.a:
```
PROJECT = baz
CFLAGS = -Wall -pedantic
OBJECTS = baz.o
all: $(PROJECT)
.cpp.o:
g++ -c $(CFLAGS) $<
$(PROJECT): $(OBJECTS) library.a
g++ $(OBJECTS) -L. -llibrary -o $(PROJECT)
```
Dynamic library left, ahem, as an exercise to the reader. | Creating a project, from Makefile to static/dynamic libraries in UNIX | [
"",
"c++",
"c",
"makefile",
"unix",
""
] |
I just saw it was using in one of the recent answers:
```
public static implicit operator bool(Savepoint sp)
{
return sp != null;
}
```
Why do we need word *implicit* here, and what does it mean? | Implicit means that the conversion doesn't require a cast in your code.
You can now do this:
```
Savepoint point = new Savepoint();
if(point) // becomes a bool using your operator
{
}
```
instead of having to do this:
```
Savepoint point = new Savepoint();
if((bool)point) // an "explicit" conversion
{
}
```
One example of why this is a useful distinction is numeric types. There's an implicit conversion from "smaller" types to "larger" types, e.g:
```
float f = 6.5;
double d = f; // implicit conversion
```
But converting larger types to smaller types can be dangerous, so there's only an explicit conversion, forcing the user to clarify that he really intends to perform the operation in question:
```
long l = 20;
// short s = l;
short s = (short)l; // explicit conversion
``` | That looks like misuse of an implicit operator. I don't know what the Savepoint class does, but converting it to a boolean does not seem logical. The implicit operator enables you to check if a Savepoint reference is null or not by simply evaluating the reference:
```
if (point) {
```
instead of:
```
if (point != null) {
```
If it's used that way, that is hiding what the code is actually doing, and that goes against pretty much everything that C# is about. | implicit operator | [
"",
"c#",
"implicit-conversion",
""
] |
Is there a library or a class/function that I can use to convert an integer to its verbal representation?
Example input:
> 4,567,788`
Example output:
> Four million, Five hundred sixty-seven thousand, seven hundred eighty-eight | If you use the code found in *[converting numbers in to words C#](https://stackoverflow.com/questions/2729752/converting-numbers-in-to-words-c-sharp)*, and you need it for decimal numbers, here is how to do it:
```
public string DecimalToWords(decimal number)
{
if (number == 0)
return "zero";
if (number < 0)
return "minus " + DecimalToWords(Math.Abs(number));
string words = "";
int intPortion = (int)number;
decimal fraction = (number - intPortion)*100;
int decPortion = (int)fraction;
words = NumericToWords(intPortion);
if (decPortion > 0)
{
words += " and ";
words += NumericToWords(decPortion);
}
return words;
}
``` | Currently the best, most robust, library for this is definitely [Humanizer](https://github.com/MehdiK/Humanizer). It's open sourced and available as a [NuGet](https://en.wikipedia.org/wiki/NuGet) package:
```
Console.WriteLine(4567788.ToWords()); // => four million five hundred and sixty-seven thousand seven hundred and eighty-eight
```
It also has a wide range of tools solving the small problems every application has with `string`s, `enum`s, `DateTime`s, `TimeSpan`s and so forth, and supports many different languages.
```
Console.WriteLine(4567788.ToOrdinalWords().Underscore().Hyphenate().ApplyCase(LetterCasing.AllCaps)); // => FOUR-MILLION-FIVE-HUNDRED-AND-SIXTY-SEVEN-THOUSAND-SEVEN-HUNDRED-AND-EIGHTY-EIGHTH
``` | How can I convert an integer into its verbal representation? | [
"",
"c#",
".net",
".net-3.5",
""
] |
My employer, a small office supply company, is switching suppliers and I am looking through their electronic content to come up with a robust database schema; our previous schema was pretty much just thrown together without any thought at all, and it's pretty much led to an unbearable data model with corrupt, inconsistent information.
The new supplier's data is much better than the old one's, but their data is what I would call *hypernormalized*. For example, their product category structure has 5 levels: Master Department, Department, Class, Subclass, Product Block. In addition the product block content has the long description, search terms and image names for products (the idea is that a product block contains a product and all variations - e.g. a particular pen might come in black, blue or red ink; all of these items are essentially the same thing, so they apply to a single product block). In the data I've been given, this is expressed as the products table (I say "table" but it's a flat file with the data) having a reference to the product block's unique ID.
I am trying to come up with a robust schema to accommodate the data I'm provided with, since I'll need to load it relatively soon, and the data they've given me doesn't seem to match the type of data they provide for demonstration on their sample website (<http://www.iteminfo.com>). In any event, I'm not looking to reuse their presentation structure so it's a moot point, but I was browsing the site to get some ideas of how to structure things.
What I'm unsure of is whether or not I should keep the data in this format, or for example consolidate Master/Department/Class/Subclass into a single "Categories" table, using a self-referencing relationship, and link that to a product block (product block should be kept separate as it's not a "category" as such, but a group of related products for a given category). Currently, the product blocks table references the subclass table, so this would change to "category\_id" if I consolidate them together.
I am probably going to be creating an e-commerce storefront making use of this data with Ruby on Rails (or that's my plan, at any rate) so I'm trying to avoid getting snagged later on or having a bloated application - maybe I'm giving it too much thought but I'd rather be safe than sorry; our previous data was a real mess and cost the company tens of thousands of dollars in lost sales due to inconsistent and inaccurate data. Also I am going to break from the Rails conventions a little by making sure that my database is robust and enforces constraints (I plan on doing it at the application level, too), so that's something I need to consider as well.
How would you tackle a situation like this? Keep in mind that I have the data to be loaded already in flat files that mimic a table structure (I have documentation saying which columns are which and what references are set up); I'm trying to decide if I should keep them as normalized as they currently are, or if I should look to consolidate; I need to be aware of how each method will affect the way I program the site using Rails since if I do consolidate, there will be essentially 4 "levels" of categories in a single table, but that definitely seems more manageable than separate tables for each level, since apart from Subclass (which directly links to product blocks) they don't **do** anything except show the next level of category under them. I'm always a loss for the "best" way to handle data like this - I know of the saying "Normalize until it hurts, then denormalize until it works" but I've never really had to implement it until now. | I would prefer the "hypernormalized" approach over a denormal data model. The self referencing table you mentioned might reduce the number of tables down and simplify life in some ways, but in general this type of relationship can be tricky to deal with. Hierarchical queries become a pain, as does mapping an object model to this (if you decide to go that route).
A couple of extra joins is not going to hurt and will keep the application more maintainable. Unless performance degrades due to the excessive number of joins, I would opt to leave things like they are. As an added bonus if any of these levels of tables needed additional functionality added, you will not run into issues because you merged them all into the self referencing table. | I totally disagree with the criticisms about self-referencing table structures for parent-child hierarchies. The linked list structure makes UI and business layer programming easier and more maintainable in most cases, since linked lists and trees are the natural way to represent this data in languages that the UI and business layers would typically be implemented in.
The criticism about the difficulty of maintaining data integrity constraints on these structures is perfectly valid, though the simple solution is to use a closure table that hosts the harder check constraints. The closure table is easily maintained with triggers.
The tradeoff is a little extra complexity in the DB (closure table and triggers) for a lot less complexity in UI and business layer code. | Dealing with "hypernormalized" data | [
"",
"sql",
"ruby-on-rails",
"database-design",
"denormalization",
"normalizing",
""
] |
I have inherited an online quiz application written in C# with these lines of code all over the place.
So how bad is this code?
What are the potential issues I could run into?
How could I improve it?
### The code:
```
strTestPasses += "<tr valign=\"top\"><td><b>Subject</b></td><td>" + ((Hashtable)((ArrayList)((Hashtable)MultipleTestPasses[i])["HasMultipleDataSet"])[j])["subject"] + "</td></tr>";
``` | I also hate these 'lines of code'. When people ask me 'Whats the biggest project you have worked on', I say '1 line of code'. When others challenge me thus 'How many lines of code can you write a day?', I say back to them, 'Only one my brother. But it is the one true line' | To get started refactoring, may I suggest:
```
TestPassesBuilder.AppendFormat(
"<tr valign='top'><td><b>Subject</b></td><td>{0}</td></tr>",
MultipleTestPasses[i]["HasMultipleDataSet"][j]["subject"]
);
```
or
```
TestPassesBuilder.AppendFormat(
"<tr valign='top'><td><b>{0}</b></td><td>{1}</td></tr>",
"Subject",
MultipleTestPasses[i]["HasMultipleDataSet"][j]["subject"]
);
```
Where `TestPassesBuilder` is of course a StringBuilder and `MultipleTestPasses` has been converted to use appropriate generic collection types rather that ArrayList/HashTable abomination. The 2nd option will also allow the title for each row to be factored out into a variable at some point.
For the next step, MultipleTestPasses should be converted to a real object. Since it looks like he's using hard-coded keys, each 'key' really corresponds to a property of a class. | How bad is this code? | [
"",
"c#",
"coding-style",
""
] |
By best, I mean most-common, easiest to setup, free. Performance doesn't matter. | I decided that pyodbc was the best fit. Very simple, stable, supported:
<http://code.google.com/p/pyodbc/> | [pymssql](http://pymssql.sourceforge.net/), the simple MS SQL Python extension module. | What's the best technology for connecting from linux to MS SQL Server using python? ODBC? | [
"",
"python",
""
] |
Is it considered bad manners/bad practice to explicitly place object members on the heap (via new)? I would think you might want to allow the client to choose the memory region to instantiate the object. I know there might be a situation where heap members might be acceptable. If you know a situation could you describe it please? | If you have a class that's designed for copy semantics and you're allocating/deallocating a bunch of memory unnecessarily, I could see this being bad practice. In general, though, it's not. There are a lot of classes that can make use of heap storage. Just make sure you're free of memory leaks (deallocate things in the destructor, reference count, etc.) and you're fine.
If you want more flexibility, consider letting your user specify an [Allocator](http://en.cppreference.com/w/cpp/memory/allocator). I'll explain.
Certain classes, e.g. `std::vector`, string, map, etc. **need** heap storage for the data structures they represent. It's not considered bad manners; when you have an automatically allocated `vector`, the user is expected to know that a buffer is allocated when the `vector` constructor gets called:
```
void foo() {
// user of vector knows a buffer that can hold at least 10 ints
// gets allocated here.
std::vector<int> foo(10);
}
```
Likewise, for `std::string`, you know there's an internal, heap-allocated `char*`. Whether there's one per `string` instance is usually up to the STL implementation; often times they're reference counted.
However, for nearly all of the STL classes, users **do** have a choice of where things are put, in that they can specify an allocator. `vector` is defined kind of like this:
```
template <typename T, typename Alloc = DefaultAllocator<T> >
class vector {
// etc.
};
```
Internally, `vector` uses `Alloc` (which defaults to whatever the default allocator is for T) to allocate the buffer and other heap storage it may need. If users doesn't like the default allocation strategy, they can specify one of their own:
```
vector<int, MyCustomAllocator> foo(10);
```
Now when the constructor allocates, it will use a `MyCustomAllocator` instead of the default. Here are some [details on writing your own STL allocator](http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4079).
If you're worried that it might be "bad manners" to use the heap for certain storage in your class, you might want to consider giving users of your class an option like this so that they can specify how things are to be allocated if your default strategy doesn't fit their needs. | I don't consider it bad practice at all. There are all sorts of reasons why you might want to explicitly allocate a member variable via new. Here are a few off the top of my head.
* Say your class has a very large buffer, e.g., 512kb or 1MB. If this buffer is not stored on the heap, your users might potentially exceed the default stack space if they create multiple local variables of your class. In this case, it would make sense to allocate the buffer in your constructor and store it as a pointer.
* If you are doing any kind of reference counting, you'll need a pointer to keep track of how many objects are actually pointing to your data.
* If your member variable has a different lifetime than your class, a pointer is the way to go. A perfect example of this is lazy evaluation, where you only pay for the creation of the member **if** the user asks for it.
* Although it is not necessarily a direct benefit to your users, compilation time is another reason to use pointers instead of objects. If you put an object in your class, you have to include the header file that defines the object in the header file for your class. If you use a pointer, you can forward declare the class and only include the header file that defines the class in the source files that need it. In large projects, using forward declarations can drastically speed up compilation time by reducing the overall size of your compilation units.
On the flip side, if your users create a lot of instances of your class for use on the stack, it would be advantageous to use objects instead of pointers for your member variables simply because heap allocations/deallocations are slow by comparison. It's more efficient to avoid the heap in this case, taking into account the first bullet above of course. | C++ Etiquette about Member Variables on the Heap | [
"",
"c++",
"heap-memory",
""
] |
I'm writing a new Windows Forms 2.0 application. This application is going to have a data file. The user will be able to open the data file, do some work and save it to disk. Then he'll be able to open it later, to continue working. Same thing as Microsoft Word and .doc files.
I'd like to use SQLite for the data file. However, I don't want changes to be written immediately to the data file. I want the user to change the data, but the file on disk remaining unchanged. **Only when the user clicks "save"** the data file on disk will be changed.
In your opinion, what's the best way to do this?
Should I load the contents of the SQLite DB into memory, maybe mapping it to objects, and write back to it when the user clicks "save"?
Or... is there a way to work with the data file with SQL commands (no objects), but leaving the changes in memory only, until "save" is clicked?
I'm a bit confused, I'd appreciate any idea regarding a best practice for this.
Cheers | 1) On startup, make a temporary copy of the Sqlite file. This will be your "working file".
2) Run all the INSERTs/UPDATEs/DELETEs against working file. When the user clicks "Save", copy the working file over the original.
3) Delete the working file and goto step #1. | Depending on your scenario, you can also wrap your SQL in a transaction (BEGIN TRANSACTION;), and when the user click save, commit the transaction; if user click cancel, rollback the transaction. | How to use SQLite for windows forms application file? | [
"",
"sql",
"winforms",
"sqlite",
""
] |
The testit() method is a closure. aString has fallen out of scope but testit() can still execute on it. testit2() is using a variable that hasn't fallen out of scope (mystring) but which was also not been passed into testit2(). Is testit2() considered a closure?
```
string mystring = "hello world";
Action testit = new Action(delegate { string aString = "in anon method"; Debug.WriteLine(aString); });
testit();
//capture mystring. Is this still a closure?
Action testit2 = new Action(delegate { Debug.WriteLine(mystring); });
//mystring is still in scope
testit2();
```
In the second example, mystring can be updated outside of the method and those changes will be reflected in testit2(). This doesn't behave like a normal method, which would only be able to capture mystring as a parameter. | Both examples are anonymous functions. The second of which use a closure in order to capture the local variables. The scope lifetime of the variable with respect to the anonymous function does not affect whether or not a closure is created to use it. As long as the variable is defined outside a anonymous function and used within, a closure will be created.
The first anonymous function uses no local state, therefore does not need a closure. It should compile down to a static method.
This is necessary because the anonymous function can live past the lifetime of the current function. Therefore all locals used in a anonymous function must be captured in order to execute the delegate at a later time. | A closure does not capture the *values* in scope, but the actual *definition* of the scope. So any other piece of code that has a reference to the same scope can modify variables within it. | Is this still a closure? | [
"",
"c#",
".net",
"function",
"closures",
"anonymous-methods",
""
] |
i have two tables, products and categories. how do i convert the following sql query to linq format?
```
select c.Name, c.DisplayName, count(p.id) from categories as c
LEFT join products as p on p.categoryId = c.id
group by c.Name, c.DisplayName
```
some categories will have 0 products in them so the LEFT JOIN is important | if you correctly define the relations in your model then the customers table should have an association with all the products, so you'll be able to access products associated with the customer just using 'c.Products'. Then should be able to write simply something like this:
```
var q =
from c in categories
select new { c.Name, c.DisplayName, Count = c.Products.Count() }
```
T. | ```
dc.categories
.Select(c => new
{
Name = c.Name,
DisplayName = c.DisplayName,
TheCount = c.Products.Count()
}
```
If you want to do a left join in other cases, check out "group join".
```
dc.categories
.GroupJoin(dc.products,
c => c.id,
p => p.categoryid,
(c, g) => new { Name = c.Name, TheCount = g.Count() }
);
``` | converting ms sql "group by" query to linq to sql | [
"",
"sql",
"sql-server",
"linq",
""
] |
I have used ExpressionBuilders here and there within my asp.net markup to return simple data types.
Does anyone have any ideas how an ExpressionBuilder might be used to wire up an event inline? Or can ExpressionBuilders only return literals?
I would like to wire up the OnLoad event (or any event) by creating an ExpressionBuilder (named AutoBind in my example). Any ideas if this can be done?
```
<asp:DropDownList ID="DropDownList1" runat="server"
DataSource='<%# GetRecords() %>'
DataTextField="Name" DataValueField="ID"
OnLoad="<%$ AutoBind: this.DataBind() %>" />
``` | Sam is correct. Expressions can only be set on properties, it will not wire an event. I got "close" by doing this with the expression builder.
```
[System.Web.Compilation.ExpressionPrefix("Delegate")]
public class DelegateExpressionBuilder : ExpressionBuilder
{
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
{
return new CodeDelegateCreateExpression(new CodeTypeReference("System.EventHandler"), null, entry.Expression);
}
}
```
In the mark of the page you would write something like this...
```
<asp:DropDownList runat="server" onload='<%$ Delegate:(o,e) => { this.DataBind(); } %>' />
```
The problem is that the compiler will generate this.
```
((System.Web.UI.IAttributeAccessor)(@__ctrl)).SetAttribute("onload", System.Convert.ToString(new System.EventHandler((o,e) => { this.DataBind(); }), System.Globalization.CultureInfo.CurrentCulture));
```
It's essentialy "converting" the delegate to a string and in reality you want the compiler to do this...
```
@__ctrl.Load += new System.EventHandler((o,e) => { this.DataBind(); });
``` | instead of using expression builder you can call any of the event method defined in your code which has the reuqired signature of event handler
in the event handle event arguments you can identify the object and data and manipulate control as you want | asp.net ExpressionBuilder: Possible to wire up an event? | [
"",
"c#",
"asp.net",
""
] |
I would like to assign a mnemonic to a `JMenu` using resource bundles (or the `ResourceMap`). So for example, the code without resource file would be...
```
JMenu fileMenu = new JMenu();
fileMenu.setText("File"); // this would be read from a resource file
fileMenu.setMnemonic('F'); // but the docs say this is obsolete
fileMenu.setMnemonic(KeyEvent.VK_F);
```
So how do I put the KeyEvent.VK\_F in a resource file?
For a `JMenuItem` I can do it with actions, but this is `JMenu`. | Java's [javax.swing.KeyStroke](http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/KeyStroke.html) class bridges the gap:
```
JMenu fileMenu = new JMenu();
String mnemonic = // string from localization
fileMenu.setMnemonic(KeyStroke.getKeyStroke(mnemonic).getKeyCode());
```
Accelerators are not supported for `JMenu`s, only for `JMenuItem`s (which makes sense, since these invoke an action without using the menu at all). | Inside the resource file use the accelerator
add.Action.accelerator = control A | Java Menu Mnemonics in Resource Files | [
"",
"java",
"internationalization",
""
] |
Ok, I've got a strange problem. I am testing a usercontrol and have code like this:
```
[TestFixture]
public myTestClass : UserControl
{
MyControl m_Control;
[Test]
public void TestMyControl()
{
m_Control = new MyControl();
this.Controls.Add(m_Control);
Assert.That(/*SomethingOrOther*/)
}
}
```
This works fine, but when I change it to:
```
[TestFixture]
public myTestClass : UserControl
{
MyControl m_Control;
[Setup]
public void Setup()
{
m_Control = new MyControl();
this.Controls.Add(m_Control);
}
[TearDown]
public void TearDown()
{
this.Controls.Clear();
}
[Test]
public void TestMyControl()
{
Assert.That(/*SomethingOrOther*/);
}
}
```
I get an Object Reference Not Set To An Instance of an Object. I even output to the console to ensure that the setup/teardown were running at the correct times, and they were... but still it isn't newing up the usercontrols.
edit> The exact code is:
```
[TestFixture]
public class MoneyBoxTests : UserControl
{
private MoneyBox m_MoneyBox;
private TextBox m_TextBox;
#region "Setup/TearDown"
[SetUp]
public void Setup()
{
MoneyBox m_MoneyBox = new MoneyBox();
TextBox m_TextBox = new TextBox();
this.Controls.Add(m_MoneyBox);
this.Controls.Add(m_TextBox);
}
[TearDown]
public void TearDown()
{
this.Controls.Clear();
}
#endregion
[Test]
public void AmountConvertsToDollarsOnLeave()
{
m_MoneyBox.Focus();
m_MoneyBox.Text = "100";
m_TextBox.Focus();
Assert.That(m_MoneyBox.Text, Is.EqualTo("$100.00"), "Text isn't $100.00");
}
[Test]
public void AmountStaysANumberAfterConvertToDollars()
{
m_MoneyBox.Focus();
m_MoneyBox.Text = "100";
m_TextBox.Focus();
Assert.That(m_MoneyBox.Amount, Is.EqualTo(100), "Amount isn't 100");
}
}
```
I get the exception(s) at the respective m\_MoneyBox.Focus() calls.
Solved - See Joseph's comments | I created a test case with exactly the same layout you presented here, but with a TextBox instead of a MyControl. I also added a constructor and a deconstructor and outputted all the various stages to the console to see the sequence of events. However, I never got an object reference exception.
In case you are interested, the sequence was [constructor called], [setup called], [test called], [tear down called]. The deconstruction never output anything to the screen for some reason.
My original thought was that the Controls property on myTestClass would not be initialized, but on my test it was, so I think it has something to do with your MyControl construction.
edit> I added the focus on my TextBox in my unit test as well but still no exception. Does your MoneyBox have any event handling going on behind the scenes during the Focus? That might be your culprit. | You haven't said where you're getting the exception, which would help - what does the stack trace look like?
It's very odd (IME) to derive from UserControl when you create a test fixture. Aside from anything else, I don't know that NUnit is going to call Dispose for you at any appropriate point... what's the purpose of it here? Can you not make your tests run with a "plain" test fixture? | nunit setup/teardown not working? | [
"",
"c#",
"unit-testing",
""
] |
This doesn't seem possible in VB.NET with properties since the property statement itself must describe whether it is `ReadOnly` or not.
In my example below, it doesn't let me make the `ReadWriteChild` compile. I guess I could make the parent Read/Write, and then have the ReadOnlyChild's setter not do anything, but that seems sort of hacky. The best alternative seems to be abandoning properties in favor of getter/setter methods in this case.
```
Public MustInherit Class Parent
Public MustOverride ReadOnly Property Foo() As String
End Class
Public Class ReadOnlyChild
Inherits Parent
Public Overrides ReadOnly Property Foo() As String
Get
' Get the Property
End Get
End Property
End Class
Public Class ReadWriteChild
Inherits Parent
Public Overrides Property Foo() As String
Get
' Get the property.
End Get
Set(ByVal value As String)
' Set the property.
End Set
End Property
End Class
``` | Given what you're trying to accomplish, and with the sample code you posted, VB.NET will not let you do this.
Ordinarily, you can declare a property in VB.NET like so:
```
Public Class qwqwqw
Public Property xyz() As String
Get
Return ""
End Get
Private Set(ByVal value As String)
'
End Set
End Property
End Class
```
Basically marking the overall property as public, but giving a more restrictive scope to the setter (or getter).
The main problem in your case is the MustInherit (i.e. abstract) base class. Since the property you're defining in there is marked as MustOverride, you can't provide a default implementation (i.e. it, too, is abstract), and this includes the "Get" and "Set" outlines, therefore, whichever "overall" scope you give to this abstract property declaration, VB.NET will force you to use this scope for *both* the getters and setters within derived classes.
Having the ReadOnly qualifier on the base class's property will force all derived classes and the implementations of this property to also be ReadOnly. Leaving off the ReadOnly qualifier still will not work, since whatever scope you give to the abstract property will be the scope you must apply to both the setters and getters within derived implementations.
For example:
```
Public MustInherit Class Parent
Public MustOverride Property Foo() As String
End Class
Public Class ReadOnlyChild
Inherits Parent
Public Overrides Property Foo() As String
Get
'
End Get
Private Set(ByVal value As String)
'
End Set
End Property
End Class
```
(Note the Private scoping on the setter). This will not work as VB.NET is insisting that since you're overriding the base classes property, your entire property must have the same scope as the property you're overriding (in this case, public).
Attempting to make the base class's abstract property protected will not work either, since you would then be required to implement the property at the same level of scoping as it's declared in your base class (i.e. protected). Ordinarily, when not overriding a base class's abstract definition with a specific scoping level, you can give a getter or setter a *more* restrictive scoping level, but you can't give it a *less* restrictive scoping level.
Therefore:
```
Public MustInherit Class Parent
Protected MustOverride Property Foo() As String
End Class
Public Class ReadOnlyChild
Inherits Parent
Protected Overrides Property Foo() As String
Public Get
'
End Get
Set(ByVal value As String)
'
End Set
End Property
End Class
```
(Note the public scoping on the getter). Doesn't work either due to the public scope being less restrictive than the overall property scope of protected, and moreover, not of the same scoping level as defined on the base class's abstract property declaration.
If the design of your classes is as you mention in your question, I personally, would go with a "java-style" getter and setter *methods* as they can then be declared separately with their own scoping levels. | Might be a longshot ... given that my knowledge of VB.NET is minimal ...
In C# you can specify the visibility of a property accessor independently of the property:
```
public virtual string Name
{
get { ... }
protected set { ... }
}
```
In this example, child classes can access the settor, but other classes cannot.
Also note that overrides can have greater visibility than what they override - so you can do this:
```
public overide string Name
{
get { ... }
public set { ... }
}
```
Could you do something like this in VB.NET ? | Overriding ReadOnly Property in a subclass to make it Read/Write (VB.NET or C#) | [
"",
"c#",
"vb.net",
"inheritance",
"properties",
"readonly",
""
] |
I want to separate a string consisting of one or more two-letter codes separated by commas into two-letter substrings and put them in a string array or other suitable data structure. The result is at one point to be databound to a combo box so this needs to be taken into account.
The string I want to manipulate can either be empty, consist of two letters only or be made up by multiple two-letter codes separated by commas (and possibly a space).
I was thinking of using a simple string array but I'm not sure if this is the best way to go.
So... what data structure would you recommend that I use and how would you implement it? | Definitely at least start with a string array, because it's the return type of `string.Split()`:
```
string MyCodes = "AB,BC,CD";
char[] delimiters = new char[] {',', ' '};
string[] codes = MyCodes.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
```
Update: added space to the delimiters. That will have the effect of trimming spaces from your result strings. | Would something like this work?
```
var list = theString.Split(", ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
``` | Separating a string into substrings | [
"",
"c#",
".net",
"string",
""
] |
Is there a way to stipulate that the clients of a class should specify a value for a set of properties in a class. For example (see below code), Can i stipulate that "EmploymentType" property in Employment class should be specified at compile time? I know i can use parametrized constructor and such. I am specifically looking for outputting a custom warning or error during compile time. Is that possible?
```
public class Employment
{
public EmploymentType EmploymentType {get; set;}
}
public enum EmploymentType
{
FullTime = 1,
PartTime= 2
}
public class Client
{
Employment e = new Employment();
// if i build the above code, i should get a error or warning saying you should specify value for EmploymentType
}
``` | As cmsjr stated what you need to do is this:
```
public class Employment
{
public Employment(EmploymentType employmentType)
{
this.EmploymentType = employmentType;
}
public EmploymentType EmploymentType { get; set; }
}
```
This will force callers to pass in the value at creation like this:
```
Employment e = new Employment(EmploymentType.FullTime);
```
In the situation where you need to have a default constructor (like serialization) but you still want to enforce the rule then you would need some sort of state validation. For instance anytime you attempt to perform an operation on the Employment class you can have it check for a valid state like this:
```
public EmploymentType? EmploymentType { get; set; } // Nullable Type
public void PerformAction()
{
if(this.Validate())
// Perform action
}
protected bool Validate()
{
if(!EmploymentType.HasValue)
throw new InvalidOperationException("EmploymentType must be set.");
}
```
If you're looking throw custom compiler warnings, this is not exactly possible. I asked a similar question here [Custom Compiler Warnings](https://stackoverflow.com/questions/154109/custom-compiler-warnings) | You could achieve what you want to do by not having a default constructor, and instead defining a constructor that takes employment type as an argument. If someone attempted to instantiate the class using a parameter-less constructor, they would get a compile error.
EDIT code sample
```
public Employment(EmploymentType eType)
{
this.EmploymentType = eType;
}
``` | Stipulating that a property is required in a class - compile time | [
"",
"c#",
".net",
"compiler-construction",
"clr",
""
] |
I have an application that has been getting strange errors when canceling out of a dialog box. The application can't continue if the box is cancelled out of, so it exits, but it is not working for some reason, and thus it keeps running and crashes.
I debugged this problem, and somehow the application runs right past the Application.Exit call. I'm running in Debug mode, and this is relevant because of a small amount of code that depends on the RELEASE variable being defined. Here is my app exit code. I have traced the code and it entered the ExitApp method, and keeps on going, returning control to the caller and eventually crashing.
This is an application which provides reports over a remote desktop connection, so that's why the exit code is a bit weird. Its trying to terminate the remote session, but only when running under release because I don't want to shut down my dev machine for every test run.
```
private void ExitApp()
{
HardTerminalExit();
Application.Exit();
}
// When in Debug mode running on a development computer, this will not run to avoid shutting down the dev computer
// When in release mode the Remote Connection or other computer this is run on will be shut down.
[Conditional("RELEASE")]
private void HardTerminalExit()
{
WTSLogoffSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, false);
}
```
I've run a debugger right past the Application.Exit line and nothing happens, then control returns to the caller after I step past that line.
What's going on? This is a Windows Forms application. | This is an article which expands on the same train of thought you are going through: <http://www.dev102.com/2008/06/24/how-do-you-exit-your-net-application/>
Basically:
> * Environment.Exit - From MSDN: Terminates this process and gives the
> underlying operating system the
> specified exit code. This is the code
> to call when you are using console
> application.
> * Application.Exit - From MSDN: Informs all message pumps that they
> must terminate, and then closes all
> application windows after the messages
> have been processed. This is the code
> to use if you are have called
> Application.Run (WinForms
> applications), this method stops all
> running message loops on all threads
> and closes all windows of the
> application. There are some more
> issues about this method, read about
> it in the MSDN page.
Another discussion of this: [Link](https://web.archive.org/web/20201029173358/http://geekswithblogs.net/mtreadwell/archive/2004/06/06/6123.aspx)
This article points out a good tip:
You can determine if System.Windows.Forms.Application.Run has been called by checking the System.Windows.Forms.Application.MessageLoop property. If true, then Run has been called and you can assume that a WinForms application is executing as follows.
```
if (System.Windows.Forms.Application.MessageLoop)
{
// Use this since we are a WinForms app
System.Windows.Forms.Application.Exit();
}
else
{
// Use this since we are a console app
System.Environment.Exit(1);
}
``` | Having had this problem recently (that Application.Exit was failing to correctly terminate message pumps for win-forms with Application.Run(new Form())), I discovered that if you are spawning new threads or starting background workers within the constructor, this will prevent Application.Exit from running.
Move all 'RunWorkerAsync' calls from the constructor to a form Load method:
```
public Form()
{
this.Worker.RunWorkerAsync();
}
```
Move to:
```
public void Form_Load(object sender, EventArgs e)
{
this.Worker.RunWorkerAsync();
}
``` | Why would Application.Exit fail to work? | [
"",
"c#",
".net",
"winforms",
""
] |
i am trying to write a program but i have no idea what to with parsing a date in this format into into a date stamp
Jan 15 2005 12:00AM
i do not care about the 12:00AM as all the records have that 12:00AM appended to them. | Use the strtotime() function ... e.g.:
$new\_date = strtotime("Jan 15 2005 12:00AM"); | Use [strtotime()](http://php.net/strtotime) to convert the date to unix timestamp. You can also use this timestamp with [date()](http://php.net/date) function to format it in any way you want. | Parsing Dates with PHP | [
"",
"php",
"parsing",
""
] |
When you can create classes and do the simple stuff (GUI, reading text files, etc...), where do I go from here? I've started reading Code Complete 2nd Edition which is great but is more of a general programming book. What topics should I learn next? | I'd argue that, at some point, it's no longer about **topics**. It's about **doing stuff**. You gotta write code an you've gotta write a lot of it.
People will often tell you to find some niche problem to try and solve when learning a new language and that's perfectly fine, but if there's an application or feature of an application that you really enjoy using or really admire, attempt to build it (or parts of it) yourself. Even more so, if you find your self wondering *Hey, how does [this application] do **that?!*** Try to build it.
Many of your projects may never see the light of day beyond your desktop, but the learning, experience, and tools you'll have under your belt will be something that you can carry over to each subsequent project.
You never know, though, one of those little hobby projects may end up solving a problem for someone. | Not to disagree with the folks who are saying "write stuff," but one topic that you should learn about next is the underlying fundamentals of the CLR -- the workings of the engine that sits behind all of these libraries. A good resource for this is Richter's "CLR Via C#." | How can I become a better C# programmer? | [
"",
"c#",
"code-complete",
""
] |
I have this code (ok, I don't, but something similar :p)
```
var dogs = Dogs.Select(ø => new Row
{
Name = ø.Name,
WeightOfNiceCats = ø.Owner
.Cats
.Where(æ => !æ.Annoying)
.Sum(æ => æ.Weight),
});
```
Here I go through all dogs and sum up the weight (into a non-nullable decimal) of all not-annoying cats which has the same owner as the dog. Of course, pretty much all cats are annoying, so I get this error:
> The null value cannot be assigned to a member with type System.Decimal which is a non-nullable value type.
None of the fields or foreign keys used can be null. So the error happens when the `Where` clause returns no cats, which it often does. But how can I solve this? I want it to return 0 when that happens. Tried with a `DefaultIfEmpty()` after the `Where` clause, but then I get this error:
> Object reference not set to an instance of an object.
Which I guess is understandable. I tried to add a `??` after the `Sum`, but then it wont compile because of this error:
> Operator '??' cannot be applied to operands of type 'decimal' and 'decimal'
Which also makes sense of course. So what can I do? Would be nice if the `Sum` thing just returned 0 when there was nothing to sum. Or a `SumOrZero` statement of some sort. Would it be difficult to make a `SumOrZero` method that worked with Linq2SQL? | This is what I ended up with for now:
```
.Sum(æ => (decimal?) æ.Weight) ?? 0.0M,
```
This works like a charm.
I would still prefer to have a `SumOrZero` I could use, which would work exactly like the regular `Sum` except it would never return `null` for any reason. Like the others have noted, this would be pretty easy to make for `IEnumerable` but a bit more icky to create for `IQueryable` so it would work with Linq2SQL, etc. So I will just leave it at that for now. Although if someone is bored one day and do write a `SumOrZero` for `IQueryable` which works with Linq2SQL for all the numeric types, please do let me know :D | In LINQ to Objects it would be easy. With LINQ to SQL it will be harder. You could write your own extension method which called `Queryable.Sum` with an expression built up from the normal one, with a cast to the nullable type. I suspect you'd need to do the ?? 0m in the calling code though. In other words, you could do:
```
.SumOrNull(æ => æ.Weight) ?? 0M,
```
Where the signature for .SumOrNull would be:
```
public static decimal? SumOrNull<TSource, decimal>(this IQueryable<TSource>,
Func<TSource,decimal> projection)
```
You could basically write that for all the value types supported in Queryable. You *could* write it generically, and call the appropriate method in Queryable using reflection, but that would be icky too.
I think you're best off with what you've got, to be honest. | Sum() causes exception instead of returning 0 when no rows | [
"",
"c#",
"linq-to-sql",
"nullreferenceexception",
""
] |
See title... | No.
You can use [WordML](http://msdn.microsoft.com/en-us/library/aa212812.aspx) (Word XML)
[Word 2007 version](http://msdn.microsoft.com/en-us/library/bb266220.aspx) | You can create Word 2007 documents using its XML format without the need of installing Word in your server.
[This](http://www.codeproject.com/KB/office/DocumentMaker.aspx) can be a starting point. | Do I need to have MS Word installed for creating Word documents from asp.net? | [
"",
"c#",
"asp.net",
""
] |
I have read a couple of articles about the perils of certain data types being used to store monetary amounts. Unfortunately, some of the concepts are not in my comfort zone.
Having read these articles, what are the best practises and recommendations for working with money in C#? Should I use a certain data type for a small amount and a different one for a larger amount? Also, I am based in the UK which means we use , (e.g. £4,000, whereas other cultures represent the same amount differently). | You should not use floating point numbers because of rounding errors. The decimal type should suit you. | Decimal is the most sensible type for monetary amounts.
Decimal is a floating point base 10 numeric type with 28+ decimal digits of precision. Using Decimal, you will have fewer surprises than you will using the base 2 Double type.
Double uses half as much memory as Decimal and Double will be much faster because of the CPU hardware for many common floating point operations, but it cannot represent most base 10 fractions (such as 1.05) accurately and has a less accurate 15+ decimal digits of precision. Double does have the advantage of more range (it can represent larger and smaller numbers) which can come in handy for some computations, particularly some statistics computations.
One answer to your question states that Decimal is fixed point with 4 decimal digits. This is not the case. If you doubt this, notice that the following line of code yields 0.0000000001:
```
Console.WriteLine("number={0}", 1m / 10000000000m);
```
Having said all of that, it is interesting to note that the most widely used software in the world for working with monetary amounts, Microsoft Excel, uses doubles. Of course, they have to jump through a lot of hoops to make it work well, and it still leaves something to be desired. Try these two formulas in Excel:
* =1-0.9-0.1
* =(1-0.9-0.1)
The first yields 0, the second yields ~-2.77e-17. Excel actually massages the numbers when adding and subtracting numbers in some cases, but not in all cases. | Best practices for dealing with monetary amounts in C# | [
"",
"c#",
"types",
"currency",
""
] |
I am currently trying to log into a site using Python however the site seems to be sending a cookie and a redirect statement on the same page. Python seems to be following that redirect thus preventing me from reading the cookie send by the login page. How do I prevent Python's urllib (or urllib2) urlopen from following the redirect? | You could do a couple of things:
1. Build your own HTTPRedirectHandler that intercepts each redirect
2. Create an instance of HTTPCookieProcessor and install that opener so that you have access to the cookiejar.
This is a quick little thing that shows both
```
import urllib2
#redirect_handler = urllib2.HTTPRedirectHandler()
class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
print "Cookie Manip Right Here"
return urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
http_error_301 = http_error_303 = http_error_307 = http_error_302
cookieprocessor = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener(MyHTTPRedirectHandler, cookieprocessor)
urllib2.install_opener(opener)
response =urllib2.urlopen("WHEREEVER")
print response.read()
print cookieprocessor.cookiejar
``` | If all you need is stopping redirection, then there is a simple way to do it. For example I only want to get cookies and for a better performance I don't want to be redirected to any other page. Also I hope the code is kept as 3xx. let's use 302 for instance.
```
class MyHTTPErrorProcessor(urllib2.HTTPErrorProcessor):
def http_response(self, request, response):
code, msg, hdrs = response.code, response.msg, response.info()
# only add this line to stop 302 redirection.
if code == 302: return response
if not (200 <= code < 300):
response = self.parent.error(
'http', request, response, code, msg, hdrs)
return response
https_response = http_response
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), MyHTTPErrorProcessor)
```
In this way, you don't even need to go into urllib2.HTTPRedirectHandler.http\_error\_302()
**Yet more common case is that we simply want to stop redirection (as required):**
```
class NoRedirection(urllib2.HTTPErrorProcessor):
def http_response(self, request, response):
return response
https_response = http_response
```
And normally use it this way:
```
cj = cookielib.CookieJar()
opener = urllib2.build_opener(NoRedirection, urllib2.HTTPCookieProcessor(cj))
data = {}
response = opener.open('http://www.example.com', urllib.urlencode(data))
if response.code == 302:
redirection_target = response.headers['Location']
``` | How do I prevent Python's urllib(2) from following a redirect | [
"",
"python",
"urllib2",
""
] |
I'm trying to give fadeout effect to a div & delete that div(id = "notification"), when an image is clicked.
This is how I'm doing that:
```
<a onclick="$("#notification").fadeOut(300,function() { $("#notification").remove(); });" class="notificationClose "><img src="close.png"/></a>
```
This seems to not be working.
What do I need to do to fix this? | Try this:
```
<a onclick='$("#notification").fadeOut(300, function() { $(this).remove(); });' class="notificationClose "><img src="close.png"/></a>
```
I think your double quotes around the `onclick` were making it not work. :)
**EDIT**: As pointed out below, inline javascript is evil and you should probably take this out of the `onclick` and move it to jQuery's [`click()`](http://docs.jquery.com/Events/click) event handler. That is how the cool kids are doing it nowadays. | you really should try to use jQuery in a separate file, not inline. Here is what you need:
```
<a class="notificationClose "><img src="close.png"/></a>
```
And then this at the bottom of your page in `<script>` tags at the very least or in a external JavaScript file.
```
$(".notificationClose").click(function() {
$("#notification").fadeOut("normal", function() {
$(this).remove();
});
});
``` | How to "fadeOut" & "remove" a div in jQuery? | [
"",
"javascript",
"jquery",
""
] |
C++ templates have been a blessing in my everyday work because of its power. But one cannot ignore the (very very very very long) compilation time that results from the heavy use of templates (hello meta-programming and Boost libraries). I have read and tried quite a lot of possibilities to manually reorganize and modify template code to make it compile as fast as possible.
Now I am wondering if there are any c++ compilers that try and minimize the needed time to interpret template classes. I might be wrong, but i feel that the compilers i do know have only added template interpretation to their previous versions.
My questions are :
* Is c++ template code so difficult to interpret that there is not much to optimize ? (i highly doubt that)
* Are there c++ compilers that truly optimize "c++ templates" interpretation ?
* Are there projects to develop a new generation of c++ compilers that would optimize this ?
* If you were to participate in such a project, what would your guidelines be ? | It seems that g++ 4.5 has made tremendous progress dealing with templates. Here are the two unavoidable changes.
* "When printing the name of a class template specialization, G++ will now omit any template arguments which come from default template arguments." That could be considered a subtle modification, but it will have an enormous impact on development with c++ templates (ever heard of unreadable error messages... ? No more !)
* "Compilation time for code that uses templates should now scale linearly with the number of instantiations rather than quadratically." This is going to severely undermine compilation-time arguments against the use of C++ templates.
See on the [gnu site](http://gcc.gnu.org/gcc-4.5/changes.html) for complete information
Actually, i am already wondering whether there still are issues with c++ templates ! Mmm, yes, there are, but let's focus on the bright side for now ! | I expect that compiling templated code will be speed up with having variadic templates / rvalue references. Today, if we want to write template code that does something at compile time, we abuse rules of the language. We create dozens of overloads and template specializations that results in what we want, but not in a way that tells the compiler our intention. So there is little to shortcut for the compiler at build-time. See [Motivation for variadic templates](http://www.osl.iu.edu/~dgregor/cpp/variadic-templates.html#motivation)
> Are there projects to develop a new generation of c++ compilers that would optimize this ?
Yes, there is [CLang](http://clang.llvm.org/) which is a C Language Frontend for the LLVM Compiler infrastructure. Both CLang and LLVM are coded using C++. Among the developers of CLang is Douglas Gregor, author of several C++1x Language Proposals like variadic templates and Concepts. For reference, see this test by Douglas Gregor of clang against GCC
[](https://i.stack.imgur.com/xlM2s.png)
> Here are some quick-n-dirty performance results for template instantiation in Clang and GCC 4.2. The test is very simple: measure compilation time (-fsyntax-only) for a translation unit that computes the Nth Fibonacci number via a template metaprogram. Clang appears to be scaling linearly (or close to it) with the number of instantiations. And, although you can't see it in the chart, Clang is a little over 2x faster than GCC at the beginning (`Fibonacci<100>`).
CLang is still in its [early days](http://clang.llvm.org/cxx_status.html) but i think it's got good chances to become a great C++ Compiler. | Are there optimized c++ compilers for template use? | [
"",
"c++",
"templates",
"compiler-construction",
""
] |
Does doing something like this use dynamic memory allocation?
```
template <class T, int _size>
class CArray
{
public:
...
private:
T m_data[_size];
};
```
Can someone explain to me what's going on behind the scenes when I create the object?
```
CArray<SomeObject, 32> myStupidArray;
``` | As mentioned in the other answers, templates are evaluated at compile time. If you're interested you can have g++ spit out the class hierarchy where you can verify its size:
```
template <class T, int _size>
class CArray
{
public:
private:
T m_data[_size];
};
int main(int argc, char **argv) {
CArray<int, 32> myStupidArray1;
CArray<int, 8> myStupidArray2;
CArray<int, 64> myStupidArray3;
CArray<int, 1000> myStupidArray4;
}
```
Compile with `-fdump-class-hierarchy`:
```
g++ -fdump-class-hierarchy blah.cc
```
There should be a file named `blah.cc.t01.class` in the current directory:
```
Class CArray<int, 32>
size=128 align=4
base size=128 base align=4
CArray<int, 32> (0x40be0d80) 0
Class CArray<int, 8>
size=32 align=4
base size=32 base align=4
CArray<int, 8> (0x40be0e80) 0
Class CArray<int, 64>
size=256 align=4
base size=256 base align=4
CArray<int, 64> (0x40be0f80) 0
Class CArray<int, 1000>
size=4000 align=4
base size=4000 base align=4
CArray<int, 1000> (0x40be6000) 0
``` | No, it will be allocated in-place (e.g. either on the stack, or as part of a containing object).
With templates the parameters are evaluated at compile-time so your code effectively becomes;
```
class CArray
{
public:
...
private:
SomeObject m_data[32];
};
``` | Does this C++ class containing a variable size array use dynamic memory allocation? | [
"",
"c++",
"templates",
"memory-management",
""
] |
I wrote this code in Processing ([www.processing.org](http://www.processing.org/)) and was wondering how would one implement it using C++?
```
int i = 0;
void setup()
{
size(1000,1000);
}
void draw()
{
// frameRate(120);
PImage slice = get();
set(0,20,slice);
if( i % 2 == 0 ) fill(128); else fill(0);
i++;
rect(0,0,width,20);
}
```
As you can see this simply scrolls down rectangles of alternating colors as fast as possible. Can the C++ implementation be as short? OpenGL? | You could also take a look at [OpenFrameworks](http://www.openframeworks.cc/) but I doubt that any C++ library will give you such a short implementation. | I'd probably use [SDL](http://www.libsdl.org/) for this. Your program will be a little longer, because you'll have to do some setup and tear-down on your own (plenty of good examples, though). You could do the same with OpenGL, but it would be quite a bit more work. If you go that route, [NeHe Productions](http://nehe.gamedev.net/) offers practically the gold standard in OpenGL tutorials. | How do you translate this code from Processing to C++? | [
"",
"c++",
"drawing",
""
] |
I'm using C#. I have a products class with fields like sku, name, description.... and methods like setSku, setDescription, setImages(products have an image attached). I was keeping these methods inside the Product class but because of the large amount of settings available to the client on how to set the sku and descriptions and images, the class was getting really, really large. There was a lot of code inside the class. So I was going to break up the large Product class into pieces like a ProductSku class, ProductDescription class...etc. The problem here is that there are some of the same fields that need to be accessed by all the classes. I starting calling the methods on those individual classes and passing in the same objects over and over again, but this didn't seem to be right. So now I decided to make one global(using Singleton pattern) CurrentProduct class that has the fields I need for all the other Product classes I created. **My questions are does this sound right and what would you do?**
The program I am working on just, on a basic level, takes products from one table from database1 and saves the products to a table on database2. However, the users have a lot of settings available to them for how they want the fields coming from database1 to look when they enter database2.
To Clarify: The set and get methods referenced above are not getter and setter methods. I use properties however I called them set because there is a lot of code that goes into formatting some of the fields prior to update. I understand the confusion and I apologize for not clarifying. | The singleton for current product does sound bad. You're just calling a global variable by a different name.
I don't know what a Sku is, but as for the rest (Description and Images), if they're attributes of a product (which I think they are) they belong in the Product class.
If you're passing your "class pieces" around together a lot that is a strong sign that they belong together.
If you wish, separate the code (not the class) into several files by using the `partial` keyword. Like this:
```
// This file is Product.CodeAboutThingA.cs
public partial class Product
{
// Some stuff related to A here...
}
```
And in another file:
```
// This file is Product.CodeAboutThingB.cs
public partial class Product
{
// Some stuff related to B here...
}
``` | To give my .5 cents, a class that can only be managed by splitting it into partials has quite some code smell.
Separating the whole thing into several classes sounds good, especially when you already identified stuff like SKU etc. to be its own class.
Things you should ask yourself are...
* Is it OK if I can only access an SKU through a valid Product instance? Even if it is just an identifier, such an identifier may be quite complex in itself.
* In what way must the SKU use stuff from the Product class? If the product is the only one instantiating an SKU, it may be OK to pass the product into the SKU. The two classes are now coupled fairly tight, but still better than a single Product mess with no semantics.
* Can you identify what are the common parts that need to be shared throughout? Maybe you are missing an entity or a value object that is that "common part"?
* Maybe you would be happier with a Product Builder, instead of letting the Client rummage around the innards of a Product instance?
From my perspective, when you have a class with 1k+ lines of code, there is still a lot of understanding missing what your "Product" really is and how it behaves in the scope of your application... | Tips on proper classes | [
"",
"c#",
"class",
""
] |
I would like to compress the results if it reached a certain number of rows.
The client program would then uncompress the result and process.
This a desktop with a client/server architecture, some clients connects through vpn.
When a client connects, it will send data to the server. After the server has done processing, the client will then download updated data from the server.
The clients are located in several towns, with average of 50-100 kms. away. They will connect through internet using vpn. But that is the initial plan, not implemented yet, using vpn or other means. | There is the [COMPRESS](http://dev.mysql.com/doc/refman/5.1/en/encryption-functions.html#function_compress) function which can be used to compress strings into binary strings. However, depending on your needs that may not really address the problem especially since database records are usually already very compact by their very nature so I'm not certain how much benefit you'll receive from attempting further compression of the result set.
One thing you need to be careful of is premature optimization. Oftentimes you can introduce unneeded complexity and actually hurt performance if you attempt to optimize prior to correctly identifying actual bottlenecks and not just shooting blindly at the possible ones.
In that vein I would ask if you have actually identified a bottleneck in your application? If so, where exactly is it and what is its nature? What environment are you working in? Is this web development or desktop with a client/server architecture?
Perhaps you can add some of this additional information to your question and then it would be possible to better assist you? | Most MySQL clients support compression (--compress option)
But are you sure you want to do this within MySQL? This sounds more like a task for a web or application server?
Most web servers support compressing responses with gzip etc
Have you got some more details to share on what the issue is and what platforms and tools you are using? | Is there a function in MySQL that will compress the results returned from a query? | [
"",
"sql",
"mysql",
""
] |
I'd like to test a function that takes runtime-allocated multidimensional arrays, by passing it a hardcoded array.
The function has a signature of `void generate_all_paths(int** maze, int size)` and the array is defined as `int arr[5][5] = {REMOVED}`.
I'm not exactly sure how to properly coerce the array for the function (or if that is impossible). | This multi dimensional array topic unfortunately confuses so many C++ programmers. Well, here is the solution:
```
void generate_all_paths(int (*maze)[5], int size);
```
That is what the function declaration has to look like. An alternative, but fully equivalent is
```
void generate_all_paths(int maze[][5], int size);
```
Both are creating a parameter that is a pointer to an array of 5 integers. You can then pass your array of arrays of 5 integers to that function:
```
generate_all_paths(arr, 5);
```
Because your array's first element is an array of 5 integers, it will be converted automatically (implicitly) to a pointer to that first element when passed to that function.
In the comments, you have shown you are bound to an `int**`, because both your inner and outer dimension must have runtime values. A multi-dimensional array can not be used anymore. What you can do for testing purposes then is to create an array of pointers like this:
```
int store[5 * 5] = { ..... };
int *arr[5] = { store, store + 5, store + 10, store + 15, store + 20 };
```
Then, actually, you can have your function accept a `int**`. As the first element of you array then is a `int*`, it will be converted to a `int**` automatically. Another way of doing this is keeping the data in the 2 dimensional array, but just creating a "view" structured of pointers to that array:
```
int *arr[5] = { store[0], store[1], store[2], store[3], store[4] };
```
Where store is your `int[5][5]` array. Since `store[n]` accesses the n'th sub-array of that two-dimensional array and the element type of it is `int`, the pointer-converted type of it is `int*`, which will be compatible again. | You can write:
```
void display(char **a)
```
And then use `a[i][j]` to refer to elements in it.
The declaration `char **` means "pointer to pointer to integer". To break it down into steps:
```
char *b = a[i];
```
That gets you a pointer to the first element of the `i`'th array in the array-of-arrays.
```
char c = b[j];
```
That gets you the `j`'th element in the array `b`.
The next problem you'll have is of allocating such an array-of-arrays.
```
char **arrayOfArrays = new char *[10];
for (int n = 0; n < 10; n++)
arrayOfArrays[n] = new char[20];
```
That allocates an array of 10 arrays, each "child" array having 20 characters.
In C/C++, array access syntax is just a way of retrieving a value some distance away from a pointer.
```
char *p = "Hello";
char *pl = p + 2; // get pointer to middle 'l'
char l = *pl; // fetch
char o = p[4]; // use array syntax instead
``` | Passing a variable of type int[5][5] to a function that requires int** | [
"",
"c++",
"c",
"multidimensional-array",
""
] |
I'm in the process of writing a BSD licensed mini-ORM targeted at embedded databases (with support for ese, sqlite and sqlce out of the box)
After working lots with Rails in the last year I have been thinking of implementing an Active Record pattern in C#.
I have come up with some demo code and was wondering if the interface design is sound.
Here you go:
```
// first param is the class, second is the primary key
public class Order : ActiveRecord<Order,int> {
BelongsTo<Customer> Customer { get; set; }
[PrimaryKey(AutoIncrement=true)]
public int Id { get; set; }
public string Details { get; set; }
}
[Index("FirstName", "LastName")]
[Index("LastName", "FirstName")]
public class Customer : ActiveRecord<Customer,int>
{
public HasMany<Order> Orders { get; set; }
[PrimaryKey(AutoIncrement=true)]
public int Id { get; set; }
[ColumnInfo(MinLength=4, MaxLength=255, Nullable=false)]
public string FirstName { get; set; }
[ColumnInfo(MinLength=4, MaxLength=255, Nullable=false)]
public string LastName { get; set; }
public string Comments { get; set; }
}
[TestClass]
public class TestActiveRecord {
public void Demo()
{
var customer = Customer.Build();
customer.FirstName = "bob";
customer.LastName = "doe";
var order = customer.Orders.Build();
order.Details = "This is the first order";
customer.Save();
var customer2 = Customer.Find(customer.Id);
Assert.AreEqual(1, customer2.Orders.Count);
}
}
```
Sorry about this being a multiple questions in one question ...
Can you think of any changes to this API? Are there any fatal flaws? Are there any open source ORMs that define similar interfaces? | The [Castle Active Record](http://castleproject.org/activerecord/index.html) Project.
Although it's not a strict implementation of the Active Record pattern, it works very well. Bonus is you will get some experience with NHibernate in the process.
As someone who has written his own, very simple, OR/M only to find it lacking when scenarios got more complex, I would strongly urge you to take a hard look at Caste ActiveRecord and NHibernate, unless you are doing this as a learning experience. | ActiveRecordMediator
Create a repository class that inherits from this AR class. Then you don't break your hierarchy and you implement a repository pattern along with your AR pattern! | Advice on an ActiveRecord design pattern in C# | [
"",
"c#",
"design-patterns",
"api",
""
] |
I have an `ArrayList` that I want to output completely as a String. Essentially I want to output it in order using the `toString` of each element separated by tabs. Is there any fast way to do this? You could loop through it (or remove each element) and concatenate it to a String but I think this will be very slow. | Java 8 introduces a `String.join(separator, list)` method; see [Vitalii Federenko's answer](https://stackoverflow.com/a/23183963/5139284).
Before Java 8, using a loop to iterate over the `ArrayList` was the only option:
**DO NOT use this code, continue reading to the bottom of this answer to see why it is not desirable, and which code should be used instead:**
```
ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
String listString = "";
for (String s : list)
{
listString += s + "\t";
}
System.out.println(listString);
```
In fact, a string concatenation is going to be just fine, as the `javac` compiler will optimize the string concatenation as a series of `append` operations on a `StringBuilder` anyway. Here's a part of the disassembly of the bytecode from the `for` loop from the above program:
```
61: new #13; //class java/lang/StringBuilder
64: dup
65: invokespecial #14; //Method java/lang/StringBuilder."<init>":()V
68: aload_2
69: invokevirtual #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
72: aload 4
74: invokevirtual #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
77: ldc #16; //String \t
79: invokevirtual #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
82: invokevirtual #17; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
```
As can be seen, the compiler optimizes that loop by using a `StringBuilder`, so performance shouldn't be a big concern.
(OK, on second glance, the `StringBuilder` is being instantiated on each iteration of the loop, so it may not be the most efficient bytecode. Instantiating and using an explicit `StringBuilder` would probably yield better performance.)
In fact, I think that having any sort of output (be it to disk or to the screen) will be at least an order of a magnitude slower than having to worry about the performance of string concatenations.
**Edit:** As pointed out in the comments, the above compiler optimization is indeed creating a new instance of `StringBuilder` on each iteration. (Which I have noted previously.)
The most optimized technique to use will be the response by [Paul Tomblin](https://stackoverflow.com/questions/599161/best-way-to-convert-an-arraylist-to-a-string/599169#599169), as it only instantiates a single `StringBuilder` object outside of the `for` loop.
Rewriting to the above code to:
```
ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
StringBuilder sb = new StringBuilder();
for (String s : list)
{
sb.append(s);
sb.append("\t");
}
System.out.println(sb.toString());
```
Will only instantiate the `StringBuilder` once outside of the loop, and only make the two calls to the `append` method inside the loop, as evidenced in this bytecode (which shows the instantiation of `StringBuilder` and the loop):
```
// Instantiation of the StringBuilder outside loop:
33: new #8; //class java/lang/StringBuilder
36: dup
37: invokespecial #9; //Method java/lang/StringBuilder."<init>":()V
40: astore_2
// [snip a few lines for initializing the loop]
// Loading the StringBuilder inside the loop, then append:
66: aload_2
67: aload 4
69: invokevirtual #14; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
72: pop
73: aload_2
74: ldc #15; //String \t
76: invokevirtual #14; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
79: pop
```
So, indeed the hand optimization should be better performing, as the inside of the `for` loop is shorter and there is no need to instantiate a `StringBuilder` on each iteration. | In Java 8 or later:
```
String listString = String.join(", ", list);
```
In case the `list` is not of type String, a joining collector can be used:
```
String listString = list.stream().map(Object::toString)
.collect(Collectors.joining(", "));
``` | Best way to convert an ArrayList to a string | [
"",
"java",
"string",
"arraylist",
""
] |
I have a very basic CSV file upload module working to bulk upload my user's data into my site. I process the CSV file in the backend with a python script that runs on crontab and then email the user the results of the bulk upload. This process works ok operationally, but my issue is with the format of the csv file.
Are there good tools or even basic rules on how to accept different formats of the csv file? The user may have a different order of data columns, slightly different names for the column headers (I want the email column to be entitled "Email", but it may say "Primary Email", "Email Address"), or missing additional data columns. Any good examples of CSV upload functionality that is very permissive and user friendly?
Also, how do I tell the user to export as CSV data? I'm importing address book information, so this data often comes from Outlook, Thunderbird, other software packages that have address books. Are there other popular data formats that I should accept? | I would handle the random column header mapping in your script once it's uploaded. It's hard to make a "catch all" that would handle whatever the users might enter. I would have it evolve as you go and slowly build a list of one-one relations based on what your user uploads.
Or!
Check the column headers and make sure it's properly formatted and advise them how to fix it if it is not.
> "Primary Email" not recognized, our
> schema is "Email", "Address", "Phone",
> etc.
You could also accept XML and this would allow you to create your own schema that they would have to adhere to. Check out [this tutorial](http://www.xfront.com/files/tutorials.html). | I'd check out Python's built-in csv module. Frankly a .replace() on your first row should cover your synonyms issue, and if you're using [csv.DictReader](http://docs.python.org/library/csv.html#csv.DictReader) you should be able to deal with missing columns very easily:
```
my_dict_reader = csv.DictReader(somecsvfile)
for row in my_dict_reader:
SomeDBModel.address2=row.get('address2', None)
```
assuming you wanted to store a None value for missing fields. | What are good ways to upload bulk .csv data into a webapp using Django/Python? | [
"",
"jquery",
"python",
"django",
"django-models",
"csv",
""
] |
Could some one explain this to me i am not familiar with preg\_match\_all filters, this code works fine except it does not return a negative value if one of the latitudes and longitudes is negative.
```
if ( preg_match_all( "#<td>\s+-?(\d+\.\d+)\s+</td>#", $output, $coords ) ) {
list( $lat, $long ) = $coords[1];
echo "Latitude: $lat\nLongitude: $long\n";
}
```
output:
`Latitude: 30.6963 Longitude: 71.6207` (longitude is missing a '-') | The value of the `coords` variable depends on what is matched by the code inside the parentheses. Moving the optional minus sign (`-?`) inside the parentheses should do the trick:
```
if ( preg_match_all( "#<td>\s+(-?\d+\.\d+)\s+</td>#", $output, $coords ) ) {
```
See the [official documentation](http://php.net/manual/en/regexp.reference.php) for details about preg in php and [php.net/preg\_match\_all](http://php.net/preg_match_all) for the details of `preg_match_all`. | Your sign is not in the parenthesis. $coords[1] contains the part of the regex that matched the part between ( and ). The +- are before the parenthesis, though, thus they are not part of what is matched and returned. | preg_match_all | [
"",
"php",
"preg-match-all",
""
] |
I am having a problem with one database on my SQL Server 2005 production server.
A number of databases are already set up for mirroring, however when I right click and go to properties in SSMS, on one particular database there is no "Mirroring" property page available.
I have done the normal tasks, such as setting Full Recovery model, running a full backup of the database and backing up the logs.
I can't see that this is a server specific issue as other databases are happily mirroring.
I've looked around and I can't see that I'm missing a setting, any help would be appreciated.
Thanks.
EDIT: This is nothing to do with the Mirror Database yet, I can't get as far as specifying the Mirror Database , I cannot see the "Mirroring" page on the principle.
EDIT: I have managed to setup mirroring using t-sql commands. However I am still unable to see the "Mirroring Page".
UPDATE: This applies to the Transaction Log Shipping option as well. I can successfully set it up in SQL but not through SSMS. | I ended up having to have a Microsoft Support call for the problem I was facing. Anyway after sometime and a number of support sessions they worked out that the database with the problem had an ID of 4 in sys.databases. IDs 1-4 are usually reserved for the system databases and if a database has any of these ids the T-log or Mirroring properties are not displayed. So somehow our database got the ID 3 and now I better get on and detach and reattach some databases to reassign IDs. | Check theese items:
> 2 . The mirror database has to be created from a full backup of the principal server and should be restored in "Restore with Norecovery" model. It is followed by a restore of transaction log backup of the principal database so that the log sequence numbers of the mirror and the principal database are in synch with each other.
> 3 . The mirror database must have the same name as the principal database.
> ...
> 8 . DB Mirroring is available in Enterprise, Developer and Standard Editions, however, please refer to Microsoft website for a comparison chart as some features are not available in the Standard Edition. SQL Server Workgroup and Express Editions can only be used as witness servers.
> [Database Mirroring in Microsoft SQL Server 2005](http://aspalliance.com/1388_Database_Mirroring_in_Microsoft_SQL_Server_2005.2)
Test monitoring with [sp\_dbmmonitorresults (Transact-SQL)](http://msdn.microsoft.com/en-us/library/ms366320.aspx) | Database Properties "Mirroring" Page | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I am using a jquery click function:
> **Button code**
```
<input type="button" id="myButtton">
```
> **Jquery code**
```
$(document).ready(function () {
$("#myButtton").click(function () {
alert("Mybutton");
});
});
```
This code works in Internet Explorer but does not work in Firefox.
What am I doing wrong? | In the code:
```
$(document).ready(function(){
$("#myButtton").click(function(){
alert("Mybutton");
});
```
I believe it's missing another closing brace:
```
$(document).ready(function(){
$("#myButtton").click(function(){
alert("Mybutton");
});
});
``` | Are you sure that element has an **id attribute**? Or does it have only a name attribute with a value of "myButton". In order to work cross browser the id attribute is mandatory, whereas name is optional (only IE and Opera AFAIK).
**N.B.**: My answer may seem idiot, but it was not the original poster that added the code example in the question (view edit history). | Click event not worked in Firefox | [
"",
"javascript",
"jquery",
"html",
"events",
""
] |
Hey, I was looking through W3's tutorial on AJAX and I decided to make a javascript function that would populate a form field based on the response of a page. I took all their functions and tried to create the below one.
Can anyone see why it wont work?
```
function populateForm(myForm,formField,PageFrom,infoToSend)
{
var xmlHttp;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
//alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.formField.value=xmlHttp.responseText;
}
}
var url=PageFrom;
url=url+"?q="+infoToSend;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
```
This is how I am calling it:
```
<form id="qwert" name="qwert">
<input id="qwer" name="qwer" type="text" onkeyup="populateForm('qwert','qwerty','echo.php',this.value);">
<input id="qwerty" name="qwerty" type="text">
</form>
``` | This is wrong:
```
document.myForm.formField.value=xmlHttp.responseText;
```
You might want to try:
```
document.getElementById(formField).value = xmlHttp.responseText;
```
With that you won't even need to pass the form name, just the id of the field you want to update. | This might be a late reply, but would definitely be helpful to folks having such a question later.
---
The best option is to use prototype.js available at <http://www.prototypejs.org/api/ajax/updater>. It would be as simple as
```
new Ajax.Updater('qwerty',url,{asynchronous:true});
```
This will take care of what you want to do. For any error-handling requirement, please go through the entire API documentation which is simple.
---
Hope this helps! | AJAX Function to populate a field in a form? | [
"",
"javascript",
"html",
"ajax",
"forms",
""
] |
I am trying to replce the follwing code that works fine
```
TcpClient oC = new TcpClient(ip, port);
oC = new TcpClient(ip, port);
StreamReader messageReader;
try {
messageReader = new StreamReader(oC.GetStream(), Encoding.ASCII);
reply = messageReader.ReadLine();
}
```
with
```
try {
using (messageReader = new StreamReader(oC.GetStream(), Encoding.ASCII))
{
reply = messageReader.ReadLine();
}
}
```
But I get an `InvalidOperationException` saying
> The operation is not allowed on
> non-connected sockets.
What is the problem and how can I fix it?
**More:** I have oc.Connect before this code, so I am connected and when It wants to be used for the first time is works fine, it is only after that that I get that Exception, I played around a bit with it and now I get:
> Cannot access a disposed
> object.\r\nObject name:
> 'System.Net.Sockets.Socket'. | Just reiterating my comment on Jareds answer.
Ali Commented:
> I have oc.Connect before this and it
> works fine for the 1st time, but the
> 2nd time it happens, I also get
> "Cannot access a disposed
> object.\r\nObject name:
> 'System.Net.Sockets.Socket'." – Ali
> (13 mins ago)
I Commented:
> "and that's because StreamReader takes
> ownership of the stream, and closes
> and disposes the Stream you initiate
> it with. In this instance, the
> NetworkStream of the TcpClient. Theres
> no need to dispose of the StreamReader
> here" | Try calling oc.Connect before creating a StreamReader. Until a socket is connected, there is nothing to actually read and hence the exception. | How can I use "using" in C# without getting "InvalidOperationException"? | [
"",
"c#",
".net",
"debugging",
"tcpclient",
""
] |
Is there a way I can improve this kind of SQL query performance:
```
INSERT
INTO ...
WHERE NOT EXISTS(Validation...)
```
The problem is when I have many data in my table (like million of rows), the execution of the `WHERE NOT EXISTS` clause if very slow. I have to do this verification because I can't insert duplicated data.
I use SQLServer 2005
thx | Make sure you are searching on indexed columns, with no manipulation of the data within those columns (like substring etc.) | Off the top of my head, you could try something like:
```
TRUNCATE temptable
INSERT INTO temptable ...
INSERT INTO temptable ...
...
INSERT INTO realtable
SELECT temptable.* FROM temptable
LEFT JOIN realtable on realtable.key = temptable.key
WHERE realtable.key is null
``` | SQL - improve NOT EXISTS query performance | [
"",
"sql",
"sql-server",
"performance",
"where-clause",
"not-exists",
""
] |
I'm trying to get a package installed on Google App Engine. The package relies rather extensively on `pkg_resources`, but there's no way to run `setup.py` on App Engine.
There's no platform-specific code in the source, however, so it's no problem to just zip up the source and include those in the system path. And I've gotten a version of `pkg_resources` installed and working as well.
The only problem is getting the package actually *registered* with `pkg_resources` so when it calls `iter_entry_points` it can find the appropriate plugins.
What methods do I need to call to register modules on `sys.path` with all the appropriate metadata, and how do I figure out what that metadata needs to be? | Create a setup.py for the package just as you would normally, and then use "setup.py sdist --formats=zip" to build your source zip. The built source zip will include an .egg-info metadata directory, which will then be findable by pkg\_resources. Alternately, you can use bdist\_egg for all your packages. | Yes, for setuptools-based libraries you'll need to deploy the library's "Egg" metadata along with it. The easiest way I've found is to deploy a whole [virtualenv](http://pypi.python.org/pypi/virtualenv/1.3.3) environment containing your project and the required libraries.
I did this process manually and added this code to main.py to initialize the site-packages folder in a way that `pkg_resources` will work:
```
import site
site.addsitedir('lib/python2.5/site-packages')
```
However, you could try [appengine-monkey](http://code.google.com/p/appengine-monkey/wiki/Pylons) which automates most of this for you. | How can I manually register distributions with pkg_resources? | [
"",
"python",
"google-app-engine",
"setuptools",
"pkg-resources",
""
] |
I'm kinda waiting for a 'no' answer on this question.
I was interested if you can save a variable at the same time when you checking it in an if-clause.
Let's say I have this code.
```
if(foo!=null){
if(foo.getBar()!=null){
Bar bar = foo.getBar();
System.out.println("Success: " + bar);
} else {
System.out.println("Failure.");
}
} else {
System.out.println("Failure.");
}
```
I handling now to "failure" -states independently, even if the outcome is the same. I could get them together like this:
```
if(foo!=null && foo.getBar()!=null){
Bar bar = foo.getBar();
System.out.println("Success: " + bar);
} else {
System.out.println("Failure.");
}
```
Much neater code already. if foo is null it will stop there and won't try foo.getBar (in the if) so I won't get a NPE. The last thing i would like to enhance, and the main question: Do I really gave to call on foo.getBar() twice? It would be nice to get away from the second identical call if getBar() would be a very heavy operation. So I am wondering if there is somehow possible to do something similiar to this:
```
if(foo!=null && (Bar bar = foo.getBar())!=null){
Bar bar = foo.getBar();
System.out.println("Success: " + bar);
} else {
System.out.println("Failure.");
}
```
I would have to break it up to two different if's again if I would like to do
```
Bar bar = foo.getBar();
if (bar!=null) ...
``` | This is the closest you can get:
```
Bar bar;
if(foo!=null && (bar = foo.getBar())!=null){
System.out.println("Success: " + bar);
} else {
System.out.println("Failiure.");
}
``` | I have used that technique when iterating over lines from a BufferedReader:
```
BufferedReader br = // create reader
String line
while ((line = br.readLine()) != null) {
// process the line
}
```
So yes, you can do an assignment, and the result off that will be the left hand side variable, which you can then check. However, it's not legal to declare variables inside a test, as they would then only be scoped to that expression. | Can you store a variable inside a if-clause? | [
"",
"java",
"if-statement",
"initialization",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.