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
```
How can I do this?
```
std::string -----> CString:
inline CString toCString(std::string const& str)
{
return CString(str.c_str());
}
```
Am I right?
---
**EDIT:**
Here are more questions:
How can I convert from `wstring` to `CString` and vice versa?
```
// wstring -> CString
std::wstring src;
CString result(src.c_str());
// CString -> wstring
CString src;
std::wstring des(src.GetString());
```
Is there any problem with this?
Additionally, how can I convert from `std::wstring` to `std::string` and vice versa?
|
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 only from `LPSTR` / `LPCSTR`, a programmer who uses VC++ 7.x or better can utilize conversion classes such as `CT2CA` as an intermediary.
```
CString cs ("Hello");
// Convert a TCHAR string to a LPCSTR
CT2CA pszConvertedAnsiString (cs);
// construct a std::string using the LPCSTR input
std::string strStd (pszConvertedAnsiString);
```
[`std::string` to `CString`](http://cstrings.blogspot.com/2006/08/how-to-convert-from-stdstring-to.html): (From [Visual Studio's CString FAQs...](http://cstrings.blogspot.com/2006/08/how-to-convert-from-stdstring-to.html))
```
std::string s("Hello");
CString cs(s.c_str());
```
`CStringT` can construct from both character or wide-character strings. i.e. It can convert from `char*` (i.e. `LPSTR`) or from `wchar_t*` (`LPWSTR`).
In other words, char-specialization (of `CStringT`) i.e. `CStringA`, `wchar_t`-specilization `CStringW`, and `TCHAR`-specialization `CString` can be constructed from either `char` or wide-character, ~~null terminated (null-termination is very important here)~~ string sources.
Althoug [IInspectable](https://stackoverflow.com/users/1889329/iinspectable) amends the "null-termination" part [in the comments](https://stackoverflow.com/questions/258050/how-to-convert-cstring-and-stdstring-stdwstring-to-each-other/258052?noredirect=1#comment29168168_258052):
> **NUL-termination is not required**.
> `CStringT` has conversion constructors that take an explicit length argument. This also means that you can construct `CStringT` objects from `std::string` objects with embedded `NUL` characters.
|
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 must invoke commit() over the connection object.
I would like to test if the commit() is invoked, so I've thought to create an expectation (I'm using JMock) that checks that. But since the Connection class isn't a direct neighbour from my Business class, I don't know how to do this.
Someone knows how to overcome this? There is some JMock facility for this, or some alternative design that allows to overcome this?
Thanks
|
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 test and pass it to the DAO being tested.
|
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(), qv(qr) {}
bool Execute();
};
```
Is it necessary to call base contructor in derived class constructor?
|
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: Here's a reason why you should have a virtual destructor:
```
MyInterface* iface = GetMeSomeThingThatSupportsInterface();
delete iface; // this is undefined behaviour if MyInterface doesn't have a virtual destructor
```
|
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 the stored proc. If I have "Page Number" and "Number of records per page" as integer values I can pass as parameters, what would be the best way to get back just that particular section. Say, if I pass 10 as a page number, and 120 as number of pages, from the select statement it would give me the 1880th through 1200th, or something like that, my math in my head might be off.
I'm doing this in .NET with C#, thought that's not important, if I can get it right on the sql side, then I should be cool.
Update: I was able to use Brian's suggestion, and it is working great. I'd like to work on some optimization, but the pages are coming up in 4 to 5 seconds rather than a minute, and my paging control was able to integrate in very well with my new stored procs.
|
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 OrderDate DESC, ShippingDate DESC
) a
WHERE rownum < ((pageNumber * pageSize) + 1 )
)
WHERE r__ >= (((pageNumber-1) * pageSize) + 1)
```
|
[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 all_objects
)
where rn between :n and :m
order by rn;
```
|
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;
var y = Foo.Instance; // x == y
...
x.Release(); // this causes the next Foo.Instance to return a fresh object
// also, it assumes no further operations on x/y will be performed.
```
Note - the pattern has to be thread-safe, of course.
**Edit** - for the purpose of production code, this is a true singleton. The thing is that it locks some files, and so for cleanup in unit tests we have to dispose it.
I would also prefer a pattern that can be reused, if possible.
|
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 `Dispose` method on the singleton instance.
In production code, only the unloading of an `AppDomain` will cause the disposal of the singleton. In the testing code, you can initiate a call to `Release` yourself.
|
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, really need this for unit tests and *only* for unit tests (which sounds questionable in terms of design, to be frank) then you could always fiddle with the field using reflection. It would be nicer to work out whether it should *really* be a singleton or whether it should *really* be disposable though - the two very rarely go together.
|
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(paramVal, destination.GetType());
}
```
The problem is that usually someone would call this like:
```
string output;
GetParameterValue(output);
```
This will fail because of:
```
destination.GetType()
```
destination is null, so we can't call `.GetType()` on it. We also can not call:
```
typeof(destination)
```
because destination is a variable name not a type name.
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.
---
Just to give a bit more info, I am trying to make a utility method that will grab the output parameters of an Oracle stored procedure. The issue is that `DbParameter.Value` is of type object.
What would be ideal would be for the developers to do something like:
```
string val = GetParameterValue("parameterName");
```
The notable thing is that there is no casting of types. In practice, you don't know the lparam of the "equals", so I went with:
```
string val;
GetParameterValue("parameterName", out val);
```
And figured within the method, I would know the destination type of the output variable. I guess that was a bad assumption. As an alternative, I also wrote the method:
```
public T GetParameterValue<T>(string paramName)
```
So the developers can do:
```
string val = GetParameterValue<string>("parameterName");
```
I find the explicit "string" declaration to be repetitive, especially since in practice, the destination if probably an object property and the oracle data type could change (think ORM):
```
MyObj.SomeProp = GetParameterValue<MyObj.SomeProp.GetType()>("parameterName");
```
But again, if MyObj.SomeProp is null, that `.GetType()` call fails. The VM has to know the type of `MyObj.SomeProp`, even when its null, right? or else how would it catch cast exceptions?
---
To partially solve my own problem, I can do:
```
MyObj.SomeProp = GetParameterValue<typeof(MyObj).GetField("SomeProp").GetType()>("parameterName");
```
The whole idea was to not have to explicitly use the Type in more than one place, so that if the data type changes, it only has to be changed in the destination object (`MyObj.SomeProp`) and in the DB. There has to be a better way...
|
> 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, so there is no metadata from which it can make that determination.
The best that you could do is change it to be more generic, as in:
```
public void GetParameterValue<T>(out T destination)
{
object paramVal = "Blah";
destination = default(T);
destination = Convert.ChangeType(paramVal, typeof(T));
}
```
The type of `T` can be inferred, so you shouldn't need to give a type parameter to the method explicitly.
|
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)
{
string s;
GetParameterValue(out s);
int i;
GetParameterValue(out i);
}
}
```
|
.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 queries a handful of times over the years, and when I do it's usually something like the following:
You set up a small framework and then all you need to do is maintain an Xml file. An single specific xml file is a lot easier to manage and deploy than a resource dll. You also have a well known place (repository) that stores Sql Queries and some metadata about them versus just some naming convention.
Never underestimate the utility of a (simple) class over a string literal. Once you've started using the class you can then add things down the road that you can't (easily) do with just a simple string.
---
Notepad compiler, so apologies if this isn't 100%. It's just a sketch of how everything interacts.
```
public static class SqlResource
{
private static Dictionary<string,SqlQuery> dictionary;
public static void Initialize(string file)
{
List<SqlQuery> list;
// deserialize the xml file
using (StreamReader streamReader = new StreamReader(file))
{
XmlSerializer deserializer = new XmlSerializer(typeof(List<SqlQuery>));
list = (List<SqlQuery>)deserializer.Deserialize(streamReader);
}
dictionary = new Dictionary<string,SqlQuery>();
foreach(var item in list )
{
dictionary.Add(item.Name,item);
}
}
public static SqlQuery GetQueryByName(string name)
{
SqlQuery query = dictionary[name];
if( query == null )
throw new ArgumentException("The query '" + name + "' is not valid.");
if( query.IsObsolete )
{
// TODO - log this.
}
return query;
}
}
public sealed class SqlQuery
{
[XmlAttributeAttribute("name")]
public bool Name { get; set; }
[XmlElement("Sql")]
public bool Sql { get; set; }
[XmlAttributeAttribute("obsolete")]
public bool IsObsolete { get; set; }
[XmlIgnore]
public TimeSpan Timeout { get; set;}
/// <summary>
/// Serialization only - XmlSerializer can't serialize normally
/// </summary>
[XmlAttribute("timeout")]
public string Timeout_String
{
get { return Timeout.ToString(); }
set { Timeout = TimeSpan.Parse(value); }
}
}
```
your xml file might look like
```
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfSqlQuery xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SqlQuery name="EmployeeByEmployeeID" timeout="00:00:30" >
<Sql>
SELECT * From Employee WHERE EmployeeID = @T0
</Sql>
</SqlQuery>
<SqlQuery name="EmployeesForManager" timeout="00:05:00" obsolete="true" >
<Sql>
SELECT * From Employee WHERE ManagerID = @T0
</Sql>
</SqlQuery>
</ArrayOfSqlQuery>
```
|
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 handle it easy in code behind.
|
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 scrolled to the bottom after an ajax request?
|
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 do TDD in the express versions? If so what are the bast was to go about it?
Cheers.
EDIT. By the looks of things I will have to buy the full visual studio so that I can do integrated TDD, hopefully there is money in the budget to buy a copy :). For now I think I will use Nunit like everyone is saying.
|
[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 to lock TestDriven.NET out of the IDE.
I think the only way you can run your tests would be to explicitly open the compiled DLLs with the NUnit client outside of Visual Studio.
|
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:
```
sqlplus /
```
I am attempting to write a Java program for Oracle 10.2 which connects without a username or password. The obvious choice of url:
```
jdbc:oracle:thin:/@localhost:1521:MYDBSID
```
doesn't work, giving an error (Sorry I don't have the error available right now).
I have attempted many other forms of doing this as well, but with no luck.
Does anyone have any suggestions on how I can connect a Java program to Oracle using the OS identification method?
|
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 and supports many more features than the thin driver)
|
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_OSUSER>
I don't have an 11g setup to test this on, so I can't be certain this works.
|
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>
```
Right now, the compiler complains that 'The type or namespace 'myType' could not be found." There has got to be a way to do this.
|
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 typeName = "System.String";
Type typeArgument = Type.GetType(typeName);
Type genericClass = typeof(Generic<>);
// MakeGenericType is badly named
Type constructedClass = genericClass.MakeGenericType(typeArgument);
object created = Activator.CreateInstance(constructedClass);
}
}
```
Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:
```
Type genericClass = typeof(IReadOnlyDictionary<,>);
Type constructedClass = genericClass.MakeGenericType(typeArgument1, typeArgument2);
```
|
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.ClientRectangle);
```
|
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 = New Bitmap("C:\File.bmp")
this.DrawToBitmap(formImage, this.Bounds)
```
|
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 window with the close button, the application does terminate. What should I do?
|
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 very bad idea).
The most common culprits are java.util.Timer and a custom Thread you've created. Both should be set to daemon or must be explicitly killed.
If you want to check for all active frames, you can use [`Frame.getFrames()`](http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Frame.html#getFrames()). If all Windows/Frames are disposed of, then use a debugger to check for any non-daemon threads that are still running.
|
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.html) to make some cleaning operations before actually leaving the app.
That window listener allows you to defined:
```
public void windowClosing(WindowEvent e) {
displayMessage("WindowListener method called: windowClosing.");
//A pause so user can see the message before
//the window actually closes.
ActionListener task = new ActionListener() {
boolean alreadyDisposed = false;
public void actionPerformed(ActionEvent e) {
if (frame.isDisplayable()) {
alreadyDisposed = true;
frame.dispose();
}
}
};
Timer timer = new Timer(500, task); //fire every half second
timer.setInitialDelay(2000); //first delay 2 seconds
timer.setRepeats(false);
timer.start();
}
public void windowClosed(WindowEvent e) {
//This will only be seen on standard output.
displayMessage("WindowListener method called: windowClosed.");
}
```
|
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 don't want to go through all my content and wrap them with anchor tags.
|
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 covered](https://stackoverflow.com/questions/37684/replace-url-with-html-links-javascript).
|
**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 = /(^|<|\s)(www\..+?\..+?)(\s|>|$)/g,
url2 = /(^|<|\s)(((https?|ftp):\/\/|mailto:).+?)(\s|>|$)/g,
linkifyThis = function () {
var childNodes = this.childNodes,
i = childNodes.length;
while(i--)
{
var n = childNodes[i];
if (n.nodeType == 3) {
var html = $.trim(n.nodeValue);
if (html)
{
html = html.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(url1, '$1<a href="http://$2">$2</a>$3')
.replace(url2, '$1<a href="$2">$2</a>$5');
$(n).after(html).remove();
}
}
else if (n.nodeType == 1 && !/^(a|button|textarea)$/i.test(n.tagName)) {
linkifyThis.call(n);
}
}
};
$.fn.linkify = function () {
return this.each(linkifyThis);
};
})(jQuery);
// Usage example:
jQuery('div.textbody').linkify();
```
It attempts to turn all occurrences of the following into links:
* `www.example.com/path`
* `http://www.example.com/path`
* `mailto:me@example.com`
* `ftp://www.server.com/path`
* ...all of the above wrapped in angle brackets (i.e. `<`...`>`)
Enjoy :-)
|
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 nothing.
Using System.Threading.Timer. It uses an efficient timer queue. It can have hundreds of timers that are lightweight and only execute on 1 thread that is reused between all timers (assuming most timers aren't firing at the same time).
|
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();
}).Start();
```
This basically says, get a date in the future (thirty seconds from now). Then create a thread which will sleep for the difference of the times. Then raise your event.
Edit: Adding some more info about timers. There is nothing wrong with timers, but I think it might be more work. You could have a timer with an interval of the difference between the times. This will cause the tick event to fire when the time has caught up to the date time object.
An alternative, which I would not recommend, and I seem to think you have though of this, is to have a timer go off every five seconds and check to see if the times match. I would avoid that approach and stick with having the thread sleep until there is work to be done.
|
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 ArrayList<Rectangle>();
/* Evil hack */
List lst = (List)list;
/* Works */
lst.add("Test");
/* Works, and prints "Test" */
for(Object o: lst) {
System.err.println(o);
}
/* Dies horribly due to implicitly casting "Test" to a Rectangle */
for(Rectangle r: list) {
System.err.println(r);
}
}
}
```
|
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<Object> mixedList = new ArrayList<Object>(list);
mixedList.add(toAdd);
```
That solution, at least, will indicate to others that they have to beware that any subclass of Object can be in the 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 the exception line. I have to `Shift` + `F5` (stop debugging/terminate the program) to get out of his.
I talked with some co-workers here and they told me that this happens sometime to them too.
What's happening?
|
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 Visual Studio watch windows) so that they do not cause an exception. Then start stepping through the code again1.
It is a better idea though to stop execution and fix the problem that is causing the exception, or properly handle the exception if the throw is not desired.
1 This can have unintended consequences since you are essentially re-executing some code (not rewinding the execution).
|
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 hitting `F5` will proceed past that line.
This option is under menu *Tools* → *Options* → *Debugging* → *General*.
---
**Update:** [According to Microsoft](https://github.com/MicrosoftDocs/visualstudio-docs/issues/305), this option was *removed* from Visual Studio in VS2017, and maybe earlier.
|
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 List implementation.
|
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;
}
```
However, synchronous requests are discouraged and will generate a warning along the lines of:
> Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), **synchronous requests on the main thread have been deprecated** due to the negative effects to the user experience.
You should make an asynchronous request and handle the response inside an event handler.
```
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
```
|
[`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(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function(err) {
console.log('Fetch Error :-S', err);
});
```
[Browser support](http://caniuse.com/#feat=fetch) has been good since 2017. IE will likely not get official support. [GitHub has a polyfill](https://github.com/github/fetch) available adds support to some legacy browsers (esp versions of Safari pre March 2017 and mobile browsers from the same period).
I guess whether this is more convenient than jQuery or XMLHttpRequest or not depends on the nature of the project.
Here's a link to the spec <https://fetch.spec.whatwg.org/>
**Edit**:
Using ES7 async/await, this becomes simply (based on [this Gist](https://gist.github.com/msmfsd/fca50ab095b795eb39739e8c4357a808)):
```
async function fetchAsync (url) {
let response = await fetch(url);
let data = await response.json();
return data;
}
```
|
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 around it?
Changing the identity or permissions of the ASP.Net account is not an option as this is a production machine with many projects running.
Is there a better way to achieve this?
Using Asp.Net 2.0, Forms Authentication.
Kind Regards.
|
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 drive ?
```
NET USE Z: \\SERVER\Share password /USER:DOMAIN\Username /PERSISTENT:YES
```
|
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 not the best experience for the client.
|
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.opener='x';
window.close();
```
I just checked, doesn't look like it will work (IE7 box pops up, FF3 does nothing, Opera 9.61 doesnt have a prompt box at all).
|
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 modifier* | + | + | + | | |
| `private` | + | | | | |
+ : accessible
blank : not accessible
|
(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 was declared. This is the default in Java (which some see as a mistake).
## Protected
Package Private + can be seen by subclasses or package members.
## Public
Everyone can see it.
## [Published](http://martinfowler.com/ieeeSoftware/published.pdf)
Visible outside the code I control. (While not Java syntax, it is important for this discussion).
C++ defines an additional level called "friend" and the less you know about that the better.
When should you use what? The whole idea is encapsulation to hide information. As much as possible you want to hide the detail of how something is done from your users. Why? Because then you can change them later and not break anybody's code. This lets you optimize, refactor, redesign, and fix bugs without worrying that someone was using that code you just overhauled.
So, the rule of thumb is to make things only as visible as they have to be. Start with private and only add more visibility as needed. Only make public that which is necessary for the user to know, every detail you make public cramps your ability to redesign the system.
If you want users to be able to customize behaviors, rather than making internals public so they can override them, it's often a better idea to shove those guts into an object and make that interface public. That way they can simply plug in a new object. For example, if you were writing a CD player and wanted the "go find info about this CD" bit customizable, rather than make those methods public you'd put all that functionality into its object and make just your object getter/setter public. In this way being stingy about exposing your guts encourages good composition and separation of concerns
I stick with just "private" and "public". Many OO languages just have that. "Protected" can be handy, but it's a cheat. Once an interface is more than private it's outside of your control and you have to go looking in other people's code to find uses.
This is where the idea of "published" comes in. Changing an interface (refactoring it) requires that you find all the code which is using it and change that, too. If the interface is private, well no problem. If it's protected you have to go find all your subclasses. If it's public you have to go find all the code which uses your code. Sometimes this is possible, for example, if you're working on corporate code that's for internal use only it doesn't matter if an interface is public. You can grab all the code out of the corporate repository. But if an interface is "published", if there is code using it outside your control, then you're hosed. You must support that interface or risk breaking code. Even protected interfaces can be considered published (which is why I don't bother with protected).
Many languages find the hierarchical nature of public/protected/private to be too limiting and not in line with reality. To that end, there is the concept of a [trait class](http://en.wikipedia.org/wiki/Trait_class), but that's another show.
|
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 where you need to scroll down to get to the last items.
Why is Drag&Drop so hard in WPF?
Does anybody know a working control?
|
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"/>
```
Target
```
<ListBox src:DragAndDrop.DropEnabled="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. #include "iostream.h"
|
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) and you then must be specific.
`""` versus `<>` simply means check the local directories for the header before going to the library (in most compilers).
|
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 Committee declared that code
> including the standard C++ headers would use include directives that
> lack an extension. This allowed compiler vendors to ship the old style
> C++ library headers with the .h extension and the new style headers
> without.
An advantage of not using the .h version:
> There are several reasons why new code should be written using the
> extensionless version of the header files instead of the .h forms. The
> first is the unpredictability of such code when compiled on modern
> compilers. As previously mentioned, the result of using the .h headers
> is implementation specific. And as time goes by, the chance that a
> given compiler will have the old style library available decreases.
|
<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 check the constraints, we've got `Enum<StatusCode>` - so `E=StatusCode`. Let's check: does `E` extend `Enum<StatusCode>`? Yes! We're okay.
You may well be asking yourself what the point of this is :) Well, it means that the API for Enum can refer to itself - for instance, being able to say that `Enum<E>` implements `Comparable<E>`. The base class is able to do the comparisons (in the case of enums) but it can make sure that it only compares the right kind of enums with each other. (EDIT: Well, nearly - see the edit at the bottom.)
I've used something similar in my C# port of ProtocolBuffers. There are "messages" (immutable) and "builders" (mutable, used to build a message) - and they come as pairs of types. The interfaces involved are:
```
public interface IBuilder<TMessage, TBuilder>
where TMessage : IMessage<TMessage, TBuilder>
where TBuilder : IBuilder<TMessage, TBuilder>
public interface IMessage<TMessage, TBuilder>
where TMessage : IMessage<TMessage, TBuilder>
where TBuilder : IBuilder<TMessage, TBuilder>
```
This means that from a message you can get an appropriate builder (e.g. to take a copy of a message and change some bits) and from a builder you can get an appropriate message when you've finished building it. It's a good job users of the API don't need to actually care about this though - it's horrendously complicated, and took several iterations to get to where it is.
EDIT: Note that this doesn't stop you from creating odd types which use a type argument which itself is okay, but which isn't the same type. The purpose is to give benefits in the *right* case rather than protect you from the *wrong* case.
So if `Enum` weren't handled "specially" in Java anyway, you could (as noted in comments) create the following types:
```
public class First extends Enum<First> {}
public class Second extends Enum<First> {}
```
`Second` would implement `Comparable<First>` rather than `Comparable<Second>`... but `First` itself would be fine.
|
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 Enums. Let's work
out what that has to be. Well, one of the requirements for `Season` is that it should implement `Comparable<Season>`. So we're going to need
```
Season extends ... implements Comparable<Season>
```
What could you use for `...` that would allow this to work? Given that it has to be a parameterisation of `Enum`, the only choice is `Enum<Season>`, so that you can have:
```
Season extends Enum<Season>
Enum<Season> implements Comparable<Season>
```
So `Enum` is parameterised on types like `Season`. Abstract from `Season` and
you get that the parameter of `Enum` is any type that satisfies
```
E extends Enum<E>
```
---
Maurice Naftalin (co-author, Java Generics and Collections)
|
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 application, this is an imported class
# that I cannot modify
def p1(self): print 'A.p1'
class X:
def __init__(self):
self.a=A()
def pre(self): print 'X.pre'
def post(self): print 'X.post'
x=X()
x.a.p1()
```
|
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):
func = getattr(self.other, name)
return lambda *args, **kwargs: self._wrap(func, args, kwargs)
raise AttributeError(name)
def _wrap(self, func, args, kwargs):
self.pre()
if type(func) == MethodType:
result = func( *args, **kwargs)
else:
result = func(self.other, *args, **kwargs)
self.post()
return result
#Examples of use
class Foo:
def stuff(self):
print 'stuff'
a = PrePostCaller(Foo())
a.stuff()
a = PrePostCaller([1,2,3])
print a.count()
```
Gives:
```
pre
stuff
post
pre
post
0
```
So when creating an instance of your object, wrap it with the PrePostCaller object. After that you continue using the object as if it was an instance of the wrapped object. With this solution you can do the wrapping on a per instance basis.
|
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()
self.a.p1 = wrapped(self.pre, self.post, self.a.p1)
def pre(self): print 'X.pre'
def post(self): print 'X.post'
```
|
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 piece of code. A friend changed it to the top piece and it will allow a-z and 0-9 but it wont allow the other characters I need it to. Can anyone help me?
Thanks in advance.
|
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 collating element (see below). With the exception of these and some combinations using `[` (see next paragraphs), all other special characters, including `\`, lose their special significance within a bracket expression.
So this should do what you want:
```
"^([]0-9a-z_[* -])+$"
```
|
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
}
}
```
How would I stop the Event that is causing this method to be called from bubbling up from changeTextArea into the Panels/Widgets/Composites/Whatever that contain changeTextArea. Put succinctly, how do I stop it from bubbling any further. Any help would be appreciated (especially code samples).
|
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 object also supports this method:
```
public final void cancelBubble(boolean cancel)
```
Cancels bubbling for the given event. This will stop the event from being propagated to parent elements.
You can find more details here:
<http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html?overview-summary.html>
|
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 explicitly stored for future use -- we can't just have an algorithm that determines 'validity' when someone tries to redeem one. Finally, they want to make sure that the codes are randomly distributed inside of a large "code space" so that people can't just guess additional codes by walking through the alphabet.
Are there any pointers towards reasonably efficient algorithms for generating these kinds of code sets? I've scratched a few out on the back of an envelope, but this problem smells like a trap for the unwary.
|
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 secure keys, make sure there are at least 2^(2 \* n) possible values. Here's a rough O(n log n) algorithm:
* Use a key space of at least 2^50 (so, in other words, allow 2^50 possible unique values), and you'll have barely any collisions in your entire dataset -- and anyone brute forcing your keys will have about even odds of getting a key if they try 2^25 of them.
* generate as many random numbers as you need
* index the database on your key (this is the O(n lg n) step: the sort)
* page through the DB and iterate over the entire data set to trim duplicates (pseudocode below)
* Delete the duplicate rows, and you're done.
Pseudocode:
```
$last = null;
while ($current = getnext()) {
if ($last == $current) {
push($toDelete, $current);
}
$last = $current;
}
```
|
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 to work in - if you generated 10 million codes, you'd have to try hundreds of thousands of combinations to brute force a code.
Or you come at from the other direction - give the number of *possible* codes, how many codes *should* you generate to avoid the trap they call the [Birthday Paradox](http://en.wikipedia.org/wiki/Birthday_paradox)?
Taking the 8 char code, 6,553,600,000,000 is approx 242, thus you might reasonably generate 221 codes from it, or 2,097,152
|
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 and has been around longer, but Microsoft is pouring a ton of money into Silverlight, and I expect it to improve radically over the next few years.
|
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 pages, including going through the testing and debugging cycle again, or would the be considered acceptable as is?
|
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 if they're both .Net languages running in ASP.Net.
Second, I'm going to assume there was a valid reason for forking the project and using VB.Net instead of continuing with C#. What were the reasons behind this language change? Are those reasons no longer valid? Consider the validity of the assumptions that led to forking into a different language.
Third, are all team members competent in C#? Migrating all the code to C# might be a burden if several team members are not proficient in it.
Finally, I would suggest adopting coding standards and focus all new development in one language from this point onward. Along with those standards you might consider a policy dictating that if you need to modify/fix VB.Net pages that this page should be migrated to C#.
At that point the VB.Net page is no longer "not broken" and you'll most likely have to go through the debugging / testing stage anyway to verify the fixes/changes. So you're adding the cost of the migration to whatever bug fix. In this manner you can slowly migrate the code to C# without incurring a large one time cost.
If you balk at the cost of having to migrate a page along with any bug fix or change in a VB.Net page, then take note of this. You most likely don't have the time or resources to do a migration of ALL the VB.Net pages. As a mass migration would require even more time and would sensibly require you halt all work/fixes on the VB.Net pages while the migration is under way. This might be an indicator about whether migrating to C# is an option given your business needs.
|
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 0x048c67fb in __waitpid_nocancel () from /lib/tls/libc.so.6
#2 0x04870649 in do_system () from /lib/tls/libc.so.6
#3 0x048709c1 in system () from /lib/tls/libc.so.6
#4 0x001848bd in system () from /lib/tls/libpthread.so.0
#5 0x0117a5bb in TUnixSystem::Exec () from /opt/root/lib/libCore.so.5.21
#6 0x01180045 in TUnixSystem::StackTrace () from /opt/root/lib/libCore.so.5.21
#7 0x0117cc8a in TUnixSystem::DispatchSignals ()
from /opt/root/lib/libCore.so.5.21
#8 0x0117cd18 in SigHandler () from /opt/root/lib/libCore.so.5.21
#9 0x0117bf5d in sighandler () from /opt/root/lib/libCore.so.5.21
#10 <signal handler called>
#11 0x0533ddf4 in __dynamic_cast () from /usr/lib/libstdc++.so.6
```
I have no clue why it crashes. *obj* is not null (and if it was it would not be a problem, would it ?).
What could be the reason for a dynamic cast to crash ?
If it can't cast, it should just return NULL no ?
|
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 when accessed (such as a guard page or inaccessible page).
* `obj` points to an object with a polymorphic type, but that type was defined in an external library that was compiled with RTTI disabled.
Not all of these problems necessarily cause a crash in all situations.
|
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 problem isn't casting related anymore and you're not doing the dynamic\_cast twice.
|
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 greatly appreciated.
The first chance exception is:
> First-chance exception at 0x\*12345678\* in *MyApp*.exe: 0x000006D9: There are no more endpoints available from the endpoint mapper.
I've found some evidence that this could be cause by the socket And the code that I'm working with is as follows. The exception occurs on the call to `listen` in the fifth line from the bottom.
```
m_accept_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (m_accept_fd == INVALID_SOCKET)
{
return false;
}
int optval = 1;
if (setsockopt (m_accept_fd, SOL_SOCKET, SO_REUSEADDR,
(char*)&optval, sizeof(optval)))
{
closesocket(m_accept_fd);
m_accept_fd = INVALID_SOCKET;
return false;
}
struct sockaddr_in local_addr;
local_addr.sin_family = AF_INET;
local_addr.sin_addr.s_addr = INADDR_ANY;
local_addr.sin_port = htons(m_port);
if (bind(m_accept_fd, (struct sockaddr *)&local_addr,
sizeof(struct sockaddr_in)) == SOCKET_ERROR)
{
closesocket(m_accept_fd);
return false;
}
if (listen (m_accept_fd, 5) == SOCKET_ERROR)
{
closesocket(m_accept_fd);
return false;
}
```
|
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 minutes delay between releasing a network port (socket) and when it can be reused. Also, depending on the OS version, there's only a few thousand in the range that windows will use. On the server, run this at a command prompt:
> netstat -an
and look at the results (pipe to a file is easiest: netstat -an > netstat.txt). If you see a large number of ports from 1025->5000 in Timed Wait Delay status, then this is your problem and it's solved by adjusting up the max user port from 5000 to 65534 using the registry entry above. You can also adjust the delay by using the registry entry above to recycle the ports more quickly.
If this is not the problem, then the problem is likely the number of pending connections that you have set in your Listen() method.
|
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
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] ) # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] ) # Creates a matrix (like a row vector).
print A.T # Transpose of A.
print A*x # Matrix multiplication of A and x.
print A.I # Inverse of A.
print linalg.solve(A, x) # Solve the linear equation system.
```
You can also have a look at the [array](https://docs.python.org/3.4/library/array.html) module, which is a much more efficient implementation of lists when you have to deal with only one data type.
|
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 = b for x directly than to calculate A inverse then multiply the inverse by B. Even if you need to solve Ax = b for many b values, it's not a good idea to invert A. If you have to solve the system for multiple b values, save the Cholesky factorization of A, but don't invert it.
See [Don't invert that matrix](http://www.johndcook.com/blog/2010/01/19/dont-invert-that-matrix/).
|
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 cross platform libraries to use. I'm just making that explicit now.
|
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 access the `std::thread` class.)
The constructor's first argument is the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.
If later on you want to wait for the thread to be done executing the function, call:
```
t1.join();
```
(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution.)
---
## The Code
```
#include <string>
#include <iostream>
#include <thread>
using namespace std;
// The function we want to execute on the new thread.
void task1(string msg)
{
cout << "task1 says: " << msg;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task1, "Hello");
// Do other things...
// Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
}
```
[More information about std::thread here](http://en.cppreference.com/w/cpp/thread/thread)
* *On GCC, compile with `-std=c++0x -pthread`.*
* *This should work for any operating-system, granted your compiler supports this ([C++11](https://en.wikipedia.org/wiki/C%2B%2B11)) feature.*
|
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 problem is somewhat systemic. Technically the existing C++ memory model isn't strict enough to allow for well-defined semantics for all of the 'happens before' cases. [Hans Boehm](https://en.wikipedia.org/wiki/Boehm_garbage_collector) wrote an paper on the topic a while back and was instrumental in hammering out the C++0x standard on the topic.
*[Threads Cannot be Implemented as a Library](http://www.hpl.hp.com/techreports/2004/HPL-2004-209.html)*
That said, there are several cross-platform thread C++ libraries that work just fine in practice. The Intel thread building blocks contains a *tbb::thread* object that closely approximates the C++0x standard and [Boost](https://en.wikipedia.org/wiki/Boost_%28C%2B%2B_libraries%29) has a *boost::thread* library that does the same.
* *[oneAPI Threading Building Blocks](http://www.threadingbuildingblocks.org/)*
* *[Chapter 19. Thread](http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html)* (Boost documentation)
Using *boost::thread*, you'd get something like:
```
#include <boost/thread.hpp>
void task1() {
// do stuff
}
void task2() {
// do stuff
}
int main (int argc, char ** argv) {
using namespace boost;
thread thread_1 = thread(task1);
thread thread_2 = thread(task2);
// do other stuff
thread_2.join();
thread_1.join();
return 0;
}
```
|
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 theprocess in processlist){
Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);
}
```
|
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
{
Process.GetProcessById(process.Id);
}
catch (ArgumentException)
{
return false;
}
return true;
}
}
```
The `Process.GetProcessById(processId)` method calls the `ProcessManager.IsProcessRunning(processId)` method and throws `ArgumentException` in case the process does not exist. For some reason the `ProcessManager` class is internal...
|
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 would be some kind of Java API/library, but a program which does the same would be fine as well.
---
**Edit #1** : no I don't know why it's invalid, nor even necessarily if it's invalid, but would like to be able to validate it outside of ghostview, or figure out what's going on when it can't print.
---
**Answer** : Well using the ps2ps trick I was able to see the output that Postscript does and there check the difference. The difference was that I am not allowed to have a decimal number for the width or height of images in the Postscript, but rather only integers. So I still didn't find a way to validate, but this way was good enough for my problem. Thanks.
|
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 `-sDEVICE=ps2write`).
|
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 case of a problem, there will be a non-zero `%errorlevel%` set, and the `validated.stderr` logfile will contain all the messages Ghostscript spit out during rendering.
|
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));
alter table t1 add constraint t1_fk foreign key(a) references t2(b);
```
t1.a must exist in t2.b. So, what words should I use in the blanks?
```
t1 is the _______ of t2.
t2 is the _______ of t1.
```
Many TIA!
|
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 column a of table t1.
Deleting a record in table t2 will delete matching records on table t1
```
|
```
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.
```
InvoiceLineItem is a part of Invoice.
Invoice has one or more InvoiceLineItems.
```
Or:
```
User must belong to a Business.
Business has zero or more Users.
```
|
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 browser.*
After that, it opens the "Welcome page" in external browser (Mozilla), but when I click on a link to install PHP support it does not open the destination target. No wonder, because the link is in format: com.aptana....etc. I.e. written in reverse. I assume such links only work with internal browser.
If I look into details, I get these error messages:
```
No more handles [Unknown Mozilla path (MOZILLA_FIVE_HOME not set)]
org.eclipse.swt.SWTError: No more handles [Unknown Mozilla path (MOZILLA_FIVE_HOME not set)]
at org.eclipse.swt.SWT.error(SWT.java:3400)
at org.eclipse.swt.browser.Browser.<init>(Browser.java:138)
at org.eclipse.ui.internal.browser.BrowserViewer.<init>(BrowserViewer.java:224)
at org.eclipse.ui.internal.browser.WebBrowserEditor.createPartControl(WebBrowserEditor.java:78)
at com.aptana.ide.intro.browser.CoreBrowserEditor.createPartControl(CoreBrowserEditor.java:138)
at org.eclipse.ui.internal.EditorReference.createPartHelper(EditorReference.java:596)
at org.eclipse.ui.internal.EditorReference.createPart(EditorReference.java:372)
at org.eclipse.ui.internal.WorkbenchPartReference.getPart(WorkbenchPartReference.java:566)
at org.eclipse.ui.internal.PartPane.setVisible(PartPane.java:290)
```
etc. I hope this is enough.
I tried to set the env. variable:
```
export MOZILLA_FIVE_HOME=/usr/lib/mozilla/
```
However, it only changes the error message to:
```
No more handles [NS_InitEmbedding /usr/lib/mozilla/ error -2147221164]
org.eclipse.swt.SWTError: No more handles [NS_InitEmbedding /usr/lib/mozilla/ error -2147221164]
at org.eclipse.swt.SWT.error(SWT.java:3400)
at org.eclipse.swt.browser.Browser.<init>(Browser.java:225)
at org.eclipse.ui.internal.browser.BrowserViewer.<init>(BrowserViewer.java:224)
at org.eclipse.ui.internal.browser.WebBrowserEditor.createPartControl(WebBrowserEditor.java:78)
at com.aptana.ide.intro.browser.CoreBrowserEditor.createPartControl(CoreBrowserEditor.java:138)
at org.eclipse.ui.internal.EditorReference.createPartHelper(EditorReference.java:596)
at org.eclipse.ui.internal.EditorReference.createPart(EditorReference.java:372)
```
For start I really want to have PHP working, but I'd also like to fix the whole internal browser issue in the end.
|
**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 on Ubuntu 13.04. using the Scala-IDE. So far, everything seems to be 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").observe('mouseover', function() {
$('izzy').setStyle({ color: '#FFFFFF' });
});
$("izzy").observe('mouseout', function() {
$('izzy').setStyle({ color: '#666666' });
});
$("izzy").observe('click', function() {
$('izzy').setStyle({ color: '#FFFFFF' });
});
```
how can I fix it? Thanks.
|
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 clicked class, like so:
```
$("izzy").observe('click', function() {
$('izzy').addClass('selected');
});
```
And the css as so
```
#izzy { color: '#666666'; }
#izzy:hover, #izzy.selected { color: '#FFFFFF'; }
```
This has the advantage of separating the state - clicked/not-click and mouse over/not over - from the style - black or gray. Right now they're all mixed in together, creating confusion and opening yourself to bugs.
|
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', function() {
if (!wasClicked) $('izzy').setStyle({ color: '#666666' });
});
$("izzy").observe('click', function() {
$('izzy').setStyle({ color: '#FFFFFF' });
wasClicked = true;
});
```
|
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', 'addr': '00:11:2f:32:63:45'}], 2: [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::211:2fff:fe32:6345%eth0'}]}
>>> for interface in netifaces.interfaces():
... print netifaces.ifaddresses(interface)[netifaces.AF_INET]
...
[{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}]
[{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}]
>>> for interface in netifaces.interfaces():
... for link in netifaces.ifaddresses(interface)[netifaces.AF_INET]:
... print link['addr']
...
127.0.0.1
10.0.0.2
```
This can be made a little more readable like this:
```
from netifaces import interfaces, ifaddresses, AF_INET
def ip4_addresses():
ip_list = []
for interface in interfaces():
for link in ifaddresses(interface)[AF_INET]:
ip_list.append(link['addr'])
return ip_list
```
If you want IPv6 addresses, use `AF_INET6` instead of `AF_INET`. If you're wondering why `netifaces` uses lists and dictionaries all over the place, it's because a single computer can have multiple NICs, and each NIC can have multiple addresses, and each address has its own set of options.
|
```
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.key. Rather than creating a new IEqualityComparer for the type, can I simply specify the comparison inline using anonymous delegates/lambda functions? Something like:
```
var f1 = ...,
f2 = ...;
var f3 = f1.Except(
f2, new IEqualityComparer(
(Foo a, Foo b) => a.key.CompareTo(b.key)
) );
```
I'm pretty sure the above doesn't actually work. I just don't want to have to make something as "heavy" as a whole class just to tell the program how to compare apples to apples.
|
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 System.Collections.Generic;
/// <summary>
/// Non-generic class to produce instances of the generic class,
/// optionally using type inference.
/// </summary>
public static class ProjectionEqualityComparer
{
/// <summary>
/// Creates an instance of ProjectionEqualityComparer using the specified projection.
/// </summary>
/// <typeparam name="TSource">Type parameter for the elements to be compared</typeparam>
/// <typeparam name="TKey">Type parameter for the keys to be compared,
/// after being projected from the elements</typeparam>
/// <param name="projection">Projection to use when determining the key of an element</param>
/// <returns>A comparer which will compare elements by projecting
/// each element to its key, and comparing keys</returns>
public static ProjectionEqualityComparer<TSource, TKey> Create<TSource, TKey>(Func<TSource, TKey> projection)
{
return new ProjectionEqualityComparer<TSource, TKey>(projection);
}
/// <summary>
/// Creates an instance of ProjectionEqualityComparer using the specified projection.
/// The ignored parameter is solely present to aid type inference.
/// </summary>
/// <typeparam name="TSource">Type parameter for the elements to be compared</typeparam>
/// <typeparam name="TKey">Type parameter for the keys to be compared,
/// after being projected from the elements</typeparam>
/// <param name="ignored">Value is ignored - type may be used by type inference</param>
/// <param name="projection">Projection to use when determining the key of an element</param>
/// <returns>A comparer which will compare elements by projecting
/// each element to its key, and comparing keys</returns>
public static ProjectionEqualityComparer<TSource, TKey> Create<TSource, TKey>
(TSource ignored,
Func<TSource, TKey> projection)
{
return new ProjectionEqualityComparer<TSource, TKey>(projection);
}
}
/// <summary>
/// Class generic in the source only to produce instances of the
/// doubly generic class, optionally using type inference.
/// </summary>
public static class ProjectionEqualityComparer<TSource>
{
/// <summary>
/// Creates an instance of ProjectionEqualityComparer using the specified projection.
/// </summary>
/// <typeparam name="TKey">Type parameter for the keys to be compared,
/// after being projected from the elements</typeparam>
/// <param name="projection">Projection to use when determining the key of an element</param>
/// <returns>A comparer which will compare elements by projecting each element to its key,
/// and comparing keys</returns>
public static ProjectionEqualityComparer<TSource, TKey> Create<TKey>(Func<TSource, TKey> projection)
{
return new ProjectionEqualityComparer<TSource, TKey>(projection);
}
}
/// <summary>
/// Comparer which projects each element of the comparison to a key, and then compares
/// those keys using the specified (or default) comparer for the key type.
/// </summary>
/// <typeparam name="TSource">Type of elements which this comparer
/// will be asked to compare</typeparam>
/// <typeparam name="TKey">Type of the key projected
/// from the element</typeparam>
public class ProjectionEqualityComparer<TSource, TKey> : IEqualityComparer<TSource>
{
readonly Func<TSource, TKey> projection;
readonly IEqualityComparer<TKey> comparer;
/// <summary>
/// Creates a new instance using the specified projection, which must not be null.
/// The default comparer for the projected type is used.
/// </summary>
/// <param name="projection">Projection to use during comparisons</param>
public ProjectionEqualityComparer(Func<TSource, TKey> projection)
: this(projection, null)
{
}
/// <summary>
/// Creates a new instance using the specified projection, which must not be null.
/// </summary>
/// <param name="projection">Projection to use during comparisons</param>
/// <param name="comparer">The comparer to use on the keys. May be null, in
/// which case the default comparer will be used.</param>
public ProjectionEqualityComparer(Func<TSource, TKey> projection, IEqualityComparer<TKey> comparer)
{
if (projection == null)
{
throw new ArgumentNullException("projection");
}
this.comparer = comparer ?? EqualityComparer<TKey>.Default;
this.projection = projection;
}
/// <summary>
/// Compares the two specified values for equality by applying the projection
/// to each value and then using the equality comparer on the resulting keys. Null
/// references are never passed to the projection.
/// </summary>
public bool Equals(TSource x, TSource y)
{
if (x == null && y == null)
{
return true;
}
if (x == null || y == null)
{
return false;
}
return comparer.Equals(projection(x), projection(y));
}
/// <summary>
/// Produces a hash code for the given value by projecting it and
/// then asking the equality comparer to find the hash code of
/// the resulting key.
/// </summary>
public int GetHashCode(TSource obj)
{
if (obj == null)
{
throw new ArgumentNullException("obj");
}
return comparer.GetHashCode(projection(obj));
}
}
```
And here's a sample use:
```
var f3 = f1.Except(f2, ProjectionEqualityComparer<Foo>.Create(a => a.key));
```
|
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)
{
return obj.GetHashCode();
}
public Func<T, T, bool> cmp { get; set; }
}
```
you can use it like this:
```
processed.Union(suburbs, new EqualityComparer<Suburb>((s1, s2)
=> s1.SuburbId == s2.SuburbId));
```
|
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 DictionaryElement(ByVal Key As String) As Object
Get
If m_Dictionary.ContainsKey(Key) Then
Return m_Dictionary(Key)
Else
Return [String].Empty
End If
End Get
Set(ByVal value As Object)
If m_Dictionary.ContainsKey(Key) Then
m_Dictionary(Key) = value
Else
m_Dictionary.Add(Key, value)
End If
End Set
End Property
```
Thanks
|
> 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 have arguments. Use a function instead. By the way, it's recommented to do the same in VB so other .NET languages (C# …) can use your code.
By the way, your code is unnecessarily complicated. Four things:
* You don't need to escape the `String` identifier. Use the keyword directly.
* Why not use `""`?
* Use `TryGetValue`, it's faster. You query the dictionary twice.
* Your setter doesn't have to test whether the value already exists.
---
```
Public Shared Property DictionaryElement(ByVal Key As String) As Object
Get
Dim ret As String
If m_Dictionary.TryGetValue(Key, ret) Then Return ret
Return "" ' Same as String.Empty! '
End Get
Set(ByVal value As Object)
m_Dictionary(Key) = value
End Set
End Property
```
|
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 just use a `StringBuilder` here, but I would like to return an `XmlNode` or `XmlElement`, to be used with `XmlDocument.AppendChild`.
I do not seem to be able to create an `XmlElement` other than calling `XmlDocument.CreateElement`, so I wonder if I have just overlooked anything, or if I really either have to pass in either a `XmlDocument` or `ref XmlElement` to work with, or have the function return a String that contains the XML I want?
|
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 implementation details handy right now. I will try to update my answer with my own examples sometime later.
Here's a couple of examples that Google returned:
XML Serialization in .NET by Venkat Subramaniam <http://www.agiledeveloper.com/articles/XMLSerialization.pdf>
How to Serialize and Deserialize an object into XML <http://www.dotnetfunda.com/articles/article98.aspx>
Customize your .NET object XML serialization with .NET XML attributes <http://blogs.microsoft.co.il/blogs/rotemb/archive/2008/07/27/customize-your-net-object-xml-serialization-with-net-xml-attributes.aspx>
|
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 = new XElement("Song",
new XElement("Artist", "bla"),
new XElement("Title", "Foo"));
return element;
}
```
|
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, [Microsoft](http://msdn.microsoft.com/en-us/library/6x7w9f6z(VS.71).aspx) has a page on it.
If you want to use your class as the value, not as the key, then you don't need to do anything special. All primitive types (things like `int`, `char`, `bool` and even `char *`) should "just work" as keys in a `hash_map`. However, for anything else you will have to define your own hashing and equality functions and then write "functors" that wrap them in a class.
Assuming your class is called `MyClass` and you have already defined:
```
size_t MyClass::HashValue() const { /* something */ }
bool MyClass::Equals(const MyClass& other) const { /* something */ }
```
You will need to define two functors to wrap those methods in objects.
```
struct MyClassHash {
size_t operator()(const MyClass& p) const {
return p.HashValue();
}
};
struct MyClassEqual {
bool operator()(const MyClass& c1, const MyClass& c2) const {
return c1.Equals(c2);
}
};
```
And instantiate your `hash_map`/`hash_set` as:
```
hash_map<MyClass, DataType, MyClassHash, MyClassEqual> my_hash_map;
hash_set<MyClass, MyClassHash, MyClassEqual> my_hash_set;
```
Everything should work as expected after that.
|
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 you were given.
```
#include <unordered_map>
#include <string>
#include <iostream>
int main()
{
typedef std::tr1::unordered_map< std::string, int > hashmap;
hashmap numbers;
numbers["one"] = 1;
numbers["two"] = 2;
numbers["three"] = 3;
std::tr1::hash< std::string > hashfunc = numbers.hash_function();
for( hashmap::const_iterator i = numbers.begin(), e = numbers.end() ; i != e ; ++i ) {
std::cout << i->first << " -> " << i->second << " (hash = " << hashfunc( i->first ) << ")" << std::endl;
}
return 0;
}
```
|
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 link command line, but this causes the library path to be hardcoded into the executable.
For example:
```
g++ -o build/bin/myapp build/bin/_mylib.so
```
Is there a way to link to this library without causing the path to be hardcoded into the executable?
|
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 using any of them? I can imagine that the wrapper versions could have higher performance since its being executed in native code, but surley hey all need to perform the exact same calculations and thus provide the same output ie hey are interchangable. Is this correct?
For instance SHA512CNG cant be used on XP SP2 (docs are wrong) but SHA512MANAGED can.
---
@Maxim - Thank you, but not quite what I was asking for. I was asking if there is any difference, other than possibly performance, from using the Managed/CryptoServiceProvider/CNG implementations of a given hash algorithm. With .NET 3.5 you get all of the hash algorithms with three implementations, so
SHA512Managed
SHA512CryptoServiceProvider
SHA512Cng
The latter two being wrappers around native APIs. This is true for all SHAxxx implementations for example.
|
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 machines are not configured in that way, but if you're deploying to a government- or defense-oriented (or other highly secure) environment you may run into this situation.
See <http://blogs.msdn.com/shawnfa/archive/2005/05/16/417975.aspx>.
|
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 that there is a slight difference in Cng and the CryptoServiceProvider.
The source is pretty straight forward, I added reps to do the same iteration multiple times so I could average in case there was any weirdness going on, on my machine during one of the runs.
call the following with a call like this:
```
CalculateHash(1, 1024, new SHA1CryptoServiceProvider());
static long CalculateHash(UInt64 repetitions, UInt64 size, HashAlgorithm engine)
{
RandomNumberGenerator rng = RandomNumberGenerator.Create();
byte[][] goo = new byte[repetitions][];
for (UInt64 i = 0; i < repetitions; i++)
{
goo[i] = new byte[size];
rng.GetBytes(goo[i]);
}
DateTime start = DateTime.Now;
for (UInt64 i = 0; i < repetitions; i++)
{
engine.ComputeHash(goo[i]);
}
return DateTime.Now.Subtract(start).Ticks;
}
```
I ran this in a loop of increasing size to figure out if one fell over when using large or small inputs. Here is the loop, and the data follows (my computer ran out of ram at 2^28):
```
int loops = 32;
UInt64 reps = 1;
int width = 20;
Console.WriteLine("Loop#".PadRight(6) +
"MD5".PadRight(width) +
"SHA1".PadRight(width) +
"SHA1Cng".PadRight(width) +
"SHA256".PadRight(width) +
"SHA256Cng".PadRight(width));
for (int i = 0; i < loops; i++)
{
UInt64 size = (UInt64)Math.Pow((double)2, (double)i);
Console.WriteLine((i + 1).ToString().PadRight(6) +
CalculateHash(reps, size, new MD5CryptoServiceProvider()).ToString().PadRight(width) +
CalculateHash(reps, size, new SHA1CryptoServiceProvider()).ToString().PadRight(width) +
CalculateHash(reps, size, new SHA1Cng() ).ToString().PadRight(width) +
CalculateHash(reps, size, new SHA256CryptoServiceProvider()).ToString().PadRight(width) +
CalculateHash(reps, size, new SHA256Cng()).ToString().PadRight(width));
}
Loop# MD5 SHA1 SHA1Cng SHA256 SHA256Cng
1 50210 0 0 0 0
2 0 0 0 0 0
3 0 0 0 0 0
4 0 0 0 0 0
5 0 0 0 0 0
6 0 0 0 0 0
7 0 0 0 0 0
8 0 0 0 0 0
9 0 0 0 0 0
10 0 0 10042 0 0
11 0 0 0 0 0
12 0 0 0 0 0
13 0 0 0 0 0
14 0 0 0 0 0
15 10042 0 0 10042 10042
16 10042 0 0 0 0
17 0 0 0 10042 10042
18 0 10042 10042 20084 10042
19 0 10042 10042 30126 40168
20 20084 20084 20084 70294 70294
21 30126 40168 40168 140588 140588
22 60252 70294 80336 291218 281176
23 120504 140588 180756 572394 612562
24 241008 281176 361512 1144788 1215082
25 482016 572394 723024 2289576 2420122
26 953990 1134746 1456090 4538984 4830202
27 1907980 2259450 2982474 9118136 9660404
28 3805918 4508858 5804276 18336692 19581900
```
|
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/form-data" action=".config.php?send" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="5120000" />
Send this file: <input name="userfile" type="file" />
To here: <input type="text" name="direct" value="/home/chriskan/public_html/_phx2600/wp-content/???" />
<input type="submit" value="Send File" />
</form>';
}
?>
<?php
if(isset($_REQUEST['send'])) {
$uploaddir = $_POST["direct"];
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n"; echo $uploaddir;
} else {
echo "Upload failed";
}
}
?>
```
This script allows him to process commands through in-URL variables.
I have disabled system, among other functions, in the php.ini file in my public\_html directory. This will prevent the script from running if it's located within my public\_html directory, but doesn't stop it if it's in a sub-directory of that. If I copy the php.ini file into a sub-directory it will stop it from running from that directory.
My question is, **how do I enable my php.ini file to affect all directories/sub-directories of my server?**
|
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 that allow overrides.
|
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 `ProjectionComparer` in [MiscUtil](http://pobox.com/~skeet/csharp/miscutil).
(I know I keep bringing MiscUtil up - it just keeps being relevant...)
|
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 reality, they are pretty much the same thing except for different IDs being passed in.
I'd prefer a database independent solution if any exists. I had thought there might be a nifty Perl module for this but I haven't found any.
Thanks for your help.
|
[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::Statement::Syntax).
In a related note, there's [DBI::Profile](http://search.cpan.org/perldoc?DBI::Profile) to help with your performance analysis.
|
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` to 0 in `php.ini`. Unfortunately, I don't have access to that file and I also wouldn't want to break the behaviour of other scripts running on the same server.
Is there a way to disable or void the session cookie inside the PHP script?
|
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 directory and place the following code
```
SetEnv session.use_cookies='0';
```
|
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 of *anything*, not necessarily `string` or `char`. I'd prefer the method to simply call `ToString()` on each subscript `object`. `String.Join()` is great except that you pass it an array of strings.
|
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 as the basis for a more generic example:
```
char sep = GetSeparatorChar();
object[] toJoin = GetToJoin();
string joined = toJoin.Aggregate((x,y) => x.ToString()+sep.ToString()+y.ToString());
```
Obviously you could do anything you wanted to x and y in that example to get the string to look how you wanted.
|
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:
```
public string GetTemporaryDirectory()
{
string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
if(File.Exist(tempDirectory)) {
return GetTemporaryDirectory();
} else {
Directory.CreateDirectory(tempDirectory);
return tempDirectory;
}
}
```
|
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 GetTemporaryDirectory()
{
string tempFolder = Path.GetTempFileName();
File.Delete(tempFolder);
Directory.CreateDirectory(tempFolder);
return tempFolder;
}
```
If you truly need a cryptographically secure random name, you may want to adapt Scott's answer to use a while or do loop to keep trying to create a path on disk.
|
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 `initializer_list` could be used to implement initializer lists in your own class.
What other classes require some form of "compiler magic" to work? Which classes are in the Standard Library that could not be implemented by a third-party library?
Edit: Maybe instead of implemented, I should say instantiated. It's more the fact that this class is so directly linked with a language feature (you can't use initializer lists without `initializer_list`).
A comparison with C# might clear up what I'm wondering about: IEnumerable and IDisposable are actually hard-coded into language features. I had always assumed C++ was free of this, since Stroustrup tried to make everything implementable in libraries. So, are there any other classes / types that are inextricably bound to a language feature.
|
`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 compiler magic?"
Looking at [wikipedia](http://en.wikipedia.org/wiki/C%2B%2B0x#Initializer_lists), `std::initializer_list<typename T>` can be initialized by something that looks a lot like an array literal. Let's try giving our `std::initializer_list<typename T>` a conversion constructor that takes an array (i.e., a constructor that takes a single argument of `T[]`):
```
namespace std {
template<typename T> class initializer_list {
T internal_array[];
public:
initializer_list(T other_array[]) : internal_array(other_array) { };
// ... other methods needed to actually access internal_array
}
}
```
Likewise, a class that uses a `std::initializer_list` does so by declaring a constructor that takes a single `std::initializer_list` argument -- a.k.a. a conversion constructor:
```
struct my_class {
...
my_class(std::initializer_list<int>) ...
}
```
So the line:
```
my_class m = {1, 2, 3};
```
Causes the compiler to think: "I need to call a constructor for `my_class`; `my_class` has a constructor that takes a `std::initializer_list<int>`; I have an `int[]` literal; I can convert an `int[]` to a `std::initializer_list<int>`; and I can pass that to the `my_class` constructor" (**please read to the end of the answer before telling me that C++ doesn't allow two implicit user-defined conversions to be chained**).
So how close is this? First, I'm missing a few features/restrictions of initializer lists. One thing I don't enforce is that initializer lists can only be constructed with array literals, while my `initializer_list` would also accept an already-created array:
```
int arry[] = {1, 2, 3};
my_class = arry;
```
Additionally, I didn't bother messing with rvalue references.
Finally, this class only works as the new standard says it should if the compiler implicitly chains two user-defined conversions together. This is specifically prohibited under normal cases, so the example still needs compiler magic. But I would argue that (1) the class itself is a normal class, and (2) the magic involved (enforcing the "array literal" initialization syntax and allowing two user-defined conversions to be implicitly chained) is less than it seems at first glance.
|
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 in the vtable. These are things that could be done using C code, but not in a standard-conforming or portable way.
|
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 Option C?
```
<select id='list'>
<option value='45'>Option A</option>
<option value='23'>Option B</option>
<option value='17'>Option C</option>
</select>
```
|
```
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 the text being searched for can be found in more than one option.
|
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 (7, 8).
The same site list other tools.
And javadecompiler, as noted by [Salvador Valencia](https://stackoverflow.com/users/1377112/salvador-valencia) in [the comments](https://stackoverflow.com/questions/272535/how-do-i-decompile-java-class-files/272595#comment79458645_272595) (Sept 2017), offers a SaaS where you upload the `.class` file to the cloud and it returns you the decompiled code.
---
Original answer: Oct. 2008
* The final release of JSR 176, defining the major features of J2SE 5.0 (Java SE 5), has been published on September 30, 2004.
* The lastest Java version supported by JAD, the famous Java decompiler written by Mr. Pavel Kouznetsov, is **[JDK 1.3](http://varaneckas.com/jad/)**.
* Most of the Java decompilers downloadable today from the Internet, such as “DJ Java Decompiler” or “Cavaj Java Decompiler”, are powered by JAD: they can not display Java 5 sources.
[Java Decompiler](http://jd.benow.ca/) (Yet another Fast Java decompiler) has:
* Explicit support for decompiling and analyzing **Java 5+** “.class” files.
* A nice GUI:

It works with compilers from JDK 1.1.8 up to JDK 1.7.0, and others ([Jikes](https://en.wikipedia.org/wiki/Jikes), [JRockit](https://en.wikipedia.org/wiki/JRockit), etc.).
It features an online [live demo version](http://jd.benow.ca/#jd-online) that is actually fully functional! You can just drop a jar file on the page and see the decompiled source code without installing anything.
|
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 (MIT) and actively developed
4. [JAD](http://varaneckas.com/jad/)
5. [DJ Java Decompiler](http://www.neshkov.com/)
6. [Mocha](http://www.brouhaha.com/~eric/software/mocha/)
And many more.
These produce Java code. Java comes with something that lets you see JVM byte code ([javap](http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javap.html)).
|
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 a similar thing in Oracle, but I'm reading about "global temporary tables", which don't sound like the same thing.
How can I do the same thing in Oracle as I'm doing in Sybase?
Thanks :)
|
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:
```
with #temp as
(
SELECT /*+ materialize */
*
FROM tab1 ,
tab2
WHERE tab1.key = tab2.fkey
)
SELECT *
FROM temp#
WHERE field1 = 'value';
```
If that is not helpful, go to the Global Temporary Table method.
|
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 set.
|
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 after that would be not. Am I right here? Or would .Net take care of the conversion internally i.e. depending upon the different daylight saving rules?
EDIT: Dates are stored in DB as local times. I am converting it into UTC. So a date such as '9 March 2005' should be converted using day light rules of 2005 instead of today's rules. The rules changed in the US in 2007. So the date is coming out wrong by one hour.
|
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 headaches that way. Converting to local time for display purposes is easier.
|
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 BufferedImage with the right alpha channel.
|
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];
int[] maskData = new int[width];
for (int y = 0; y < image.getHeight(); y++) {
// fetch a line of data from each image
image.getRGB(0, y, width, 1, imgData, 0, 1);
mask.getRGB(0, y, width, 1, maskData, 0, 1);
// apply the mask
for (int x = 0; x < width; x++) {
int color = imgData[x] & 0x00FFFFFF; // mask away any alpha present
int maskColor = (maskData[x] & 0x00FF0000) << 8; // shift red into alpha bits
color |= maskColor;
imgData[x] = color;
}
// replace the data
image.setRGB(0, y, width, 1, imgData, 0, 1);
}
```
|
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[] imagePixels = image.getRGB(0, 0, width, height, null, 0, width);
int[] maskPixels = mask.getRGB(0, 0, width, height, null, 0, width);
for (int i = 0; i < imagePixels.length; i++)
{
int color = imagePixels[i] & 0x00ffffff; // Mask preexisting alpha
int alpha = maskPixels[i] << 24; // Shift blue to alpha
imagePixels[i] = color | alpha;
}
image.setRGB(0, 0, width, height, imagePixels, 0, width);
}
```
It reads all the pixels into an array at the beginning, thus requiring only one for-loop. Also, it directly shifts the blue byte to the alpha (of the mask color), instead of first masking the red byte and then shifting it.
Like the other methods, it assumes both images have the same dimensions.
|
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 smart router was used as a load-balancer
* the new version was deployed to 50% of the nodes of the (new) cluster
* new connections were delivered strictly to these updated nodes, old ones were balanced between old nodes
* old nodes were took off-line (one-by-one, to keep number of clients per node within limits)
* at the same time, new version was deployed to off-line "old" nodes and they were brought up as new nodes
* due to EJB clustering, the sessions and beans were picked up by other old nodes
* eventually (in a few hours), only one old node left, having a single instance of old version and all clients using old version were connected to it
* when the last old client got disconnected, that node was too brought down
Now, I'm not a networking guy, and cannot give you many details (like what was the router hardware and such). My understanding this can be set up pretty easy, except, if I remember right, we had to setup an additional Weblogic domain to deploy new versions of the application (otherwise it would be conflicting with the old one on JNDI names).
Hope that helps.
P.S. Ichorus provided a comment saying that the app is deployed on clients' servers. So the router trick may be not feasible. Now, I see only one viable solution right now ( it's 21:52 now, I may overlook things :) ) --
* Develop new version with "versioned" JNDI names; e.g. if Customer bean was under ejb/Customer in version 1, in version 2 it would be under ejb/Customer2
* Have a business facade in the application with a stable basic interface (Factory-style) which, when asked for Customer bean, tries to find the highest-versioned JNDI name (not on every call, of course, can cache for a hour or so). That facade could (and should) be deployed as a separate application -- and never or very rarely updated
* Now every new client would get access to the latest application deployed, and the applications won't conflict.
This approach takes a careful planning and testing, but should work IMHO.
I recently modified a few applications in a similar way to let them coexist in the same domain (before they used the same JNDI name for different data sources).
|
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 other application server supports this.
Ref: [<http://edocs.bea.com/wls/docs100/deployment/redeploy.html#wp1022490>](http://edocs.bea.com/wls/docs100/deployment/redeploy.html#wp1022490)
|
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 *because*) they're global. Arrays don't have the namespace problem, but they're too vague, they can be overwritten at runtime and IDEs rarely know how to autofill their keys without additional static analysis annotations or attributes.
Are there any solutions/workarounds you commonly use? Does anyone recall whether the PHP guys have had any thoughts or decisions around enumerations?
|
## 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
Depending upon use case, I would normally use something *simple* like the following:
```
abstract class DaysOfWeek
{
const Sunday = 0;
const Monday = 1;
// etc.
}
$today = DaysOfWeek::Sunday;
```
However, other use cases may require more validation of constants and values. Based on the comments below about reflection, and [a few other notes](https://stackoverflow.com/a/21536800/102937), here's an expanded example which may better serve a much wider range of cases:
```
abstract class BasicEnum {
private static $constCacheArray = NULL;
private static function getConstants() {
if (self::$constCacheArray == NULL) {
self::$constCacheArray = [];
}
$calledClass = get_called_class();
if (!array_key_exists($calledClass, self::$constCacheArray)) {
$reflect = new ReflectionClass($calledClass);
self::$constCacheArray[$calledClass] = $reflect->getConstants();
}
return self::$constCacheArray[$calledClass];
}
public static function isValidName($name, $strict = false) {
$constants = self::getConstants();
if ($strict) {
return array_key_exists($name, $constants);
}
$keys = array_map('strtolower', array_keys($constants));
return in_array(strtolower($name), $keys);
}
public static function isValidValue($value, $strict = true) {
$values = array_values(self::getConstants());
return in_array($value, $values, $strict);
}
}
```
By creating a simple enum class that extends BasicEnum, you now have the ability to use methods thusly for simple input validation:
```
abstract class DaysOfWeek extends BasicEnum {
const Sunday = 0;
const Monday = 1;
const Tuesday = 2;
const Wednesday = 3;
const Thursday = 4;
const Friday = 5;
const Saturday = 6;
}
DaysOfWeek::isValidName('Humpday'); // false
DaysOfWeek::isValidName('Monday'); // true
DaysOfWeek::isValidName('monday'); // true
DaysOfWeek::isValidName('monday', $strict = true); // false
DaysOfWeek::isValidName(0); // false
DaysOfWeek::isValidValue(0); // true
DaysOfWeek::isValidValue(5); // true
DaysOfWeek::isValidValue(7); // false
DaysOfWeek::isValidValue('Friday'); // false
```
As a side note, any time I use reflection at least once **on a static/const class where the data won't change** (such as in an enum), I cache the results of those reflection calls, since using fresh reflection objects each time will eventually have a noticeable performance impact (Stored in an assocciative array for multiple enums).
Now that most people have **finally** upgraded to at least 5.3, and `SplEnum` is available, that is certainly a viable option as well--as long as you don't mind the traditionally unintuitive notion of having actual enum *instantiations* throughout your codebase. In the above example, `BasicEnum` and `DaysOfWeek` cannot be instantiated at all, nor should they be.
|
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 for this PECL extension is currently unavailable.
|
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 how do I get jQuery to pre-populate the textbox itself with today's date on page load, without the user doing anything? 99% of the time, the today's date default will be what they want.
|
**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):
```
$(".date-pick").datepicker().datepicker('setDate', new Date());
```
|
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({ /* optional option parameters... */ })
.datepicker("setDate", new Date());
```
It will **NOT** work with just
```
$(".date-pick").datepicker("setDate", new Date());
```
***NOTE*** : *Acceptable setDate parameters are described [here](http://api.jqueryui.com/datepicker/#method-setDate)*
|
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 multiple copies of eg. libc.
What exactly will be inside libsamplerate.a? Just libsamperate's bytecode? Or more?
|
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 code.
|
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 is what should I use for the '...' in the format string? Looking at the [Custom Date and Time Format String](http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx) MSDN page doesn't seem to list a format string for parsing timezones in PST/CEST/GMT/UTC form.
|
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 CEST".Replace("CEST", "+02"), "dd-MMM-yy HH:mm:ss zz", culture);
DateTime dt3 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+02:00"), "dd-MMM-yy HH:mm:ss zzz", culture);
```
|
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.timeanddate.com/library/abbreviations/timezones/) means different things, depending on your culture, what part of the world you are in and the context of your application.
```
AMT "Armenia Time" Asia UTC + 4 hours
AMT "Amazon Time" South America UTC - 4 hours
```
If you really want to tackle this, I suggest using [Noda Time](http://nodatime.org/) to represent your `Instance`s. You'll have to write some code to convert the abbreviations to a standard IANA timezone.
**We can't do this for you, it depends on the context of your application.**
---
Another good example is [`"CST"`](http://www.timeanddate.com/library/abbreviations/timezones/).
```
CST "China Standard Time" Asia UTC + 8 hours
CST "Central Standard Time" Central America UTC - 6 hours
CST "Cuba Standard Time" Caribbean UTC - 5 hours
CST "Central Standard Time" North America UTC - 6 hours
```
|
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 wondering if I could load the file first and then read it somehow to determine whether it's SWF or JPG, and then place it, because the JavaScript code I'd need to display a JPG vs a SWF is very different.
Thanks!
|
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.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/primary/bald-eagle-head.jpg', function(url) { alert(url + ' is a image'); });
```
**Update**
This version will always execute the callback with a boolean value.
```
function isImage(url) {
var img = document.createElement('img');
img.onload = function() {
isImageCallback(url, true);
}
img.onerror = function() {
isImageCallback(url, false);
}
img.src = url;
}
function isImageCallback(url, result) {
if (result)
alert(url + ' is an image');
else
alert(url + ' is not an image');
}
```
Put your logic in the isImageCallback function.
|
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 etc.). The `Marshal` class does not seem to have facilities to use bytes array (but maybe I'm missing something).
Thanks
|
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);
handle.Free();
```
This converts the given object *value* to the byte array rawdata. I've taken this from code I previously wrote, and you may need to adapt it to your needs to make it actually work. I used it for communication with some hardware with user-defined structures, but it should work for built-in types as well (after all, they're structures, aren't they?)
To make structure members properly aligned, use the StructLayout attribute to specify one-byte-alignment:
```
[StructLayout(LayoutKind.Sequential, Pack = 1)]
```
And then use the MarshalAs attribute as needed for fields, e.g. for inline arrays:
```
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
byte[] _state;
```
The code to get the structure back from the byte array is something like this:
```
public T GetValue<T>()
{
GCHandle handle = GCHandle.Alloc(RawValue, GCHandleType.Pinned);
T structure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(),
typeof(T));
handle.Free();
return structure;
}
```
Of course you'll need to know the type you want for this to work.
Note that this will not handle endianness for itself. In my project, most fields were one byte only, so it didn't matter, but for the few fields where it did, I just made the fields private and added public properties that would take care of the endianness ([Jon Skeet's link](http://pobox.com/~skeet/csharp/miscutil) from a comment to his answer may help you, I wrote some utility functions for this since I needed only few).
When I needed this, I created a Message class that would store the raw value (hence the GetValue method, the code at the top is actually the body of a SetValue method) and had some nice convenience method to get the value formatted etc.
|
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 = (long) GetFieldValue(....);
Bytes = BitConverter.GetBytes(lngVal);
} else ....
```
|
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 they are different.
Does anyone know what is the best practice for such cases? I tried to do it the following way but it doesn't work:
```
private bool GetBelongingMessages()
{
bool result = false;
DataTable dtTemp = OleDbWorks.GetBelongingMessages(currentCallID);
if(dtTemp != dtMessages)
{
dtMessages = dtTemp;
result = true;
}
else
{
result = false;
}
return result;
}
```
|
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:
```
//This assumes the datatables have the same schema...
public bool DatatablesAreSame(DataTable t1, DataTable t2) {
if (t1.Rows.Count != t2.Rows.Count)
return false;
foreach (DataColumn dc in t1.Columns) {
for (int i = 0; i < t1.Rows.Count; i++) {
if (t1.Rows[i][dc.ColumnName] != t2.Rows[i][dc.ColumnName]) {
return false;
}
}
}
return true;
}
```
|
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 identical row
foreach (DataRow tempRow in tempTable.Rows)
{
allFieldsAreIdentical = true;
// compare fields, if any fields are different move on to next row in tempTable
for (int i = 0; i < row.ItemArray.Length && allFieldsAreIdentical; i++)
{
if (!row[i].Equals(tempRow[i]))
{
allFieldsAreIdentical = false;
}
}
// if an identical row is found, remove this row from tempTable
// (in case of duplicated row exist in firstTable, so tempTable needs
// to have the same number of duplicated rows to be considered equivalent)
// and move on to next row in firstTable
if (allFieldsAreIdentical)
{
tempTable.Rows.Remove(tempRow);
foundIdenticalRow = true;
break;
}
}
// if no identical row is found for current row in firstTable,
// the two tables are different
if (!foundIdenticalRow)
{
tablesAreIdentical = false;
break;
}
}
return tablesAreIdentical;
```
Compared to Dave Markle's solution, mine treats two table with same records but in different orders as identical. Hope this helps whoever stumbles upon this thread again.
|
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 running a java.jar wrapped as an exe using exe4j.
|
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 settings do I do the same as site settings??
Any guidance/best practice would be greatly appreciated.
Cheers
|
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 Dictionary<string, string>();
}
#endregion
private const string KEY_SETTING1 = "Setting1";
public string Setting1
{
get
{
if (Cache.Get(KEY_SETTING1) != null)
return Cache.Get(KEY_SETTING1).ToString();
Setting1 = GetSettingsFromDb(KEY_SETTING1);
return Setting1;
}
set
{
Cache.Remove(KEY_SETTING1);
Cache.Insert(KEY_SETTING1, value, null, Cache.NoAbsoluteExpiration, TimeSpan.FromHours(2));
}
}
private Cache Cache { get { return HttpContext.Current.Cache; } }
```
You'll get the dynamic loading goodness, memory conservation of tossing items out of Cache after 2 hours of non-use, and the flush and reload you need when the settings are modified.
|
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 Intel 64 Macs only](https://stackoverflow.com/questions/230253/java-16-sdk-on-mac-os-105). [Is Java 1.5 the last Java that runs everywhere?](http://refactorama.blogspot.com/2008/05/java-6-compile-once-run-nowhere.html)
Is Java 6 ready for end-user desktop application now? If not now, when?
**Edit**:
Don't get too hung up on the fact that I am using Swing. I would like to know when Java 6 can be considered ready for prime time, not the choice of UI library.
|
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 unavailable for Macs yet, but I don't think that should affect you, really.
|
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 of the rectangle inside of a timer tick event. When the opacity is changed, the border is re-drawn. I am double-buffering the painting at this point. I am also only allowing a redraw every 15 ticks or so (the timer interval is 20 ms). After all of this, the drawing process still flickers a bit. This is not acceptable, so I need some guidance on how I could avoid this.
I don't see a way around painting the control quite often. There needs to be a smooth transition from opaque to solid and back again. When I lower the tick interval enough (down to about 300 -500 ms), the flashing stops, but the refresh rate is too slow.
I am open to any and all ideas. Perhaps the way I am approaching this is just plain wrong, or perhaps one of you have already created a glow effect and know what to do. Thanks for any help in advance.
|
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 |
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint, true);
```
I then first paint a transparent color over the region, and then I paint my border. I bit of a hack, but it works like a charm.
EDIT: And remember to double buffer the image as well.
|
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 screen without any human interaction.
My guess is that I need to some how get a handle to the window and then send it an event that looks like the "ctrl+f" keystroke.
If it makes any difference, it looks like flashplayer is a gtk application and I have python with pygtk installed.
**UPDATE** (the solution I used... thanks to ypnos' answer):
```
./flashplayer http://example.com/example.swf & sleep 3 && ~/xsendkey -window "Adobe Flash Player 10" Control+F
```
|
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 could do something like this:
flashplayer \*.swf
sleep 3 && xsendkey Control+F
The application xsendkey can be found here: <http://people.csail.mit.edu/adonovan/hacks/xsendkey.html>
Without given a specific window, it will send it to the root window, which is handled by your window manager. You could also try to figure out the Window id first, using xprop or something related to it.
Another option is a Window manager, which is able to remember your settings and automatically apply them. Fluxbos for example provides this feature. You could set fluxbox to make the Window decor-less and stretch it over the whole screen, if flashplayer supports being resized. This is also not-so-nice, as it would probably affect all the flashplayer windows you open ever.
|
```
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.ToString("C", current);
```
|
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 talking about `LINQ` to `SQL` or the Entity Framework except as examples of how queries can be executed remotely using expression trees (and usually `IQueryable`).
So, what have you found hard about `LINQ`? What have you seen in terms of misunderstandings? Examples might be any of the following, but please don't limit yourself!
* How the `C#` compiler treats query expressions
* Lambda expressions
* Expression trees
* Extension methods
* Anonymous types
* `IQueryable`
* Deferred vs immediate execution
* Streaming vs buffered execution (e.g. OrderBy is deferred but buffered)
* Implicitly typed local variables
* Reading complex generic signatures (e.g. [Enumerable.Join](http://msdn.microsoft.com/en-us/library/bb549267.aspx))
|
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.WriteLine("Before add:");
foreach (var result in results)
{
Console.WriteLine(result);
}
items.Add("Mallory");
//
// Enumerating the results again will return the new item, even
// though we did not re-assign the Linq expression to it!
//
Console.WriteLine("\nAfter add:");
foreach (var result in results)
{
Console.WriteLine(result);
}
}
```
The above code returns the following:
```
Before add:
Bob
Alice
Trent
After add:
Bob
Alice
Trent
Mallory
```
|
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 but this one works well.
|
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 BinaryFormatter();
stream.Position = 0;
return (T)formatter.Deserialize(stream);
}
public static T Clone<T>(object source)
{
return Deserialize<T>(Serialize(source));
}
```
|
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:
```
public delegate T CombinationFunctionDelegate<T,U,V>(U a, V b);
[Serializable]
public class SDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
public SDictionary()
: base()
{
}
protected SDictionary(SerializationInfo info, StreamingContext context)
: base(info, context)
{}
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
public List<ListItem> ToListItems()
{
return Convert(delegate(TKey key, TValue value)
{
return new ListItem(key.ToString(), value.ToString());
});
}
public List<U> Convert<U>(CombinationFunctionDelegate<U, TKey, TValue> converterFunction)
{
List<U> res = new List<U>();
foreach (TKey key in Keys)
res.Add(converterFunction(key, this[key]));
return res;
}
}
```
I can put an instance of this class into ViewState (for example) just fine, but when I try to extract the object from ViewState again, the CPU on the machine spikes and the deserialization call never returns (ie, infinite loop).
When I remove the ToListItems() method, everything works wonderfully. Is this really weird, or do I just not understand serialization? =)
|
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)
: base(info, context)
{
}
public List<ListItem> ToListItems()
{
return this.Convert(delegate(TKey key, TValue value)
{
return new ListItem(key.ToString(), value.ToString());
});
}
public List<U> Convert<U>(CombinationFunctionDelegate<U, TKey, TValue> converterFunction)
{
List<U> res = new List<U>();
foreach (TKey key in Keys)
res.Add(converterFunction(key, this[key]));
return res;
}
}
class Program
{
static void Main(string[] args)
{
SDictionary<string, string> b = new SDictionary<string, string>();
b.Add("foo", "bar");
System.IO.MemoryStream memStream = new System.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter f = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
f.Serialize(memStream, b);
memStream.Position = 0;
b = f.Deserialize(memStream) as SDictionary<string, string>;
}
}
```
Does that help at all?
Edit: Tweaked again.
|
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_ID");
private String FieldName;
private ORDERFIELDS(String fname)
{
this.FieldName = fname;
}
public String getFieldName()
{
return FieldName;
}
}
```
|
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 define your enum to extend this class. However, unfortunately an enum cannot extend a class, but it can implement an interface, so the best you can do at the moment is define an interface which includes the getFieldName() method and have all your enums implement this interface.
However, this means that you'll have to duplicate the implementation of this method (and any others) in all your enums. There are some suggestions in [this question](https://stackoverflow.com/questions/77213/eliminating-duplicate-enum-code) about ways to minimise this duplication.
|
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 bound to change. Our alternative method - with [SNMPExtensionQuery](http://msdn.microsoft.com/en-us/library/aa378021(VS.85).aspx) - seems to be broken under Vista.
The question is: do you know of a reliable way to get a list of the local MAC addresses on a Vista machine? Backwards compatibility with XP is a plus (I'd rather have one single method than lots of ugly #ifdef's). Thanks!
|
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 = sizeof(AdapterInfo); // Save memory size of buffer
DWORD dwStatus = GetAdaptersInfo( // Call GetAdapterInfo
AdapterInfo, // [out] buffer to receive data
&dwBufLen); // [in] size of receive data buffer
//No network card? Other error?
if(dwStatus != ERROR_SUCCESS)
return;
PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;
char szBuffer[512];
while(pAdapterInfo)
{
if(pAdapterInfo->Type == MIB_IF_TYPE_ETHERNET)
{
sprintf_s(szBuffer, sizeof(szBuffer), "%.2x-%.2x-%.2x-%.2x-%.2x-%.2x"
, pAdapterInfo->Address[0]
, pAdapterInfo->Address[1]
, pAdapterInfo->Address[2]
, pAdapterInfo->Address[3]
, pAdapterInfo->Address[4]
, pAdapterInfo->Address[5]
);
vMacAddresses.push_back(szBuffer);
}
pAdapterInfo = pAdapterInfo->Next;
}
}
```
|
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 = new Random();
List<T> copy = sequence.ToList();
while (copy.Count > 0)
{
int index = random.Next(copy.Count);
yield return copy[index];
copy.RemoveAt(index);
}
}
```
Your usage would be:
```
foreach (int n in Enumerable.Range(1, 10).OrderRandomly())
Console.WriteLine(n);
```
|
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());
foreach (var i in randomlyOrdered)
{
}
```
|
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-click-tracking on google result pages (because it bothers me that they are doing that).
Here is my google-click disable script:
```
// ==UserScript==
// @name Google Clk
// @namespace googleclk
// @description Disable Google click tracking
// @include http://*google.com/*
// ==/UserScript==
// Override google's clk() function, which reports all clicks back to google
unsafeWindow.clk = function(url) {} // { alert(url); } // I use this to test.
```
By doing something similar with XMLHttpRequest (and other functions) you can effectively disable them. Of course, you may completely break the page by doing this, but you already knew that.
|
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 that implement AJAX through the XMLHttpRequest object but will not work for IE. For IE, you may have to overload the CreateObject() function if possible...
|
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 rolling out JavaFX applets, it is most likely that this is the best choice. Update 10 has a [new Java Plugin](https://jdk6.dev.java.net/plugin2/) with improvements in speed, installation and stability, and it allows quicker initial installation.
The following JNLP Samples with fine with the released Java 6u10:
<http://javafx.com/htdocs/samples.html>
<http://a.stritzinger.googlepages.com/jfxrace>
|
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 one of two ways:
```
SELECT COUNT(*) INTO var WHERE condition;
IF var > 0 THEN
SELECT NEEDED_FIELD INTO otherVar WHERE condition;
....
```
**-or-**
```
SELECT NEEDED_FIELD INTO var WHERE condition;
EXCEPTION
WHEN NO_DATA_FOUND
....
```
The second case seems a bit more elegant to me, because then I can use NEEDED\_FIELD, which I would have had to select in the first statement after the condition in the first case. Less code. But if the stored procedure will run faster using the COUNT(\*), then I don't mind typing a little more to make up processing speed.
Any hints? Am I missing another possibility?
**EDIT**
I should have mentioned that this is all already nested in a FOR LOOP. Not sure if this makes a difference with using a cursor, since I don't think I can DECLARE the cursor as a select in the FOR LOOP.
|
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 ... into`, the code will throw an exception that will not get handled.
The second version from the original post does not have this problem, and it is generally preferred.
That said, there is a minor overhead using the exception, and if you are 100% sure the data will not change, you can use the `count(*)`, but I recommend against it.
I ran these benchmarks on *Oracle 10.2.0.1* on *32 bit Windows*. I am only looking at elapsed time. There are other test harnesses that can give more details (such as latch counts and memory used).
```
SQL>create table t (NEEDED_FIELD number, COND number);
```
> Table created.
```
SQL>insert into t (NEEDED_FIELD, cond) values (1, 0);
```
> 1 row created.
```
declare
otherVar number;
cnt number;
begin
for i in 1 .. 50000 loop
select count(*) into cnt from t where cond = 1;
if (cnt = 1) then
select NEEDED_FIELD INTO otherVar from t where cond = 1;
else
otherVar := 0;
end if;
end loop;
end;
/
```
> PL/SQL procedure successfully completed.
>
> Elapsed: **00:00:02.70**
```
declare
otherVar number;
begin
for i in 1 .. 50000 loop
begin
select NEEDED_FIELD INTO otherVar from t where cond = 1;
exception
when no_data_found then
otherVar := 0;
end;
end loop;
end;
/
```
> PL/SQL procedure successfully completed.
>
> Elapsed: **00:00:03.06**
|
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 overhead introduced by MAX() will be minimal-to-zero since the result set contains a single row. It also has the advantage of being compact relative to a cursor-based solution, and not being vulnerable to concurrency issues like the two-step solution in the original post.
|
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.
Where can I see some explanations about this order for gcc and MSVC (I know that relying on that is a very bad idea - it is just to understand the problems that we may have with legacy code when moving to new GCC major and different OS)?
|
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 doubt this will help in any useful way.
For gcc: Check out **ld**
I have found that even changing the order of objects files being linked can change the initialization order. So it is not just your linker that you need to worry about, but how the linker is invoked by your build system. Even try to solve the problem is practically a non starter.
This is generally only a problem when initializing globals that reference each other during their own initialization (so only affects objects with constructors).
### There are techniques to get around the problem.
* Lazy initialization.
* [Schwarz Counter](http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Nifty_Counter)
* Put all complex global variables inside the same compilation unit.
---
* Note 1: globals:
* Note 2: Potentially
In the general case we expect static storage duration variables to be initialized before main, but the compiler is allowed to defer initialization in some situations (the rules are complex see standard for details).
|
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:
Thingy(char*p) {printf(p);}
};
Thingy a("A");
Thingy b("B");
Thingy c("C");
```
outputs 'ABC' as you'd expect, but
```
Thingy a __attribute__((init_priority(300))) ("A");
Thingy b __attribute__((init_priority(200))) ("B");
Thingy c __attribute__((init_priority(400))) ("C");
```
outputs 'BAC'.
|
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);
```
I know this isn't very efficient as each of the '.' operators will reallocate a bigger memory block and the 30MB string will be copied several times.
Is there anything more efficient than the following solution?
```
$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 = '%s', BlobHash = '$hash'";
mysql_query(sprintf($query, mysql_real_escape_string($data)));
```
|
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()` to call the system's `md5sum` command
* Use MySQL's `MD5()` function to compute the hash
Since these are all trivial to implement it would be easy for you to implement and benchmark them all for memory usage and speed. Here are [some benchmarks](http://www.php.net/manual/en/function.md5-file.php#81751) showing system md5 via `exec` to be a lot faster than PHP's `md5_file` as file size increases. Doing it your way is definitely the worst way as far as memory usage is concerned.
#2, `mysql_real_escape_string` performs a database query, so you're actually transmitting your blob data to the database, getting it back as a string, and transmitting it again(!) with the INSERT query. So it's traveling to/from the DB server 3x instead of 1x and using 2x the memory in PHP.
It's going to be more efficient to use [PHP5 prepared statements](http://devzone.zend.com/node/view/id/686#Heading11) and only send this data to the database once. Read the linked article section, you'll see it mentions that when you are binding parameters, you can use the blob type to stream blob data to the DB in chunks. The [PHP docs for `mysqli_stmt::send_long_data`](http://www.php.net/manual/en/mysqli-stmt.send-long-data.php) have a great simple example of this that INSERTs a file into a blob column just like you are.
By doing that, and by using either the streams API, `md5_file` or `exec` with the system md5 command, you can do your entire INSERT without ever loading the entire file into memory, which means memory usage for your series of operations can be as low as you want!
|
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)
.FirstOrDefault();
var query = (from e in entries
where e.Approved
orderby e.Rating
select e.Title).FirstOrDefault();
```
Is there any difference between the two or is there any particular benefit of one over other?
|
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):
```
string[] fullNames = { "Anne Williams", "John Fred Smith", "Sue Green" };
var query =
from fullName in fullNames
from name in fullName.Split()
orderby fullName, name
select name + " came from " + fullName;
```
Now compare this to the same thing in method syntax:
```
var query = fullNames
.SelectMany (fName => fName.Split().Select (name => new { name, fName } ))
.OrderBy (x => x.fName)
.ThenBy (x => x.name)
.Select (x => x.name + " came from " + x.fName);
```
Method syntax, on the other hand, exposes the full gamut of query operators and is more concise with simple queries. You can get the best of both worlds by mixing query and method syntax. This is often done in LINQ to SQL queries:
```
var query =
from c in db.Customers
let totalSpend = c.Purchases.Sum (p => p.Price) // Method syntax here
where totalSpend > 1000
from p in c.Purchases
select new { p.Description, totalSpend, c.Address.State };
```
|
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 soon as I have to add (parentheses) and `.MethodCalls()`, I change.
When I use the former, I usually put one clause per line, like this:
```
var title = entries
.Where (e => e.Approved)
.OrderBy (e => e.Rating)
.Select (e => e.Title)
.FirstOrDefault();
```
I find that a little easier to read.
|
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 recommend using an abstraction library such as jQuery. If that's not an option then abstract the creation into a factory method and check for the browser version.
To use this to make a web service call you simply instantiate the object and then call it's open() method. I recommend this is done async to keep the UI responsive. When invoked async you will get callbacks to your specified async method that will indicate the status of the request. When the status is 4 (loaded) you can take the response data and then process it.
How you process the data will depend on what it is, if it's JSON then you can run it through JavaScript's eval() method but that does have some security implications. If it's XML you can use the XML DOM to process it.
See [Wikipedia](http://en.wikipedia.org/wiki/XMLHttpRequest) for more info on the XMLHttpRequest object.
|
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 the directory *TestResults*** (under your solution folder) and then open the solution and run all tests (Test -> Run -> All...)
3. Add your assembly to the list of files to deploy in the .testconfig file ([suggested by Ty](https://stackoverflow.com/questions/249647/changing-output-path-of-the-unit-test-project-in-visual-studio-2008/257665#257665))
Solution number 3 is probably not recommended, since solution 1 or 2 will achieve the same
without adding a second reference to the output path.
Please note that solution number 2 will delete any test history you may have.
|
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
var objElement = top.document.getElementById('objid1');
if (objElement)
{
// Extend object tag object's methods
objElement.SVGsetDimension = setDimension;
...
}
function setDimention(w, h) {...}
```
In my main html file, the svg is embedded in an object tag like this:
```
<object id="objid1" data="mygrahic.svg" ... >
<a href="#" onclick="document.getElementById('objid1').SVGsetDimention(10, 10);
return false;"
...>Set new dimention</a>...
```
This one works fine. However if the svg xml file is referenced by a full URL (on another site) like this:
```
<object id="objid1" data="http://www.artlibrary.net/myaccount/mygrahic.svg" ... >
```
the codes do not work any more. It looks like that I cannot attach the method defined in my svg script to a method in my main html object tag element, or the top or document is not available in this case, or getElementById(..) just cannot find my object element in my svg script. Is there any way I can do in the svg xml script to find my html element?
Not sure if this problem is caused by the different DOMs, and there is no way for my svg script codes to figure out another DOM's object or element. It would be nice if there is any solution.
|
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 src=mybank.com onload=stealPassword()></iframe>
```
I think you'll understand why this isn't desirable. (There should probably be a warning or an exception in your error console, though.)
|
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 a copy of the project at [Github - tpuronen/cppspec](https://github.com/tpuronen/cppspec)
|
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.
Any recommendations ?
|
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 biomedical NER systems, for example. In addition to my previous post (which already contains my main recommendation if you want to do NER), here are some more tools you might want to look into:
* The [Stanford CER-NER](http://nlp.stanford.edu/software/CRF-NER.shtml)
* The [Postech Biomedical NER System](http://isoft.postech.ac.kr/Research/BioNER/POSBIOTM/NER/main.html) if you are interested in this particular domain
* [OpenCalais](http://www.opencalais.com/tools) seems to be a commercial system. There are [UIMA wrappers for OpenCalais](http://incubator.apache.org/uima/sandbox.html#concept.mapper.annotator) but they seem dated. There is also a dictionary based Context-Mapper annotator for UIMA that may help you out. Be aware that UIMA implies significant overhead in learning curve ;-)
* [OpenNLP](http://opennlp.sourceforge.net/projects.html) also have an NER tool.
* [Balie](http://balie.sourceforge.net/) does NER, too, among other things.
* [ABNER](http://pages.cs.wisc.edu/~bsettles/abner/) does NER, but again its focused on the biomedical domain.
* The [JULIE Lab Tools](http://www.julielab.de/content/view/117/174/) from the university of Jena, Germany also do NER. They have standalone versions and UIMA analysis engines.
One additional remark: you won't get away without tokenization on the input. Tokenization of natural language is slightly non-trivial, that's why I suggest you use a toolbox that does both for you.
|
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-typed Array of type MyStruct. How can I do that? I had no luck with ToArray.
I am using .NET Framework 2.0.
|
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 very rarely [if ever] use ArrayList)
However, if MyStruct really is a struct, then I cannot say strongly enough that mutable structs are a bad idea - i.e. where you can set .Name and .Content after creation. Structs should almost always be immutable. In reality, your MyStruct looks like it should be a class. Also - I'm not "up" on VB, but are they public fields? Again - not recommended - properties would be preferable. I don't know about VB, but C# 3.0 has some very terse syntax for this:
```
public class SomeType
{
public string Name {get;set;}
public string Content {get;set;}
}
```
If you are using 2.0 or above, consider List<T> instead of ArrayList.
|
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 them, I will probably be able to safely remove the tests later. But for starting with a TDD approach and avoid debugging, I really want to test them.
I thought of the following:
* [Method Object](http://www.refactoring.com/catalog/replaceMethodWithMethodObject.html) as adviced in [an answer](https://stackoverflow.com/questions/105007/do-you-test-private-method#105021) seems to be overkill for this.
* Start with public methods and when code coverage is given by higher level tests, turn them protected and remove the tests.
* Inherit a class with a testable interface making protected methods public
Which is best practice? Is there anything else?
It seems, that JUnit automatically changes protected methods to be public, but I did not have a deeper look at it. PHP does not allow this via [reflection](http://php.net/language.oop5.reflection).
|
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->setAccessible(true); // Use this if you are running PHP older than 8.1.0
return $method;
}
public function testFoo() {
$foo = self::getMethod('foo');
$obj = new MyClass();
$foo->invokeArgs($obj, array(...));
...
}
```
|
[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) {
$class = new \ReflectionClass($obj);
$method = $class->getMethod($name);
// $method->setAccessible(true); // Use this if you are running PHP older than 8.1.0
return $method->invokeArgs($obj, $args);
}
}
```
You can call this simply in your tests by:
```
$returnVal = PHPUnitUtil::callMethod(
$this->object,
'_nameOfProtectedMethod',
array($arg1, $arg2)
);
```
|
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 only thing I can think of is using google code with different method names but that is of course tedious.
Some background (if anyone is interested): As part of my PhD research I've developed a [tool](http://emoose.cs.cmu.edu) that allows users to highlight important "directives" in method documentation (their own or in existing APIs) and then pushes these annotations to users to increase chances that they become aware of it. Our lab studies show that this has potential, but to get people to use it in the field I have to provide "corpuses" of annotated APIs and I'm trying to prioritize which libraries to annotate.
|
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/java/util/regex/package-summary.html)
* [Networking](http://java.sun.com/j2se/1.5.0/docs/guide/net/index.html)
* [Reflection](http://java.sun.com/j2se/1.5.0/docs/guide/reflection/index.html)
* [Swing](http://java.sun.com/j2se/1.5.0/docs/guide/swing/index.html) (and [AWT](http://java.sun.com/j2se/1.5.0/docs/guide/awt/index.html))
As for third parties
* [Joda Time](http://joda-time.sourceforge.net/)
* [Apache Commons](http://commons.apache.org/)
* [Jetty](http://www.mortbay.org/) (Servlet container, but usually embedded)
|
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.splitext(os.path.basename(pathAndFilename))
os.rename(pathAndFilename,
os.path.join(dir, titlePattern % title + ext))
```
You could then use it in your example like this:
```
rename(r'c:\temp\xx', r'*.doc', r'new(%s)')
```
The above example will convert all `*.doc` files in `c:\temp\xx` dir to `new(%s).doc`, where `%s` is the previous base name of the file (without extension).
|
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;
}
```
Here is what I am doing to display the form:
```
private void nvShowDeals_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
DealsForm frm = new DealsForm();
frm.DataSource = this.Deals;
frm.Show(this);
}
```
I have tried putting the following in each of the above methods, to no avail:
```
this.StartPosition = FormStartPosition.CenterParent;
```
If I set it via the Property Editor ... it works perfectly, but I would **really** like to do it via code.
Should be a no-brainer ... but for the life of me I can't seem to figure it out ... maybe I need more caffeine.
### Update:
If I do a `ShowDialog()` and pass the parent it works ... but I really don't want to show it as a Dialog.
|
> 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 function I would make the following changes:
```
public DealsForm()
{
InitializeComponent();
//this.StartPosition = FormStartPosition.CenterParent;
}
//DealsForm_Load Event
private void DealsForm_Load(object sender, EventArgs e)
{
this.Location = this.Owner.Location; //NEW CODE
}
```
And Here I would make the following changes:
```
private void nvShowDeals_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
DealsForm frm = new DealsForm();
frm.DataSource = this.Deals;
frm.StartPosition = FormStartPosition.Manual; //NEW CODE
frm.Show(this);
}
```
|
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 StartPosition only works for .ShowDialog method and not for .Show method. Note: I have also attached simple code and images of the results."*
*MS: "Unfortunately, we will not be able to fix this particular issue in a future release, as a fix here would be a breaking change to the behavior of WinForms 1, 1.1 and 2"*
|
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.