Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
`CString` is quite handy, while `std::string` is more compatible with STL container. I am using `hash_map`. However, `hash_map` does not support `CString`s as keys, so I want to convert the `CString` into a `std::string`.
Writing a `CString` hash function seems to take a lot of time.
```
CString -----> std::string
``... | According to [CodeGuru](http://www.codeguru.com/forum/archive/index.php/t-231155.html):
`CString` to `std::string`:
```
CString cs("Hello");
std::string s((LPCTSTR)cs);
```
**BUT:** `std::string` cannot always construct from a `LPCTSTR`. i.e. the code will fail for UNICODE builds.
As `std::string` can construct onl... | Solve that by using `std::basic_string<TCHAR>` instead of `std::string` and it should work fine regardless of your character setting. | How do you convert CString and std::string std::wstring to each other? | [
"",
"c++",
"mfc",
"c-strings",
"stdstring",
""
] |
I'm writing tests for a business method that invokes some DAO classes to perform operations over a database.
This method, firstly retrieves a JDBC connection from a DataSource object, The same connection is passed to all DAO instances, so I can use it to control the transaction. So, if everything works properly, I mus... | You need to mock `DataSource` *and* `Connection` so that your mock `DataSource` returns your mock `Connection`. And yes, this kind of thing ends up becoming a real pain... | It's hard for me to tell from your description exactly how your classes are composed, but the DataSource should be injected into your DAO class, either thru it's constructor or a `setDataSource()` method.
This would allow you to test the DAO in isolation, and allow you to construct the mock DataSource in your unit tes... | How to mock classes instantiated as local variables | [
"",
"java",
"unit-testing",
"tdd",
"mocking",
""
] |
I was wondering if its possible to inject a thread into a remote app domain running in a separate process.
My guess is that I could do this using the debugging interfaces (ICorDebug) but I was wondering if there is any other way? | This can be done there is sample code in [snoop](http://blois.us/Snoop/) It sets up a hook, and using managed c++ tells the appdomain to load an assembly. Really impressive ... | There was recently an announcement of a new facility Mono provides to do just this. See this post on [assembly injection](http://tirania.org/blog/archive/2008/Sep-29.html). | Can I inject a thread in a remote app domain from C# | [
"",
"c#",
".net",
"appdomain",
"code-injection",
""
] |
```
class AbstractQuery {
virtual bool isCanBeExecuted()=0;
public:
AbstractQuery() {}
virtual bool Execute()=0;
};
class DropTableQuery: public AbstractQuery {
vector< std::pair< string, string> > QueryContent;
QueryValidate qv;
public:
explicit DropTableQuery(const string& qr): AbstractQuery(... | No, in fact for it is unnecessary for the base class to have an explicitly defined constructor (though make sure you have a virtual destructor).
So for a typical interface you could have something like this:
```
class MyInterface {
public:
virtual ~MyInterface() {}
virtual void execute() = 0;
};
```
EDIT: He... | It is **never** obligatory to explicitly call the base class constructor, unless it has parameters. The compiler will call the constructor automatically. Theoretically the base class still has a constructor, but the compiler may optimize it away into non-existence if it doesn't do anything. | If abstract base class is an interface, is it obligatory to call base class constructor in derived class constructor? | [
"",
"c++",
"oop",
"constructor",
"class-design",
"abstract-class",
""
] |
I am not as familiar with Oracle as I would like to be. I have some 250k records, and I want to display them 100 per page. Currently I have one stored procedure which retrieves all quarter of a million records to a dataset using a data adapter, and dataset, and the dataadapter.Fill(dataset) method on the results from t... | Something like this should work: [From Frans Bouma's Blog](http://weblogs.asp.net/fbouma/archive/2007/05/21/api-s-and-production-code-shouldn-t-be-designed-by-scientists.aspx)
```
SELECT * FROM
(
SELECT a.*, rownum r__
FROM
(
SELECT * FROM ORDERS WHERE CustomerID LIKE 'A%'
ORDER BY OrderDat... | [Ask Tom](https://blogs.oracle.com/oraclemagazine/post/on-top-n-and-pagination-queries) on pagination and very, very useful analytic functions.
This is excerpt from that page:
```
select * from (
select /*+ first_rows(25) */
object_id,object_name,
row_number() over
(order by object_id) rn
from a... | Paging with Oracle | [
"",
"sql",
"oracle",
"stored-procedures",
""
] |
I have a singleton that uses the "static readonly T Instance = new T();" pattern. However, I ran into a case where T is disposable, and actually needs to be disposed for unit tests. How can I modify this pattern to support a disposable singleton?
The interface I would like is something like:
```
var x = Foo.Instance;... | Mark `Release` as `internal` and use the `InternalsVisibleTo` attribute to expose it only to your unit testing assembly. You can either do that, or if you're wary someone in your own assembly will call it, you can mark it as `private` and access it using reflection.
Use a finalizer in your singleton that calls the `Di... | At that point I don't think I'd really consider it to be a singleton any more, to be honest.
In particular, if a client uses a singleton they're really not going to expect that they have to dispose of it, and they'd be surprised if someone else did.
What's your production code going to do?
EDIT: If you really, reall... | Disposable singleton in C# | [
"",
"c#",
".net",
"singleton",
"dispose",
""
] |
I have a method with an out parameter that tries to do a type conversion. Basically:
```
public void GetParameterValue(out object destination)
{
object paramVal = "I want to return this. could be any type, not just string.";
destination = null; // default out param to null
destination = Convert.ChangeType... | > So is there any way to get the type of an object that is set to null? I would think there would have to be a way to know what type a storage location is without it being assigned anything.
Not necessarily. The best that you can say is that it is an `object`. A `null` reference does not point to any storage location,... | It's possible if you don't mind declaring your method as a generic. Try this.
```
class Program
{
public static void GetParameterValue<T>(out T destination)
{
Console.WriteLine("typeof(T)=" + typeof(T).Name);
destination = default(T);
}
static void Main(string[] args)
{
stri... | .NET : How do you get the Type of a null object? | [
"",
"c#",
".net",
"types",
"gettype",
""
] |
Is it a good idea to store my SQL queries in a global resource file instead of having it in my codebehind? I know stored procedures would be a better solution but I don't have that luxury on this project.
I don't want queries all over my pages and thought a central repository would be a better idea. | Resource files are usually used for localization. But a string is just a string is just a string, and do you really want to be sending any old string in a resource file to your database?
I completely agree with others that you should be using linq or typed datasets, etc. Personally I've only had to resort to text quer... | I would look up strongly typed datasets with tableadapters and let the tableadapters handle all queries. When you are used with it you'll never go back.
Just add a dataset to your solution, add a connection, and a tableadapter for a table, then start build all querys (update, select, delete, search and so on) and hand... | ASP.NET - Storing SQL Queries in Global Resource File? | [
"",
"asp.net",
"sql",
""
] |
I am creating a chat using Ajax requests and I'm trying to get messages div to scroll to the bottom without much luck.
I am wrapping everything in this div:
```
#scroll {
height:400px;
overflow:scroll;
}
```
Is there a way to keep it scrolled to the bottom by default using JS?
Is there a way to keep it scro... | Here's what I use on my site:
```
var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;
``` | This is much easier if you're using [jQuery scrollTop](https://api.jquery.com/scrollTop/):
```
$("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);
``` | Scroll to bottom of div? | [
"",
"javascript",
"html",
"ajax",
"chat",
""
] |
I have been looking in to doing some test driven development for one of the applications that I'm currently writing(OLE wrapper for an OLE object). The only problem is that I am using the express versions of Visual Studio(for now), at the moment I am using VB express but sometimes I use C# express.
Is it possible to d... | [Nunit](http://www.nunit.org/index.php) seems to work independently, why not try it with the express versions of Visual Studio?
It looks like you have to use the test dlls outside of VS , from the Nunit GUI. | Unfortunately Jamie Cansdale, main proponent of TestDriven.NET and NUnit, [ran into a lot of legal trouble when he put up TestDriven.NET that works with Visual Studio Express 2005](http://weblogs.asp.net/nunitaddin/archive/2007/07/06/microsoft-amp-testdriven-net.aspx) edition.
VS 2008 Express's EULA has been modified ... | Best way to do TDD in express versions of visual studio(eg VB Express) | [
"",
"c#",
"vb.net",
"unit-testing",
"testing",
"tdd",
""
] |
Oracle has this concept of allowing database users to be identified by the operating system user who is running the program that is connecting to Oracle. See [here](http://www.oracle-base.com/articles/misc/OsAuthentication.php).
This allows you to do, as that user on a unix machine for example, a command such as:
```... | The JDBC Thin driver is a 100% pure Java implementation that cannot collect the needed information from the operating system.
The JDBC OCI driver can do this! Use `jdbc:oracle:oci8:/@MYDBSID`, it will require that the Oracle driver be installed on that machine, not a problem if this is a server (and is faster to boot ... | Thanks to those that answered. We've gone with the OCI driver.
I did find documentation to suggest that Oracle 11g **does** support OS user authentication via the thin driver though:
<http://www.orindasoft.com/public/Oracle_JDBC_JavaDoc/javadoc1110/oracle/jdbc/OracleConnection.html#CONNECTION_PROPERTY_THIN_VSESSION_O... | Connection to Oracle without a username or password | [
"",
"java",
"oracle",
"jdbc",
"connection",
""
] |
The title is kind of obscure. What I want to know is if this is possible:
```
string typeName = <read type name from somwhere>;
Type myType = Type.GetType(typeName);
MyGenericClass<myType> myGenericClass = new MyGenericClass<myType>();
```
Obviously, MyGenericClass is described as:
```
public class MyGenericClass<T... | You can't do this without reflection. However, you *can* do it with reflection. Here's a complete example:
```
using System;
using System.Reflection;
public class Generic<T>
{
public Generic()
{
Console.WriteLine("T={0}", typeof(T));
}
}
class Test
{
static void Main()
{
string ty... | Unfortunately no there is not. Generic arguments must be resolvable at Compile time as either 1) a valid type or 2) another generic parameter. There is no way to create generic instances based on runtime values without the big hammer of using reflection. | Pass An Instantiated System.Type as a Type Parameter for a Generic Class | [
"",
"c#",
".net",
"generics",
""
] |
How do you programmatically obtain a picture of a .Net control? | There's a method on every control called [DrawToBitmap](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.drawtobitmap.aspx). You don't need to p/invoke to do this.
```
Control c = new TextBox();
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(c.Width, c.Height);
c.DrawToBitmap(bmp, c.ClientRe... | You can get a picture of a .NET control programmatically pretty easily using the ***DrawToBitmap*** method of the Control class starting in .NET 2.0
Here is a sample in VB
```
Dim formImage As New Bitmap("C:\File.bmp")
Me.DrawToBitmap(formImage, Me.Bounds)
```
And here it is in C#:
```
Bitmap formImage = N... | How to get a screen capture of a .Net WinForms control programmatically? | [
"",
"c#",
".net",
"image",
"winforms",
"capture",
""
] |
What is the proper way to terminate a Swing application from the code, and what are the pitfalls?
I'd tried to close my application automatically after a timer fires. But just calling `dispose()` on the `JFrame` didn't do the trick - the window vanished but the application did not terminate. However when closing the w... | Your JFrame default close action can be set to "`DISPOSE_ON_CLOSE`" instead of `EXIT_ON_CLOSE` (why people keep using EXIT\_ON\_CLOSE is beyond me).
If you have any undisposed windows or non-daemon threads, your application will not terminate. This should be considered a error (and solving it with System.exit is a ver... | I guess a [EXIT\_ON\_CLOSE](http://java.sun.com/docs/books/tutorial/uiswing/components/frame.html#windowevents)
```
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
```
before `System.exit(0)` is better since you can write a [Window Listener](http://java.sun.com/docs/books/tutorial/uiswing/events/windowlistener.... | How to close a Java Swing application from the code | [
"",
"java",
"swing",
""
] |
Does anyone know of a script that can select all text references to URLs and automatically replace them with anchor tags pointing to those locations?
```
For example:
http://www.google.com
would automatically turn into
<a href="http://www.google.com">http://www.google.com</a>
```
Note: I am wanting this because I... | JQuery isn't going to help you a whole lot here as you're not really concerned with DOM traversal/manipulation (other than creating the anchor tag). If all your URLs were in <p class="url"> tags then perhaps.
A vanilla JavaScript solution is probably what you want, and as fate would have it, [this guy should have you ... | **NOTE:** An updated and corrected version of this script is now available at <https://github.com/maranomynet/linkify> (GPL/MIT licence)
---
Hmm... to me this seems like the perfect task for jQuery.
...something like this came off the top of my mind:
```
// Define: Linkify plugin
(function($){
var url1 = /(^|<... | jQuery Text to Link Script? | [
"",
"javascript",
"jquery",
"html",
"anchor",
""
] |
Are there any classes in the .NET framework I can use to throw an event if time has caught up with a specified DateTime object?
If there isn't, what are the best practices when checking this? Create a new thread constantly checking? A timer (heaven forbid ;) )? | I wouldn't go with the thread approach. While a sleeping thread doesn't consume user CPU time, it does use Kernel/system CPU time. Secondly, in .NET you can't adjust the Thread's stack size. So even if all it does is sleep, you are stuck with a 2MB hit (I believe that is the default stack size of a new thread) for noth... | When a thread is sleeping it consumes no CPU usage. A very simple way would be to have a thread which sleeps until the DateTime. For example
```
DateTime future = DateTime.Now.Add(TimeSpan.FromSeconds(30));
new Thread(() =>
{
Thread.Sleep(future - DateTime.Now);
//RaiseEvent... | Best way to check when a specified date occurs | [
"",
"c#",
".net",
"vb.net",
"datetime",
""
] |
Can an ArrayList of Node contain a non-Node type?
Is there a very dirty method of doing this with type casting? | Yes, but you will get class cast exceptions if you try to access a non-node element as if it were a node. Generics are discarded at (for) runtime.
For example:
```
import java.util.*;
import java.awt.Rectangle;
public class test {
public static void main(String args[]) {
List<Rectangle> list = new ArrayL... | Given:
```
List<Node> nodelist = new ArrayList<Node>();
Object toAdd = new Object();
```
then:
```
((List) nodelist).add(toAdd);
```
or
```
((List<Object>) nodelist).add(toAdd);
```
will do the hack. Ick. I feel dirty. But, you should not do this. If you really need to mix types, then do this:
```
List... | Can an ArrayList of Node contain non-Node type? | [
"",
"java",
""
] |
When I debug a C# program and I get an exception throwed (either thrown by code OR thrown by the framework), the IDE stops and get me to the corresponding line in my code.
Everything is fine for now.
I then press "F5" to continue. From this moment, it seams like I'm in an infinite loop. The IDE always get me back to ... | This is because the exception is un-handled and Visual Studio can not move past that line without it being handled in some manner. Simply put, it is by design.
One thing that you can do is drag and drop the execution point (yellow line/arrow) to a previous point in your code and modify the in memory values (using the ... | You probably have the option "**Unwind the callstack on unhandled exceptions**" checked in Visual Studio. When this option is on Visual Studio will unwind to right before the exception, so hitting `F5` will keep ramming into the same exception.
If you uncheck the option Visual Studio will break at the exception, but h... | Continuing in the Visual Studio debugger after an exception occurs | [
"",
"c#",
"debugging",
"exception",
""
] |
I am an upper level Software Engineering student currently in a Data Structures and Algorithms class. Our professor wants us to write a program using the List structure found in the C++ STL. I have been trying to use C# more and more, and was wondering if the ArrayList structure in .NET is a good substitute for the STL... | Unless you're stuck with .NET 1.1, use `List<T>` instead of `ArrayList`. But what are you fundamentally concerned about? Suppose you didn't have List to refer to - what do you need the appropriate data structure to do? | You should be able to answer this question yourself. What is the implementation strategy used in STL lists? What is the one of ArrayList? Likewise, what is the abstract API presented by STL list (in terms of operations provided)? Compare this to STL List: what does the one provide that the other doesn't? | Using Lists in C# | [
"",
"c#",
".net",
"list",
"stl",
"arraylist",
""
] |
I need to do an [HTTP GET](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) request in JavaScript. What's the best way to do that?
I need to do this in a Mac OS X dashcode widget. | Browsers (and Dashcode) provide an XMLHttpRequest object which can be used to make HTTP requests from JavaScript:
```
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
... | [`window.fetch`](https://developers.google.com/web/updates/2015/03/introduction-to-fetch?hl=en) is a modern replacement for `XMLHttpRequest` that makes use of ES6 promises. There's a nice explanation [here](https://jakearchibald.com/2015/thats-so-fetch/), but it boils down to (from the article):
```
fetch(url).then(fu... | HTTP GET request in JavaScript? | [
"",
"javascript",
"http-get",
"dashcode",
""
] |
I need to access a network resource on which only a given Domain Account has access.
I am using the LogonUser call, but get a "User does not have required priviliege" exception, as the web application is running with the asp.net account and it does not have adequate permissions to make this call.
Is there a way to get... | Just calling LogonUser is not enough. You need to impersonate that user. You can impersonate for just the access to the network resource.
Sample code can be found on [MSDN](http://msdn.microsoft.com/en-us/library/chf6fbt4.aspx). | You could add an
```
<identity impersonate="true" userName=""/>
```
tag to your web.config but that might not be ideal as you probably don't want to run the entire site as that user...
Can you map the network share as a local drive with the DomainName & Password... and then pull files to the website via the mapped d... | Need to Impersonate user forAccessing Network resource, Asp.Net Account | [
"",
"c#",
".net",
"asp.net",
"impersonation",
"delegation",
""
] |
In the iPhone is there a way I can use JavaScript to close the browser and return to the home screen? After the last page a wizard I am calling out to another iPhone app (ex: maps) and I do NOT what the user to come back to the browser screen when they are done. My backup plan is to have a "Complete" page but that is n... | I have confirmed with apple this is not possible in iPhone OS 2.2 and before.
I have tried each of these good suggestions but, they will not close the browser on the iPhone. | Knowing Apple, this may not be possible with JavaScript. Have you tried anything yet? If not, try one of these guys out:
```
javascript:self.close();
window.close();
```
EDIT: I found this thru google, this may bypass the confirmation box, but I don't think it works with the modern browsers anymore:
```
window.opene... | Can I close the iPhone browser using JavaScript | [
"",
"javascript",
"iphone",
"safari",
""
] |
In Java, are there clear rules on when to use each of access modifiers, namely the default (package private), `public`, `protected` and `private`, while making `class` and `interface` and dealing with inheritance? | [The official tutorial](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) may be of some use to you.
---
| | Class | Package | Subclass (same pkg) | Subclass (diff pkg) | World |
| --- | --- | --- | --- | --- | --- |
| `public` | + | + | + | + | + |
| `protected` | + | + | + | + | |
| *no modif... | (Caveat: I am not a Java programmer, I am a Perl programmer. Perl has no formal protections which is perhaps why I understand the problem so well :) )
## Private
Like you'd think, only the **class** in which it is declared can see it.
## Package Private
It can only be seen and used by the **package** in which it wa... | What is the difference between public, protected, package-private and private in Java? | [
"",
"java",
"private",
"public",
"protected",
"access-modifiers",
""
] |
Been trying to find a working implementation of a WPF listview (or listbox) where
you can order items by dragging them up or down.
I have found a few, but none really works,
for example this one
<http://www.codeproject.com/KB/WPF/ListViewDragDropManager.aspx?msg=2765618#xx2765618xx>
stops working once you have list wh... | Drag&Drop is not SO hard, really :)
Try reading this [post](http://www.beacosta.com/blog/?p=53) about Drag&Drop. | Also check out [this](http://www.codeproject.com/KB/WPF/WPFDragDrop.aspx) article on CodeProject!
It is not as full featured as Josh & Bea's implementation but it is very simple to use...
This implementation rely on attached properties (Attached behaviour)
Source
```
<ListBox src:DragAndDrop.DragEnabled="true"/>
``... | A working Drag&Drop enabled ListView implementation for WPF? | [
"",
"c#",
".net",
"wpf",
"listview",
"controls",
""
] |
When including a header file in C++, what's the difference between...
1. including the *.h* part versus not including *.h* part when wrapping it in *<>* signs?
#include <iostream> vs. #include <iostream.h>
2. wrapping the header name in double quotes versus wrapping it in < > signs?
#include <iostream.h> vs. #... | In short:
`iostream.h` is deprecated—it is the original Stroustrup version. `iostream` is the version from the standards committee. Generally, compilers point them both to the same thing, but some older compilers won't have the older one. In some odd cases, they will both exist and be different (to support legacy code... | Here is a decent link [article.](http://members.gamedev.net/sicrane/articles/iostream.html)
To summarize, the reason given:
> The version of the iostream library that the Standards Committee
> produced was quite a bit different from the CFront implementation.
> {snip}
>
> To ease transition, the C++ Standards Committ... | <iostream> vs. <iostream.h> vs. "iostream.h" | [
"",
"c++",
"iostream",
""
] |
I thought I understood Java generics pretty well, but then I came across the following in java.lang.Enum:
```
class Enum<E extends Enum<E>>
```
Could someone explain how to interpret this type parameter? Bonus points for providing other examples of where a similar type parameter could be used. | It means that the type argument for enum has to derive from an enum which itself has the same type argument. How can this happen? By making the type argument the new type itself. So if I've got an enum called StatusCode, it would be equivalent to:
```
public class StatusCode extends Enum<StatusCode>
```
Now if you ch... | The following is a modified version of the explanation from the book *Java Generics and Collections*:
We have an `Enum` declared
```
enum Season { WINTER, SPRING, SUMMER, FALL }
```
which will be expanded to a class
```
final class Season extends ...
```
where `...` is to be the somehow-parameterised base class for... | Java Enum definition | [
"",
"java",
"generics",
"enums",
"crtp",
""
] |
I am instantiating a class A (which I am importing from somebody
else, so I can't modify it) into my class X.
Is there a way I can intercept or wrap calls to methods in A?
I.e., in the code below can I call
```
x.a.p1()
```
and get the output
```
X.pre
A.p1
X.post
```
Many TIA!
```
class A:
# in my real appli... | Here is the solution I and my colleagues came up with:
```
from types import MethodType
class PrePostCaller:
def __init__(self, other):
self.other = other
def pre(self): print 'pre'
def post(self): print 'post'
def __getattr__(self, name):
if hasattr(self.other, name):
fu... | You could just modify the A instance and replace the p1 function with a wrapper function:
```
def wrapped(pre, post, f):
def wrapper(*args, **kwargs):
pre()
retval = f(*args, **kwargs)
post()
return retval
return wrapper
class Y:
def __init__(self):
self.a=A()
... | Python: wrapping method invocations with pre and post methods | [
"",
"python",
"metaprogramming",
""
] |
I'm in the process of designing a small website and was curious when an XML file can/should be substituted for a database table. There are some cases where I think using a database table may be overkill and was just wondering if anyone else has come across making this decision.
Thanks! | If you think you'll end up needing more than a tiny amount of CRUD, or your site will grow beyond a handful users, **use a database**.
Searching or updating XML files can kill performance and future scalability. | I'd opt for using database tables when concurrent writes might happen, i.e. in any situation when you cannot guarantee that only a single change to the data will happen at any one time.
Further, if the data is relational, I'd use a database.
For small things which are likely to be low traffic, XML is fine. | Database Table or XML | [
"",
"asp.net",
"sql",
"xml",
"database",
""
] |
```
if(!eregi("^([0-9a-z_\[\]\*\- ])+$", $subuser))
$form->setError($field, "* Username not alphanumeric");
```
Can anybody tell me why it is not allowing characters such as `-` and `*`?
```
if(!eregi("^([0-9a-z])+$", $subuser))
$form->setError($field, "* Username not alphanumeric");
```
That is the original... | For bracket expressions:
To include a literal `]` in the list, make it the first character (following a possible `^`). To include a literal `-`, make it the first or last character, or the second endpoint of a range. To use a literal `-` as the first endpoint of a range, enclose it in `[.` and `.]` to make it a collat... | Your regex uses PCRE syntax, so you have to use preg\_match() instead of eregi().
Try this code instead:
```
else if (!preg_match("/^([0-9a-z_\[\]* -])+$/i", $subuser)) {
$form->setError($field, "* Username not alphanumeric");
}
``` | Can't use certain characters in a regex | [
"",
"php",
"regex",
""
] |
I have the following snippet of code, changeTextArea is a TextArea object.
```
changeTextArea.addKeyboardListener(new KeyboardListenerAdapter()
public void onKeyPress( Widget sender, char keyCode, int modifier){
//do something
//I WISH TO STOP THE EVENT THAT MAPS TO THIS KEYPRESS FROM BUBBLING ANY FURTHER
... | As far as I know you can't do it via a keyboard listener, but it is possible by adding an event preview using the DOM class:
```
DOM.addEventPreview(EventPreview preview)
```
Then when you get the event:
```
onEventPreview(Event event)
```
You should return false, to say you want to cancel the event. The Event obje... | You can definitely use the Event's cancelBubble() and preventDefault() methods from within any code that has access to the Event. There's no need to have an event preview... | Stop a event from bubbling in GWT | [
"",
"java",
"events",
"gwt",
""
] |
I'm working with a client that needs to generate millions of the alphanumeric codes used in magazine scratch-off cards, bottlecap prizes, and so on. They have to be short enough to print on a cap, they want to make sure that ambiguous characters like 1 and I, 0 and O, etc. are not included, and they have to be explicit... | If you need about 10 million unique keys (for example), the best approach is to pick a key-space that's exponentially bigger, and start randomly generating. Read about the [Birthday Paradox](http://en.wikipedia.org/wiki/Birthday_paradox) -- it's the main thing you should be worried about. If you want 2^n unique and sec... | Let's suppose you can use a character set of, say, 40 symbols of unambiguous upper,lower and numeric characters.
For a sequence of n chars, you've got 40n combinations
* 404 = 2,560,000
* 405 = 102,400,000
* 406 = 4,096,000,000
* 407 = 163,840,000,000
* 408 = 6,553,600,000,000
Thus 8 chars gives a pretty good space ... | Generating unique codes in PHP/MySQL? | [
"",
"php",
"mysql",
"random",
"generator",
"serial-number",
""
] |
I'd like to allow users to record videos directly from their webcam.
I haven't done much work with PHP but am stuck with it for this project.
We currently have a system in place for video uploading and encoding, but nothing to actually access a user's webcam.
How would you recommend I proceed? | Webcams aren't available to HTML or JavaScript/DOM in any browsers that I know of, so you're going to end up dependent on some sort of plugin. I'd recommend you start your search with Adobe Flash/Flex, though It's possible that Microsoft Silverlight is able to do the same thing. Flex is a bit more reliable technology a... | You need client side technology -- PHP is server side. Check out Adobe Flash/Flex. I don't know anything about Microsoft Silverlight. | Using PHP to Access a User's Webcam | [
"",
"php",
"drupal",
"video",
"webcam",
""
] |
For the purposes of this question, the code base is an ASP.NET website that has multiple pages written in both C# and Visual Basic .NET. The primary language is C# and the Visual Basic .NET webpages where forked into the project as the same functionality is needed.
Should the time be taken to actually rewrite these pa... | There are three points you should keep in mind:
1. If it aint' broke don't fix it.
2. Team makeup and proficiencies
3. Coding standards and uniformity
First off, like many have said if it's not broken, then why go through the effort of changing the code base. You risk adding bugs during the language transition, even ... | What you are suggesting is a partial rewrite.
I could only advocate a rewrite if there were something severely wrong with the functionality or architecture of the existing code.
A preference for C# over VB is not justification enough IMO. | It the use of multiple languages in ASP.NET code behind pages acceptable? | [
"",
"c#",
"asp.net",
"vb.net",
""
] |
I have a bit of html like so:
```
<a href="#somthing" id="a1"><img src="something" /></a>
<a href="#somthing" id="a2"><img src="something" /></a>
```
I need to strip off the links so I'm just left with a couple of image tags. What would be the most efficient way to do this with jQuery? | ```
$("a > img").parent() // match all <a><img></a>, select <a> parents
.each( function() // for each link
{
$(this).replaceWith( // replace the <a>
$(this).children().remove() ); // with its detached children.
});
``` | This should do it:
```
$('a[id^=a]').each(function() { $(this).replaceWith($(this).html()); });
``` | Stripping out a link in jQuery | [
"",
"javascript",
"jquery",
""
] |
I have a piece of code looking like this :
```
TAxis *axis = 0;
if (dynamic_cast<MonitorObjectH1C*>(obj))
axis = (dynamic_cast<MonitorObjectH1C*>(obj))->GetXaxis();
```
Sometimes it crashes :
```
Thread 1 (Thread -1208658240 (LWP 11400)):
#0 0x0019e7a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2
#1 0x048c67... | Some possible reasons for the crash:
* `obj` points to an object with a non-polymorphic type (a class or struct with no virtual methods, or a fundamental type).
* `obj` points to an object that has been freed.
* `obj` points to unmapped memory, or memory that has been mapped in such a way as to generate an exception w... | I suggest using a different syntax for this code snippet.
```
if (MonitorObjectH1C* monitorObject = dynamic_cast<MonitorObjectH1C*>(obj))
{
axis = monitorObject->GetXaxis();
}
```
You can still crash if some other thread is deleting what monitorObject points to or if obj is crazy garbage, but at least your proble... | What could cause a dynamic_cast to crash? | [
"",
"c++",
"crash",
"casting",
"dynamic-cast",
""
] |
I am using winsock and C++ to set up a server application. The problem I'm having is that the call to `listen` results in a first chance exception. I guess normally these can be ignored (?) but I've found others having the same issue I am where it causes the application to hang every once in a while. Any help would be ... | On a very busy server, you may be running out of Sockets. You may have to adjust some TCPIP parameters. Adjust these two in the registry:
```
HKLM\System\CurrentControlSet\Services\Tcpip\Parameters
MaxUserPort REG_DWORD 65534 (decimal)
TcpTimedWaitDelay REG_DWORD 60 (decimal)
```
By default, there's a few min... | The original problem has nothing to do with winsock. All the answers above are WRONG. Ignore the first-chance exception, it is not a problem with your application, just some internal error handling. | Socket Exception: "There are no more endpoints available from the endpoint mapper" | [
"",
"c++",
"exception",
"sockets",
"winsock",
"rpc",
""
] |
How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it. | You should have a look at [numpy](https://numpy.org/devdocs/user/quickstart.html) if you do matrix manipulation. This is a module mainly written in C, which will be much faster than programming in pure python. Here is an example of how to invert a matrix, and do other matrix manipulation.
```
from numpy import matrix
... | Make sure you really need to invert the matrix. This is often unnecessary and can be numerically unstable. When most people ask how to invert a matrix, they really want to know how to solve Ax = b where A is a matrix and x and b are vectors. It's more efficient and more accurate to use code that solves the equation Ax ... | Python Inverse of a Matrix | [
"",
"python",
"algorithm",
"matrix",
"linear-algebra",
"matrix-inverse",
""
] |
Can someone post a simple example of starting two (Object Oriented) threads in C++.
I'm looking for actual C++ thread objects that I can extend run methods on (or something similar) as opposed to calling a C-style thread library.
I left out any OS specific requests in the hopes that whoever replied would reply with c... | Create a function that you want the thread to execute, for example:
```
void task1(std::string msg)
{
std::cout << "task1 says: " << msg;
}
```
Now create the `thread` object that will ultimately invoke the function above like so:
```
std::thread t1(task1, "Hello");
```
(You need to `#include <thread>` to acces... | Well, technically any such object will wind up being built over a C-style thread library because C++ only just specified a stock [`std::thread`](http://en.cppreference.com/w/cpp/thread/thread) model in [C++0x](https://en.wikipedia.org/wiki/C%2B%2B11), which was just nailed down and hasn't yet been implemented.
The pro... | Simple example of threading in C++ | [
"",
"c++",
"multithreading",
""
] |
I have a MySQL database of keywords that are presently mixed-case. However, I want to convert them all to lowercase. Is there an easy command to do this, either using MySQL or MySQL and PHP? | ```
UPDATE table SET colname=LOWER(colname);
``` | Yes, the function is LOWER() or LCASE() (they both do the same thing).
For example:
```
select LOWER(keyword) from my_table
``` | Is there a MySQL command to convert a string to lowercase? | [
"",
"php",
"mysql",
""
] |
When I get a reference to a `System.Diagnostics.Process`, how can I know if a process is currently running? | This is a way to do it with the name:
```
Process[] pname = Process.GetProcessesByName("notepad");
if (pname.Length == 0)
MessageBox.Show("nothing");
else
MessageBox.Show("run");
```
You can loop all process to get the ID for later manipulation:
```
Process[] processlist = Process.GetProcesses();
foreach(Process... | This is the simplest way I found after using reflector.
I created an extension method for that:
```
public static class ProcessExtensions
{
public static bool IsRunning(this Process process)
{
if (process == null)
throw new ArgumentNullException("process");
try
{
... | How can I know if a process is running? | [
"",
"c#",
".net",
"process",
""
] |
Saving data to Postscript in my app results in a Postscript file which I can view without issues in GhostView, but when I try to print it, the printer isn't able to print it because it seems to be invalid.
Is there a way to validate / find errors in Postscript files without actually sending it to a printer? Preferred ... | If you can see it on ghostview, it means ghostscript can parse it.
So, one trick you could try using to print (but not to actually validate) your file would be to use ghostscript's postscript output mode (there is a wrapper called `ps2ps` for it, which mainly adds `-sDEVICE=pswrite`; there is also `ps2ps2` which uses ... | Whenever I need to validate a PostScript file using Ghostscript without having to actually look at its rendered page images I use the "nullpage" device:
```
gswin32c ^
-sDEVICE=nullpage ^
-dNOPAUSE ^
-dBATCH ^
c:/path/to/file/to/be/validated.pdf-or-ps ^
1>validated.stdout ^
2>validated.stderr
```
In... | Validating a Postscript without trying to print it? | [
"",
"java",
"validation",
"postscript",
"ghostscript",
""
] |
I'm doing some FK analysis of our tables by making a directed
graph representing FK dependencies and then traversing the
graph. In my code, I name everything using directed graph
terminology, but I'd like to have something a bit more
"user friendly" in the report.
In this scenario:
```
create table t1(a varchar2(20))... | I'd say (things between brackets are optional, but I'd use them)
```
[Column a of] table t1 references [column b of] table t2
```
and
```
[Column b of] table t2 is referenced by [column a of] table t1
```
?
I'd also specify the action that happens on delete/update if any.
```
Column b of table t2 is referenced by... | ```
t1 is the parent of t2.
t2 is the child of t1.
```
What is the audience for this? If it's people that understand a relational schema, then that will probably do. If it is non-technical people, then generally I have documented in my modelling tool (ERWin) the meaning of the relationships specifically.
```
InvoiceL... | relational terminology: foreign key source, destination? | [
"",
"sql",
"oracle",
"terminology",
""
] |
I downloaded the Aptana\_Studio\_Setup\_Linux.zip package, unpacked it and run ./AptanaStudio. It starts fine, but reports one problem:
*The embedded browser widget for this editor cannot be created. It is either not available for your operating system or the system needs to be configured in order to support embedded ... | **Edit:** getting internal browser to work is NOT required in order to get PHP support in Aptana. Just install PHP support from **Help**, **Software updates** menu. | I happened to come across this: <https://groups.google.com/forum/#!msg/xmind/5SjPTy0MmEo/PbPi0OGzqPwJ>
Which advised running:
```
sudo apt-get install libwebkitgtk-1.0-0
```
should solve the problem. It worked for me so I figured I'd share here.
FWIW, I ended up here while trying to get the Play! Framework working ... | How to set up internal browser for Aptana on Linux | [
"",
"php",
"linux",
"aptana",
""
] |
I'm trying to do a very simple button that changes color based on mouseover, mouseout and
click, I'm doing this in prototype and the weird thing is if I used mouseover and mouseout,
after I clicked on the button, the button wouldn't change to white, seems like it is because of the mouseout, here's my code
```
$("izzy"... | Unless there's something else happening in mouse over and out, why not use css?
```
#izzy:hover { color: '#FFFFFF'; }
```
However, I'm a little confused as to what exactly you want to happen. Assuming you want the button white if it has been clicked or if the mouse is over it. I'd have the click event handler add a c... | Do you mean that you wan the mouse click to cause a permenant change in the style that is not replaced by mouseout? If so, try using a flag, like so:
```
var wasClicked = false;
$("izzy").observe('mouseover', function() {
if (!wasClicked) $('izzy').setStyle({ color: '#FFFFFF' });
});
$("izzy").observe('mouseout'... | Prototype click, mouseover and mouseout can't work together? | [
"",
"javascript",
"prototypejs",
"mouseevent",
""
] |
I have multiple Network Interface Cards on my computer, each with its own IP address.
When I use `gethostbyname(gethostname())` from Python's (built-in) `socket` module, it will only return one of them. How do I get the others? | Use the [`netifaces`](https://pypi.org/project/netifaces/) module. Because networking is complex, using netifaces can be a little tricky, but here's how to do what you want:
```
>>> import netifaces
>>> netifaces.interfaces()
['lo', 'eth0']
>>> netifaces.ifaddresses('eth0')
{17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'ad... | ```
import socket
[i[4][0] for i in socket.getaddrinfo(socket.gethostname(), None)]
``` | How do I determine all of my IP addresses when I have multiple NICs? | [
"",
"python",
"sockets",
"ip-address",
""
] |
So .NET 3.0/3.5 provides us with lots of new ways to query, sort, and manipulate data, thanks to all the neat functions supplied with LINQ. Sometimes, I need to compare user-defined types that don't have a built-in comparison operator. In many cases, the comparison is really simple -- something like foo1.key ?= foo2.ke... | My [MiscUtil](http://pobox.com/~skeet/csharp/miscutil) library contains a ProjectionComparer to build an IComparer<T> from a projection delegate. It would be the work of 10 minutes to make a ProjectionEqualityComparer to do the same thing.
EDIT: Here's the code for ProjectionEqualityComparer:
```
using System;
using ... | here is a simple helper class that should do what you want
```
public class EqualityComparer<T> : IEqualityComparer<T>
{
public EqualityComparer(Func<T, T, bool> cmp)
{
this.cmp = cmp;
}
public bool Equals(T x, T y)
{
return cmp(x, y);
}
public int GetHashCode(T obj)
{
... | Can I specify my explicit type comparator inline? | [
"",
"c#",
".net",
"linq",
"lambda",
""
] |
I'd like to do the same in C#. Is there anyway of using properties in C# with parameters in the same way I've done with the parameter 'Key' in this VB.NET example?
> ```
> Private Shared m_Dictionary As IDictionary(Of String, Object) = New Dictionary(Of String, Object)
> ```
```
Public Shared Property DictionaryEleme... | > Is there anyway of using properties in C# with parameters
No. You only can provide the *default* property in C# with an argument, to model indexed access (as in a dictionary):
```
public T this[string key] {
get { return m_Dictionary[key]; }
set { m_Dictionary[key] = value; }
}
```
Other properties can't h... | The "proper" way to do it in C# is to create child class specifically to access the collection. It should either hold the collection itself or have internal linkages to the parent class. | Using the typical get set properties in C#... with parameters | [
"",
"c#",
"vb.net",
"properties",
""
] |
I have a simple class that essentially just holds some values. I have overridden the `ToString()` method to return a nice string representation.
Now, I want to create a `ToXml()` method, that will return something like this:
```
<Song>
<Artist>Bla</Artist>
<Title>Foo</Title>
</Song>
```
Of course, I could ju... | You may want to look at how you can use the built-in features of .NET to serialize and deserialize an object into XML, rather than creating a `ToXML()` method on every class that is essentially just a Data Transfer Object.
I have used these techniques successfully on a couple of projects but don’t have the implementat... | I would recommend to use XDoc and XElement of System.Xml.Linq instead of XmlDocument stuff. This would be better and you will be able to make use of the LINQ power in querying and parsing your XML:
Using XElement, your ToXml() method will look like the following:
```
public XElement ToXml()
{
XElement element = n... | Creating an XmlNode/XmlElement in C# without an XmlDocument? | [
"",
"c#",
"xml",
""
] |
I'm relatively new to C++. In Java, it's easy for me to instantiate and use a hashmap. I'd like to know how to do it in a simple way in C++, since I saw many different implementations and none of them looked simple to me. | Most compilers should define `std::hash_map` for you; in the coming `C++0x` standard, it will be part of the standard library as [`std::unordered_map`](http://en.cppreference.com/w/cpp/container/unordered_map). The [STL Page](http://www.sgi.com/tech/stl/hash_map.html) on it is fairly standard. If you use Visual Studio,... | Using hashmaps in C++ is easy! It's like using standard C++ map. You can use your's compiler/library implementation of `unordered_map` or use the one provided by [boost](http://www.boost.org/doc/libs/1_37_0/doc/html/unordered.html), or some other vendor. Here's a quick sample. You will find more if you follow the links... | Simple hashmap implementation in C++ | [
"",
"c++",
"hashmap",
"hashtable",
""
] |
I have a shared library that I wish to link an executable against using GCC. The shared library has a nonstandard name not of the form libNAME.so, so I can not use the usual -l option. (It happens to also be a Python extension, and so has no 'lib' prefix.)
I am able to pass the path to the library file directly to the... | The -l option of g++ has a ":" prefix that allows you to use libraries with unconventional file names.
The command
```
g++ -o build/bin/myapp -l:_mylib.so other_source_files
```
should search your path for the shared library with the file name \_mylib.so. | If you can copy the shared library to the working directory when g++ is invoked then this should work:
```
g++ -o build/bin/myapp _mylib.so other_source_files
``` | How to link using GCC without -l nor hardcoding path for a library that does not follow the libNAME.so naming convention? | [
"",
"c++",
"c",
"gcc",
"linker",
"shared-libraries",
""
] |
So I was wondering if there are any major differences between the various implementations of the hash algorithms, take the SHA series of algorithms for example. All of them have 3 implementations each, 1 in managed code and 2 wrappers around different native crypto APIs, but are there any major differences between usin... | One difference is that the native versions (at least some of them) are FIPS-certified (i.e., approved by the US government), whereas the managed ones are not. If your code happens to be running on a Windows machine that has been configured as "FIPS only", attempts to use the managed versions will fail.
Most Windows ma... | The Cng versions are supposed to be a little faster, but I just wrote up a little program that compares the speeds of each. (I had a client that was asking about the performance characteristics of MD5 vs. SHA1)
I was surprised to find out there is little to no difference between MD5 and SHA1, but was also surprised th... | CNG, CryptoServiceProvider and Managed implementations of HashAlgorithm | [
"",
"c#",
".net",
"security",
"hash",
"cryptography",
""
] |
A few weeks ago I opened up a hole on my shared server and my friend uploaded the following PHP script:
```
<?php
if(isset($_REQUEST['cmd'])) {
echo "<pre>";
$cmd = ($_REQUEST['cmd']);
system($cmd);
echo "</pre>";
die;
}
?>
<?php
if(isset($_REQUEST['upload'])) {
echo '<form enctype="multipart/... | Thanks guys, your answers were great, but the answer was right under my nose the entire time. Via cPanel I was able to edit my server to use a single php.ini file. | One, kick off a "friend" that chooses to run scripts like this.
Then worry about securing your server. Your system has a master php.ini somewhere (often /etc/php.ini, but if can be in several places, check php\_info()). That file controls the default settings for your server. Also, you can block local settings files t... | How do I enable my php.ini file to affect all directories/sub-directories of my server? | [
"",
"security",
"php",
""
] |
I'm using C# on Framework 3.5. I'm looking to quickly sort a Generic `List<T>`. For the sake of this example, let's say I have a List of a `Person` type with a property of lastname. How would I sort this List using a lambda expression?
```
List<Person> people = PopulateList();
people.OrderBy(???? => ?????)
``` | If you mean an in-place sort (i.e. the list is updated):
```
people.Sort((x, y) => string.Compare(x.LastName, y.LastName));
```
If you mean a new list:
```
var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional
``` | Do you need the list to be sorted in place, or just an ordered sequence of the contents of the list? The latter is easier:
```
var peopleInOrder = people.OrderBy(person => person.LastName);
```
To sort in place, you'd need an `IComparer<Person>` or a `Comparison<Person>`. For that, you may wish to consider `Projectio... | List<T> OrderBy Alphabetical Order | [
"",
"c#",
"generics",
"list",
"lambda",
"sorting",
""
] |
Does anyone know of any code or tools that can strip literal values out of SQL statements?
The reason for asking is I want to correctly judge the SQL workload in our database and I'm worried I might miss out on bad statements whose resource usage get masked because they are displayed as separate statements. When, in r... | [SQL::Statement](http://search.cpan.org/perldoc?SQL::Statement), in particular the [SQL::Statement::Structure](http://search.cpan.org/perldoc?SQL::Statement::Structure) module, will let you parse and manipulate SQL statements. The subset of SQL syntax it understands [can be seen here](http://search.cpan.org/perldoc?SQL... | If you use JDBC or something like thar your SQL shouldn't have any literals, just '?' marking where they should be. | What's the best way to strip literal values out of SQL to correctly identify db workload? | [
"",
"sql",
"database",
"perl",
"parsing",
""
] |
I am writing PHP code where I want to pass the session id myself using POST. I don't want a cookie to store the session, as it should get lost when the user gets out of the POST cycle.
PHP automatically sets the cookie where available. I learned it is possible to change this behaviour by setting `session.use_cookies` ... | err its possible to override the default settings of your host by creating your own .htaccess file and here's a great tutorial if you havent touched that yet
<http://www.askapache.com/htaccess/apache-htaccess.html>
or if you're too lazy to learn
just create a ".htaccess" file (yes that's the filename) on your sites di... | Use [ini\_set()](http://php.net/ini_set):
```
ini_set('session.use_cookies', '0');
```
Or in your php.ini file:
```
session.use_cookies = 0
``` | How to disable PHP session cookie? | [
"",
"php",
"session",
""
] |
What I'm looking for is a basic equivalent of JavaScript's `Array::join()` whereby you pass in a separator character and uses that in its return string of all the subscripts. I could certainly write my own function using a `StringBuilder` or whatnot, but there *must* be something built into the .NET BCL.
EDIT: Array o... | If the array contains strings, you can just use [`String.Join()`](http://msdn.microsoft.com/en-us/library/57a79xd0.aspx). If the array does not contain strings, you'll need something a little more complicated so you can handle the cast or conversion process for each item it contains.
**Update:** Using @JaredPar's code... | If String.Join doesn't do it for you - e.g. you have an `IEnumerable<string>` instead of a `string[]` or you have a collection of some other type, see [this earlier question](https://stackoverflow.com/questions/145856/how-to-join-int-to-a-charcter-separated-string-in-c). | What's the C# method/syntax for converting an array to a simple string? | [
"",
"c#",
".net",
"arrays",
"string",
"join",
""
] |
What's the best way to get a temp directory name in Windows? I see that I can use `GetTempPath` and `GetTempFileName` to create a temporary file, but is there any equivalent to the Linux / BSD [`mkdtemp`](http://linux.die.net/man/3/mkdtemp) function for creating a temporary directory? | No, there is no equivalent to mkdtemp. The best option is to use a combination of [GetTempPath](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.gettemppath) and [GetRandomFileName](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getrandomfilename).
You would need code similar to this:
```
publ... | I hack `Path.GetTempFileName()` to give me a valid, pseudo-random filepath on disk, then delete the file, and create a directory with the same file path.
This avoids the need for checking if the filepath is available in a while or loop, per Chris' comment on Scott Dorman's answer.
```
public string GetTemporaryDirect... | Creating a temporary directory in Windows? | [
"",
"c#",
".net",
"windows",
"temporary-directory",
""
] |
I was looking through the plans for C++0x and came upon `std::initializer_list` for implementing initializer lists in user classes. This class could not be implemented in C++
without using itself, or else using some "compiler magic". If it could, it wouldn't be needed since whatever technique you used to implement `ini... | `std::type_info` is a simple class, although populating it requires `typeinfo`: a compiler construct.
Likewise, exceptions are normal objects, but throwing exceptions requires compiler magic (where are the exceptions allocated?).
The question, to me, is "how close can we get to `std::initializer_list`s without compil... | The only other one I could think of was the [type\_info](http://msdn.microsoft.com/en-us/library/70ky2y6k.aspx) class returned by typeid. As far as I can tell, VC++ implements this by instantiating all the needed type\_info classes statically at compile time, and then simply casting a pointer at runtime based on values... | Which standard c++ classes cannot be reimplemented in c++? | [
"",
"c++",
"compiler-construction",
""
] |
If I had the following select, and did not know the value to use to select an item in advance like in this [question](https://stackoverflow.com/questions/196684/jquery-get-select-option-text) or the index of the item I wanted selected, how could I select one of the options with jQuery if I did know the text value like ... | ```
var option;
$('#list option').each(function() {
if($(this).text() == 'Option C') {
option = this;
return false;
}
});
``` | This should do the trick:
```
// option text to search for
var optText = "Option B";
// find option value that corresponds
var optVal = $("#list option:contains('"+optText+"')").attr('value');
// select the option value
$("#list").val( optVal )
```
As eyelidlessness points out, this will behave unpredictably when th... | How do I select an item by its text value in a dropdown using jQuery? | [
"",
"javascript",
"jquery",
"dom",
""
] |
What program can I use to decompile a class file? Will I actually get Java code, or is it just JVM assembly code?
On Java performance questions on this site I often see responses from people who have "decompiled" the Java class file to see how the compiler optimizes certain things. | Update February 2016:
[www.javadecompilers.com](http://www.javadecompilers.com/) lists JAD as being:
> the most popular Java decompiler, but primarily of this age only. Written in C++, so very fast.
> Outdated, unsupported and does not decompile correctly Java 5 and later
So your mileage may vary with recent jdk (... | There are a few decompilers out there... A quick search yields:
1. [Procyon](https://bitbucket.org/mstrobel/procyon): open-source (Apache 2) and actively developed
2. [Krakatau](https://github.com/Storyyeller/Krakatau): open-source (GPLv3) and actively developed
3. [CFR](http://www.benf.org/other/cfr/): open-source (M... | How do I "decompile" Java class files? | [
"",
"java",
"decompiler",
""
] |
I'm familiar with Sybase / SQL server, where I can create a temp. table like this:
```
SELECT *
INTO #temp
FROM tab1 ,
tab2
WHERE tab1.key = tab2.fkey
SELECT *
FROM #temp
WHERE field1 = 'value'
```
#temp only exists for the duration of this session, and can only be seen by me.
I would like to do... | Your first approach ought to be to do this as a single query:
```
SELECT *
FROM
(
SELECT *
FROM tab1 ,
tab2
WHERE tab1.key = tab2.fkey
)
WHERE field1 = 'value';
```
For very complex situations or where temp# is very large, try a subquery factoring clause, optionally with the materialize hint:
```
w... | A global temporary table is not the same, the definition remains after the end of the session, also the table (but not the data) is visible to all sessions.
If you are writing stored procedures, have you looked into cursors? It's a bit more complicated, but a very efficient and clean way to work with a temporary data ... | Sybase Developer Asks: How To Create a Temporary Table in Oracle? | [
"",
"sql",
"sql-server",
"oracle",
"sybase",
"temp-tables",
""
] |
Basically I'm converting local dates stored in the database into UTC. But I've read somewhere that daylight saving rules have changed in 2007. So does the Date.ToUniversalTime() function still work correctly. Basically the dates before 2007(when the new rules came into effect) would be converted correctly but the dates... | It will depend on which version of .NET you're using and possibly which version of Windows you're using. .NET 3.5 has the [TimeZoneInfo](http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx) class which includes historical changes etc - before then, the support was far more patchy, unfortunately. | I would expect `ToUniversalTime()` to take that into account. Have you tried and checked the result with dates from before and after the DST change?
EDIT
If you *know* the timezone offset of all the dates in your DB, I definitively recommend you to convert them to UTC at the table level. You get rid of a whole lot of... | Daylight saving changes affecting UTC conversion | [
"",
"c#",
".net",
""
] |
I have two BufferedImages I loaded in from pngs. The first contains an image, the second an alpha mask for the image.
I want to create a combined image from the two, by applying the alpha mask. My google-fu fails me.
I know how to load/save the images, I just need the bit where I go from two BufferedImages to one Buf... | Your solution could be improved by fetching the RGB data more than one pixel at a time(see <http://java.sun.com/javase/6/docs/api/java/awt/image/BufferedImage.html>), and by not creating three Color objects on every iteration of the inner loop.
```
final int width = image.getWidth();
int[] imgData = new int[width];
in... | I'm too late with this answer, but maybe it is of use for someone anyway. This is a simpler and more efficient version of Michael Myers' method:
```
public void applyGrayscaleMaskToAlpha(BufferedImage image, BufferedImage mask)
{
int width = image.getWidth();
int height = image.getHeight();
int[] imagePix... | Set BufferedImage alpha mask in Java | [
"",
"java",
"graphics",
"alpha",
"compositing",
""
] |
I have heard that this is what JavaRebel does but is there any other good way to deploy a new version of an EAR while allowing users to remain active on the previous version? We use JBoss for the application server... | It's not what JavaRebel does. JavaRebel (according to description) hot-replaces the classes in memory. It's not acceptable in the case of existing connections to the system, since the updated classes may break the client's logic.
Once a company I was working for had a similar problem, and it was solved this way:
* a ... | As I understand WebLogic has a feature called parallel deployment to eliminate downtime during EAR version upgrade. You can deploy the new version without stopping the existing application and once the new version deployed successfully you can switch over transparently from the old one to new one.
I am not sure if oth... | Hot Deploy a Java EAR to Minimize or Eliminate Downtime of an Application on a Server? | [
"",
"java",
"deployment",
"jboss",
""
] |
I know that PHP doesn't yet have native Enumerations. But I have become accustomed to them from the Java world. I would love to use enums as a way to give predefined values which IDEs' auto-completion features could understand.
Constants do the trick, but there's the namespace collision problem and (or actually *becau... | ## Since PHP 8.1, Enums are supported:
<https://www.php.net/manual/en/language.types.enumerations.php>
```
enum DaysOfWeek: int
{
case Sunday = 0;
case Monday = 1;
// etc.
}
$today = DaysOfWeek::Sunday;
var_dump($today->value); // 0
var_dump($today->name); // "Sunday"
```
## PHP 8.0 and earlier
Dependin... | There is a native extension, too. The **SplEnum**
> SplEnum gives the ability to emulate and create enumeration objects
> natively in PHP.
<http://www.php.net/manual/en/class.splenum.php>
Attention:
<https://www.php.net/manual/en/spl-types.installation.php>
> The PECL extension is not bundled with PHP.
>
> A DLL f... | Enumerations on PHP | [
"",
"php",
"enumeration",
""
] |
I have a very simple jQuery Datepicker calendar:
```
$(document).ready(function(){
$("#date_pretty").datepicker({
});
});
```
and of course in the HTML...
```
<input type="text" size="10" value="" id="date_pretty"/>
```
Today's date is nicely highlighted for the user when they bring up the calendar, but ho... | **Update: There are reports this no longer works in Chrome.**
This is concise and does the job (obsolete):
```
$(".date-pick").datepicker('setDate', new Date());
```
This is less concise, utilizing [chaining](https://www.w3schools.com/jquery/jquery_chaining.asp) allows it to work in chrome (2019-06-04):
```
$(".dat... | You must FIRST call datepicker() > **then** use 'setDate' to get the current date.
```
$(".date-pick").datepicker();
$(".date-pick").datepicker("setDate", new Date());
```
OR chain your setDate method call after your datepicker initialization, as noted in a comment on this answer
```
$('.date-pick').datepicker({ /* ... | How do I pre-populate a jQuery Datepicker textbox with today's date? | [
"",
"javascript",
"jquery",
"jquery-ui",
"date",
"jquery-ui-datepicker",
""
] |
My application links against libsamplerate.a. I am doing this to make distributing the final binary easier.
I am worried that perhaps the code inside the .a file depends on some other libraries I also will need to distribute.
But if it doesn't I am worried I am bloating up my application too much by including multipl... | A static library is just a collection of object files. When you compile a program against a static library, the object code for the functions used by your program is copied from the library into your executable. Linking against a static library will not cause any functions outside that library to be included in your co... | A .a file is basically just a bundle of .o files. You can demonstrate this using the `ar` tool.
For instance, to display the contents of your library:
```
ar -t libsamplerate.a
```
To create a .a file from scratch:
```
ar -r tim.a *.txt
``` | What does a GCC compiled static library contain? | [
"",
"c++",
"gcc",
"static-libraries",
""
] |
I'm trying to parse an international datetime string similar to:
```
24-okt-08 21:09:06 CEST
```
So far I've got something like:
```
CultureInfo culture = CultureInfo.CreateSpecificCulture("nl-BE");
DateTime dt = DateTime.ParseExact("24-okt-08 21:09:06 CEST",
"dd-MMM-yy HH:mm:ss ...", culture);
```
The problem ... | AFAIK the time zone abbreviations are not recognized. However if you replace the abbreviation with the time zone offset, it will be OK. E.g.:
```
DateTime dt1 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+2"), "dd-MMM-yy HH:mm:ss z", culture);
DateTime dt2 = DateTime.ParseExact("24-okt-08 21:09:06 ... | The quick answer is, you can't do it.
---
Here is why,
There is a definitive database of world timezones, you can get it from the [IANA here](http://www.iana.org/time-zones).
The problem is, the 3 or 4 letter abbreviations have a many-to-one association with the IANA timezones. For instance [`"AMT"`](http://www.tim... | Parse DateTime with time zone of form PST/CEST/UTC/etc | [
"",
"c#",
".net",
"parsing",
"datetime",
"timezone",
""
] |
Is there a way (preferrably using JavaScript) to determine whether a URL is to a SWF or a JPG?
The obvious answer is to sniff the filename for ".jpg" or ".swf" but I'm dealing with banners that are dynamically decided by the server and usually have a lot of parameters and generally don't include an extension.
so i'm ... | You could use javascript to detect if it is a image by creating a dynamic img-tag.
```
function isImage(url, callback) {
var img = document.createElement('img');
img.onload = function() {
callback(url);
}
img.src = url;
}
```
And then calling it with:
```
isImage('http://animals.nationalgeogr... | I would extend Sijin's answer by saying:
An HTTP HEAD request to the url can be used to examine the resource's mime-type. You
won't need to download the rest of the file that way. | how to detect if a URL points to a SWF | [
"",
"javascript",
"flash",
"detect",
"file-type",
""
] |
Given a FieldInfo object and an object, I need to get the actual bytes representation of the field. I know that the field is either `int,Int32,uint,short` etc.
How can I get the actual byte representation? BinaryFormatter.Serialize won't help, since it'll give me more information than I need (it also records type name... | You may also try code like the following if what you actually want is to transfer structures as a byte array:
```
int rawsize = Marshal.SizeOf(value);
byte[] rawdata = new byte[rawsize];
GCHandle handle = GCHandle.Alloc(rawdata, GCHandleType.Pinned);
Marshal.StructureToPtr(value, handle.AddrOfPinnedObject(), false);
h... | Use BitConverter.GetBytes()
You'll first have to convert the value to it's native type, than use BitConverter to get the bytes:
```
byte[] Bytes;
if (valType == typeof(int))
{
int intVal = (int) GetFieldValue(....);
Bytes = BitConverter.GetBytes(intVval);
}
else if (valType == typeof(long))
{
int lngVal... | getting an Int/short/byte structure byte representation with C# | [
"",
"c#",
"reflection",
"marshalling",
"binary-data",
""
] |
I built an application which displays the records from database in the window and checks the the database for new records every couple of seconds. The problem is that the window blinks each time I check for new records and I want to fix it. I have tried to compare the old datatable with the new one and refresh only if ... | First off, it's important to recognize that what you're comparing in your code is the *references* of the datatables, not the *contents* of the datatables. In order to determine if both datatables have the same contents, you're going to have to loop through all of the rows and columns and see if they're equal:
```
//T... | I've been trying to find a way to do DataTable comparison for a while and ended up writing up my own function, here is what I got:
```
bool tablesAreIdentical = true;
// loop through first table
foreach (DataRow row in firstTable.Rows)
{
foundIdenticalRow = false;
// loop through tempTable to find an identic... | Compare datatables | [
"",
"c#",
"datatable",
""
] |
I have a query that has 7 inner joins (because a lot of the information is distributed in other tables), a few coworkers have been surprised. I was wondering if they should be surprised or is having 7 inner joins normal? | it's not unheard of, but I would place it into a view for ease of use, and maintenance | Two questions:
1. Does it work?
2. Can you explain it?
If so, then seven is fine. If you can't explain the query, then seven is too many. | Is seven inner joins in a query too much? | [
"",
"sql",
"inner-join",
""
] |
I've done numerous searches and I realize that I can just download this file and install it either in windows/system32 or in the application's directory. My question is, how does this dll generally get installed on Vista? I tried installing the .net framework 3.5 and it didn't get installed with that.
Background:
I'm ... | msvcr71.dll is the Microsoft Visual C++ Common Runtime for Visual Studio 2003. Applications developed with VS2003 will usually install this. | i tried this fix to resolve MSVCR71.dll missing error in Windows 7 X64:
<http://backspacetab.com/2011/05/09/msvcr71-dll-windows-7-x64/>
Its only for 64Bit users... 32bit users follow the guide here: <http://i.justrealized.com/2009/how-to-fix-missing-msvcr71dll-problem-in-windows/>
Thanks and enjoy !! | msvcr71.dll file missing on Win Vista when trying to run my java swing application | [
"",
"java",
".net",
"windows-vista",
"exe4j",
""
] |
There have been a couple of questions that sort of dealt with this but not covering my exact question so here we go.
For site settings, if these are stored in a database do you:
1. retrieve them from the db every time someone makes a request
2. store them in a session variable on login
3. ???????
For user specific s... | I prefer an approach like Glomek proposes... Caching the settings in the WebCache will greatly enhance speed of access. Consider the following:
```
#region Data Access
private string GetSettingsFromDb(string settingName)
{
return "";
}
private Dictionary<string,string> GetSettingsFromDb()
{
return new Dic... | I suggest creating a module for retrieving preferences that could be implemented either way, and then for your first implementation hit the database every time since that's easier. If you have performance problems, add caching to the module to reduce the database traffic. | Best way to access user/site settings | [
"",
"c#",
"asp.net",
"settings",
""
] |
I am writing a desktop application written in Swing developed using Java 1.5. Some of the users seem to be using Mac, but I am interested in Java 6's scripting feature (Java 6 ships with Rhino). Java 6, although it came out almost 2 years ago, doesn't seem to be widely in use. I also hear [Apple ships Java 6 only for I... | As far as I know, it already is, and has been for some time now. Swing's just fine for writing native looking apps.
It is true though, that if you are targeting older Macs, you'll never be able to use Java 6.
Are you asking about Java 6 Update 10 (AKA, the consumer oriented JRE)? That just came out, and is unavailabl... | Java 6 is not officially out for all Macs yet. If you want to be more widely accepted, go with 1.5 (5). | Java: When is Java 6 ready for end-user desktop application? | [
"",
"java",
"swing",
"macos",
"java-6",
""
] |
I have a simple panel that is used as a drawing surface. The goal here is to draw a 4 pixel wide outline around a child ListView under certain circumstances. I would like to make the outline pulsate when something can be dragged into it.
I am just drawing a simple rectangle around the ListView and updating the opacity... | I stumbled on a solution for this if anyone is interested. It turns out that the flashing is caused by the painting of the background. I used SetStyle to tell the control that I will be handling all of the painting.
```
SetStyle(ControlStyles.SupportsTransparentBackColor |
ControlStyles.Opaque |
Cont... | Set DoubleBuffered = true on the form. | How to avoid screen flickering when a control must be constantly repainted in C#? | [
"",
"c#",
".net",
"onpaint",
""
] |
The standalone flashplayer takes no arguments other than a .swf file when you launch it from the command line. I need the player to go full screen, no window borders and such. This can be accomplished by hitting ctrl+f once the program has started. I want to do this programmatically as I need it to launch into full scr... | You can use a dedicated application which sends the keystroke to the window manager, which should then pass it to flash, if the window starts as being the active window on the screen. This is quite error prone, though, due to delays between starting flash and when the window will show up.
For example, your script coul... | ```
nspluginplayer --fullscreen src=path/to/flashfile.swf
```
which is from the [<http://gwenole.beauchesne.info//en/projects/nspluginwrapper](nspluginwrapper> project) | Programmatically launching standalone Adobe flashplayer on Linux/X11 | [
"",
"python",
"linux",
"adobe",
"x11",
"flash",
""
] |
Does anyone know of an already implemented money type for the .NET framework that supports i18n (currencies, formatting, etc)? I have been looking for a well implemented type and can't seem to find one. | Check this article [A Money type for the CLR](http://www.codeproject.com/KB/recipes/MoneyTypeForCLR.aspx)
> A convenient, high-performance money
> structure for the CLR which handles
> arithmetic operations, currency types,
> formatting, and careful distribution
> and rounding without loss. | I think you want to use the decimal data type, and use the appropriate overload for [ToString()](http://msdn.microsoft.com/en-us/library/fzeeb5cd.aspx).
```
CultureInfo current = CultureInfo.CurrentCulture;
decimal myMoney = 99.99m;
//formats as money in current culture, like $99.99
string formattedMoney = myMoney.T... | Does anyone know of a money type in .NET? | [
"",
"c#",
".net",
"currency",
""
] |
Background: Over the next month, I'll be giving three talks about or at least including `LINQ` in the context of `C#`. I'd like to know which topics are worth giving a fair amount of attention to, based on what people may find hard to understand, or what they may have a mistaken impression of. I won't be specifically t... | Delayed execution | I know the deferred execution concept should be beaten into me by now, but this example really helped me get a practical grasp of it:
```
static void Linq_Deferred_Execution_Demo()
{
List<String> items = new List<string> { "Bob", "Alice", "Trent" };
var results = from s in items select s;
Console.WriteLi... | What's the hardest or most misunderstood aspect of LINQ? | [
"",
"c#",
"linq",
"c#-3.0",
""
] |
I am using C# 2.0 with Nunit Test. I have some object that needs to be serialized. These objects are quite complex (inheritance at different levels and contains a lot of objects, events and delegates).
How can I create a Unit Test to be sure that my object is safely serializable? | I have this in some unit test here at job:
```
MyComplexObject dto = new MyComplexObject();
MemoryStream mem = new MemoryStream();
BinaryFormatter b = new BinaryFormatter();
try
{
b.Serialize(mem, dto);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
```
Might help you... maybe other method can be better ... | Here is a generic way:
```
public static Stream Serialize(object source)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
formatter.Serialize(stream, source);
return stream;
}
public static T Deserialize<T>(Stream stream)
{
IFormatter formatter = new BinaryFormat... | How to unit test if my object is really serializable? | [
"",
"c#",
".net",
"unit-testing",
"serialization",
".net-2.0",
""
] |
Has anyone else run into this problem before? I've got a method that calls a generic method with a delegate, inside of a generic class. I've marked the class as Serializable, and it serializes without complaint. But, when I try to deserialize an object of this class, it pegs the CPU and hangs the machine.
Code example... | Are you using VS2008 SP1? There's a known problem with SP1.
<https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361615> | This is the code I currently have, which works fine?
```
[Serializable]
public class SDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
public SDictionary()
: base()
{
}
protected SDictionary(SerializationInfo info, StreamingContext context)
: ba... | Delegate calling generic method inside of a generic class pegs CPU during deserialization | [
"",
"c#",
"generics",
"serialization",
""
] |
Is there a way to write an enumeration that can be extended. I have several methods that I would like to always have available for my enumerations. For example I use an enumeration for my database fields. I include the actual field name in the database.
```
public enum ORDERFIELDS
{
OrderID("Order_... | If I understand correctly, what you'd like to do is something like this:
```
public abstract class DatabaseField {
private String fieldName;
private DatabaseField(String fieldName) {
this.fieldName = fieldName;
}
public String getFieldName() {
return fieldName;
}
}
```
Then defin... | All enums implicitly extend `java.lang.Enum`. Since Java does not support multiple inheritance, an enum cannot extend anything else. | Java extendable enumeration | [
"",
"java",
"design-patterns",
"enums",
"enumeration",
""
] |
We are currently using the [NetBios method](http://support.microsoft.com/default.aspx?scid=kb;en-us;118623), and it works ok under XP. Preliminary tests under Vista show that it also works, but there are caveats - NetBIOS has to be present, for instance, and from what I've been reading, the order of the adapters is bou... | Could you use the [WMIService](http://msdn.microsoft.com/en-us/library/aa394579(VS.85).aspx)? I used it to get the mac-address of a machine in pre-Vista days though. | This will give you a list of all MAC addresses on your computer. It will work with all versions of Windows as well:
```
void getdMacAddresses(std::vector<std::string> &vMacAddresses;)
{
vMacAddresses.clear();
IP_ADAPTER_INFO AdapterInfo[32]; // Allocate information for up to 32 NICs
DWORD dwBufLen = ... | C++: Get MAC address of network adapters on Vista? | [
"",
"c++",
"windows-vista",
"mac-address",
""
] |
Is there a way to use a `foreach` loop to iterate through a collection backwards or in a completely random order? | As other answers mention, the [`Reverse()` extension method](http://msdn.microsoft.com/en-us/library/bb358497.aspx) will let you enumerate a sequence in reverse order.
Here's a random enumeration extension method:
```
public static IEnumerable<T> OrderRandomly<T>(this IEnumerable<T> sequence)
{
Random random = ne... | Using `System.Linq` you could do...
```
// List<...> list;
foreach (var i in list.Reverse())
{
}
```
For a random order you'd have to sort it randomly using `list.OrderBy` (another Linq extension) and then iterate that ordered list.
```
var rnd = new Random();
var randomlyOrdered = list.OrderBy(i => rnd.Next());
for... | Can you enumerate a collection in C# out of order? | [
"",
"c#",
"loops",
"foreach",
""
] |
Is it possible to disable AJAX without disabling JavaScript completely? | If you are using Firefox, you could accomplish this with GreaseMonkey. (<https://addons.mozilla.org/en-US/firefox/addon/748>)
GM is a framework for applying scripts to some or all of the pages you visit. I have GM scripts that disable google-analytics downloads (because they slow things down), and which disable google... | You can replace the browser tool to make AJAX (XMLHttpRequest object) with your own that does nothing.
```
XMLHttpRequest = function(){}
XMLHttpRequest.prototype = {
open: function(){},
send: function(){}
}
```
Be sure that your replacement code executes before any AJAX call.
This will work for any browser t... | Is it possible to disable AJAX without disabling JavaScript completely? | [
"",
"javascript",
"ajax",
""
] |
Do the clients need something else than a proper jdk and javafx compliant browser to visit javafx applets? | JavaFX is based on download able JARs. I think there are multiple runtimes, but all of them Require JRE 1.6. The JavaFX classes will be loaded by the WebStart or Applet Classloader, so the JRE does not need to provide this extension.
However as there are some new Features of Java 6 Update 10 specifically targeted for ... | Ok, thanks for this information. All the samples were "standalone" applications that run "outside" the web browser (a new program was launched, you had to download it and accept some signatures/certs). Is it possible to run the applets inside a browser? (more transparency for my client) | javafx on client side | [
"",
"java",
"javafx",
""
] |
I'm writing a stored procedure that needs to have a lot of conditioning in it. With the general knowledge from C#.NET coding that exceptions can hurt performance, I've always avoided using them in PL/SQL as well. My conditioning in this stored proc mostly revolves around whether or not a record exists, which I could do... | I would not use an explicit cursor to do this. Steve F. no longer advises people to use explicit cursors when an implicit cursor could be used.
The method with `count(*)` is unsafe. If another session deletes the row that met the condition after the line with the `count(*)`, and before the line with the `select ... in... | Since SELECT INTO assumes that a single row will be returned, you can use a statement of the form:
```
SELECT MAX(column)
INTO var
FROM table
WHERE conditions;
IF var IS NOT NULL
THEN ...
```
The SELECT will give you the value if one is available, and a value of NULL instead of a NO\_DATA\_FOUND exception. The ... | Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance? | [
"",
"sql",
"oracle",
"exception",
"plsql",
""
] |
C++ guarantees that variables in a compilation unit (.cpp file) are initialised in order of declaration. For number of compilation units this rule works for each one separately (I mean static variables outside of classes).
But, the order of initialization of variables, is undefined across different compilation units.
... | As you say the order is undefined across different compilation units.
Within the same compilation unit the order is well defined: The same order as definition.
This is because this is not resolved at the language level but at the linker level. So you really need to check out the linker documentation. Though I really ... | I expect the constructor order between modules is mainly a function of what order you pass the objects to the linker.
However, GCC does let you [use `init_priority` to explicitly specify the ordering](https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html) for global ctors:
```
class Thingy
{
public:
Thin... | Static variables initialisation order | [
"",
"c++",
"visual-studio",
"gcc",
"static",
"linker",
""
] |
I have code looking something like this:
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table
SET BlobData = '" . mysql_real_escape_string($data) . "',
BlobHash = '$hash'
";
mysql_query($query);
``... | You have two issues here:
#1, there are several different ways you can compute the MD5 hash:
* Do as you do and load into PHP as a string and use PHP's `md5()`
* Use PHP's `md5_file()`
* As of PHP 5.1+ you can use PHP's streams API with either of `md5` or `md5_file` to avoid loading entirely into memory
* Use `exec()... | If you are using PDO, and prepared statments you can use the PDO::PARAM\_LOB type. See example #2 on the LOB page showing how to insert an image to a database using the file pointer.
<https://www.php.net/manual/en/pdo.lobs.php> | How to build large MySQL INSERT query in PHP without wasting memory | [
"",
"php",
"mysql",
""
] |
LINQ is one of the greatest improvements to .NET since generics and it saves me tons of time, and lines of code. However, the fluent syntax seems to come much more natural to me than the query expression syntax.
```
var title = entries.Where(e => e.Approved)
.OrderBy(e => e.Rating).Select(e => e.Title)
.FirstO... | Neither is better: they serve different needs. Query syntax comes into its own when you want to leverage **multiple range variables**. This happens in three situations:
* When using the let keyword
* When you have multiple generators (*from* clauses)
* When doing joins
Here's an example (from the LINQPad samples):
`... | I prefer to use the latter (sometimes called "query comprehension syntax") when I can write the whole expression that way.
```
var titlesQuery = from e in entries
where e.Approved
orderby e.Rating
select e.Titles;
var title = titlesQuery.FirstOrDefault();
```
As ... | Fluent and Query Expression — Is there any benefit(s) of one over other? | [
"",
"c#",
"linq",
""
] |
Is there a way to consume a web service using JavaScript? I'm Looking for a built-in way to do it, using a JavaScript framework is not an option. | You can consume a web service using JavaScript natively using the XmlHttpRequest object. However instantiating this object varies between browsers. For example Firefox and IE 7+ let you instantiate it as a native JavaScript object but IE6 requires you to instantiate it as an ActiveX control.
Because of this I'd recomm... | You can create an [XMLHttpRequest](http://www.w3schools.com/XML/xml_http.asp) if the service is hosted within your domain. If not, you will have cross-domain issues. | Consuming a Web service using Javascript | [
"",
"javascript",
"web-services",
""
] |
I changed the output path of the test project, because the default path doesn't conform to our projects directory structure. After I did that, Visual Studio 2008 fails to run the tests, because it can't find the Unit Test project assembly.
What else do I have to change for the Unit Test Engine to find the assembly? | There are at least three ways to solve this problem
1. Set up the output path **before** you run any test in the solution (as [suggested by Paulius Maruška](https://stackoverflow.com/questions/249647/changing-output-path-of-the-unit-test-project-in-visual-studio-2008/395998#395998)).
2. Close the solution, **delete th... | If you open up your .testrunconfig file and go to the Deployment option, you can add your test assembly to the list of files to deploy. You should then be able to run your tests. | Changing Output path of the Unit Test project in Visual Studio 2008 | [
"",
"c#",
"visual-studio-2008",
"unit-testing",
".net-2.0",
""
] |
svg is an xml based graphics and you can add JavaScripts to it. I have tried to access to the script functions defined in a svg. The script in my svg is something like this:
```
<svg ... onload="RunScript(evt);"...>
<script type="text/javascript">
...
function RunScript(loadEvent) {
// Get object in my html by id
... | I think the clue might be in 'on another site'. There are strict rules about when JavaScript programs from different sites are allowed to communicate with teach other. The embedded SVG is being treated the same way a document inside an `iframe` would. | So, what you're doing is, from the point of view of a browser, equivalent to the following:
```
<script>
function stealPassword() {
var passwordInput = document.querySelector('input[type="password"]');
var value = passwordInput.value; // My password!
sendPasswordToServerToStealMyMoney(value);
}
</script>
<iframe... | Access to svg's scripts | [
"",
"javascript",
"html",
"svg",
""
] |
I love the Ruby RSpec BDD development style. Are there any good tools for doing this with C/C++? | [cspec](http://github.com/arnaudbrejeon/cspec/wikis/home) is for C. Presumably it will work with C++. There is a list of tools for various languages on the [Behavior Driven Development Wikipedia page](http://en.wikipedia.org/wiki/Behavior_Driven_Development). | The original link ([CppSpec](http://www.laughingpanda.org/projects/cppspec)) is dead, but it is still accessible at the [Internet Archive](https://archive.org/web/) at [CppSpec](https://web.archive.org/web/20080208105001/http://www.laughingpanda.org/projects/cppspec/).
And as @VickyChijwani already mentioned, there's ... | Are there any good open source BDD tools for C/C++? | [
"",
"c++",
"c",
"testing",
"bdd",
""
] |
I am looking for a simple but "good enough" Named Entity Recognition library (and dictionary) for java, I am looking to process emails and documents and extract some "basic information" like:
Names, places, Address and Dates
I've been looking around, and most seems to be on the heavy side and full NLP kind of projects... | BTW, I recently ran across [OpenCalais](http://www.opencalais.com/) which seems to havethe functionality I was looking after. | You might want to have a look at one of [my earlier answers](https://stackoverflow.com/questions/163923/methods-for-geotagging-or-geolabelling-text-content#164722) to a similar problem.
Other than that, most lighter NER systems depend a lot on the domain used. You will find a whole lot of tools and papers about biomed... | Named Entity Recognition Libraries for Java | [
"",
"java",
"nlp",
"named-entity-recognition",
""
] |
Here I have:
```
Public Structure MyStruct
Public Name as String
Public Content as String
End Structure
Dim oStruct as MyStruct = New MyStruct()
oStruct.Name = ...
oStruct.Content = ...
Dim alList as ArrayList = new ArrayList()
alList.Add(oStruct)
```
I'd like to convert the ArrayList to a static strongly-typ... | I assume that since you are using ArrayList, you are using 1.1?
In which case, I suspect the following would work:
```
ArrayList list = new ArrayList();
MyStruct[] array = new MyStruct[list.Count];
list.CopyTo(array);
```
(edit - Bill's ToArray usage is more convenient - I didn't know about that one, but then, I ver... | You have to cast the result of `ToArray`
```
MyStruct[] structs = (MyStruct[]) alList.ToArray(typeof(MyStruct));
``` | How to convert ArrayList to an array of structure? | [
"",
"c#",
".net",
"vb.net",
"arrays",
"arraylist",
""
] |
I found the discussion on [Do you test private method](https://stackoverflow.com/questions/105007/do-you-test-private-method) informative.
I have decided, that in some classes, I want to have protected methods, but test them.
Some of these methods are static and short. Because most of the public methods make use of th... | If you're using PHP5 (>= 5.3.2) with PHPUnit, you can test your private and protected methods by using reflection to set them to be public prior to running your tests:
```
protected static function getMethod($name) {
$class = new ReflectionClass('MyClass');
$method = $class->getMethod($name);
// $method->setAcce... | [teastburn](https://stackoverflow.com/questions/249664/best-practices-to-test-protected-methods-with-phpunit/8702347#answer-5671560) has the right approach. Even simpler is to call the method directly and return the answer:
```
class PHPUnitUtil
{
public static function callMethod($obj, $name, array $args) {
... | Best practices to test protected methods with PHPUnit | [
"",
"php",
"unit-testing",
"phpunit",
""
] |
Given a large API (an in particular, the Java or J2EE standard libraries), is there a tool or search engine or other resource that can tells me which methods, classes, or even packages people in general tend to use the most?
I am annotating (see below) APIs and would like to focus my attention on popular areas.
The onl... | I wouldn't know if such statistics are even feasible, but I think a pretty safe bet would be to start with the basics plus some famous third party libraries. For example:
* [Collections](http://java.sun.com/j2se/1.5.0/docs/guide/collections/index.html)
* [Regular Expressions](http://java.sun.com/j2se/1.5.0/docs/api/ja... | This "simple" bash script will count most used classes in your current project codebase.
```
find . -name "*.java" | xargs cat | grep "^import java" | sort | uniq -c | sort -nr | head -100
``` | Are there some statistics on the most frequently used Java API functions? | [
"",
"api",
"java",
""
] |
Is there an easy way to rename a group of files already contained in a directory, using Python?
**Example:** I have a directory full of \*.doc files and I want to rename them in a consistent way.
> X.doc -> "new(X).doc"
>
> Y.doc -> "new(Y).doc" | Such renaming is quite easy, for example with [os](http://docs.python.org/lib/module-os.html) and [glob](http://docs.python.org/lib/module-glob.html) modules:
```
import glob, os
def rename(dir, pattern, titlePattern):
for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
title, ext = os.path.spl... | I prefer writing small one liners for each replace I have to do instead of making a more generic and complex code. E.g.:
This replaces all underscores with hyphens in any non-hidden file in the current directory
```
import os
[os.rename(f, f.replace('_', '-')) for f in os.listdir('.') if not f.startswith('.')]
``` | Batch Renaming of Files in a Directory | [
"",
"python",
"file-io",
"rename",
"batch-rename",
""
] |
Is there a way to set the StartPosition of a Windows Forms form using code? It seems whatever I try results in the StartPostion being the default.
Here is what I am doing in the form to display:
```
public DealsForm()
{
InitializeComponent();
this.StartPosition = FormStartPosition.CenterParent... | > If I do a ShowDialog() and pass the
> parent it works ... but I really don't
> want to show it as a Dialog.
That is correct since ShowDialog would set frm.Parent == nvShowDeals.Parent
Since you are using .Show() then frm.Parent == null thus FormStartPosition.CenterParent is ignored.
So to accomplish this functio... | Maybe you are not alone. Maybe you are not insane. Read this (Microsoft Connect Customer Feedback):
[Windows Form StartPosition property only works for .ShowDialog method and not for .Show method](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=107589)
*Customer: "Windows Form StartPos... | How do you set the StartPosition of a Windows Forms form using code? | [
"",
"c#",
".net",
"winforms",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.