Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
What is the "django-way" of specifying channel image in rss feed? I can do it manually by rolling my own xml, but was looking for a proper way of doing it.
**Edit**
dobrych's solution is not quite applicable here because I was asking specifically about RSS not Atom feeds | Found the *right* way of doing it. As the [documentation](http://docs.djangoproject.com/en/dev/ref/contrib/syndication/?from=olddocs#custom-feed-generators) describes, I needed to create a custom feed generator by subclassing from *Rss201rev2Feed* and overriding method
```
add_root_elements()
```
like this:
```
class RssFooFeedGenerator(Rss201rev2Feed):
def add_root_elements(self, handler):
super(RssFooFeedGenerator, self).add_root_elements(handler)
handler.addQuickElement(u"image", '',
{
'url': u"http://www.example.com/images/logo.jpg",
'title': u"Some title",
'link': u"http://www.example.com/",
})
class RssFooFeed(Feed):
feed_type = RssFooFeedGenerator
title = u"Foo items"
link = u"http://www.example.com/"
description = u"Some description"
``` | For valid RSS 2.0 you shoud use this:
```
class ImageRssFeedGenerator(Rss201rev2Feed):
def add_root_elements(self, handler):
super(ImageRssFeedGenerator, self).add_root_elements(handler)
handler.startElement(u'image', {})
handler.addQuickElement(u"url", self.feed['image_url'])
handler.addQuickElement(u"title", self.feed['title'])
handler.addQuickElement(u"link", self.feed['link'])
handler.endElement(u'image')
class LastPublishedPromiseFeed(Feed):
link = 'http://www.example.com'
feed_type = ImageRssFeedGenerator
def feed_extra_kwargs(self, obj):
return {'image_url': self.link + '/image.jpg'}
``` | Django-way of specifying channel image in rss feed | [
"",
"python",
"django",
"rss",
""
] |
Lets say we have a negative integer say
int a;
is there a faster implementation of
-a?
Do I have to do some bitwise operation on this? | To clarify Pax's statement,
C++ compilers are not mandated to use two's complement, except in 1 case. When you convert a signed type to an unsigned type, if the number is negative, the result of the conversion must be the 2's complement representation of the integer.
In short, there is not a faster way than -a; even if there were, it would not be portable.
Keep in mind as well that premature optimization is evil. Profile your code first and then work on the bottlenecks.
See *The C++ Programming Language, 3rd Ed.*, section C.6.2.1. | There's almost certainly nothing faster than the machine code NEG instruction that your compiler will most likely turn this into.
If there was, I'm sure the compiler would use it.
For a twos-complement number, you could NOT it and add 1 but that's almost certainly going to be slower. But I'm not entirely certain that the C/C++ standards mandate the use of twos-complement (they may, I haven't checked).
I think this question belongs with those that attempt to rewrite `strcpy()` et al to get more speed. Those people naively assume that the C library `strcpy()` isn't already heavily optimized by using special machine code instructions (rather than a simplistic loop that would be most people's first attempt).
Have you run performance tests which seem to indicate that your negations are taking an overly long time?
<subtle-humor-or-what-my-wife-calls-unfunny>
A NEG on a 486 (state of the art the last time I had to worry
about clock cycles) takes 3 clock cycles (memory version,
register only takes 1) - I'm assuming the later chips will be
similar. On a 3Ghz CPU, that means you can do 1 billion of
these every second. Is that not fast enough?
</subtle-humor-or-what-my-wife-calls-unfunny> | C++ Optimization on negative integers | [
"",
"c++",
"c",
"optimization",
"micro-optimization",
""
] |
I'm trying to implement localization with routes
I have the following:
```
routes.MapRoute( "DefaultLocalized",
"{lang}/{controller}/{action}/{id}",
new { controller = "Home",
action = "Index",
id = "",
lang = "en" }
);
routes.MapRoute( "Default",
"{controller}/{action}/{id}",
new { controller = "Home",
action = "Index",
id = "" }
);
```
When I call my page `domain/en/home/index`, it works fine but when i call `domain/home/index` I get error 404: resource cannot be found.
Also when I'm at `domain/en/home/index` and I click a secured page I get redirected to `domain/Account/login` how can I be redirected to `domain/en/Account/login`?
Also when I get an application error how can I be redirected to `domain/en/home/error`?
The real question is how can I implement localization with language as a route parameter? | You could also introduce a constraint even tighter than Marc Gravell and Freddy Rios.
something like "en|de|fr|es". This would mean hardcoding the languages but usually these are few and known. | The routes will match, by default, left-to-right, so "domain/home/index" will match first to lang=domain, controller=index, action (default to index), id (default to 0/null).
To fix this, I believe you can specify a regex on the MapRoute (matching, for example, languages with exactly 2 characters) - it has changed at some point, though... (sorry, no IDE at the moment, so I can't check exactly).
From memory, it *might* be:
```
routes.MapRoute( "DefaultLocalized",
"{lang}/{controller}/{action}/{id}",
new { controller = "Home",
action = "Index",
id = "",},
new { lang = "[a-z]{2}" }
);
```
Note that you probably aren't going to want every action to take a "string lang", so you should handle the "lang" part of the route either in a base-controller, or an action-filter (in either case, presumably add the info to the ViewData). | asp.net mvc localization | [
"",
"c#",
"asp.net-mvc",
"localization",
"routes",
""
] |
I am using jQuery and I need to get the local time for Germany.
Anyone coming to my website from any country should be able to know what time it is in Germany.
If the time is between 0:00 and 12:00 I need to make an alert reading: "Good Morning".
If the time is between 12:00 and 17:00 I need to make an alert reading: "Good Afternoon".
How can I implement this in jQuery? | You can get the local timezone offset of the client to get the GMT time and then add the offset hours of the Germany timezone (Central European Time GMT+1):
```
function getDate(offset){
var now = new Date();
var hour = 60*60*1000;
var min = 60*1000;
return new Date(now.getTime() + (now.getTimezoneOffset() * min) + (offset * hour));
}
//...
var dateCET = getDate(1); // Central European Time is GMT +1
if (dateCET.getHours() < 12) {
alert ("Good morning.");
} else {
alert ("Good afternoon.");
}
```
**Update:** I agree with @Josh, the above code is completely client dependent. Let's try to do it better:
```
$(document).ready(function(){
var timezone = "Europe/Berlin";
$.getJSON("http://json-time.appspot.com/time.json?tz="+timezone+"&callback=?",
function(data){
if (data.hour < 12) {
alert ("Good morning in "+timezone);
} else {
alert ("Good afternoon in "+timezone);
}
})
});
```
We are now taking advantage of [JSONP](http://remysharp.com/2007/10/08/what-is-jsonp/) to do Cross-Domain requests to the [jsontime](http://simonwillison.net/2008/Jun/21/jsontime/) server, this server exposes a complete JSON API to query time and timezone information.
You can play with the code [here](http://jsbin.com/ozuku/edit) and you can explore the JSONP API [here](http://json-time.appspot.com/).
Hurray!, no server-side code! | Do you want to get the time in Germany, or the time for the user's timezone, wherever they are? If the latter, the `Date()` function defaults to work in the local timezone.
```
var d = new Date(); // defaults to the current time in the current timezone
if (d.getHours() < 12) {
alert ("Good morning.");
} else {
alert ("Good afternoon.");
}
``` | How can I obtain the local time in jQuery? | [
"",
"javascript",
"jquery",
"plugins",
"time",
""
] |
I have to execute several command line executables in Windows through Java. Rather than using Runtime.exec, I thought of using Ant Tasks to do these invocations, hoping it would be a better way.
Is there any other better approach or any popular library to do this? | Runtime.exec is *the* way of doing this in Java. Any other library would likely be platform specific. You'd need a very good reason not to use Runtime.exec.
I've currently got several programs that make use of this feature and it hasn't caused any trouble.
With Runtime.exec you can optionally block while waiting for the call to complete. You can capture return codes and anything the command line program writes to the console. And I'm sure there are many other features, those are just the ones that were useful to me.
And you can always have it invoke an ant task if you really want to use ant! :) | What exactly is wrong with using `Runtime.exec()`? It's in the API for a good reason... | Executing command line programs from Java | [
"",
"java",
"ant",
"process",
""
] |
Is it only possible if I rename the file? Or is there a `__module__` variable to the file to define what's its name? | Yes, you should rename the file. Best would be after you have done that to remove the `oldname.pyc` and `oldname.pyo` compiled files (if present) from your system, otherwise the module will be importable under the old name too. | If you really want to import the file 'oldname.py' with the statement 'import newname', there is a trick that makes it possible: Import the module *somewhere* with the old name, then inject it into `sys.modules` with the new name. Subsequent import statements will also find it under the new name. Code sample:
```
# this is in file 'oldname.py'
...module code...
```
Usage:
```
# inject the 'oldname' module with a new name
import oldname
import sys
sys.modules['newname'] = oldname
```
Now you can everywhere your module with `import newname`. | How to change a Python module name? | [
"",
"python",
"module",
""
] |
I'd like to be able to return all columns in a table or in the resulting table of a join and still be able to transform a date to a string by name.
For example
Select ID, DESCRIPTION, TO\_CHAR(CHANGE\_DATE,'YYYY-MM-DD HH24:MI:SS') AS FORMATED\_DATE FROM MY\_TABLE;
This is all well and good for just these three columns. But, the table will actually have many more columns and may be joined onto other tables. I'd like to be able to use a wildcard to get all the columns and still be able to perform the TO\_CHAR transformation.
Something like :
SELECT \*, (CHANGE\_DATE, 'YYYY-MM-DD HH24:MI:SS') AS FORMATED\_DATE FROM MY\_TABLE;
As you would have guessed from TO\_CHAR, I am using an Oracle so I'm using PLSQL.
So my specific question is: Is there a syntax that would allow me to select all columns (via \*) and still be able to call a function on single column within those columns. | The closest you could do is something like:
```
SELECT
MY_TABLE.*,
(CHANGE_DATE, 'YYYY-MM-DD HH24:MI:SS') AS FORMATED_DATE
FROM MY_TABLE;
``` | Rather than lecture you, here. Oracle is a little fussier than MSSQL about it, but this worked for me.
SELECT
GENERAL.GOREMAL.\*
,rownum
,current\_date
from GENERAL.GOREMAL | Select * from Table and still perform some function on a single named column | [
"",
"sql",
"select",
"plsql",
"wildcard",
"to-char",
""
] |
Why is virtual behavior being prevented?
```
class MyClass
{
//........
virtual double GetX();
virtual double GetSomethingElse();
virtual double GetT();
virtual double GetRR();
//........
};
class Processor
{
private:
typedef double (MyClass::*MemFuncGetter)();
static map<std::string, MemFuncGetter> descrToFuncMap;
public:
static void Initialize();
void Process(Myclass m, string);
};
void Processor::Initialize()
{
descrToFuncMap["X"]=&MyClass::GetX;
descrToFuncMap["SomethingElse"]=&MyClass::GetSomethingElse;
descrToFuncMap["RR"]=&MyClass::GetRR;
descrToFuncMap["T"]=&MyClass::GetT;
};
void Processor::Process(MyClass *ms, const std::string& key)
{
map<std::string, Getter>::iterator found=descrToFuncMap.find(key);
if(found!=descrToFuncMap.end())
{
MemFuncGetter memFunc=found->second;
double dResult=(ms).*memFunc();
std::cout<<"Command="<<key<<", and result="<<result<<std::end;
}
}
``` | This line here:
```
void Processor::Process(MyClass ms, const std::string& key)
```
Try replacing it with
```
void Processor::Process(MyClass &ms, const std::string& key)
```
What is happening is called [slicing](https://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c), even though you may have passed in a sub-class of MyClass, when you call Process, a new MyClass object is made on the stack using MyCLass's copy-constructor. This new object is a MyClass in everyway, including having MyClass's virtual table.
When you pass by reference, or with a pointer, no copy is made, and the reference to MyClass can be refering to an object that is really of a type SubClassOfMyClass.
Edit:
Well, the issue is with one of the many compile errors, if you get this all to compile it works just fine:
```
class MyClass
{
public:
//........
virtual double GetX() { return 0.0; }
};
class MyClass2 : public MyClass
{
public:
//........
virtual double GetX() { return 1.0; }
};
class Processor
{
public:
typedef double (MyClass::*MemFuncGetter)();
static void Initialize();
void Process(MyClass *m, const string &);
private:
static map<std::string, MemFuncGetter> descrToFuncMap;
};
void Processor::Initialize()
{
descrToFuncMap["X"]=&MyClass::GetX;
}
void Processor::Process(MyClass *ms, const std::string& key)
{
map<std::string, MemFuncGetter>::iterator found=descrToFuncMap.find(key);
if(found!=descrToFuncMap.end())
{
MemFuncGetter memFunc=found->second;
double dResult=(ms->*memFunc)();
std::cout<<"Command="<<key<<", and result="<<dResult<<std::endl;
}
}
map<std::string, Processor::MemFuncGetter> Processor::descrToFuncMap;
int main()
{
Processor::Initialize();
Processor p;
MyClass2 mc2;
p.Process(&mc2, "X");
}
```
Which outputs:
> Command=X, and result=1 | Wow I have never seen a sample piece of code have so many other syntax errors before you get to the real problem.
When posting code it should be compilable by the people you want to help.
With the exception of the ONE bug you want others to help you with.
I am not sure what you are trying to achieve but it is not virtual functions. SO you should porobably re-name your question.
I presume your main problem is with this line:
```
MemFuncGetter memFunc=found->second;
double dResult=(ms).*memFunc();
```
Depending if you accepted Josh's advice the syntax should look like this.
```
MemFuncGetter memFunc=found->second;
double dResult=(ms.*memFunc)(); // MyClass& ms
-- or
double dResult=(ms->*memFunc)(); // MyClass* ms
``` | Virtual behavior by storing pointers to member functions | [
"",
"c++",
""
] |
Given the [Python documentation](http://docs.python.org/library/threading.html) for `Thread.run()`:
> You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
I have constructed the following code:
```
class DestinationThread(threading.Thread):
def run(self, name, config):
print 'In thread'
thread = DestinationThread(args = (destination_name, destination_config))
thread.start()
```
But when I execute it, I receive the following error:
```
Exception in thread Thread-1:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner
self.run()
TypeError: run() takes exactly 3 arguments (1 given)
```
It seems I am missing something obvious, but the various examples I have seen work with this methodology. Ultimately I am trying to just pass the string and dictionary into the thread, if the Constructor is not the right way, but rather to make a new function to set the values prior to starting the thread, I am open to that.
Any suggestions on how to best accomplish this? | You really don't need to subclass Thread. The only reason the API supports this is to make it more comfortable for people coming from Java where that's the only way to do it sanely.
The pattern that we recommend you use is to pass a method to the Thread constructor, and just call `.start()`.
```
def myfunc(arg1, arg2):
print 'In thread'
print 'args are', arg1, arg2
thread = Thread(target=myfunc, args=(destination_name, destination_config))
thread.start()
``` | Here's is an example of passing arguments using threading and not extending `__init__`:
```
import threading
class Example(threading.Thread):
def run(self):
print '%s from %s' % (self._Thread__kwargs['example'],
self.name)
example = Example(kwargs={'example': 'Hello World'})
example.start()
example.join()
```
And here's an example using mutliprocessing:
```
import multiprocessing
class Example(multiprocessing.Process):
def run(self):
print '%s from %s' % (self._kwargs['example'],
self.name)
example = Example(kwargs={'example': 'Hello World'})
example.start()
example.join()
``` | Overriding python threading.Thread.run() | [
"",
"python",
"multithreading",
""
] |
I am in the process of converting several queries which were hard-coded into the application and built on the fly to parameterized queries. I'm having trouble with one particular query, which has an `in` clause:
```
UPDATE TABLE_1 SET STATUS = 4 WHERE ID IN (1, 14, 145, 43);
```
The first parameter is easy, as it's just a normal parameter:
```
MySqlCommand m = new MySqlCommand("UPDATE TABLE_1 SET STATUS = ? WHERE ID IN (?);");
m.Parameters.Add(new MySqlParameter("", 2));
```
However, the second parameter is a list of integers representing the ids of the rows that need updating. How do I pass in a list of integers for a single parameter? Alternatively, how would you go about setting up this query so that you don't have to completely build it each and every time you call it, and can prevent SQL injection attacks? | You could build up the parametrised query "on the fly" based on the (presumably) variable number of parameters, and iterate over that to pass them in.
So, something like:
```
List foo; // assuming you have a List of items, in reality, it may be a List<int> or a List<myObject> with an id property, etc.
StringBuilder query = new StringBuilder( "UPDATE TABLE_1 SET STATUS = ? WHERE ID IN ( ?")
for( int i = 1; i++; i < foo.Count )
{ // Bit naive
query.Append( ", ?" );
}
query.Append( " );" );
MySqlCommand m = new MySqlCommand(query.ToString());
for( int i = 1; i++; i < foo.Count )
{
m.Parameters.Add(new MySqlParameter(...));
}
``` | This is not possible in MySQL.
You can create a required number of parameters and do UPDATE ... IN (?,?,?,?). This prevents injection attacks (but still requires you to rebuild the query for each parameter count).
Other way is to pass a comma-separated string and parse it. | C# Parameterized Query MySQL with `in` clause | [
"",
"c#",
"mysql",
"parameters",
""
] |
I have some status data that I want to cache from a database. Any of several threads may modify the status data. After the data is modified it will be written to the database. The database writes will always be done in series by the underlying database access layer which queues database operations in a different process so I cam not concerned about race conditions for those.
Is it a problem to just modify the static data from several threads? In theory it is possible that modifications are implemented as read, modify, write but in practice I can't imagine that this is so.
My data handling class will look something like this:
```
class StatusCache
{
public:
static void SetActivityStarted(bool activityStarted)
{ m_activityStarted = activityStarted; WriteToDB(); }
static void SetActivityComplete(bool activityComplete);
{ m_activityComplete = activityComplete; WriteToDB(); }
static void SetProcessReady(bool processReady);
{ m_processReady = processReady; WriteToDB(); }
static void SetProcessPending(bool processPending);
{ m_processPending = processPending; WriteToDB(); }
private:
static void WriteToDB(); // will write all the class data to the db (multiple requests will happen in series)
static bool m_activityStarted;
static bool m_activityComplete;
static bool m_processReady;
static bool m_processPending;
};
```
I don't want to use locks as there are already a couple of locks in this part of the app and adding more will increase the possibility of deadlocks.
It doesn't matter if there is some overlap between 2 threads in the database update, e.g.
```
thread 1 thread 2 activity started in db
SetActivityStarted(true) SetActivityStarted(false)
m_activityStated = true
m_activityStarted = false
WriteToDB() false
WriteToDB() false
```
So the db shows the status that was most recently set by the m\_... = x lines. This is OK.
Is this a reasonable approach to use or is there a better way of doing it?
[Edited to state that I only care about the last status - order is unimportant] | No, it's not safe.
The code generated that does the writing to m\_activityStarted and the others may be atomic, but that is not garantueed. Also, in your setters you do two things: set a boolean and make a call. That is definately not atomic.
You're better off synchronizing here using a lock of some sort.
For example, one thread may call the first function, and before that thread goes into "WriteDB()" another thread may call another function and go into WriteDB() without the first going there. Then, perhaps the status is written in the DB in the wrong order.
If you're worried about deadlocks then you should revise your whole concurrency strategy. | You never know exactly how things are implemented at the lower levels. Especially when you start dealing with multiple cores, the various cache levels, pipelined execution, etc. At least not without a lot of work, and implementations change frequently!
If you don't mutex it, eventually you will regret it!
My favorite example involves integers. This one particular system wrote its integer values in two writes. E.g. not atomic. Naturally, when the thread was interrupted between those two writes, well, you got the upper bytes from one set() call, and the lower bytes() from the other. A classic blunder. But far from the worst that can happen.
Mutexing is trivial.
You mention: ***I don't want to use locks as there are already a couple of locks in this part of the app and adding more will increase the possibility of deadlocks.***
You'll be fine as long as you follow the golden rules:
* Don't mix mutex lock orders. E.g. A.lock();B.lock() in one place and B.lock();A.lock(); in another. Use one order or the other!
* Lock for the briefest possible time.
* Don't try to use one mutex for multiple purposes. Use multiple mutexes.
* Whenever possible use recursive or error-checking mutexes.
* Use RAII or macros to insure unlocking.
E.g.:
```
#define RUN_UNDER_MUTEX_LOCK( MUTEX, STATEMENTS ) \
do { (MUTEX).lock(); STATEMENTS; (MUTEX).unlock(); } while ( false )
class StatusCache
{
public:
static void SetActivityStarted(bool activityStarted)
{ RUN_UNDER_MUTEX_LOCK( mMutex, mActivityStarted = activityStarted );
WriteToDB(); }
static void SetActivityComplete(bool activityComplete);
{ RUN_UNDER_MUTEX_LOCK( mMutex, mActivityComplete = activityComplete );
WriteToDB(); }
static void SetProcessReady(bool processReady);
{ RUN_UNDER_MUTEX_LOCK( mMutex, mProcessReady = processReady );
WriteToDB(); }
static void SetProcessPending(bool processPending);
{ RUN_UNDER_MUTEX_LOCK( mMutex, mProcessPending = processPending );
WriteToDB(); }
private:
static void WriteToDB(); // read data under mMutex.lock()!
static Mutex mMutex;
static bool mActivityStarted;
static bool mActivityComplete;
static bool mProcessReady;
static bool mProcessPending;
};
``` | Is it practically safe to write static data from multiple threads | [
"",
"c++",
"multithreading",
""
] |
In our legacy code, as well as our modern code, we use macros to perform nifty solutions like code generations, etc. And we make use of both the `#` and `##` operators.
I am curious how other developers use macros to do cool things, if they use them at all. | In C, it's common to define macros that do some stuff getting the verbatim argument, and at the same time define functions to be able to get the address of it transparently.
```
// could evaluate at compile time if __builtin_sin gets
// special treatment by the compiler
#define sin(x) __builtin_sin(x)
// parentheses avoid substitution by the macro
double (sin)(double arg) {
return sin(arg); // uses the macro
}
int main() {
// uses the macro
printf("%f\n", sin(3.14));
// uses the function
double (*x)(double) = &sin;
// uses the function
printf("%f\n", (sin)(3.14));
}
``` | There is also the X Macro idiom which can be useful for DRY and simple code generation :
One defines in a header gen.x a kind of table using a **not yet defined** macro :
```
/** 1st arg is type , 2nd is field name , 3rd is initial value , 4th is help */
GENX( int , "y" , 1 , "number of ..." );
GENX( float , "z" , 6.3 , "this value sets ..." );
GENX( std::string , "name" , "myname" , "name of ..." );
```
Then he can use it in different places defining it for each #include with a usually different definition :
```
class X
{
public :
void setDefaults()
{
#define GENX( type , member , value , help )\
member = value ;
#include "gen.x"
#undef GENX
}
void help( std::ostream & o )
{
#define GENX( type , member , value , help )\
o << #member << " : " << help << '\n' ;
#include "gen.x"
#undef GENX
}
private :
#define GENX( type , member , value , help )\
type member ;
#include "gen.x"
#undef GENX
}
``` | What are some tricks I can use with macros? | [
"",
"c++",
"c",
"c-preprocessor",
"stringification",
""
] |
I want to know how to program a 2D RPG game in C++ with SDL.
I have searched, but was unable to find anything good. Many of the articles were too basic and didn't delve into anything practical. Can anyone help give me some articles, free books or other resources so I can learn how to program a RPG using C++ and SDL?
EDIT:
I don't need documentation of SDL. I'm programming a RPG Game with SDL, and I need some examples that help me in this task. | Do you have examples of articles that are too simple?
Are these too simple: [devshed](http://www.devshed.com/c/a/Multimedia/Game-Programming-using-SDL-Getting-Started/) or [gpwiki](http://gpwiki.org/index.php/C:SDL_tutorials) ?
You might consider studying the topics separately. For example Bruce Eckels has, IMO, the best C++ books, "Thinking in C++ I & II" that will take you from novice to expert (including SQA techniques like unit testing) and they are available for [free.](http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html)
I've found that C++ is a harsh mistress and if you aren't prepared for the language, no tutorial specific to 'SDL and Games' will help much - this is true for any other advanced libraries, toolkits, etc. | Programming an RPG game isn't any different than programming any other game.
If you understand RPG's and you have a fully formed idea of what you want to do, then you use the same techniques that you would use working on any game.
Google is your friend here, use it to do the research to gain the skills you need. | How to program a RPG game in C++ with SDL? | [
"",
"c++",
"sdl",
""
] |
If I have a util class with static methods that will call Hibernate functions to accomplish basic data access. I am wondering if making the method `synchronized` is the right approach to ensure thread-safety.
I want this to prevent access of info to the same DB instance. However, I'm now sure if the following code are preventing `getObjectById` being called for all Classes when it is called by a particular class.
```
public class Utils {
public static synchronized Object getObjectById (Class objclass, Long id) {
// call hibernate class
Session session = new Configuration().configure().buildSessionFactory().openSession();
Object obj = session.load(objclass, id);
session.close();
return obj;
}
// other static methods
}
``` | By using synchronized on a static method lock you will [synchronize the class methods and attributes](https://stackoverflow.com/questions/437620/java-synchronized-methods-lock-on-object-or-class/437627#437627) ( as opposed to instance methods and attributes )
So your assumption is correct.
> *I am wondering if making the method synchronized is the right approach to ensure thread-safety.*
Not really. You should let your RDBMS do that work instead. They are good at this kind of stuff.
The only thing you will get by synchronizing the access to the database is to make your application terribly slow. Further more, in the code you posted you're building a Session Factory each time, that way, your application will spend more time accessing the DB than performing the actual job.
Imagine the following scenario:
Client A and B attempt to insert different information into record X of table T.
With your approach the only thing you're getting is to make sure one is called after the other, when this would happen anyway in the DB, because the RDBMS will prevent them from inserting half information from A and half from B at the same time. The result will be the same but only 5 times ( or more ) slower.
Probably it could be better to take a look at the ["Transactions and Concurrency"](http://www.hibernate.org/hib_docs/v3/reference/en-US/html/transactions.html) chapter in the Hibernate documentation. Most of the times the problems you're trying to solve, have been solved already and a much better way. | To address the question more generally...
Keep in mind that using synchronized on methods is really just shorthand (assume class is `SomeClass`):
```
synchronized static void foo() {
...
}
```
is the same as
```
static void foo() {
synchronized(SomeClass.class) {
...
}
}
```
and
```
synchronized void foo() {
...
}
```
is the same as
```
void foo() {
synchronized(this) {
...
}
}
```
You can use any object as the lock. If you want to lock subsets of static methods, you can
```
class SomeClass {
private static final Object LOCK_1 = new Object() {};
private static final Object LOCK_2 = new Object() {};
static void foo() {
synchronized(LOCK_1) {...}
}
static void fee() {
synchronized(LOCK_1) {...}
}
static void fie() {
synchronized(LOCK_2) {...}
}
static void fo() {
synchronized(LOCK_2) {...}
}
}
```
(for non-static methods, you would want to make the locks be non-static fields) | How do synchronized static methods work in Java and can I use it for loading Hibernate entities? | [
"",
"java",
"multithreading",
"hibernate",
"concurrency",
"synchronization",
""
] |
I need to convert the IL to c# code.
I have an assembly and I am reading this assembly.
I get MethodBody from MethodInfo and the methodbody has a method GetILAsByteArraY()
which returns a byte array now I want to convert this IL to C# code.
Please help me out in solving this. | Don't reinvent the wheel; use Lutz Roeder's [.NET Reflector](http://www.red-gate.com/products/reflector/). | The Lutz Roeder reflector was purchased and is no longer available for free download.
There is now a free (once again) tool called [**ILSpy**](https://github.com/icsharpcode/ILSpy). I've found it to be very good, and it will not only generate C# code from IL but will also create a `.csproj` project if decompiling an entire DLL assembly. | Converting IL to C# code | [
"",
"c#",
".net",
""
] |
Can you help me refactor this code:
```
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode()==39)
{
//Right arrow key code
}
else if (e.getKeyCode()==37)
{
//Left arrow key code
}
repaint();
}
```
Please mention how to check for up/down arrow keys as well.Thanks! | ```
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
switch( keyCode ) {
case KeyEvent.VK_UP:
// handle up
break;
case KeyEvent.VK_DOWN:
// handle down
break;
case KeyEvent.VK_LEFT:
// handle left
break;
case KeyEvent.VK_RIGHT :
// handle right
break;
}
}
``` | ```
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT ) {
//Right arrow key code
} else if (e.getKeyCode() == KeyEvent.VK_LEFT ) {
//Left arrow key code
} else if (e.getKeyCode() == KeyEvent.VK_UP ) {
//Up arrow key code
} else if (e.getKeyCode() == KeyEvent.VK_DOWN ) {
//Down arrow key code
}
repaint();
}
```
The KeyEvent codes are all a part of the API: <http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html> | How to check if the key pressed was an arrow key in Java KeyListener? | [
"",
"java",
"events",
""
] |
I'm wondering if you can put the main class (or the class with the init method, whatever) inside a package and still have it run in a browser? Most of the time I put my applets into the (default package) but my applet here is in a package, so can I still embed it into the webpage?
I've googled it with little results. Say I've got `MyApplet.class` in a directory called `app` in the jar file called `MyApp.jar`.
I've tried these with no success:
```
<applet archive="MyApp.jar" code="MyApplet.class">
<applet archive="MyApp.jar" code="app/MyApplet.class">
<applet archive="MyApp.jar" code="/app/MyApplet.class">
<applet archive="MyApp.jar/app/" code="MyApplet.class">
<applet archive="MyApp.jar" codebase="app/" code="MyApplet.class">
```
Each of these gives me a ClassNotFoundException.
Thanks in advance. | The archive attribute should contain the file name of the jar, and it should be placed in the same directory as the web page.
The class file in the code attribute should contain the fully qualified class name separated by forward slashes to indicate the directory structure.
Therefore, in your list of trials attempted, trial 2 should succeed, provided that MyApp.jar is actually present along side the html page. Additionally, MyApp.jar should contain the 'app' directory in the root, which should contain the MyApplet classfile. Don't forget to have MyApplet class itself in the app package.
You could take a look at [this page](http://www.math.gatech.edu/~carlen/applets/archived/ClassFiles/Basins.html) for reference. | Well you list the package in a dotted form and you don't put the '.class' on the end.
```
<applet code="packagefolder1.packagefolder2.MyApplet" archive="folder1/folder2/MyApp.jar">
</applet>
``` | Java applet with init() in a package? | [
"",
"java",
"applet",
""
] |
I have a html table and I want to freeze the header row th tag for scrolling the data. How I can do that? Does I need to use the Dom?
Thanks !! | My solution is to use two tables and fix the column widths. The lower table is in a scrollable div and has no header. | If you take Accessibility seriously, two tables is not the way to go since it breaks rules.
There are ways to do it in pure CSS, but it is a headache to get it to work in all browsers. There are a few examples out on the net, but they do not all work 100% with IE without tweaks.
I am currently working on a CSS only version, this is getting pretty close: <http://www.coderanch.com/t/431995/HTML-JavaScript/Table-with-fixed-header-scolling#1918825>
Does not work in IE8rc1 yet, IE6/7 has a border issue and you have to live with the scrollbar looking different in FF vs IE. | Freeze TH header and scrolling data | [
"",
"javascript",
"jquery",
"html",
""
] |
What is the best way to keep the user logged in when something like "third-party" cookies are disabled. I currently have a Facebook connect app (in only PHP) that works great when I have that checked in Firefox, but redirects to my login page when it's unchecked. Even Facebook's own sample application ([therunaround](http://www.somethingtoputhere.com/therunaround/index.php)) has the same problem with this unchecked so I'm wondering if there's no way around the issue.
**Edit:**
@codege3k
Tried a bunch of p3p headers. No dice so far. I've got a login page that redirects to my index when the user "connects" ... the first load, I'm able to get the user id from `get_loggedin_user()` but when I refresh, that function returns null. The cookies exist, and when I go back to the login page and click connect again it doesn't prompt me for a login, so I know it's partly working. With "third-party cookies" turned on in Firefox, it works like a charm.
**Edit:**
What is the best way to handle facebook connect in the context of a user login then if third party cookies is not widely supported? Should I just use the initial login that works and set a local cookie for my own site and use that instead of checking the facebook status every time? | Ok, promoting the session seems to work.
```
$fbUserId = self::$facebook->get_loggedin_user();
if ($fbUserId)
{
self::$facebook->promote_session();
return $fbUserId;
}
```
**Edit:**
So this gets the session on every request, but essentially, third party cookies must be enabled for Facebook Connect to work as expected. From their docs:
> The user's browser must be set to
> accept 3rd Party Cookies in order for
> it to stay connected between clicks.
Source: <http://wiki.developers.facebook.com/index.php/Logging_In_And_Connecting> | I had a similar issue with 3rd party cookies. Check this [question](https://stackoverflow.com/questions/540926/ie7-iframe-blank-page) and see if it resolves
It can be solved by adding p3p headers. | Facebook connect and third-party cookies? | [
"",
"php",
"cookies",
"facebook",
""
] |
When I create a library on Linux, I use this method:
1. Build: libhelloworld.so.1.0.0
2. Link: libhelloworld.so.1.0.0 libhelloworld.so
3. Link: libhelloworld.so.1.0.0 libhelloworld.so.1
The versioning is so that if you change the public facing methods, you can build to libhelloworld.so.2.0.0 for example (and leave 1.0.0 where it is), so that applications using the old library won't break.
However, what's the point in naming it 1.0.0 - why not just stick with libhelloworld.so and libhelloworld.so.1?
**Also**, is it best practice to name your library using 1.0.0 for example, or just 1?
```
g++ ... -Wl,-soname,libhelloworld.1
```
Or:
```
g++ ... -Wl,-soname,libhelloworld.1.0.0
``` | From an old email I sent to a colleague about this question:
Let's look at libxml as an example. First of all, shared
objects are stored in /usr/lib with a series of symlinks to represent
the version of the library availiable:
```
lrwxrwxrwx 1 root root 16 Apr 4 2002 libxml.so -> libxml.so.1.8.14
lrwxrwxrwx 1 root root 16 Apr 4 2002 libxml.so.1 -> libxml.so.1.8.14
-rwxr-xr-x 1 root root 498438 Aug 13 2001 libxml.so.1.8.14
```
If I'm the author of libxml and I come out with a new version, libxml
2.0.0 that breaks interface compatiblity with the previous version, I
can install it as libxml.so.2, and libxml.so.2.0.0. Note that it is
up to the application programmer to be responsible about what he links
to. If I'm really anal, I can link directly to libxml.so.1.8.14 and
any other version will result in my program not running. Or I can
link against libxml.so.1 and hope that the libxml developer doesn't
break symbol compatibility on me in the 1.X version. Or if you don't
care and are reckless, just link to libxml.so and get whatever version
there is. Sometimes, when enough people do this, the library author
has to get creative with later versions. Hence, libxml2:
```
lrwxrwxrwx 1 root root 17 Apr 4 2002 libxml2.so.2 -> libxml2.so.2.4.10
-rwxr-xr-x 1 root root 692727 Nov 13 2001 libxml2.so.2.4.10
```
Note that there's no libxml2.so in this one. Looks like the developer
got fed up with irresponsible application developers. | ## Library naming conventions
According to [Wheeler](http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html), we have the `real name`, the `soname` and the `linker name`:
```
Real name libfoo.so.1.2.3
Soname libfoo.so.1
Linker name libfoo.so
```
The `real name` is the name of the file containing the actual library code. The `soname` is usually a symbolic link to the `real name`, and its number is incremented when the interface changes in an incompatible way. Finally, the `linker name` is what the linker uses when requesting a library, which is the soname without any version number.
So, to answer your last question first, you should use the `soname`, `libhelloworld.so.1`, for the linker option [when creating the shared library](http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html#AEN95):
```
g++ ... -Wl,-soname,libhelloworld.so.1 ...
```
[In this document](http://man7.org/conf/lca2006/shared_libraries/slide6.html), Kerrisk provides a very brief example on how to create a shared library using standard naming conventions. I think both [Kerrisk](http://man7.org/conf/lca2006/shared_libraries/index.html) and [Wheeler](http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html) are well worth a read if you want to know more about Linux libraries.
## Library numbering conventions
There is some confusion regarding the intent and purpose of each of the numbers in the `real name` of the library. I personally think that the [Apache Portable Runtime Project](http://apr.apache.org/versioning.html) does a good job of explaining the rules for when each number should be incremented.
In short, the versioning numbers can be thought of as `libfoo.MAJOR.MINOR.PATCH`.
* `PATCH` is incremented for changes that are both forwards and backwards compatible with other versions.
* `MINOR` should be incremented if the new version of the library is source and binary compatible with the old version. Different minor versions are backwards compatible, but not necessarily forwards compatible, with each other.
* `MAJOR` is incremented when a change is introduced that breaks the API, or is otherwise incompatible with the previous version.
What this means is that `PATCH` releases may only differ internally, for example in the way a function is implemented. Changing the API, the signature of public functions, or the interpretation of function parameters is **not allowed**.
A new `MINOR` release may introduce new functions or constants, and deprecate existing functions, but **may not remove** anything that is externally exposed. This ensures *backwards compatibility*. In other words, a minor release `1.12.3` may be used to replace any other `1.12.x` *or earlier* version, such as `1.11.2` or `1.5.0`. It is not a drop in replacement for `1.16.1` though, since different minor versions are not necessarily *forward compatible*.
Any kind of change can be made with the release of a new `MAJOR` version; constants may be removed or changed, (deprecated) functions may be removed, and of course, any changes that would normally increment the `MINOR` or `PATCH` number (though it might be worth it to backport such changes to the previous `MAJOR` version also).
Of course, there are factors that can complicate this further; you might have developed your library so that the same file may [hold multiple versions simultaneously](https://docs.google.com/viewer?url=http://people.redhat.com/drepper/dsohowto.pdf&embedded=true#:0.page.36), or you might use `libtool`'s convention of `current:revision:age`. But that's a discussion for another time. :) | Can someone explain Linux library naming? | [
"",
"c++",
"linux",
"shared-libraries",
""
] |
i have to work away from my desktop computer from time to time (for instance on trips). It is a low end laptop. I can use Eclipse but it is awfully slow.
Is there a better choice? If possible not something like vi oder emacs.
Laptop:
512 MB DDR RAM
Intel Pentium M 760 2.0 GHz
Windows XP SP3
There is no possibility to add more RAM | How low end is it? I used to use [IntelliJ Idea](http://www.jetbrains.com/idea/) and loved, it also ran faster than eclipse for me. [DrJava](http://drjava.sourceforge.net/) is also very small and light weight. But personally I prefer vim + javac the best. :) | Netbeans is a little less sluggish than Eclipse, but it's a huge memory hog.
Emacs is always a fine choice too. | What is a good IDE for Java programming on a low end laptop? | [
"",
"java",
"windows",
"ide",
""
] |
I've asked few people why using xml as a parameter in stored procedure doesn't work and everyone said , that's just the way it is. I can't belive that.
```
command.Parameters.Add("@xmldoc", SqlDbType.Xml);
```
That's where compiler returns error and I can't use NVarChar beacouse it's limiteed to 4k sings. XML would be perfect as it can be 2gigs big.
How come other SqlDbTypes work well and this one retruns error ?
\*
> Error: Specified argument was out of
> the range of valid values. Parameter
> name: @xmldoc: Invalid SqlDbType
> enumeration value: 25.
\* | It does work. You will have to set up the Value as SqlXml and not a string, but it can be done. Imagine this table:
```
CREATE TABLE XmlTest
(
[XmlTestId] [int] identity(1,1) primary key,
[XmlText] [xml] NOT NULL
)
```
And the sproc:
```
CREATE PROCEDURE XmlTest_Insert
(
@XmlText xml
)
AS
INSERT INTO XmlTest (XmlText)
VALUES (@XmlText)
```
Now picture a console application that looks like this:
```
using System.Data.SqlClient;
using System.Data;
using System.Data.SqlTypes;
using System.Xml;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
string xmlDoc = "<root><el1>Nothing</el1></root>";
string connString = "server=(local);database=IntroDB;UID=sa;PWD=pwd";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("XmlTest_Insert", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter("@XmlText", SqlDbType.Xml);
param.Value = new SqlXml(new XmlTextReader(xmlDoc
, XmlNodeType.Document, null));
cmd.Parameters.Add(param);
conn.Open();
cmd.ExecuteNonQuery();
conn.Dispose();
}
}
}
```
Bingo!
This was done in Visual Studio 2008 (.NET 3.5), but I am fairly sure it should work in Visual Studio 2005 (2.0 Framework), as well. | Instead of using the Add Method, try using AddWithValue where you do not need to specify the type just the name and the value. Unless you are using a different direction to input? | C#/SQL - What's wrong with SqlDbType.Xml in procedures? | [
"",
"c#",
"xml",
"stored-procedures",
"sql-server-ce",
"compact-framework",
""
] |
In PHP, I want to encode ampersands that have not already been encoded. I came up with this regex
```
/&(?=[^a])/
```
It seems to work good so far, but seeing as how I'm not much of a regex expert, I am asking if any potential pitfalls can be seen in this regex?
Essentially it needs to convert `&` to `&` but leave the `&` in `&` as is (so as not to get `&amp;`)
Thanks
## Update
Thanks for the answers. It seems I wasn't *thinking* broadly enough to cover all bases. This seems like a common pitfall of regexs themselves (having to think of all possibilities which may make your regex get false positives). It sure does beat my original one `str_replace(' & ', ' & ', $string);` :) | Even better would be [negative lookahead assertion](http://www.perl.com/doc/manual/html/pod/perlre.html#item__pattern_) to verify & isn't followed by amp;
```
/&(?!amp;)/
```
Though that will change any ampersands used for *other* entities. If you're likely to have others, then how about something like
```
/&(?!#?[a-zA-Z0-9]+;)/
```
This will look for an ampersand, but asserting that it is NOT followed by an optional hash symbol (for numeric entities), a series of alphanumerics and a semicolon, which should cover [named and numeric entities](http://www.w3schools.com/tags/ref_entities.asp) like `"e;` or `ª`
## Test code
```
$text="It’s 30 ° outside & very hot. T-shirt & shorts needed!";
$text=preg_replace('/&(?!#?[a-z0-9]+;)/', '&', $text);
echo "$text\n";
```
Which will output
```
It’s 30 ° outside & very hot. T-shirt & shorts needed!
```
which is more easily read as *"It’s 30 ° outside & very hot. T-shirt & shorts needed!"*
## Alternative for PHP 5.2.3+
As Ionut G. Stan points out below, from PHP 5.2.3 you can use [htmlspecialchars](http://php.net/htmlspecialchars) with a fourth parameter of *false* to prevent double-encoding, e.g.
```
$text=htmlspecialchars($text,ENT_COMPAT,"UTF-8",false);
``` | It will apply it for any other encoded char. | Any pitfalls with this regex that matches ampersands not already encoded | [
"",
"php",
"regex",
""
] |
SQLite version 3.4.0
What's wrong with aggregate functions? Additionally, I suspect that ORDER BY won't work as well. How to rewrite this?
```
sqlite> SELECT p1.domain_id, p2.domain_id, COUNT(p1.domain_id) AS d1, COUNT(p2.domain_id) AS d2
...> FROM PDB as p1, Interacting_PDBs as i1, PDB as p2, Interacting_PDBs as i2
...> WHERE p1.id = i1.PDB_first_id
...> AND p2.id = i2.PDB_second_id
...> AND i1.id = i2.id
...> AND d1>100
...> AND d2>100
...> ORDER BY d1, d2;
SQL error: misuse of aggregate:
sqlite>
``` | When using an aggregate function (sum / count / ... ), you also have to make use of the GROUP BY clause.
Next to that, when you want to filter on the result of an aggregate , you cannot do that in the WHERE clause, but you have to do that in the HAVING clause.
```
SELECT p1.domain_id, p2.domain_id, COUNT(p1.domain_id) AS d1, COUNT(p2.domain_id) AS d2
FROM PDB as p1, Interacting_PDBs as i1, PDB as p2, Interacting_PDBs as i2
WHERE p1.id = i1.PDB_first_id
AND p2.id = i2.PDB_second_id
AND i1.id = i2.id
GROUP BY p1.domain_Id, p2.domain_Id
HAVING d1 > 100 AND d2 > 100
ORDER BY d1, d2;
``` | Short-version fix for this is:
When you're using function like `COUNT/SUM`, you need to use `HAVING` instead of `WHERE`. | SQL error: misuse of aggregate | [
"",
"sql",
"sqlite",
""
] |
Which was the first version of python to include the [else clause for for loops](http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops)?
I find that the python docs usually does a good job of documenting when features were added, but I can't seem to find the info on this feature.
(It doesn't help that 'for' and 'else' are particularly difficult terms to google for on a programming website) | It's been present since the beginning. To see that, get the source from alt.sources, specifically the message titled "[Python 0.9.1 part 17/21](http://groups.google.com/group/alt.sources/browse_thread/thread/74a577bbcfc4be0a/cbaaec4fbfebbbb6)". The date is Feb 21, 1991. This post included the grammar definition, which states:
```
for_stmt: 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
```
You might be able to find the 0.9.0 sources if you try harder than I did, but as the first public release was 0.9.0 on 20 Feb, that would get you back one day. The 0.9.1 release was a minor patch that did not affect this part of the grammar.
(Is that a [UTSL](http://catb.org/jargon/html/U/UTSL.html) reference or what? When was the last time *you* looked at a shar file? ;)
BTW, I reconstructed the original source and tweaked it a bit to compile under gcc-4.0 on my OS X 10.4 box. [Details](http://www.dalkescientific.com/writings/diary/archive/2009/03/27/python_0_9_1p1.html) for those interested few, including [python-0.9.1.tar.gz](http://dalkescientific.com/Python/python-0.9.1.tar.gz).
The entire development history is available from version control, even after changing version control systems twice. "hg log -p -r 6:7" from the cpython Mercurial archive shows that the "for/else" was committed on Sun Oct 14 12:07:46 1990 +0000, and the previous commit was Sat Oct 13 19:23:40 1990 +0000. for/else has been part of Python since October 1990. | It's been around since at least [1.4](http://www.python.org/doc/1.4/ref/ref7.html#HDR2), which is the [oldest version of the documentation](http://www.python.org/doc/versions/) I know of. | Which version of python added the else clause for for loops? | [
"",
"python",
"for-loop",
""
] |
In my experience, `input type="text"` `onchange` event usually occurs only after you leave (`blur`) the control.
Is there a way to force browser to trigger `onchange` every time `textfield` content changes? If not, what is the most elegant way to track this “manually”?
Using `onkey*` events is not reliable, since you can right-click the field and choose Paste, and this will change the field without any keyboard input.
Is `setTimeout` the only way?.. Ugly :-) | ***Update:***
See [Another answer](https://stackoverflow.com/questions/574941/best-way-to-track-onchange-as-you-type-in-input-type-text/26202266#26202266) (2015).
---
*Original 2009 Answer:*
So, you want the `onchange` event to fire on keydown, blur, *and* paste? That's magic.
If you want to track changes as they type, use `"onkeydown"`. If you need to trap paste operations with the mouse, use `"onpaste"` ([IE](http://msdn.microsoft.com/en-us/library/ms536955(VS.85,loband).aspx), [FF3](https://developer.mozilla.org/En/DOM/Element.onpaste)) and `"oninput"` ([FF, Opera, Chrome, Safari](http://help.dottoro.com/ljhxklln.php)1).
1Broken for `<textarea>` on Safari. Use [`textInput`](http://help.dottoro.com/ljhiwalm.php) instead | **These days listen for [`oninput`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput).** It feels like [`onchange`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onchange) without the need to lose focus on the element. It is HTML5.
It’s supported by everyone (even mobile), except IE8 and below. For IE add `onpropertychange`. I use it like this:
```
const source = document.getElementById('source');
const result = document.getElementById('result');
const inputHandler = function(e) {
result.innerText = e.target.value;
}
source.addEventListener('input', inputHandler);
source.addEventListener('propertychange', inputHandler); // for IE8
// Firefox/Edge18-/IE9+ don’t fire on <select><option>
// source.addEventListener('change', inputHandler);
```
```
<input id="source">
<div id="result"></div>
``` | Best way to track onchange as-you-type in input type="text"? | [
"",
"javascript",
"html",
"forms",
""
] |
I have a PHP form for uploading files and it works fine and displays an error message if something went wrong. This is all good.
The problem is when I test with a really big file, it just refreshes the page as if I hadn't sent a file at all, and none of the $\_POST variables from the form are even sent to the server.
I want to display an error to the user, letting them know that the file is too big. However, I can't do this.
Does anyone know what is happening? | Check your PHP ini file, which governs how large a file PHP will allow to be uploaded. These variables are important:
* max upload filesize (upload\_max\_filesize)
* max post data size (post\_max\_size)
* memory limit (memory\_limit)
Any uploads outside these bounds will be ignored or errored-out, depending on your settings.
This section in the docs has the best summary: <https://www.php.net/manual/en/features.file-upload.common-pitfalls.php>
EDIT: Also note that most browsers won't send uploads over 2GB in size. This link is outdated, but gives an idea: <http://www.motobit.com/help/scptutl/pa98.htm>. Anyone have a better source of info on this?
There are also limits that can be imposed by the server, such as Apache: <http://httpd.apache.org/docs/2.2/mod/core.html#limitrequestbody>
To truly see what's going on, you should probably check your webserver logs, check the browser upload limit (if you're using firefox), and try seeing if `print_r($_FILES)` generates any useful error numbers. If all else fails, try the net traffic monitor in firebug. The key is to determine if the request is even going to the server, and if it is what the request (including headers) looks like. Once you've gotten that far in the chain, then you can go back and see how PHP is handling the upload. | Your $\_POST is most likely empty because the upload exceeded the *post\_max\_size* directive:
From PHP's [directives page](https://www.php.net/ini.core):
> If the size of post data is greater
> than post\_max\_size, **the $\_POST
> and $\_FILES superglobals are empty**.
> This can be tracked in various ways,
> e.g. by passing the $\_GET variable to
> the script processing the data, i.e.
> `<form action="edit.php?processed=1">`, and
> then checking if $\_GET['processed']
> is set. | No error when uploading a really big file in PHP? | [
"",
"php",
"upload",
""
] |
Is it possible to import css stylesheets into a html page using Javascript? If so, how can it be done?
P.S the javascript will be hosted on my site, but I want users to be able to put in the `<head>` tag of their website, and it should be able to import a css file hosted on my server into the current web page. (both the css file and the javascript file will be hosted on my server). | Here's the "old school" way of doing it, which hopefully works across all browsers. In theory, you would use `setAttribute` unfortunately IE6 doesn't support it consistently.
```
var cssId = 'myCss'; // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://website.example/css/stylesheet.css';
link.media = 'all';
head.appendChild(link);
}
```
This example checks if the CSS was already added so it adds it only once.
Put that code into a JavaScript file, have the end-user simply include the JavaScript, and make sure the CSS path is absolute so it is loaded from your servers.
# VanillaJS
Here is an example that uses plain JavaScript to inject a CSS link into the `head` element based on the filename portion of the URL:
```
<script type="text/javascript">
var file = location.pathname.split( "/" ).pop();
var link = document.createElement( "link" );
link.href = file.substr( 0, file.lastIndexOf( "." ) ) + ".css";
link.type = "text/css";
link.rel = "stylesheet";
link.media = "screen,print";
document.getElementsByTagName( "head" )[0].appendChild( link );
</script>
```
Insert the code just before the closing `head` tag and the CSS will be loaded before the page is rendered. Using an external JavaScript (`.js`) file will cause a Flash of unstyled content ([FOUC](http://en.wikipedia.org/wiki/Flash_of_unstyled_content)) to appear. | If you use jquery:
```
$('head').append('<link rel="stylesheet" type="text/css" href="style.css">');
``` | How to load up CSS files using Javascript? | [
"",
"javascript",
"html",
"css",
"dhtml",
""
] |
I'm researching the idea of building a super-small (preferably PHP) web app, which will serve (among other things) as a minimal front-end to a git repository.
**Any library/article for reading a git repository** (".git" folder) **without having to execute the "git" process?** I'm looking for an API to manage a git repository. I'm only interested in basic functions, such as reading last commits (name of commiter, commit note, date), displaying and traversing branches...
Thanks,
ANaimi | Would [this](http://www.kernel.org/pub/software/scm/git/docs/technical/api-index.html) (git API documents) be of any help?
Here's a list of resources about extending php (i.e. to to provide wrappers around other library code):
* [extending php - an overview](http://www.whenpenguinsattack.com/2006/11/15/how-to-write-php-extensions/)
* [writing php extension modules in C](http://www.php.net/~wez/extending-php.pdf)
* [PHP extension writing](http://talks.somabo.de/200707_extension_writing.pdf)
* [writing extensions](http://www.tuxradar.com/practicalphp/20/0/0)
* [Practical PHP Programming:Writing extensions](http://www.ipbwiki.com/Practical_PHP_Programming:Writing_extensions)
* [Extending PHP: examples](http://people.apache.org/~nabeel/php/examples/index.html)
* [Writing a PHP Extension](http://talks.php.net/show/extending-php-apachecon2003)
* [Extension Writing Part I: Introduction to PHP and Zend](http://devzone.zend.com/node/view/id/1021)
* [Zend API: Hacking the Core of PHP](http://de.php.net/manual/en/internals2.ze1.zendapi.php)
* [PHP at the Core: A Hacker's Guide to the Zend Engine](http://de.php.net/manual/en/internals2.php)
* [Creating a PHP5 Extension with MS VC++ 2005](http://blog.slickedit.com/?p=128)
* [Writing a PHP Extension (C++)](http://www.cstruter.com/articles/replyarticle.aspx?ContentID=151)
Also, these would seem relevant, too:
* [git-php](http://code.google.com/p/git-php/)
* [git library?](http://aseigo.blogspot.com/2009/01/git-library.html)
* [Pure-Python Git Library](https://launchpad.net/dulwich)
* [Git library?](http://kerneltrap.org/mailarchive/git/2008/4/28/1638484)
* [libgit2 - a true git library](http://kerneltrap.org/mailarchive/git/2008/10/31/3880864) & [libgit2 source code at GitHub](https://github.com/libgit2/libgit2)
* [php-git, a libgit2 binding](https://github.com/libgit2/php-git)
* [ActionScript3 git library](http://thillerson.blogspot.com/2008/05/as3-git-library.html) | You may also want to check out the [Cgit](http://hjemli.net/git/cgit/) project since they've done something similar (except they build their own git library -- also to avoid running `git` directly).
There's [JGit](http://www.jgit.org/), a pure Java implementation, that may be useful to you. | Reading a Git repository, without Git | [
"",
"php",
"git",
"version-control",
""
] |
Is it built-in in [Sphinx](http://sphinx.pocoo.org/)? | It look like Sphinx contains own search engine for English language. See <http://sphinx.pocoo.org/_static/searchtools.js> and searchindex.js/.json (see [Sphinx docs index](http://sphinx.pocoo.org/searchindex.js) 36Kb, [Python docs index](http://docs.python.org/searchindex.js) 857Kb, and [Grok docs](http://grok.zope.org/doc/dev/searchindex.json) 37Kb).
Index is being precomputed when docs are generated.
When one searches, static page is being loaded and then \_static/searchtools.js extract search terms from query string, normalizes (case, stemming, etc.) them and looks up in searchindex.js as it is being loaded.
First search attempt takes rather long time, consecutive are much faster as index is cached in your browser. | The Sphinx search engine is built in Javascript. It uses *JQuery* and a *(sometimes very big)* javascript file containing the search terms. | What's the search engine used in the new Python documentation? | [
"",
"python",
"python-sphinx",
""
] |
how would one go about writing the contents of a structure in C++ to a text file? What I want to do is, say I have a structure called A, with data members A.one, A.two, and so on, and I want to write them out line by line into a text file, like so
Structure A
A.one = value
A.two = value
...
Structure B
B.one = value
B.two = value
Basically I want to make a dump.. Is there an easy way to do this? What's the best I/O method for this? CFile? iostream? Thanks.. Is there an easier way to dump all of the values of member data of a class?
---
EDIT: Crap, thanks guys.. | No reflection in C++, so you have to do it manually, eg (using iostream, for simplicty):
```
dump_A(std::cout, "A", a);
void dump_A(std::iostream& os, const char* name, A const& a)
{
os << "Structure " << name << '\n'
<< name << ".one = " << a.one << '\n'
<< name << ".two = " << a.two << '\n';
}
``` | C++ isn't introspective. That is, it doesn't know anything about the contents of its structures. You have to use some sort of manual annotation or a reflection system to do this.
Of course, if you're OK with hardcoding information about the structures, you can dump the information with any I/O method.
For instance:
```
struct A
{
int member1;
char member2;
};
void PrintA (const A& a)
{
std::printf ("member1: %d\n", a.member1);
std::printf ("member2: %c\n", b.member2);
}
```
As you can see this is tedious because it requires intimate knowledge of the structure, and won't be updated automatically if the structure is changed. But the overhead of a reflection system to do this "properly" can be a disadvantage, especially if you're learning. | dumping c++ structures to a text file | [
"",
"c++",
"logging",
"file-io",
""
] |
Is there any way to check from .NET if windows update is enabled?
I want to prompt the users every time they log into my app that their computer might be at risk and give them a link to windows update website (or windows update application from control panel).
Preferably it should work on XP, Vista and Windows 7. Maybe there is a registry key or even better an API? | First add a reference to WUApiLib "C:\windows\system32\Wuapi.dll"
Then you can use this code snippet.
```
WUApiLib.AutomaticUpdatesClass auc = new WUApiLib.AutomaticUpdatesClass();
bool active = auc.ServiceEnabled;
```
MSDN: "The ServiceEnabled property indicates whether all the components that Automatic Updates requires are available."
The Setting auc.Settings.NotificationLevel contains the information about the current mode. <http://msdn.microsoft.com/en-us/library/aa385806(VS.85).aspx> | Of course it is your choice to do that but getting prompted every few minutes that WindowsUpdate was switched off was by far the worst usability issue in XP.
You don't want to irritate your users. You should love them. And definitely not intrude in their private affairs like checking out if WU is off because honestly it's no business of yours. | Check from .NET if Windows Update is enabled | [
"",
"c#",
".net",
"windows",
"vb.net",
""
] |
I'm currently trying to perform a search over 2 fields in my MySQL table (text type) using PHP.
```
SELECT * FROM content_items WHERE MATCH (content,name) AGAINST ('".urldecode($_REQUEST['term'])."' IN BOOLEAN MODE)
```
I'm always getting zero results, no matter what I search for (even tried to make the query static and it still didn't work). I have Fulltext indexes on both fields.
What can cause this?
Thanks,
Roy
p.s
The search should fit any length of sting (even short ones) | It was a problem with the indexes. Rebuilding them solved this. | The sql statement makes sense. I think the problem lies here:
```
urldecode($_REQUEST['term'])
```
There's a note in the PHP Manual regarding this
> Warning
>
> The superglobals $\_GET and $\_REQUEST
> are already decoded. Using urldecode()
> on an element in $\_GET or $\_REQUEST
> could have unexpected and dangerous
> results.
Cheers,
Mark | Fulltext search in MySQL and PHP doesn't work | [
"",
"php",
"mysql",
"full-text-search",
""
] |
I'm using the latest release of IKVM to "compile" a Java .jar file into a .NET DLL. That all worked fine, and now I'm trying to reference the DLL in a .NET 3.5 C# project.
In my C# project, I've created an static "StringExtensions" class with an extension method on string.
For some reason this seemed to work yesterday, but today, I'm getting a build error on my extension class (not sure how this worked yesterday...).
```
Missing compiler required member System.Runtime.CompilerServices.ExtensionAttribute..ctor
```
And a build warning as well:
```
The predefined type 'System.Runtime.CompilerServices.ExtensionAttribute' is defined in multiple assemblies in the global alias; using definition from 'c:\TEMP\IKVM.Runtime.dll'
```
I discovered that both IKVM.Runtime.dll and System.Core.dll (3.5 version) have the same type: "System.Runtime.CompilerServices.ExtensionAttribute"
Since the namespace is the same, how can I get this to compile with the System.Core version of ExtensionAttribute (or how can I fix this)?
Thanks | If you target .Net 2.0 you can only create extension methods if you define this attribute yourself. This works great until you move to .Net 3.5.
I don't know "IKVM" but the only real fix is to ask them to remove the attribute and target 3.5. | Updating to IKVM 0.40.0.1 fixed this problem for me. | IKVM and System.Core System.Runtime.CompilerServices.ExtensionAttribute | [
"",
"c#",
".net",
"extension-methods",
"ikvm",
"build-error",
""
] |
I have a custom control (compiled as a DLL) which loads a user control. (i.e, the custom control does a LoadControl) In the user control is a button and a textbox. I wire up the button's click event.
I type in a value into the text box. When I click the button, the page does a postback. My user control knows that a postback occured because Page.IsPostBack = true. However, the click event of the button is never fired and my text box has also lost the value that I typed in.
Anyone have any thoughts as to what might be going on?
EDIT:
I did a test on this and took SharePoint out of the picture; I was able to reproduce it so I removed all references to SharePoint. | If you are dynamically loading the user control, you have to reload it on each page load (postback or not) in order for the .net processor to know where to wire up the submit event. | One way to load the User Control is to override CreateChildControl, call base.CreateChildControls and then call your LoadControl method. If you need to place the UserControl is a specific location, place a PlaceHolder on the page and add your control to the place holders control collection.
You can also just add the user control directly to the markup.
Register the control as such:
```
<%@ Register Src="~/path/ControlName.ascx" TagName="tagName" TagPrefix="myPrefix" %>
```
and then add it in as follows:
```
<myPrefix:tagName ID="myId" runat="server"/>
``` | Custom Control loads a user control; Postback events are not triggered | [
"",
"c#",
"asp.net",
"postback",
""
] |
Is there a straightforward way to take docbook content and convert it into DokuWiki content? So far I've only found the [DokuWiki plugin](http://www.dokuwiki.org/plugin:docbook) that will interpret docbook content and output it in XHTML, but this happens on every page load.
I would like to find a way to convert docbook content directly to DokuWiki's native formatting syntax so I only have to interpret it once. Any ideas? | Another option will be to
1. Use 'docbook2html' - [[DocBook tools]](http://sources.redhat.com/docbook-tools/) to convert docbook to HTML, and then
2. use something like this Perl Module to convert the HTML to wiki markup. <http://metacpan.org/pod/HTML::WikiConverter> | I'm not familar with the tool you mentioned, but I have some thoughts on general strategies you might employ.
1. If you're happy with the output from the DocuWiki plugin you could write some sort of script in perl, sh, ruby, etc. that executes the plugin and stores the content to be served up statically in the future.
2. It appears that DocuWiki is simply calling the xsltproc program and serving up the output. If the plugin is working then you should be able to call xsltproc directly from the command line or your own script. Take a look at these lines from DocuWiki
exec("$xsltproc -o $tmpXhtmlFile $docbookXsl $tmpDocbookFile 2>&1", $errors);
$returnXhtml = shell\_exec("$xsltproc " . DOKU\_PLUGIN . "/docbook/xhtmlCleaner.xsl $tmpXhtmlFile");
3. Once you have option 1 or 2 working. Setup a cron job or hook in your revision control system to watch for changes to the original docbook source and call the script to regenerate the static version. | DocBook to DokuWiki | [
"",
"php",
"documentation",
"phpdoc",
"docbook",
"dokuwiki",
""
] |
Let's say I have a (convex) polygon with vertices 0..n-1. I want to split this polygon in half, say, between verticies i and j. Vertices i and j should appear in both polygons.
As far as I can tell, there are only two cases. One where i < j, or when i > j. i is never equal to j (nor are they ever adjacent).
I'm storing my vertices like `vector<Point> poly`. You can assume `Point` is just a basic struct with two doubles `x` and `y`, with points indexed sequentially in CCW order.
If i < j, then I just need to copy the vertices from i to j (inclusive) into one vector, and then from j to n-1 plus 0 to i into another. Or vice versa for the other case, right?
Here's the code I'm using, but it doesn't seem to work right (let j == closestIndex):
```
if (i < closestIndex) {
lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + closestIndex + 1);
upperPoly.insert(upperPoly.end(), poly.begin() + closestIndex, poly.end());
upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1);
} else {
lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end());
lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + closestIndex + 1);
upperPoly.insert(upperPoly.end(), poly.begin() + closestIndex, poly.begin() + i + 1);
}
``` | As a side note:
You don't really have 2 cases. If i > j then just swap i and j. Then you are always in the case where i < j, assuming i != j.
I would probably code it like follows:
```
if (i > closestIndex)
std::swap (i, closestIndex);
assert(closestIndex - i > 1);
// make sure i != closestIndex and i is not adjacent to closestIndex
lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + closestIndex + 1);
upperPoly.insert(upperPoly.end(), poly.begin() + closestIndex, poly.end());
upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1);
``` | I think there's another restriction you need to include, in addition to i never equal to j.
You also need to ensure that if i is the starting point that you aren't splitting at either i-1 or i+1. If the sides are linear, splitting at consecutive points means that the dividing line is simply an edge, so you get back the original polygon and an edge line, which doesn't seem very interesting.
Instead of two arrays x and y, I'd recommend a single array of 2D points, with verticies numbered consecutively in a counterclockwise direction around the polygon.
So the two polygons will be:
Polygon 1 : start with i, iterate to the ending point j, and finish with the edge from j back to i;
Polygon 2: start with i, to the ending point j, and then over j+1, j+2, back to i. | Splitting an STL vector | [
"",
"c++",
"geometry",
""
] |
I'm using a RegExp to validate some user input on an ASP.NET web page. It's meant to enforce the construction of a password (i.e. between 8 and 20 long, at least one upper case character, at least one lower case character, at least one number, at least one of the characters #@!$% and no use of letters L or O (upper or lower) or numbers 0 and 1. This RegExp works fine in my tester (Expresso) and in my C# code.
This is how it looks:
```
(?-i)^(?=.{8,20})(?=.*[2-9])(?=.*[a-hj-km-np-z])(?=.*[A-HJ-KM-NP-Z])
(?=.*[#@!$%])[2-9a-hj-km-np-zA-HJ-KM-NP-Z#@!$%]*$
```
(Line break added for formatting)
However, when I run the code it lives in in IE6 or IE7 (haven't tried other browsers as this is an internal app and we're a Microsoft shop), I get a runtime error saying 'Syntax error in regular expression'. That's it - no further information in the error message aside from the line number.
What is it about this that JavaScript doesn't like? | Well, there are two ways of defining a Regex in Javascript:
a. Through a Regexp object constructor:
```
var re = new RegExp("pattern","flags");
re.test(myTestString);
```
b. Using a string literal:
```
var re = /pattern/flags;
```
You should also note that JS does not support some of the tenets of Regular Expressions. For a non-comprehensive list of features unsupported in JS, check out the [regular-expressions.info](http://www.regular-expressions.info/javascript.html) site.
Specifically speaking, you appear to be setting some flags on the expression (for example, the case insensitive flag). I would suggest that you use the `/i` flag (as indicated by the syntax above) instead of using `(?-i)`
That would make your Regex as follows (Positive Lookahead appears to be supported):
```
/^(?=.{8,20})(?=.*[2-9])(?=.*[a-hj-km-np-z])(?=.*[A-HJ-KM-NP-Z])(?=.*[#@!$%])[2-9a-hj-km-np-zA-HJ-KM-NP-Z#@!$%]*$/i;
```
For a very good article on the subject, check out [Regular Expressions in JavaScript](http://www.evolt.org/article/Regular_Expressions_in_JavaScript/17/36435/).
**Edit** (after Howard's comment)
---
If you are simply assigning this Regex pattern to a RegularExpressionValidator control, then you will not have the ability to set Regex options (such as ignore case). Also, you will not be able to use the Regex literal syntax supported by Javascript. Therefore, the only option that remains is to make your pattern intrinsically case insensitive. For example, `[a-h]` would have to be written as `[A-Ha-h]`. This would make your Regex quite long-winded, I'm sorry to say.
[Here is a solution](http://reflectedthought.com//thecoder/archive/2007/11/25/regularexpressionvalidator_ignore_case.aspx) to this problem, though I cannot vouch for it's legitimacy. Some other options that come to mind may be to turn of Client side validation altogether and validate exclusively on the Server. This will give you access to the full Regex flavour implemented by the `System.Text.RegularExpressions.Regex` object. Alternatively, use a CustomValidator and create your own JS function which applies the Regex match using the patterns that I (and others) have suggested. | I'm not familiar with C#'s regular expression syntax, but is this (at the start)
```
(?-i)
```
meant to turn the case insensitivity pattern modifier on? If so, that's your problem. Javascript doesn't support specifying the pattern modifiers in the expression. There's two ways to do this in javascript
```
var re = /pattern/i
var re = new RegExp('pattern','i');
```
Give one of those a try, and your expression should be happy. | Why is my RegExp construction not accepted by JavaScript? | [
"",
"javascript",
"regex",
""
] |
I have a Qt project which I have had a debug console displayed whilst I am developing, I am about to ship the product to I removed the qmake console command:
CONFIG += console
However when I do that I get the following error:
```
link /LIBPATH:"c:\Qt\4.5.0\lib" /NOLOGO /INCREMENTAL:NO /LTCG /MANIFEST /MANIFESTFILE:"./_obj/win32\Lynx.intermediate.manifest" /SUBSYSTEM:WINDOWS "/MANIFESTDEPENDENCY:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' publicKeyToken='6595b64144ccf1df' language='*' processorArchitecture='*'" /VERSION:4.00 /OUT:bin\win32\Lynx.exe @C:\DOCUME~1\hannentp\LOCALS~1\Temp\nm1C9.tmp
link_.exe /LIBPATH:c:\Qt\4.5.0\lib /NOLOGO /INCREMENTAL:NO /LTCG /MANIFEST /MANIFESTFILE:./_obj/win32\Lynx.intermediate.manifest /SUBSYSTEM:WINDOWS /MANIFESTDEPENDENCY:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' publicKeyToken='6595b64144ccf1df' language='*' processorArchitecture='*' /VERSION:4.00 /OUT:bin\win32\Lynx.exe @C:\DOCUME~1\hannentp\LOCALS~1\Temp\nm1C9.tmp~
LINK_ : fatal error LNK1181: cannot open input file 'name='Microsoft.Windows.Common-Controls''
NMAKE : fatal error U1077: '"C:\Program Files\Microsoft Visual Studio 9.0\VC\Bin\link.EXE"' : return code '0x49d'
Stop.
```
I think that a lib path is missing, however I do have a large number of environment variables setup and working already. Has anybody seen this and know the location of the Microsoft.Windows.Common-Controls?
Also I am running this from buildbot so VS2008's IDE is not really somewhere I want help with. | It seems that the command line is just underquoted:
```
"/MANIFESTDEPENDENCY:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' publicKeyToken='6595b64144ccf1df' language='*' processorArchitecture='*'"
```
On the second line, the quotes are gone and the linker treats each word as an object to link. You should probably just add quotes (if it was you who added this argument), ie. begin and end with `"\"` (3 characters in place of one quote). It seems other sources suggest that too, so try experimenting with that. | Not sure, if you made any futher progress on this issue.
I had the very similar error, but with msvc2005 (not IDE).
I don't have any instances of link\_.exe so I can not verify your fix.
When i enabled console (CONFIG += console), it did not manage to link
due to other problem - could not find entry point:
```
Fatal Error LNK1561: Entry Point Must Be Defined
```
I randomly found `http://support.microsoft.com/kb/140597`
which talks about trailing backslash characters, thought it is stated that is for msvc 4 and was fixed later. I checked my code, and I have trailing forwardslashes when specified
the LIBPATH in .pro file. I fixed those, and got the thing to compile with (CONFIG += console). Now I removed the option, and having different but somewhat logical problem:
```
MSVCRT.lib(crtexew.obj) : error LNK2001: unresolved external symbol _WinMain@16
app.exe : fatal error LNK1120: 1 unresolved externals
```
Looking at your nmake output, I am wondering if mixing forward and backslash characters
in
```
/MANIFESTFILE:"./_obj/win32\Lynx.intermediate.manifest"
```
causing this problem. Though it might something different.
Note, I also have `CONFIG -= embed_manifest_exe` in my .pro file.
My nmake out looks like this:
```
link /LIBPATH:"c:\Apps\boost\boost_1_38\lib" /NOLOGO /INCREMENTAL:NO /LTCG /SUBSYSTEM:WINDOWS "/MANIFESTDEPENDENCY:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' publicKeyToken='6595b64144ccf1df' language='*' processorArchitecture='*'" /OUT:valueForSba.exe @C:\DOCUME~1\LOCALS~1\Temp\nm398.tmp
Creating library app.lib and object app.exp
MSVCRT.lib(crtexew.obj) : error LNK2001: unresolved external symbol _WinMain@16
app.exe : fatal error LNK1120: 1 unresolved externals
```
I also not using any qt classes in this project, and only use qmake to get the Makefile.
(qmake from 4.5.1 commercial edition) | What am I missing from my environment variables for my linker to fail with LNK1181? | [
"",
"c++",
"qt",
"linker",
"nmake",
""
] |
I have an object, a Timeline, that encapsulates a thread. Events can be scheduled on the timeline; the thread will wait until it is time to execute any event, execute it, and go back to sleep (for either (a) the time it takes to get to the next event or (b) indefinitely if there are no more events).
The sleeping is handled with a WaitEventHandle, which is triggered when the list of event is altered (because the sleep delay may need to be adjusted) or when the thread should be stopped (so the thread can terminate gracefully).
The destructor calls Stop(), and I've even implemented IDisposable and Dispose() also calls Stop().
Still, when I use this component in a forms application, my application will never shut down properly when I close the form. For some reason, Stop() is never called, so neither my object's destructor triggers, nor is the Dispose() method called, *before* .NET decides to wait for all threads to finish.
I suppose the solution would be to explicitly call Dispose() myself on the FormClose event, but since this class is going to be in a library, *and* it is actually a layer deeper (that is, the application developer will never actually see the Timeline class), this seems very ugly and an extra (unnecessary) gotcha for the application developer. The using() clause, which I would normally use when resource release becomes an issue, doesn't apply as this is going to be a long-lived object.
On the one hand, I can understand that .NET will want to wait for all threads to finish before it does its final round of garbage collection, but in this case that produces a very clumsy situation.
How can I make my thread clean up after itself properly without adding requirements to consumers of my library? Put another way, how can I make .NET notify my object when the application is exiting, but before it will wait for all threads to finish?
---
EDIT: In response to the people saying that it is ok for the client program to be aware of the thread: I respectfully disagree.
As I said in my original post, the thread is hidden away in another object (an Animator). I instantiate an Animator for another object, and I tell it to perform animations, such as "blink this light for 800ms".
As a consumer of the Animator object, I do not care how the Animator makes sure that the light blinks for exactly 800ms. Does it start a thread? I don't care. Does it create a hidden window and use system timers (ew)? I don't care. Does it hire midgets to turn my light on and off? I don't care.
And I *especially* don't want to have to care that if I ever create an Animator, I have to keep track of it and call a special method when my program exits, in contrast to every other object. It should be a concern of the library implementor, not the library consumer.
---
EDIT: The code is actually short enough to show. I'll include it for reference, *sans* methods that add events to the list:
```
internal class Timeline : IDisposable {
private Thread eventThread;
private volatile bool active;
private SortedList<DateTime, MethodInvoker> events = new SortedList<DateTime,MethodInvoker>();
private EventWaitHandle wakeup = new EventWaitHandle(false, EventResetMode.AutoReset);
internal Timeline() {
active = true;
eventThread = new Thread(executeEvents);
eventThread.Start();
}
~Timeline() {
Dispose();
}
private DateTime NextEvent {
get {
lock(events)
return events.Keys[0];
}
}
private void executeEvents() {
while (active) {
// Process all events that are due
while (events.Count > 0 && NextEvent <= DateTime.Now) {
lock(events) {
events.Values[0]();
events.RemoveAt(0);
}
}
// Wait for the next event, or until one is scheduled
if (events.Count > 0)
wakeup.WaitOne((int)(NextEvent - DateTime.Now).TotalMilliseconds);
else
wakeup.WaitOne();
}
}
internal void Stop() {
active = false;
wakeup.Set();
}
public void Dispose() {
Stop();
}
}
``` | I don't think it is unreasonable to require clients to Stop() the thread for shutdown at all. There are ways you can create threads whose continued execution will not stop the application from exiting (although I don't have the details off the top of my head). But expecting to launch and terminate a worker thread is not too much of a burden for the client. | Maybe set the T[hread.IsBackground](http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx) property to true?
```
eventThread = new Thread(executeEvents);
eventThread.IsBackground = true;
eventThread.Start();
```
Another option is to use the [Interrupt](http://msdn.microsoft.com/en-us/library/system.threading.thread.interrupt.aspx) method to wake it up. Just make sure that you catch the `ThreadInterruptedException` in the thread that you are interrupting, and that it shuts down when it happens.
```
active = false;
eventThread.Interrupt();
try { eventThread.Join(); } // Wait for graceful shutdown
catch (Exception) { }
```
Not quite sure how that `EventWaitHandle` of yours works though... When I did something similar once, I just used the regular `Thread.Sleep` =) | Proper way to clean up a permanent thread in C# | [
"",
"c#",
"multithreading",
"termination",
""
] |
I am working on an application that has to assign numeric codes to elements. This codes are not consecutives and my idea is not to insert them in the data base until have the related element, but i would like to find, in a sql matter, the not assigned codes and i dont know how to do it.
Any ideas?
Thanks!!!
**Edit 1**
The table can be so simple:
```
code | element
-----------------
3 | three
7 | seven
2 | two
```
And I would like something like this: 1, 4, 5, 6. Without any other table.
**Edit 2**
Thanks for the feedback, your answers have been very helpful. | This will return `NULL` if a code is not assigned:
```
SELECT assigned_codes.code
FROM codes
LEFT JOIN
assigned_codes
ON assigned_codes.code = codes.code
WHERE codes.code = @code
```
This will return all non-assigned codes:
```
SELECT codes.code
FROM codes
LEFT JOIN
assigned_codes
ON assigned_codes.code = codes.code
WHERE assigned_codes.code IS NULL
```
There is no pure `SQL` way to do exactly the thing you want.
In `Oracle`, you can do the following:
```
SELECT lvl
FROM (
SELECT level AS lvl
FROM dual
CONNECT BY
level <=
(
SELECT MAX(code)
FROM elements
)
)
LEFT OUTER JOIN
elements
ON code = lvl
WHERE code IS NULL
```
In `PostgreSQL`, you can do the following:
```
SELECT lvl
FROM generate_series(
1,
(
SELECT MAX(code)
FROM elements
)) lvl
LEFT OUTER JOIN
elements
ON code = lvl
WHERE code IS NULL
``` | Contrary to the assertion that this cannot be done using pure SQL, here is a counter example showing how it can be done. (Note that I didn't say it was easy - it is, however, possible.) Assume the table's name is `value_list` with columns `code` and `value` as shown in the edits (why does everyone forget to include the table name in the question?):
```
SELECT b.bottom, t.top
FROM (SELECT l1.code - 1 AS top
FROM value_list l1
WHERE NOT EXISTS (SELECT * FROM value_list l2
WHERE l2.code = l1.code - 1)) AS t,
(SELECT l1.code + 1 AS bottom
FROM value_list l1
WHERE NOT EXISTS (SELECT * FROM value_list l2
WHERE l2.code = l1.code + 1)) AS b
WHERE b.bottom <= t.top
AND NOT EXISTS (SELECT * FROM value_list l2
WHERE l2.code >= b.bottom AND l2.code <= t.top);
```
The two parallel queries in the from clause generate values that are respectively at the top and bottom of a gap in the range of values in the table. The cross-product of these two lists is then restricted so that the bottom is not greater than the top, and such that there is no value in the original list in between the bottom and top.
On the sample data, this produces the range 4-6. When I added an extra row (9, 'nine'), it also generated the range 8-8. Clearly, you also have two other possible ranges for a suitable definition of 'infinity':
* `-infinity` .. `MIN(code)-1`
* `MAX(code)+1` .. `+infinity`
Note that:
1. If you are using this routinely, there will generally not be many gaps in your lists.
2. Gaps can only appear when you delete rows from the table (or you ignore the ranges returned by this query or its relatives when inserting data).
3. It is usually a bad idea to reuse identifiers, so in fact this effort is probably misguided.
However, if you want to do it, here is one way to do so. | Selecting elements that don't exist | [
"",
"sql",
"select",
""
] |
Is there a difference between using const:
Cannot change the datatype but can change the value of a or b
```
int add(const int a, const int b);
```
Can change the datatype but cannot change the value of a or b
```
int add(int const a, int const b);
```
Cannot change the datatype and cannot change the value of a or b
```
int add(const int const a, const int const b);
```
Many thanks for any suggestions | I don't know how one is supposed to changed the datatype of a variable in C++ ...
'const' is a promise you make to the compiler about not modifying a value. It complains when you don't (probably uncovering z bug in the process).
It also helps it to do various optimizations.
Here are some const examples and what they mean :
```
f ( const int a )
```
f cannot change the value of 'a'.
```
f ( int const a )
```
the same but written in a weird way
```
f ( const int const a )
```
means nothing, gcc tells me "duplicate const"
```
f ( const int * pa )
```
f cannot change the value pointed to by pa
```
f ( int * const pa )
```
f cannot change the value of the pointer
```
f ( const int * const pa )
```
f cannot change the value of the pointer nor the value pointed to
```
f ( int a ) const
```
The member function f cannot modify its object
Hope it makes things clearer .. | **Difference between const int and int const:**
int const and const int are the same.
There is a difference with pointers though:
```
char sz[3] = "hi";
//const char* allows you to change what is pointed to,
//but not change the memory at the address that is pointed to
const char *p = sz;
p = "pi";//ok
//p[0] = 'p';//not valid, bad
//char * const allows you to change the memory at the address that is
//pointed to, but not change what is pointed to.
char * const q = sz;
//q = "pi";//not valid, bad
q[0] = 'p';//ok
//or disallow both:
const char * const r = sz;
//r = "pi";//not valid, bad
//r[0] = 'p';//not valid, bad
```
Most of the time you want to use const char \*.
**Changing the type of a varaible:**
You cannot change the type of a variable, but you can re-interpret the address of a variable to be of another type. To do this you use casting. | using const to prevent datatype changing and value changing | [
"",
"c++",
"constants",
""
] |
First, I'm new to Python, so I apologize if I've overlooked something, but I would like to use `dict.fromkeys` (or something similar) to create a dictionary of lists, the keys of which are provided in another list. I'm performing some timing tests and I'd like for the key to be the input variable and the list to contain the times for the runs:
```
def benchmark(input):
...
return time_taken
runs = 10
inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55)
results = dict.fromkeys(inputs, [])
for run in range(0, runs):
for i in inputs:
results[i].append(benchmark(i))
```
The problem I'm having is that all the keys in the dictionary appear to share the same list, and each run simply appends to it. Is there any way to generate a unique empty list for each key using `fromkeys`? If not, is there another way to do this without generating the resulting dictionary by hand? | The problem is that in
```
results = dict.fromkeys(inputs, [])
```
[] is evaluated only once, right there.
I'd rewrite this code like that:
```
runs = 10
inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55)
results = {}
for run in range(runs):
for i in inputs:
results.setdefault(i,[]).append(benchmark(i))
```
Other option is:
```
runs = 10
inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55)
results = dict([(i,[]) for i in inputs])
for run in range(runs):
for i in inputs:
results[i].append(benchmark(i))
``` | Check out [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) (requires Python 2.5 or greater).
```
from collections import defaultdict
def benchmark(input):
...
return time_taken
runs = 10
inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55)
results = defaultdict(list) # Creates a dict where the default value for any key is an empty list
for run in range(0, runs):
for i in inputs:
results[i].append(benchmark(i))
``` | How do I create a unique value for each key using dict.fromkeys? | [
"",
"python",
"dictionary",
"fromkeys",
""
] |
To add a new value to a dotnet Hashtable I've always used:
```
myHashtable.Add(myNewKey, myNewValue);
```
but I've just come across some code which does the following instead:
```
myHashTable[myNewKey] = myNewValue;
```
Is there any difference between the two methods? | To correct Sergej's answer a little...
* `Add` will indeed throw an exception if the key already exists.
* Using the indexer as a setter *won't* throw an exception (unless you specify a null key).
* Using the indexer as a getter will throw an exception if the key doesn't exist and if you're using a generic `IDictionary<TKey,TValue>`. In the non-generic `IDictionary` implementations (e.g. `Hashtable`) you'll get a null reference. You can't use a null key for either one though - you'll get an `ArgumentNullException`. | first will throw exception if there already were an item with given key and the second will throw an exception if there was no item with such key | Assigning a new value to Hashtable without using the Add method | [
"",
"c#",
".net",
"hashtable",
""
] |
I have code similar to this:
```
class Foo {
Dictionary<Type, Object> _dict;
void Create(string myType, string myValue)
{
var instance = Type.Instanciate(myType) // How do I do this?
if (var.IsPrimitive)
{
var.GetType().Parse(myValue) // I know this is there...how to invoke?
Dictionary[instance.GetType()] = instance;
}
}
T GetValue<T>(T myType) { return (T)_dict[T]; }
}
// Populate with values
foo.Create("System.Int32", "15");
foo.Create("System.String", "My String");
foo.Create("System.Boolean", "False");
// Access a value
bool b = GetValue(b);
```
So my questions are:
a) How do I instantiate the type
b) Parse the type value from a string when Parse is supported. | * Getting a type: [`Type.GetType()`](http://msdn.microsoft.com/en-us/library/system.type.gettype.aspx)
* Instantiating a type from a Type object: [`Activator.CreateInstance`](http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx) (You don't actually need this in your code.)
* Converting from a string: [`Convert.ChangeType`](http://msdn.microsoft.com/en-us/library/system.convert.changetype.aspx)
Note that if the type isn't in `mscorlib` or the currently executing assembly, you'll need to include the assembly name (and version information if it's strongly named).
Here's a complete example using your original code. Note that `GetValue` doesn't need a normal parameter, as you've already given the type parameter (T).
```
using System;
using System.Collections.Generic;
public class Foo {
Dictionary<Type, Object> _dict = new Dictionary<Type, Object>();
public void Create(string myType, string myValue)
{
Type type = Type.GetType(myType);
object value = Convert.ChangeType(myValue, type);
_dict[type] = value;
}
public T GetValue<T>() { return (T)_dict[typeof(T)]; }
}
class Test
{
static void Main()
{
Foo foo = new Foo();
// Populate with values
foo.Create("System.Int32", "15");
foo.Create("System.String", "My String");
foo.Create("System.Boolean", "False");
Console.WriteLine(foo.GetValue<int>());
Console.WriteLine(foo.GetValue<string>());
Console.WriteLine(foo.GetValue<bool>());
}
}
``` | > a) How do I instantiate the type
You're looking for [System.Activator.CreateInstance](http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx).
> b) Parse the type value from a string when Parse is supported.
You're looking for [System.Convert.ChangeType](http://msdn.microsoft.com/en-us/library/system.convert.changetype.aspx). | How do I instantiate a type and its value from a string? | [
"",
"c#",
".net",
""
] |
How do i encrypt a file in C#? i would like to use a db (like sqlite) and use it normally except have the file encrypted and have my user enter his password before having access to the database. | There are multiple ways to do this:
* Use DPApi (Data Protection API), which is supplied in the ProtectedData (System.Security.Cryptography class), and use an entrophy based on a password
* Use SQL Compact Edition, which has this built in
* Generate a key based on a password and encrypt/decrypt the file with that
* Use Encrypted File System, so the OS will take care of encryption on the disk. (Consumer editions of Windows don't have this though.)
And there are probably more ways to do this.
Hope this helps. | [SQL Server Compact Edition](http://www.microsoft.com/Sqlserver/2005/en/us/compact.aspx) (it's an inprocess database server like SQLite) allows you to encrypt the file [without writing any additional code](http://msdn.microsoft.com/en-us/library/ms171966.aspx#).
To change the password, use the [Engine.Compact](http://msdn.microsoft.com/en-us/library/ms171752.aspx) method. | encrypt a file automagically in C#? | [
"",
"c#",
"encryption",
""
] |
### Exact duplicate:
> [Why does one often see “null != variable” instead of “variable != null” in C#?](https://stackoverflow.com/questions/271561/why-does-one-often-see-null-variable-instead-of-variable-null-in-c)
I have seen senior developers using syntaxes mentioned in the title.
Is there a need for specifying a constant first in .NET? (as opposed to in C/C++ world) | No, there's no need for this, because the problem it tries to avoid - namely the typo of:
```
if (variable = 0)
```
wouldn't compile in C# anyway. The conditions in `if` statements have to be Boolean. There's still a risk of making one of these mistakes:
```
if (something = true)
if (something = false)
```
if `something` is a Boolean variable, but the better way to fix this is to avoid the constant:
```
if (something)
if (!something)
```
If you have developers bringing over idioms like this from other languages without thinking about whether they're appropriate in C#, you should keep an eye for them doing more of the same. If you try to write C# as if it's C++ (or any other language, pretty much - with the possible exception of VB.NET) you'll end up writing non-idiomatic C# code.
EDIT: As cletus noted, there *is* another potential area for concern:
```
bool a = false, b = true;
if (a = b) { } // No warnings
```
So the error can still occur - but then we're outside the realm of comparing with a constant anyway :) I'd say this crops up incredibly rarely, and isn't worth too much time spent worrying about it. | There is no need for this syntax in the modern world. It's a habit that many of us got into when our C compiler wouldn't warn us that we were about to launch the missiles.
```
if(status = RED_ALERT)
{
launchMissiles();
}
``` | (0 == variable) or (null == obj): An outdated practice in C#? | [
"",
"c#",
".net",
"coding-style",
""
] |
I have a table like this:
```
serialnumber partnb id actual nominal
1 1 AGR 15,2176803 15,2
1 1 APR 5,8060656 5,8
1 1 DCI 61,9512259 62
1 43 AGR 15,4178727 15,4
1 43 APR 7,235779 7,2
1 43 DCI 52,0080535 52
2 2 AGR 15,2097009 15,2
2 2 APR 5,8009968 5,8
2 2 DCI 61,9582795 62
2 44 AGR 15,4191387 15,4
2 44 APR 7,2370065 7,2
2 44 DCI 52,010244 52
```
And I want this:
```
serialnumber partnb AGR AGR_nominal APR APR_nominal DCI DCI_nominal
1 1 15,217 15,2 5,806 5,8 61,951 62
1 43 15,417 15,2 7,235 7,2 52,008 62
2 2 15,209 15,2 5,800 5,8 61,958 62
2 44 15,419 15,4 7,237 7,2 52,010 52
```
How can I achieve this in SQL Server 2005? | I have found the solution
```
SELECT
planid,
serialnumber,
partnb,
DFI,
(SELECT nominal FROM vwMeasurement v WHERE p.planid=v.planid
AND p.serialnumber=v.serialnumber AND p.partnb=v.partnb
AND v.id='DFI') AS nominal_DFI,
DCI,
(SELECT nominal FROM vwMeasurement v WHERE p.planid=v.planid
AND p.serialnumber=v.serialnumber AND p.partnb=v.partnb
AND v.id='DCI') AS nominal_DCI,
DPI,
(SELECT nominal FROM vwMeasurement v WHERE p.planid=v.planid
AND p.serialnumber=v.serialnumber AND p.partnb=v.partnb
AND v.id='DPI') AS nominal_DPI,
AGR,
(SELECT nominal FROM vwMeasurement v WHERE p.planid=v.planid
AND p.serialnumber=v.serialnumber AND p.partnb=v.partnb
AND v.id='AGR') AS nominal_AGR,
APR,
(SELECT nominal FROM vwMeasurement v WHERE p.planid=v.planid
AND p.serialnumber=v.serialnumber AND p.partnb=v.partnb
AND v.id='APR') AS nominal_APR,
DGR,
(SELECT nominal FROM vwMeasurement v WHERE p.planid=v.planid
AND p.serialnumber=v.serialnumber AND p.partnb=v.partnb
AND v.id='DGR') AS nominal_DGR,
DPR,
(SELECT nominal FROM vwMeasurement v WHERE p.planid=v.planid
AND p.serialnumber=v.serialnumber AND p.partnb=v.partnb
AND v.id='DPR') AS nominal_DPR,
DFE,
(SELECT nominal FROM vwMeasurement v WHERE p.planid=v.planid
AND p.serialnumber=v.serialnumber AND p.partnb=v.partnb
AND v.id='DFE') AS nominal_DFE,
DKE,
(SELECT nominal FROM vwMeasurement v WHERE p.planid=v.planid
AND p.serialnumber=v.serialnumber AND p.partnb=v.partnb
AND v.id='DKE') AS nominal_DKE,
MDKE,
(SELECT nominal FROM vwMeasurement v WHERE p.planid=v.planid
AND p.serialnumber=v.serialnumber AND p.partnb=v.partnb
AND v.id='MDKE') AS nominal_MDKE,
MDKI,
(SELECT nominal FROM vwMeasurement v WHERE p.planid=v.planid
AND p.serialnumber=v.serialnumber AND p.partnb=v.partnb
AND v.id='MDKI') AS nominal_MDKI,
DKI,
(SELECT nominal FROM vwMeasurement v WHERE p.planid=v.planid
AND p.serialnumber=v.serialnumber AND p.partnb=v.partnb
AND v.id='DKI') AS nominal_DKI
FROM(SELECT DISTINCT serialnumber, planid, partnb, id, actual FROM vwMeasurement) driver
PIVOT (
SUM(driver.actual)
FOR driver.id IN (DFI, DCI, DPI, AGR, APR, DGR, DPR, DFE, DKE, MDKE, MDKI, DKI)
) AS p
ORDER BY planid, serialnumber, partnb
``` | There is a PIVOT keyword in Sql Server 2005 you can use. Here is the description <http://msdn.microsoft.com/en-us/library/ms177410.aspx> | Pivoting tables | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I have a very large array which must be 262144 elements in length (and potentially much larger in future). I have tried allocating the array on the stack like so:
```
#define SIZE 262144
int myArray[SIZE];
```
However, it appears that when I try and add elements past a certain point, the values are different when I try to access them. I understand that this is because there is only a finite amount of memory on the stack, as opposed to the heap which has more memory.
I have tried the following without much luck (does not compile):
```
#define SIZE 262144
int *myArray[SIZE] = new int[SIZE];
```
And then I considered using `malloc`, but I was wondering if there was a more C++ like way of doing this...
```
#define SIZE 262144
int *myArray = (int*)malloc(sizeof(int) * SIZE);
```
Should I just go with `malloc`? | You'll want to use new like such:
```
int *myArray = new int[SIZE];
```
I'll also mention the other side of this, just in case....
Since your transitioning from the stack to the heap, you'll also need to clean this memory up when you're done with it. On the stack, the memory will automatically cleanup, but on the heap, you'll need to delete it, and since its an array, you should use:
```
delete [] myArray;
``` | The more C++ way of doing it is to use vector. Then you don't have to worry about deleting the memory when you are done; vector will do it for you.
```
#include <vector>
std::vector<int> v(262144);
``` | How do I create an array in C++ which is on the heap instead of the stack? | [
"",
"c++",
"arrays",
"stack",
"malloc",
"heap-memory",
""
] |
I am working with C++ unmanaged and Excel 2007. I am using a call to the Excel4 API to get the range of cells selected by the user.
When the user selects what I call a "common" range, this call returns a range like this "R1C1:R4C3", which is exactly the format that I need for doing other operations in my application.
However, when the user decides to select whole columns then this API call returns a range only with columns, something like this "C1:C3", which of course is a valid excel range, but it means to me that I have to modify it so it looks like the the range above; in other words I have to manually add it the rows range.
So I take this range "C1C3" and change it to be "R1C1:R65534C3".
Perhaps at this point you already noticed my problem, as you can see I'm hard coding the rows range to be the max numbers of rows supported by Excel 2003 (the application also works with this version of excel).
This of course is not what I'm looking for, because once I get the selected range, I read the info in that range and use that info to make a query to the server, so imagine that the user only entered data until row 534 and still my query will have 65000 rows with nothing.
So my question is how can I get the last cell in which the user entered data, I think it is called the last active cell, so I can delimit my range until that row and please remember that I'm working with unmanaged code. | The Excel 4 API? Really?
There's a command xlcSelectEnd which you can use to jump to the last cell with text entered in it in any direction from a given cell. | Try casting range.selection to a Range object. | How to get Last Active Cell in Excel 2007 | [
"",
"c++",
"excel-2007",
""
] |
I need to create a velocity document that has some lines prefixed with ¨## Foo", but since the `#` is the velocity directive command, it is not working for me.
What I want my **output** document to look like:
```
## Foo this
## Bar that
k1, v1
k2, v2
k3, v3
```
Escaping has not worked out how I expected. The below does not work, obviously, as the `#`s are un-escaped):
```
## Foo this
## Bar that
#foreach( $foo in $bar )
$foo.key, $foo.value
#end
```
The ## lines don't show up--again, as expected. But, my attempts at escaping do not work either. Escaping solution one:
```
\## Foo this
\## Bar that
#foreach( $foo in $bar )
$foo.key, $foo.value
#end
```
or this, escaping solution two:
```
\#\# Foo this
\#\# Bar that
#foreach( $foo in $bar )
$foo.key, $foo.value
#end
```
or even this...
```
# set($msg = "##")
$msg Foo this
$msg Bar that
#foreach( $foo in $bar )
$foo.key, $foo.value
#end
```
This last one really confused me.
Any ideas? | Sigh....There is a difference between single quote and double quotes. This works as expected:
```
#set($msg = '##')
$msg Foo this
```
Which prints out exactly what I wanted:
```
## Foo this
```
From the [Velocity Users Guide](http://velocity.apache.org/engine/releases/velocity-1.5/user-guide.html):
> Single quotes will ensure that the quoted value will be assigned to the reference as is. Double quotes allow you to use velocity references and directives to interpolate, such as "Hello $name"
*(I'm still stumped as to why \#\# does not work.)* | Use the [Velocity context](http://velocity.apache.org/tools/devel/generic/EscapeTool.html):
```
${esc.h}${esc.h}
``` | How do I create a velocity template that outputs two '#' litterals at the beginning of the line? | [
"",
"java",
"velocity",
""
] |
A textbox on my form may change depending on what's selected in various drop down lists.
Is there a way to call a javascript function when the textbox value changes?
Tried onchange event but this only seems to work if a user manually changes the textbox value.
Cheers,
Breandán | No, javascript-triggered changes to form elements don't trigger events. If they did, this would cause all sorts of recursive infinite loops.
The simple solution is to call your onchange function manually whenever you change the value of the textbox, however you could also use some kind of wrapper function. As a very basic example:
```
function updateTextField(new_text) {
text_field.value = new_text;
text_field.onchange();
}
``` | When setting the content of the text box from your JS code, call out to another function passing in the text to set, you can then call it from where ever you need and do your logic then. | Javascript event that fires without user interaction? | [
"",
"javascript",
"events",
""
] |
I have before created a quick Ajax Framework for one of my projects. It was an ASP.Net Website (C#). There was not a lot of Ajax type functions so I just made a new Page with nothing in it and in the code behind file I put some code in the Page\_Load method which would look for an action in the request and then call the appropriate method.
I am in the same scenario again and I am finding that I am tempted to do the same again.
I am letting the user create a new accommodation. Two of the fields that belong with accommodation are accommodation type and area. Both of these fields are maintained by the users so they can CRUD both of these fields on other pages. I was thinking that if the area or accommodation type did not yet exist it would be irritating to have to go to another page. So instead I want to give them the functionality of adding new areas and adding new accommodation types on the same form. So I have tickboxes for the accommodation type, when they click new I present them a textbox they enter the value and click add. It makes an Ajax call to the database to add the value and then a new tickbox appears if successful else an error message. Very similar for area except I will be using a drop down list.
This time however I am using some jQuery too. I am not that familiar with jQuery's Ajax libraries YET. My question is, "Is there a...
1. Better
2. Easier
3. Smarter
4. More Extendable
5. All of the above
way of doing this." If so can you please point me in the right direction. | Given that with VS2008 there's support for AJAX already built into the IDE (and with jQuery support coming), I think you'll find it tough to come up with something which is not only a better *user* experience but also a better *developer* experience.
The Visual Studio team not only have a lot of resources invested in making this work well, but they also know how to integrate features into the IDE, almost certainly better than you do (and with more access to do so, I suspect).
If you want to do this for fun (or as part of MonoDevelop, for instance), that makes sense - but from a productivity point of view, I'd just stick to Visual Studio. | I dont think you need to create an entirely new Ajax Framework. A lot of time and effort by many people has been put into other frameworks like the Asp.net Ajax, jQuery, and others. Take some time to learn what these frameworks provide for you and how you can use them. If you still find them lacking nearly all of them have ways to extend on their already built features. | I need to build a very light weight Ajax Engine using C# and ASP.Net. What do you suggest? | [
"",
"c#",
"asp.net",
"jquery",
"ajax",
""
] |
I am using PHP 4, the only way I know of to cause an error and stop everything is calling die(). But in case I run into the error later and don't remember where its coming from I would like to specify the page and line number that the die() occurred on (like other php errors do). Is there a way to do this?
Thanks! | You should look into the [magic constants.](https://www.php.net/manual/en/language.constants.predefined.php)
```
echo __LINE__; // Line number
```
You can also run [error\_log()](https://www.php.net/manual/en/function.error-log.php) to send errors quietly to the log. | The simplest way is to use:
```
echo __FILE__ . ": line " . __LINE__;
die();
```
If you were to use PHP5, you could also use Exceptions:
```
throw new Exception("My error message!");
```
The stack trace will reveal the whole call stack and the line this was thrown on.
(EDIT: Thanks to [@John Isaacs] and [@Emil H] for informing me that Exceptions weren't added to PHP until PHP5) | Specify page/line when throwing die()? | [
"",
"php",
"die",
""
] |
I need to create a table of attributes where each record is essentially just a name-value pair. The problem is that the value can be a string, integer or decimal and I'm using MySQL which doesn't support table inheritance. So, the question is - should I create a separate table for each value type or should I just create str\_value, int\_value and dec\_value columns with an additional value\_type column that tells you which type to use? There won't be many records in this table (less than 100), so performance shouldn't be much of an issue, but I just don't want to make a design decision that's going to make the SQL more complex than it has to be. | Having different tables, or even multiple columns where only one of the 3 are populated, is going to be a nightmare. Store it all as varchar along with a type column. | When querying the database, you will always receive strings, no matter what the column type is - so there is no reason to make a design decision here - just store everything as a string.
By the way: Having an additional value\_type column is redundant - the entry has the type of the only column that has a not-null value. | How do you handle multiple value types in MySQL when inheritance isn't supported? | [
"",
"sql",
"mysql",
""
] |
I'm looking for a Python module that can do simple fuzzy string comparisons. Specifically, I'd like a percentage of how similar the strings are. I know this is potentially subjective so I was hoping to find a library that can do positional comparisons as well as longest similar string matches, among other things.
Basically, I'm hoping to find something that is simple enough to yield a single percentage while still configurable enough that I can specify what type of comparison(s) to do. | Levenshtein Python extension and C library.
[https://github.com/ztane/python-Levenshtein/](http://code.google.com/p/pylevenshtein/)
The Levenshtein Python C extension module contains functions for fast
computation of
- Levenshtein (edit) distance, and edit operations
- string similarity
- approximate median strings, and generally string averaging
- string sequence and set similarity
It supports both normal and Unicode strings.
```
$ pip install python-levenshtein
...
$ python
>>> import Levenshtein
>>> help(Levenshtein.ratio)
ratio(...)
Compute similarity of two strings.
ratio(string1, string2)
The similarity is a number between 0 and 1, it's usually equal or
somewhat higher than difflib.SequenceMatcher.ratio(), becuase it's
based on real minimal edit distance.
Examples:
>>> ratio('Hello world!', 'Holly grail!')
0.58333333333333337
>>> ratio('Brian', 'Jesus')
0.0
>>> help(Levenshtein.distance)
distance(...)
Compute absolute Levenshtein distance of two strings.
distance(string1, string2)
Examples (it's hard to spell Levenshtein correctly):
>>> distance('Levenshtein', 'Lenvinsten')
4
>>> distance('Levenshtein', 'Levensthein')
2
>>> distance('Levenshtein', 'Levenshten')
1
>>> distance('Levenshtein', 'Levenshtein')
0
``` | [difflib](http://docs.python.org/library/difflib.html) can do it.
Example from the docs:
```
>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
['apple', 'ape']
>>> import keyword
>>> get_close_matches('wheel', keyword.kwlist)
['while']
>>> get_close_matches('apple', keyword.kwlist)
[]
>>> get_close_matches('accept', keyword.kwlist)
['except']
```
Check it out. It has other functions that can help you build something custom. | Good Python modules for fuzzy string comparison? | [
"",
"python",
"string",
"string-comparison",
"fuzzy-comparison",
""
] |
I'm building up results by joining tables
```
select t1.*, t2.col2 from t1, t2 where t1.col1=t2.col1
```
Is there a way to create a temporary 'mapping' table 'inline' in a select statement for instances where the t2 table doesn't exist?
So something like
```
select t1.*, tempt2.col2 from t1, (<create temp table>) tempt2 where ...
```
I'm using Oracle | Table with `1` row:
```
SELECT t1.*, t2.col2
FROM t1,
(
SELECT 1 AS col2
FROM dual
) t2
```
Table with `0` rows:
```
SELECT t1.*, t2.col2
FROM t1,
(
SELECT 1 AS col2
FROM dual
WHERE 1 = 0
) t2
```
Table with `N` rows:
```
SELECT t1.*, t2.col2
FROM t1,
(
SELECT 1 AS col2
FROM dual
CONNECT BY
level <= :N
) t2
``` | I'm not sure this is what you're looking for, but you can do multiple SELECTs with UNIONs to get a derived table
```
SELECT t1.*, t2.col2
FROM t1, (
SELECT 1 as Id, 'Foo' as Col2
UNION ALL
SELECT 2 as Id, 'Bar' as Col2
UNION ALL
SELECT 3 as Id, 'FooBar' as Col2
) t2
WHERE
t1.Id = t2.Id
``` | SQL create a temporary 'mapping' table in a select statement | [
"",
"sql",
"oracle",
""
] |
I used to set things like this when I wanted blank values.
```
$blankVar = '';
```
Then after some months, I decided this looked better and had a clearer intent.
```
$blankVar = null;
```
This worked without hiccup for a while, but recently with a PDO prepared statements I ran into a problem. Binding a value to null made the query fail, whilst binding it to '' did not. I needed to bind it to null, so that if a condition was met, it would insert blank data.
What are the differences between the 2? I still think equaling null (or at least a constant) looks better, so should I do this?
```
define('EMPTY', '');
``` | **Null is just another datatype in PHP, which has only one value (null).** Since PHP is a loosly typed language, it can be confusing how it handles different values.
`"", 0, "0", False, array(), Null` are all considered False in PHP.
Null, however, is a different kind of animal. The **main** incompatibility with using Null is that you cannot tell if it isset().
```
$x = false;
isset($x) -> true
echo $x -> ""
$y = null;
isset($y) -> false
echo $y -> ""
//$z is not set
isset($z) -> false
echo $z -> E_NOTICE
```
So null is odd in the sense that it doesn't follow normal variable rules in PHP (at least some). In most cases, it is fine.
**When it comes to database columns, PHP's NULL has no place there.** You see, SQL is a string based language. SQL's NULL must be represented by `NULL` with no quotes.
So if you want an EMPTY field, set it to ""
```
INSERT INTO foo SET bar = ""
```
But if you want a NULL field, set it to NULL
```
INSERT INTO foo SET bar = NULL
```
BIG DIFFERENCE.
But if you try to insert the PHP NULL directly, it will add zero characters to the query, (which leaves you with a blank or syntax error, depending on if you quoted it). | **null** is a special placeholder value in the programming language that literally means "nothing". It's not 0, it's not an empty string, it's nothing. There is no value in memory being pointed to. An empty string, on the other hand, is still a string object, just a very short one :) | In PHP, what is the differences between NULL and setting a string to equal 2 single quotes | [
"",
"php",
"null",
""
] |
I would like to do simple date calculations in Java. For example, compute the difference in days between to dates (having a 0 time component). Of course you could do a simple substraction of milliseconds, divided by the number of milliseconds per day, which works fine - until daylight saving times enter the scene.
I am conscious that different interpretations of the "difference in days" are possible, in particuliar, whether one should take into account the time component or not. Let us assume we have a 0 time component for simplicity.
This kind of calculation seems to be a very common need, and I would find it nice to have a discussion on different approaches to the question. | I would have a look at the [Joda](http://joda-time.sourceforge.net/) date/time library, and in particular the [ReadableInterval](http://joda-time.sourceforge.net/api-release/org/joda/time/ReadableInterval.html) class.
Joda makes life a lot easier when manipulating dates/times in Java, and I believe it's the foundation of the new Java [JSR 310](http://www.infoq.com/news/2007/02/jsr-310) wrt. dates/times. i.e. it (or something very similar) will be present in a future version of Java. | It looks like Date, Calendar, and DateUtils will do everything you're looking for.
<http://commons.apache.org/lang/api/org/apache/commons/lang/time/DateUtils.html>
DateUtils allows truncating or rounding the time so you can just deal with only the dates. You also mentioned daylight savings time. The main problem is when someone says they did something at 01:30 on a day where there was DST change... which 01:30 was it? The first one or the second? Luckily this can be handled by the Calendar class since it stores the timezone and DST offset. For the specifics on all that, check this out:
<http://www.xmission.com/~goodhill/dates/deltaDates.html> | Simple Java Date Calculations | [
"",
"java",
"date-arithmetic",
""
] |
I have a variable, `x`, and I want to know whether it is pointing to a function or not.
I had hoped I could do something like:
```
>>> isinstance(x, function)
```
But that gives me:
```
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
```
The reason I picked that is because
```
>>> type(x)
<type 'function'>
``` | If this is for Python 2.x or for Python 3.2+, you can use [`callable()`](https://docs.python.org/3/library/functions.html#callable). It used to be deprecated, but is now undeprecated, so you can use it again. You can read the discussion here: <http://bugs.python.org/issue10518>. You can do this with:
```
callable(obj)
```
If this is for Python 3.x but before 3.2, check if the object has a `__call__` attribute. You can do this with:
```
hasattr(obj, '__call__')
```
The oft-suggested [`types.FunctionTypes`](https://docs.python.org/3/library/types.html#types.FunctionType) or [`inspect.isfunction`](https://docs.python.org/3/library/inspect.html#inspect.isfunction) approach (both do [the exact same thing](https://github.com/python/cpython/blob/ea46c7bc503d1103d60c0ec7023bb52c5defa11d/Lib/inspect.py#L159-L170)) comes with a number of caveats. It returns `False` for non-Python functions. Most [builtin functions](https://docs.python.org/3/library/functions.html), for example, are implemented in C and not Python, so they return `False`:
```
>>> isinstance(open, types.FunctionType)
False
>>> callable(open)
True
```
so `types.FunctionType` might give you surprising results. The proper way to check properties of duck-typed objects is to ask them if they quack, not to see if they fit in a duck-sized container. | Builtin types that don't have constructors in the built-in namespace (e.g. functions, generators, methods) are in the `types` module. You can use `types.FunctionType` in an `isinstance` call:
```
>>> import types
>>> types.FunctionType
<class 'function'>
>>> def f(): pass
>>> isinstance(f, types.FunctionType)
True
>>> isinstance(lambda x : None, types.FunctionType)
True
```
Note that this uses a very specific notion of "function" that is usually not what you need. For example, it rejects `zip` (technically a class):
```
>>> type(zip), isinstance(zip, types.FunctionType)
(<class 'type'>, False)
```
`open` (built-in functions have a different type):
```
>>> type(open), isinstance(open, types.FunctionType)
(<class 'builtin_function_or_method'>, False)
```
and `random.shuffle` (technically a method of a hidden `random.Random` instance):
```
>>> type(random.shuffle), isinstance(random.shuffle, types.FunctionType)
(<class 'method'>, False)
```
If you're doing something specific to `types.FunctionType` instances, like decompiling their bytecode or inspecting closure variables, use `types.FunctionType`, but if you just need an object to be callable like a function, use `callable`. | How do I detect whether a variable is a function? | [
"",
"python",
""
] |
I am currently working on a web application, I have a JS logging mechanism that Handles Javascript error that are not caught by the js code inside the page. I am using window.onerror to catch all such errors and log them else where.
However, Problem is with Opera which does not have window.onerror event. one approach I could think of is, to string process all js functions code and insert try catch blocks inside those functions after body load. It does not work in many cases though, But, It at least works to some extent.
I am sure this approach sucks, But, I could not think of anything better.
Please advise.
Update: For now, I am calling the code below to Catch as many errors as I could.
```
function OnBodyLoad()
{
var allElements = document.getElementsByTagName("*");
for(var cnt = 0;cnt < allElements.length;cnt++)
{
RegisterAllEvents(allElements[cnt]);
}
}
function RegisterAllEvents(objToProcess){
for(var cnt = 0;cnt < objToProcess.attributes.length;cnt++){
if(IsAttributeAnEvent(objToProcess.attributes[cnt].name))
{
objToProcess.attributes[cnt].value = 'try{'+objToProcess.attributes[cnt].value+'}catch(err){LogError("'+ objToProcess.id+'"'+ ',err);}';
}
}
}
``` | This also happens on Safari, AFAIK.
What you could certainly do is create a global try/catch block for all JS code instead of text parsing - which could be tricky if you come into things like:
```
(function ($){
$(function (){
});
})(jQuery);
``` | Opera 11.60+ supports `window.onerror`.
Opera's [Dragonfly](http://dev.opera.com/articles/view/introduction-to-opera-dragonfly/) supports [remote debugging](http://dev.opera.com/articles/view/remote-debugging-with-opera-dragonfly/). You might be able to [hack it](https://dragonfly.opera.com/app/core-2-2/) (it's all written in JavaScript) and log errors yourself (unfortunately the protocol [isn't published yet](http://dev.opera.com/articles/view/opera-dragonfly-architecture/#scopeprotocol)). | Mimic Window. onerror in Opera using javascript | [
"",
"javascript",
"opera",
""
] |
I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno.
Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at it.
Using ctypes, libc.errno doesn't work because errno is a macro in GNU libc. Python 2.6 has some affordances but Debian still uses Python 2.5. Inserting a C module into my pure Python program just to read errno disgusts me.
Is there some way to access errno? A Linux-only solution is fine, since the library being wrapped is Linux-only. I also don't have to worry about threads, as I'm only running one thread during the time in which this can fail. | Update: On **Python 2.6+**, use [`ctypes.get_errno()`](https://docs.python.org/3/library/ctypes.html#ctypes.get_errno).
## Python 2.5
Belowed code is not reliable (or comprehensive, there are a plefora of ways `errno` could be defined) but it should get you started (or reconsider your position on a tiny extension module (after all on Debian `python setup.py install` or `easy_install` should have no problem to build it)). From <http://codespeak.net/pypy/dist/pypy/rpython/lltypesystem/ll2ctypes.py>
```
if not hasattr(ctypes, 'get_errno'):
# Python 2.5 or older
if sys.platform == 'win32':
standard_c_lib._errno.restype = ctypes.POINTER(ctypes.c_int)
def _where_is_errno():
return standard_c_lib._errno()
elif sys.platform in ('linux2', 'freebsd6'):
standard_c_lib.__errno_location.restype = ctypes.POINTER(ctypes.c_int)
def _where_is_errno():
return standard_c_lib.__errno_location()
elif sys.platform in ('darwin', 'freebsd7'):
standard_c_lib.__error.restype = ctypes.POINTER(ctypes.c_int)
def _where_is_errno():
return standard_c_lib.__error()
ctypes.get_errno = lambda: _where_is_errno().contents.value
```
Where `standard_c_lib`:
```
def get_libc_name():
if sys.platform == 'win32':
# Parses sys.version and deduces the version of the compiler
import distutils.msvccompiler
version = distutils.msvccompiler.get_build_version()
if version is None:
# This logic works with official builds of Python.
if sys.version_info < (2, 4):
clibname = 'msvcrt'
else:
clibname = 'msvcr71'
else:
if version <= 6:
clibname = 'msvcrt'
else:
clibname = 'msvcr%d' % (version * 10)
# If python was built with in debug mode
import imp
if imp.get_suffixes()[0][0] == '_d.pyd':
clibname += 'd'
return clibname+'.dll'
else:
return ctypes.util.find_library('c')
# Make sure the name is determined during import, not at runtime
libc_name = get_libc_name()
standard_c_lib = ctypes.cdll.LoadLibrary(get_libc_name())
``` | Here is a snippet of code that allows to access `errno`:
```
from ctypes import *
libc = CDLL("libc.so.6")
get_errno_loc = libc.__errno_location
get_errno_loc.restype = POINTER(c_int)
def errcheck(ret, func, args):
if ret == -1:
e = get_errno_loc()[0]
raise OSError(e)
return ret
copen = libc.open
copen.errcheck = errcheck
print copen("nosuchfile", 0)
```
The important thing is that you check `errno` as soon as possible after your function call, otherwise it may already be overwritten. | Access to errno from Python? | [
"",
"python",
"linux",
"python-2.5",
"errno",
""
] |
How do I divide two integers to get a double? | You want to cast the numbers:
```
double num3 = (double)num1/(double)num2;
```
Note: If any of the arguments in C# is a `double`, a `double` divide is used which results in a `double`. So, the following would work too:
```
double num3 = (double)num1/num2;
```
For more information see:
[Dot Net Perls](http://www.dotnetperls.com/numeric-casts) | Complementing the @NoahD's answer
To have a greater precision you can cast to decimal:
```
(decimal)100/863
//0.1158748551564310544611819235
```
Or:
```
Decimal.Divide(100, 863)
//0.1158748551564310544611819235
```
Double are represented allocating 64 bits while decimal uses 128
```
(double)100/863
//0.11587485515643106
```
### In depth explanation of "precision"
For more details about the floating point representation in binary and its precision take a look at [this article](http://csharpindepth.com/Articles/General/FloatingPoint.aspx) from Jon Skeet where he talks about `floats` and `doubles` and [this one](http://csharpindepth.com/Articles/General/Decimal.aspx) where he talks about `decimals`. | How can I divide two integers to get a double? | [
"",
"c#",
"math",
"int",
"double",
""
] |
In our app we have resource strings that are apparently too long for the compiler. The build breaks stating the "line length is too long." I have found little information about the topic of lengthy string resources and even had a difficult time finding what the limit on such a resource string is. Eventually I found this article which gives the limit: [MSDN](http://msdn.microsoft.com/en-us/library/cc194808.aspx) .
Have you had any expierence with limits on string resources?
Is there some way to concatonate these without doing any coding?
Any other suggestions would be greatly appriecated. | I would have a look at `RCDATA` resources. I used it to store large text files in my application.
**Edit:** Here is my MFC code, it should be able to give you some pointers.
```
CString CWSApplication::LoadTextResource(UINT nID)
{
HRSRC hResInfo;
HGLOBAL hResData;
hResInfo = ::FindResource(AfxGetResourceHandle(),
MAKEINTRESOURCE(nID),
RT_RCDATA);
if ( hResInfo == NULL )
{
return CString();
}
hResData = ::LoadResource(NULL, hResInfo);
if ( hResData == NULL )
{
return CString();
}
char *data = (char*)(::LockResource(hResData));
DWORD len = ::SizeofResource(NULL, hResInfo);
return CString(data, len);
}
``` | The string resources are designed to store essentially UI-related resources and messages to be shown to the user; this way an application can be internationalized switching from one DLL containing strings for language A to another DLL containing the same string IDs for another language B. I recommend to review for what purpose are you using string resources. If you intend to store large data, use a custom binary resource in the RC. Later you can interpret it as you want. | VC++ Resource Files and Lengthy String Resources | [
"",
"c++",
"resources",
""
] |
Below, I'm *not* declaring `my_ints` as a pointer. I don't know where the memory will be allocated. Please educate me here!
```
#include <iostream>
#include <vector>
class FieldStorage
{
private:
std::vector<int> my_ints;
public:
FieldStorage()
{
my_ints.push_back(1);
my_ints.push_back(2);
}
void displayAll()
{
for (int i = 0; i < my_ints.size(); i++)
{
std::cout << my_ints[i] << std::endl;
}
}
};
```
And in here, I'm declaring the field `my_ints` as a pointer:
```
#include <iostream>
#include <vector>
class FieldStorage
{
private:
std::vector<int> *my_ints;
public:
FieldStorage()
{
my_ints = new std::vector<int>();
my_ints->push_back(1);
my_ints->push_back(2);
}
void displayAll()
{
for (int i = 0; i < my_ints->size(); i++)
{
std::cout << (*my_ints)[i] << std::endl;
}
}
~FieldStorage()
{
delete my_ints;
}
};
```
`main()` function to test:
```
int main()
{
FieldStorage obj;
obj.displayAll();
return 0;
}
```
Both of them produces the same result. What's the difference? | In terms of memory management, these two classes are virtually identical. Several other responders have suggested that there is a difference between the two in that one is allocating storage on the stack and other on the heap, but that's not necessarily true, and even in the cases where it is true, it's terribly misleading. In reality, all that's different is where the *metadata* for the `vector` is allocated; the actual underlying storage in the `vector` is allocated from the heap regardless.
It's a little bit tricky to see this because you're using `std::vector`, so the specific implementation details are hidden. But basically, `std::vector` is implemented like this:
```
template <class T>
class vector {
public:
vector() : mCapacity(0), mSize(0), mData(0) { }
~vector() { if (mData) delete[] mData; }
...
protected:
int mCapacity;
int mSize;
T *mData;
};
```
As you can see, the `vector` class itself only has a few members -- capacity, size and a pointer to a dynamically allocated block of memory that will store the actual contents of the vector.
In your example, the only difference is where the storage for those few fields comes from. In the first example, the storage is allocated from whatever storage you use for your containing class -- if it is heap allocated, so too will be those few bits of the `vector`. If your container is stack allocated, so too will be those few bits of the `vector`.
In the second example, those bits of the `vector` are always heap allocated.
In both examples, the actual *meat* of the `vector` -- the contents of it -- are allocated from the heap, and you cannot change that.
Everybody else has pointed out already that you have a memory leak in your second example, and that is also true. Make sure to delete the vector in the destructor of your container class. | You have to release ( to prevent memory leak ) memory allocated for vector in the second case in the FieldStorage destructor.
```
FieldStorage::~FieldStorage()
{
delete my_ints;
}
``` | What's the difference between these two classes? | [
"",
"c++",
"memory",
""
] |
I am curious about how to find out what the maximum stack size is for a particular compiler/os combo. I am using Ubuntu/GNU compiler. A few questions I have in addition are:
1. Who controls the default maximum stack size; OS or compiler?
2. Is the default maximum scaled according to total memory? (ie a machine with 2gb memory would have larger default size than a machine with only 512mb) For this example both machines are same os/compiler setup, just different amounts of system RAM.
Thanks! | > Who controls the default maximum stack size; OS or compiler?
The compiler typically. The OS/hardware does limit it to a certain extent. Default is 8MB on linux IIRC. Think of `ulimit -s` on Linux (to change stack sizes).
> Is the default maximum scaled according to total memory? (ie a machine with 2gb memory would have larger default size than a machine with only 512mb) For this example both machines are same os/compiler setup, just different amounts of system RAM.
No. Until and unless you do it yiurself.You can alter stack sizes via compiler switches.
```
ld --stack=<STACK_SIZE>
```
or
```
gcc -Wl,--stack=<STACK_SIZE>
```
> The C++ Standard's take on the issue of stacks and heaps:
The standard is based on an abstract machine and does not really concern itself with hardware or stacks or heaps. It does talk about an allocated store and a free store. The free store is where you'd be if you are calling new (mostly). FWIW, an implementation can have only one memory area masquerading as both stack and heap when it comes to object allocation.
Your question, therefor, boils down to be an implementation specific issue rather than a language issue.
Hope this helps. | On Linux (Ubuntu), operating system controls the maximum size. See "man limit" or "man ulimit" for reference. | How can you find out the maximum size of the memory stack for a C++ program on linux? (gnu compiler) | [
"",
"c++",
"memory",
"gnu",
""
] |
On Linux, the command ps aux outputs a list of processes with multiple columns for each stat. e.g.
```
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
...
postfix 22611 0.0 0.2 54136 2544 ? S 15:26 0:00 pickup -l -t fifo -u
apache 22920 0.0 1.5 198340 16588 ? S 09:58 0:05 /usr/sbin/httpd
```
I want to be able to read this in using Python and split out each row and then each column so they can be used as values.
For the most part, this is not a problem:
```
ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
processes = ps.split('\n')
```
I can now loop through processes to get each row and split it out by spaces, for example
```
sep = re.compile('[\s]+')
for row in processes:
print sep.split(row)
```
However, the problem is that the last column, the command, sometimes has spaces in. In the example above this can be seen in command
```
pickup -l -t fifo -u
```
which would be split out as
```
['postfix', '22611', '0.0', '0.2', '54136', '2544', '?', 'S', '15:26', '0:00', 'pickup', '-l', '-t', 'fifo', '-u']
```
but I really want it as:
```
['postfix', '22611', '0.0', '0.2', '54136', '2544', '?', 'S', '15:26', '0:00', 'pickup -l -t fifo -u']
```
So my question is, how can I split out the columns but when it comes to the command column, keep the whole string as one list element rather than split out by spaces? | Use the second parameter to `split` which specifies the maximum number of fields to split the string into. I guess you can find the number by counting the number of fields in the first line, i.e. the column titles.
```
ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
processes = ps.split('\n')
# this specifies the number of splits, so the splitted lines
# will have (nfields+1) elements
nfields = len(processes[0].split()) - 1
for row in processes[1:]:
print row.split(None, nfields)
``` | Check out the [python.psutils](http://pypi.python.org/pypi/psutil/) package.
`psutil.process_iter` returns a generator which you can use to iterate over all processes.
`p.cmdline` is a list of each Process object's cmdline arguments, separated just the way you want.
You can create a dictionary of pids vs `(pid,cmdline,path)` with just one line and then use it anyway you want.
```
pid_dict = dict([(p.pid, dict([('pid',p.pid), ('cmdline',p.cmdline), ('path',p.path)]))
for p in psutil.process_iter()]))
``` | Splitting out the output of ps using Python | [
"",
"python",
"regex",
"linux",
""
] |
I have read a lot about ReSharper on here. It sounds like it has a lot of cool features to help the programmer out. Trouble is, I don't write C#.
Is there any tool that has similar functionality to ReSharper, but for Java instead?
Thank you! | Use [IntelliJ IDEA](http://www.jetbrains.com/idea/index.html) an IDE from JetBrains - the creator of ReSharper.
It's not "like resharper" - it's the original and resharper is like it for C#. | I believe most Java IDEs already have it - I certainly view ReSharper as [the tool which brings Visual Studio up to the level of Eclipse](http://codeblog.jonskeet.uk/archive/2007/03/27/visual-studio-2005-vs-eclipse-again-but-this-time-with-resharper) :)
Do you have any specific R# features in mind? | A tool like ReSharper, but for Java? | [
"",
"java",
"resharper",
""
] |
I'm using VS2008, been using it for quite some time now, and since I [hate using the mouse while developing](http://www.codinghorror.com/blog/archives/000825.html), I'm always using `F6` to build the solution, or `Shift`+`F6` to build the current project. What's weird though is for some strange reason, it simply stopped working over the last few days. In fact, when I pull down the Build menu, next to "Build MyProject" there's no longer a "`Shift`+`F6`" shortcut there on the menu?!? Anyone ever experienced this? Is there a setting I need to change? | You can change keyboard bindings in the Tools->Options dialog. It's under Environment->Keyboard.
You can reset the binding here, and also check what might have stolen it by checking what's currently bound to those keys.
If you recently installed any add-ins, they're known to set (sometimes unwanted) keyboard shortcuts. | Your Keyboard Mapping Scheme has changed.
Go to Tools -> Options. In Environments->Keyboard in the dropdown for "Apply the following additional mapping scheme" select **"Visual C# 2005"** | Visual Studio F6 stopped working. It no longer builds the project | [
"",
"c#",
".net",
"visual-studio",
"visual-studio-2008",
"keyboard-shortcuts",
""
] |
I can't find a definitive answer for this. As far as I know, you can't have multiple `__init__` functions in a Python class. So how do I solve this problem?
Suppose I have a class called `Cheese` with the `number_of_holes` property. How can I have two ways of creating cheese objects...
1. One that takes a number of holes like this: `parmesan = Cheese(num_holes=15)`.
2. And one that takes no arguments and just randomizes the `number_of_holes` property: `gouda = Cheese()`.
I can think of only one way to do this, but this seems clunky:
```
class Cheese:
def __init__(self, num_holes=0):
if num_holes == 0:
# Randomize number_of_holes
else:
number_of_holes = num_holes
```
What do you say? Is there another way? | Actually `None` is much better for "magic" values:
```
class Cheese:
def __init__(self, num_holes=None):
if num_holes is None:
...
```
Now if you want complete freedom of adding more parameters:
```
class Cheese:
def __init__(self, *args, **kwargs):
# args -- tuple of anonymous arguments
# kwargs -- dictionary of named arguments
self.num_holes = kwargs.get('num_holes', random_holes())
```
To better explain the concept of `*args` and `**kwargs` (you can actually change these names):
```
def f(*args, **kwargs):
print('args:', args, 'kwargs:', kwargs)
>>> f('a')
args: ('a',) kwargs: {}
>>> f(ar='a')
args: () kwargs: {'ar': 'a'}
>>> f(1,2,param=3)
args: (1, 2) kwargs: {'param': 3}
```
<http://docs.python.org/reference/expressions.html#calls> | Using `num_holes=None` as the default is fine if you are going to have just `__init__`.
If you want multiple, independent "constructors", you can provide these as [class methods](https://docs.python.org/library/functions.html#classmethod). These are usually called factory methods. In this case you could have the default for `num_holes` be `0`.
```
class Cheese(object):
def __init__(self, num_holes=0):
"defaults to a solid cheese"
self.number_of_holes = num_holes
@classmethod
def random(cls):
return cls(randint(0, 100))
@classmethod
def slightly_holey(cls):
return cls(randint(0, 33))
@classmethod
def very_holey(cls):
return cls(randint(66, 100))
```
Now create object like this:
```
gouda = Cheese()
emmentaler = Cheese.random()
leerdammer = Cheese.slightly_holey()
``` | What is a clean "pythonic" way to implement multiple constructors? | [
"",
"python",
"class",
"constructor",
""
] |
I have image, and on mouse over it fades in two arrows (on the left and right sides), then on mouseout it fades those arrows out. My problem is that when the user hovers over the arrows, the image considers it a mouseout (since the arrows float above the image), and fades the arrows out, causing an infinate loop of fading in/out until you move the mouse away. What is the best way to prevent the arrows from fading out when the mouse hovers over them? I've tried one method, which you'll see below, but that hasen't been working out...
Here's some code:
```
$(".arrow").mouseover(function() {
overArrow = 1;
$("#debug_oar").text(1)
})
$(".arrow").mouseout(function() {
overArrow = 0;
$("#debug_oar").text(0)
})
$("#image").mouseout(function() {
$(".arrow").fadeOut(250,function() { $(".arrow").remove();})
})
$("#image").mouseover(function() {
if(overArrow == 0) {
$("#image").after("<div class='arrow' id='lArrow' style='display:none;position:absolute;'>←</div><div class='arrow' id='rArrow' style='display:none;position:absolute;'>→</div>")
// Define variables...
aWidth = $("#lArrow").width();
aHeight = $("#lArrow").height();
height = $("#image").height()
width = $("#image").width()
pos = $("#image").position();
// Calculate positioning
nHeight = height/2
y = pos.top + nHeight - (aHeight/2)
// Position the left arrow
$("#lArrow").css("top",y)
$("#lArrow").css("left",pos.left+10)
// Now the right...
$("#rArrow").css("top",y)
$("#rArrow").css("left",pos.left+width-aWidth-20)
// Display 'em
$(".arrow").fadeIn(250);
// Debug info
$("#debug_x").text(pos.left)
$("#debug_y").text(y)
$("#debug_height").text(height)
}
})
```
Thanks
For those who are interested in the final code:
```
$("#image").mouseenter(function() {
$("#image").append("<div class='arrow' id='lArrow' style='display:none;position:absolute;'>←</div><div class='arrow' id='rArrow' style='display:none;position:absolute;'>→</div>")
// Define variables...
aWidth = $("#lArrow").width();
aHeight = $("#lArrow").height();
height = $("#image").height()
width = $("#image").width()
pos = $("#image").position();
// Calculate positioning
nHeight = height/2
y = pos.top + nHeight - (aHeight/2)
// Position the left arrow
$("#lArrow").css("top",y)
$("#lArrow").css("left",pos.left+10)
// Now the right...
$("#rArrow").css("top",y)
$("#rArrow").css("left",pos.left+width-aWidth-20)
// Display 'em
$(".arrow").fadeIn(250);
// Debug info
$("#debug_x").text(pos.left)
$("#debug_y").text(y)
$("#debug_height").text(height)
});
$("#image").mouseleave(function() {
$(".arrow").fadeOut(250,function() { $(".arrow").remove();})
})
``` | Try to call [stopPropagation()](http://docs.jquery.com/Events/jQuery.Event#event.stopPropagation.28.29) on your events, or use an alternative event that stops propagation by default like, [mouseenter](http://docs.jquery.com/Events/mouseenter), [mouseleave](http://docs.jquery.com/Events/mouseleave) or [hover(over, out)](http://docs.jquery.com/Events/hover). | The arrows probably aren't children of the image, so hovering them *is* leaving the image.
You want to wrap the image and the arrows with a wrapper element, and put the hover() call on that element instead. That way hovering over either the image or arrows triggers it.
Alternately, learn how to use event delegation. Attach hover() to a higher up element that happens to encompass them both, and then check the target of the hover every time. If it matches either the image or the arrows, trigger the appropriate animation on the arrows.
[This is a good tutorial explaining event delegation in jQuery and how to use it.](http://lab.distilldesign.com/event-delegation/)
Finally, just for simplicity, use hover() rather than mouseover()/mouseout(). It captures your intent much more clearly. The first function you pass to hover() gets applied on mouseover, the second gets applied on mouseout. | jQuery mouseover issues | [
"",
"javascript",
"jquery",
"events",
""
] |
I have a bookmarklet which inserts a CSS stylesheet into the target DOM via a "link" tag (external stylesheet).
Recently, this stopped working on Amazon.com, in Internet Explorer only. It works on other sites, and with other browsers (even on Amazon.com). The technique we're using to insert the stylesheet is pretty straightforward:
```
document.getElementsByTagName('head')[0].appendChild(s);
```
Where "s" is a link object created with `document.createElement`. Even on Amazon, I see via the Internet Explorer Developer Toolbar DOM inspector that the element is there. **However** if I alert the `document.styleSheets` collection in JavaScript, it's not there.
As a test, I tried to use the IE-only [document.createStyleSheet](http://msdn.microsoft.com/en-us/library/ms531194(VS.85).aspx) method passing the URL to my stylesheet as an argument. This throws the error:
> Not enough storage is available to
> complete this operation
Points of interest:
* The documentation for `document.createStyleSheet` says an error will be thrown if there are more than 31 stylesheets on the page but (1) it's a different error, and (2) there are only 10 external stylesheets on the page.
* My googling for the error turned up a number of dead-ends, and the only one that suggested anything stylesheet-related was [this drupal post](http://drupal.org/node/114188), but it refers to a character limit on inline styles, as opposed to a problem relating to external styles.
* The same code, even the `createStyleSheet` call, works on other sites in IE.
This has reached "complete mystery" status for me. | I just tried this
```
javascript:(function(d) { d.createStyleSheet().cssText="* {color:blue !important;}" })(document);
```
and
```
javascript:(function(d) { d.createStyleSheet("http://myschemas.com/pub/clear.css") })(document);
```
from IE on amazon.com and both worked.
Maybe you need to add the !important to some items of your css to be sure they take effect now?
UPDATE:
Found a possible solution for you...
```
javascript:(function(c) {c[c.length-1].addImport("http://myschemas.com/pub/clear.css")})(document.styleSheets);
```
Hope it helps you. | Looking for an answer, I have found that the 31 stylesheets limit raise this exception when loading CSS programatically:
<http://www.telerik.com/community/forums/aspnet-ajax/general-discussions/not-enough-storage-is-available-to-complete-this-operation.aspx>
The original limitation is described in a Knowledge Base document (suppossed only to happen on IE8 and below, but repeatedly reported as happening in IE9):
<http://support.microsoft.com/kb/262161> | Trouble programmatically adding CSS to IE | [
"",
"javascript",
"internet-explorer",
"dom-manipulation",
""
] |
I can't seem to get the right magic combination to make this work:
```
OracleDataSource ods = new oracle.jdbc.pool.OracleDataSource();
ods.setURL("jdbc:oracle:thin:app_user/pass@server:1521:sid");
DefaultContext conn = ods.getConnection();
CallableStatement st = conn.prepareCall("INSERT INTO tableA (some_id) VALUES (1) RETURNING ROWID INTO :rowid0");
st.registerReturnParameter(1, OracleTypes.ROWID);
st.execute();
```
The error I get is "Protocol Violation". If I change to registerOutParameter(), I get notified that I haven't registered all return variables. If I wrap the statement in a PL/SQL begin; end; block then I get the parameter just fine using a regular registerOutParameter() call. I would really prefer to avoid wrapping all my inserts statements in PL/SQL - so what is missing from above? | A few things you'll need to do
* Change CallableStatement to OracleCallableStatement
* Try and return into a NUMBER, ie: OracleTypes.Number
Sample code for returning info from a query:
```
OraclePreparedStatement pstmt = (OraclePreparedStatement)conn.prepareStatement(
"delete from tab1 where age < ? returning name into ?");
pstmt.setInt(1,18);
/** register returned parameter
* in this case the maximum size of name is 100 chars
*/
pstmt.registerReturnParameter(2, OracleTypes.VARCHAR, 100);
// process the DML returning statement
count = pstmt.executeUpdate();
if (count>0)
{
ResultSet rset = pstmt.getReturnResultSet(); //rest is not null and not empty
while(rset.next())
{
String name = rset.getString(1);
...
}
}
```
More info on Oracle's JDBC extensions:
* <http://download-uk.oracle.com/docs/cd/B19306_01/java.102/b14355/oraint.htm> | Usually you don't want to make code database dependent. Instead of OraclePreparedStatement, you should use CallableStatement.
```
CallableStatement statement = connection.prepareCall("{call INSERT INTO tableA (some_id) VALUES (1) RETURNING ROWID INTO ? }");
statement.registerOutParameter( 1, Types.VARCHAR );
int updateCount = statement.executeUpdate();
if (updateCount > 0) {
return statement.getString(1);
}
``` | Return ROWID Parameter from insert statement using JDBC connection to oracle | [
"",
"java",
"oracle",
"jdbc",
""
] |
I found the following code in a library:
```
class Bar {
public:
bool foo(int i) {
return foo_(i);
}
private:
virtual bool foo_(int i) = 0;
};
```
Now I'm wondering: Why would you use this indirection? Could there be any reasons why the above would be better than the simple alternative:
```
class Bar {
public:
virtual bool foo(int i) = 0;
};
``` | This is the [Non-Virtual Interface Idiom](http://www.gotw.ca/publications/mill18.htm) (NVI). That page by Herb Sutter has a good bit of detail about it. However, temper what you read there with what the C++ FAQ Lite says [here](http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.3) and [here](http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.4).
The primary advantage of NVI is separating interface from implementation. A base class can implement a generic algorithm and present it to the world while its subclasses can implement the details of the algorithm through virtual functions. Outside users are shielded from changes in the algorithm details, especially if you later decide you want to do add pre- and post-processing code.
The obvious disadvantage is that you have to write extra code. Also, `private` virtual functions are confusing to a lot of people. Many coders mistakenly think you can't override them. Herb Sutter seems to like `private` virtuals, but IMHO it's more effective in practice to follow the C++ FAQ Lite's recommendation and make them `protected`. | This is often called a Template-Hook pair (a.k.a Hotspot), coined by Wolfgang Pree.
See this [PDF](http://www.exciton.cs.rice.edu/comp410/frameworks/Pree/J008.pdf), [PowerPoint](http://davidvancamp.com/OODWkshp_files/Ood_wk18.ppt), [HTML](http://alumni.media.mit.edu/~tpminka/patterns/ET++/)
One reason for doing the *indirection* as you call it is that things often can/has to be *setup* prior a method, and some cleaing *post* a method call. In the subclasses you only need to supply the necessary behaviour without doing the *setup* and *cleaning*... | What's the advantage of this indirect function call? | [
"",
"c++",
"inheritance",
"function",
"abstract-class",
"virtual-functions",
""
] |
I have a program that will analyzes source code. It can recursively go through a directory to find all projects, and then recursively go through the project to find all source code.
I want to create a cancel process button, which allows the user to stop the code parsing. I run the code parsing in a background worker. I want to be able to watch for the cancel event.
The problem is figuring out how to edit my code so that it will go and check that item and return back to the GUI. The parsing process goes several methods deep.
In a much smaller process, I successfully use a thread-safe singleton that has a bool that says whether or not a cancel has been requested, and stop the loop where it is running.
What would be the best way of working this cancel request into my code?
EDIT: Here is an idea, inspired by John Saunders' answer.
What if I run a background thread in my processing thread that watches for the Cancel Singleton to change, and then throw an exception from that process? Does this seem like good practice? This does not work as intended
EDIT 2: John Saunders' answer seems to be the best for now. I will just throw my own exception when the Singleton is true for now. I'll wait to see if any other solutions are proposed | Thread.Abort is a bad idea, as it interrupts the thread at an arbitrary point - probably interrupts it where you'd least like to be interrupted.
Set a flag that it seen by the thread being cancelled. Check it at the beginning of each operation. The idea would be to identify places in the code where it is safe to stop, and to check the flag at only those points.
You may find it useful to throw an exception at those points. The exception should be one that is not caught by your code until it reaches the boundary between your code and the UI. At that point, your code would simply return. | You could use the `Thread.Abort()` function on your background worker thread. This throws a `ThreadAbortException` which you can catch in any of your methods but which will atomatically be rethrown at the end of the `catch` blocks.
Also all `finally`-blocks will be executed. | Creating a cancel scheme | [
"",
"c#",
"events",
"program-flow",
""
] |
I stumbled upon this piece of code which seems totaly broken to me, but it does happen that `this` is `null`. I just don't get how this can be `null`
it is inside a normal method call such as
```
myObject->func();
```
inside `MyObject::func()` we have
```
if (!this) { return false; }
```
is there any way I can have the first line to throw a `NullPointerException` instead of going inside the `null`(?) method? | If you have:
```
MyObject *o = NULL;
o->func();
```
What happens next depends on whether `func` is virtual. If it is, then it will crash, because it needs an object to get the vtable from. But if it's not virtual the call proceeds with the this pointer set to NULL.
I believe the standard says this is "undefined behaviour", so anything could happen, but typical compilers just generate the code to not check whether the pointer is NULL. Some well known libraries rely on the behaviour I described: MFC has a function called something like `SafeGetHandle` that can be called on a null pointer, and returns NULL in that case.
You might want to write a reusable helper function:
```
void CheckNotNull(void *p)
{
if (p == NULL)
throw NullPointerException();
}
```
You can then use that at the start of a function to check all its arguments, including `this`:
```
CheckNotNull(this);
``` | A way to trap these kind of errors (by design) is using a pointer-wrapper class (resembling a `shared_ptr`) that throws upon creation with a null pointer argument. It may throw also when dereferenced, but that's a little late - better than nothing, I guess. | if (!this) { return false; } | [
"",
"c++",
"null",
"this",
""
] |
How do I expose a class from a dll ?
The application importing the dll should be able to create the objects of the class and also he should be able to call into the member functions of the class .
Is it similar to exposing C type functions using `__declspec(dllexport)` ?
And also when I built the dll ( which only contains class definition in a header file and its member function definitions in a cpp file ) , no corresponding lib file is created . | > Is it similar to exposing C type functions using `_declspec(dllexport)` ?
Yes. And the \_\_declspec can be applied to the class.
> no corresponding lib file is created
IIRC this is the default, but you can override default linker options. | [Here](http://msdn.microsoft.com/en-us/library/a90k134d(VS.80).aspx). Remember you cannot use this exported class using LoadLibrary()/GetProcAddress(). | Exporting a class from a C++ dll? | [
"",
"c++",
"winapi",
"visual-c++",
""
] |
For a university assignment I have been assigned I have a Prize object which contains either text, image, or video content. I would like to persist this information into a BLOB field within an Apache Derby database (which will be running on a low powered PDA). How can I add this data to the database?
Thanks in advance. | In this article [Five Steps to Managing Unstructured Data with Derby](http://www.ibmpressbooks.com/articles/article.asp?p=1146304&seqNum=3)
you can read how to do this.
It describes how to insert binary data into a column with the BLOB datatype in Apache Derby using JDBC. | I assume you'll be connecting via JDBC. If so, simply write your SQL and look at the setBlob method of a PreparedStatement. Should be pretty straightforward. | Adding Java Objects to database | [
"",
"java",
"database",
"blob",
"derby",
""
] |
I've stumbled upon the following pecularity:
$handle = fopen(realpath("../folder/files.php"), "r");
can't read a file, but as soon as I remove php tags from the file,
it becomes readable and my scripts prints non-empty file content on the page.
Also, file.php is never ever executed, so I wonder why it is the problem.
I guess somehow Apache or PHP doesn't let read files containing php tags PHP as just text.
How can I enable it for my particular file (course doing it globally would be unsecure)?
Using PHP 5.2.x and Apache 2.0 | I got it. I was using Google chrome to debug the page, and I realized that when viewing the source, Chrome hides PHP tags for some reason. I ran the same test on Firefox, and viewing the source proved that everything was okay.
Here are the test details:
Code:
```
$fh = fopen("test.php","r");
while ($line = fgets($fh)){
echo $line;
}
```
File to be read (test.php):
```
testing <?php testing2 ?> testing3
```
Rendering (on both Chrome and firefox):
```
testing testing3
```
View source (using firefox):
```
testing <?php testing2 ?> testing3
```
View source (using Chrome - source of my mistake):
```
testing testing3
``` | Are you sure you're interpreting the output correctly? If you print the file contents directly to your page output, a browser won't display text inside angle brackets because it thinks it's a tag. Serve your content as `text/plain`, or use your browser's "view source" command to make sure you're looking at what's really there, and not just what the browser chose to display. | PHP can't read files containing PHP code as text files | [
"",
"php",
"security",
"permissions",
"fopen",
""
] |
## Introduction a.k.a. what do I intend to do
*feel free to skip this part, no real information is comprised in here*
Because of the lack of a good, free (as in speech) `vim`-Mode for the otherwise excellent JavaEditor in Eclipse(3.4), I'm thinking about writing one. The available solutions are:
* [ViPlugin](http://www.viplugin.com/viplugin/): commercial and not good (e.g. no `vim` `text-objects`, such as `daW`)
* [VimPlugin](http://vimplugin.org/): new editor, not the power of the built in JavaEditor
* see [SO: *Painless* integration of Eclipse with Vim?](https://stackoverflow.com/questions/597117/painless-integration-of-eclipse-with-vim) : nothing really good turned up
(However feel free to mention **other** solutions than the ones above which could help me.)
In my opinion, it's the wrong way of writing a completely new editor based on [`TextEditor`](http://help.eclipse.org/stable/topic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/ui/editors/text/TextEditor.html), because you will then loose the cool features the standard JavaEditor gives you for free (such as 'organize imports', 'refactor menu', ...).
I'm thinking of a 'skin' to the normal JavaEditor which behaves like `vim`, everything else should be unchanged.
## Now the questions
* How can I detect if a [`IWorkbenchPart`](http://help.eclipse.org/stable/topic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/ui/IWorkbenchPart.html) given by [`IPartListener.partActivated()`](http://help.eclipse.org/stable/topic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/ui/IPartListener.html#partActivated(org.eclipse.ui.IWorkbenchPart)) is the JavaEditor?
* How can I then replace JavaEditor's [`KeyListener`](http://help.eclipse.org/stable/topic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/swt/events/KeyListener.html); something like the [`ITextViewerExtension.prependVerifyKeyListener`](http://help.eclipse.org/stable/topic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/jface/text/ITextViewerExtension.html#prependVerifyKeyListener(org.eclipse.swt.custom.VerifyKeyListener)) is needed?
* Is this a good way to go on? | I am the developer of something you might be looking for. It is still under heavy development and does not have all features you are looking for, but I am working hard on it and I am always open for feature and enhancement requests.
The plugin is called [Vrapper](http://vrapper.sourceforge.net).
It is FOSS and follows the principles you describe, although I don't think it is much more powerful than the ViPlugin at the moment. But as I said, I am constantly working on it and try to respond fast to feature requests. :-) | I use the VI plugin from [here](http://www.satokar.com/viplugin/) (note: this link is down as of the time of writing and I'm hoping it'll be back soon). This works very well indeed and ties in very well with the coding/refactoring capabilities of Eclipse (see [this answer](https://stackoverflow.com/questions/495268/any-good-tutorial-for-moving-from-eclipse-to-vim)).
So you may want to try that link (if it comes up!) before you embark on engineering your own solution :-) | Extending Eclipse's JavaEditor (to act like Vim/change KeyListener) | [
"",
"java",
"eclipse",
"vim",
"eclipse-plugin",
"eclipse-rcp",
""
] |
While looking over various PHP libraries I've noticed that a lot of people choose to prefix some class methods with a single underscore, such as
```
public function _foo()
```
...instead of...
```
public function foo()
```
I realize that ultimately this comes down to personal preference, but I was wondering if anyone had some insight into where this habit comes from.
My thought is that it's probably being carried over from PHP 4, before class methods could be marked as protected or private, as a way of implying "do not call this method from outside the class". However, it also occurred to me that maybe it originates somewhere (a language) I'm not familiar with or that there may be good reasoning behind it that I would benefit from knowing. | It's from the bad old days of Object Oriented PHP (PHP 4). That implementation of OO was pretty bad, and didn't include things like private methods. To compensate, PHP developers prefaced methods that were intended to be private with an underscore. In some older classes you'll see `/**private*/ __foo() {` to give it some extra weight.
I've never heard of developers prefacing all their methods with underscores, so I can't begin to explain what causes that. | I believe the most authoritative source for these kinds of conventions for PHP right now would be the [PSR-2: Coding Style Guide](http://www.php-fig.org/psr/psr-2/) because the Zend Framework is part of [PSR](http://www.php-fig.org/members/):
> Property names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility. | What's the deal with a leading underscore in PHP class methods? | [
"",
"php",
""
] |
I have recently taken on a php web developer position for a large firm. They have multiple sites that share much of the same content (mainly news articles). All the sites although written in PHP, the content is static and manually edited on all the sites when a news article is added or other information is changed. The "senior programmer" there is against using a cms for some reason, against upgrading to php 5, against installing mod\_rewrite, basically I have to work within a very small parameter.
I have taken the first 3 weeks to write a whole lot of classes to make some sort of sanity out the mess, but I have to find a way to replicate this data in an easy manner. I am thinking something without the need of a database (the head guy doesnt want to decentralise data so databases anywhere other than the intranet are a no-no), I just want a centralised XML file or something, even if I need to hand edit it... any ideas??? | Treat PHP as a templating engine, and have all the main pages pull the html marked up (or xml) articles from an RSS feed from one site.
Edit the feed to add a new article, add the marked up article to the main site, and it's all very, very simple, easy to understand, and scales.
No need to involved a 'real' cms, database, or anything.
-Adam | User one folder for all documents which your websites consume. | Shared data multiple sites | [
"",
"php",
"php4",
""
] |
I have a large collection of strings (up to 1M) alphabetically sorted. I have experimented with LINQ queries against this collection using HashSet, SortedDictionary, and Dictionary. I am static caching the collection, it's up to 50MB in size, and I'm always calling the LINQ query against the cached collection. My problem is as follows:
Regardless of collection type, performance is much poorer than SQL (up to 200ms). When doing a similar query against the underlying SQL tables, performance is much quicker ( 5-10ms). I have implemented my LINQ queries as follows:
```
public static string ReturnSomething(string query, int limit)
{
StringBuilder sb = new StringBuilder();
foreach (var stringitem in MyCollection.Where(
x => x.StartsWith(query) && x.Length > q.Length).Take(limit))
{
sb.Append(stringitem);
}
return sb.ToString();
}
```
It is my understanding that the HashSet, Dictionary, etc. implement lookups using binary tree search instead of the standard enumeration. What are my options for high performance LINQ queries into the advanced collection types? | In your current code you don't make use of any of the special features of the `Dictionary` / `SortedDictionary` / `HashSet` collections, you are using them the same way that you would use a `List`. That is why you don't see any difference in performance.
If you use a dictionary as index where the first few characters of the string is the key and a list of strings is the value, you can from the search string pick out a small part of the entire collection of strings that has possible matches.
I wrote the class below to test this. If I populate it with a million strings and search with an eight character string it rips through all possible matches in about 3 ms. Searching with a one character string is the worst case, but it finds the first 1000 matches in about 4 ms. Finding all matches for a one character strings takes about 25 ms.
The class creates indexes for 1, 2, 4 and 8 character keys. If you look at your specific data and what you search for, you should be able to select what indexes to create to optimise it for your conditions.
```
public class IndexedList {
private class Index : Dictionary<string, List<string>> {
private int _indexLength;
public Index(int indexLength) {
_indexLength = indexLength;
}
public void Add(string value) {
if (value.Length >= _indexLength) {
string key = value.Substring(0, _indexLength);
List<string> list;
if (!this.TryGetValue(key, out list)) {
Add(key, list = new List<string>());
}
list.Add(value);
}
}
public IEnumerable<string> Find(string query, int limit) {
return
this[query.Substring(0, _indexLength)]
.Where(s => s.Length > query.Length && s.StartsWith(query))
.Take(limit);
}
}
private Index _index1;
private Index _index2;
private Index _index4;
private Index _index8;
public IndexedList(IEnumerable<string> values) {
_index1 = new Index(1);
_index2 = new Index(2);
_index4 = new Index(4);
_index8 = new Index(8);
foreach (string value in values) {
_index1.Add(value);
_index2.Add(value);
_index4.Add(value);
_index8.Add(value);
}
}
public IEnumerable<string> Find(string query, int limit) {
if (query.Length >= 8) return _index8.Find(query, limit);
if (query.Length >= 4) return _index4.Find(query,limit);
if (query.Length >= 2) return _index2.Find(query,limit);
return _index1.Find(query, limit);
}
}
``` | I bet you have an index on the column so SQL server can do the comparison in O(log(n)) operations rather than O(n). To imitate the SQL server behavior, use a sorted collection and find all strings s such that s >= query and then look at values until you find a value that does not start with s and then do an additional filter on the values. This is what is called a range scan (Oracle) or an index seek (SQL server).
This is some example code which is very likely to go into infinite loops or have one-off errors because I didn't test it, but you should get the idea.
```
// Note, list must be sorted before being passed to this function
IEnumerable<string> FindStringsThatStartWith(List<string> list, string query) {
int low = 0, high = list.Count - 1;
while (high > low) {
int mid = (low + high) / 2;
if (list[mid] < query)
low = mid + 1;
else
high = mid - 1;
}
while (low < list.Count && list[low].StartsWith(query) && list[low].Length > query.Length)
yield return list[low];
low++;
}
}
``` | LINQ Performance for Large Collections | [
"",
"c#",
".net",
"linq",
"performance",
""
] |
i want search a value in on row like this
```
<p align="center"><input type="hidden" name="e79e7ec" value="15302f565b">
```
i need name="" value and value="" value :P create this code , but this code dosent work
```
Regex rloginRand = new Regex(@"<p align=center><input type=hidden name=\w*");
Match mloginRand = rloginRand.Match(source);
string loginrand = "";
if (mloginRand.Success)
{
loginrand = mloginRand.ToString().Replace("<p align=center><input type=hidden name=", "");
}
string loginrnd = "";
Regex rloginRnd = new Regex(@"name="+ loginrand+"value=\w*");
Match mloginRnd = rloginRnd.Match(source);
if (mloginRand.Success)
{
loginrnd = mloginRnd.ToString().Replace("name="+loginrand+" value=", "");
}
```
error is
Form1.cs(71,69): error CS1009: Unrecognized escape sequence
at this line
Regex rloginRnd = new Regex(@"name="+ loginrand+"\*\*\*value=\w\*\*\*\*"); | You need to put an `@` before each part of the string:
```
Regex rloginRnd = new Regex(@"name="+ loginrand+@"value=\w*");
``` | Regex is not always the best tool for HTML; I'd use the [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack) (since it isn't xhtml), and xpath - it should be pretty trivial then:
```
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
HtmlNode node = doc.DocumentNode.SelectSingleNode("input");
// read (if you want)
string name = node.GetAttributeValue("name", ""),
value = node.GetAttributeValue("value", "");
// wipe
node.SetAttributeValue("name", loginrand);
node.SetAttributeValue("value", "");
// get html
html = doc.DocumentNode.OuterHtml;
``` | c# Regex problem | [
"",
"c#",
"regex",
""
] |
I asked a question about interfaces previously and got some excellent responses. I'm really excited to start developing really flexible code.
I now have a question about overriding a virtual method.
I am currently working with the Community Server SDK. One of the controls is a 'tag' bread crumb. So it will list the 'tags' on the relevant object.
```
<CSBlog:TagBreadCrumb />
```
I am using tags to allow adminstrators to target specific spots for content to appear in a layout, however those tags are not relevant to the end user. For example, 'Home\_Main' tag is used to target the main panel on the home page, but I don't want user to see that.
Since I have the SDK for Community Server, I found the control which renders the 'tag list' and made modifications to it that do what I want - however my understanding is that it's not good to modify the core for many reasons.
So what I'd like to do is create my own control, which is essentially almost 100% identical to the base control, but override one method.
Here is the method:
```
public virtual string FormatTags(string[] tagList)
```
Inside of there is code to format the tags, and I'd like to write my own code which does all of the same stuff, except checks a configuration file for 'tags' to exclude.
So my understanding is that I create my control, deriving from the base control - and I can write my own FormatTags() method - is that correct?
I only need to change one aspect of it, but does this mean I have to copy the original code for that method from the base class - and change what I need to in there? It just doesn't feel right copyign code from one spot, but I don't know of another way to extend the method without changing code in the base class.
Thanks for any suggestions. | You can still run the dervied method and operate on it's results:
```
public override string FormatTags(string[] tagList) {
string result = base.FormatTags(tagList);
// do something with result
return result;
}
``` | In your case (Where you want to suppress certain tags from being printed in the breadcrumbs), you would strip out all special tags before calling the base method.
So your code would look something like:
```
public override string FormatTags(string[] tagList)
{
// strip special tags
string[] newTagList = stripTags(tagList);
return base.FormatTags(newTagList);
}
```
This way you don't need to understand how the base class formats the output string.
If you instead wanted to modify the format of the output string, you wouldn't make any calls to the base method (Since that method might be changing it's formatting in future releases, which you don't want to be impacted by). | How to override a method in another assembly? | [
"",
"c#",
"asp.net",
"community-server",
""
] |
Is there an object in Java that acts like a Map for storing and accessing key/value pairs, but can return an ordered list of keys and an ordered list of values, such that the key and value lists are in the same order?
So as explanation-by-code, I'm looking for something that behaves like my fictitious OrderedMap:
```
OrderedMap<Integer, String> om = new OrderedMap<>();
om.put(0, "Zero");
om.put(7, "Seven");
String o = om.get(7); // o is "Seven"
List<Integer> keys = om.getKeys();
List<String> values = om.getValues();
for(int i = 0; i < keys.size(); i++)
{
Integer key = keys.get(i);
String value = values.get(i);
Assert(om.get(key) == value);
}
``` | The [SortedMap](https://docs.oracle.com/javase/8/docs/api/java/util/SortedMap.html) interface (with the implementation [TreeMap](https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html)) should be your friend.
The interface has the methods:
* [`keySet()`](https://docs.oracle.com/javase/8/docs/api/java/util/SortedMap.html#keySet--) which returns a set of the keys in ascending order
* [`values()`](https://docs.oracle.com/javase/8/docs/api/java/util/SortedMap.html#values--) which returns a collection of all values in the ascending order of the corresponding keys
So this interface fulfills exactly your requirements. However, the keys must have a meaningful order. Otherwise you can used the [LinkedHashMap](https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html) where the order is determined by the insertion order. | > Is there an object that acts like a Map for storing and accessing key/value pairs, but can return an ordered list of keys and an ordered list of values, such that the key and value lists are in the same order?
You're looking for [**java.util.LinkedHashMap**](http://java.sun.com/javase/6/docs/api/java/util/LinkedHashMap.html). You'll get a list of [**Map.Entry<K,V>**](http://java.sun.com/javase/6/docs/api/java/util/Map.Entry.html) pairs, which always get iterated in the same order. That order is the same as the order by which you put the items in. Alternatively, use the [**java.util.SortedMap**](http://java.sun.com/javase/6/docs/api/java/util/SortedMap.html), where the keys must either have a *natural ordering* or have it specified by a `Comparator`. | Java Ordered Map | [
"",
"java",
"collections",
""
] |
In cases where you have a function that works for many different custom types with the same implementation, is it ok to use a design pattern like this?:
```
type1 implicitly casts to type0
type2 implicitly casts to type0
type3 implicitly casts to type0
Operate ( type0 )
```
and call:
```
type1 a
type2 b
type3 c
Operate ( a )
Operate ( b )
Operate ( c )
```
Are there any problems with this technique? Performance wise, clarity, etc?
EDIT: Also by implicit cast, I meant custom implemented casts for the type with no data loss, just convenience. Say you have a Pixel class, then sending an instance of this to a method that takes a Point2 automatically casts the pixel to a Point2. | This is a perfectly normal practice.
Performance wise, I don't believe there are any issues.
Clarity wise, because of Intellisense, you're unlikely to have issues with this either. | That's the basis of how interfaces work.
```
public interface IBlah {
void DoSomething();
}
public class Type1 : IBlah {
void DoSomething() { /* implementation */ }
}
public class Type2 : IBlah {
void DoSomething() { /* implementation */ }
}
public class Type3 : IBlah {
void DoSomething() { /* implementation */ }
}
public class Foo {
void Operate(IBlah blah) {
blah.DoSomething();
}
}
``` | Single method for multiple types? | [
"",
"c#",
".net",
"casting",
"types",
""
] |
I'm using .NET 3.5 and would like to be able to obtain every \*`n`\*th item from a List. I'm not bothered as to whether it's achieved using a lambda expression or LINQ.
**Edit**
Looks like this question provoked quite a lot of debate (which is a good thing, right?). The main thing I've learnt is that when you think you know every way to do something (even as simple as this), think again! | ```
return list.Where((x, i) => i % nStep == 0);
``` | I know it's "old school," but why not just use a for loop with `stepping = n`? | How can I get every nth item from a List<T>? | [
"",
"c#",
"linq",
"list",
"lambda",
""
] |
I'm curious what everyone does for handling/abstracting the QueryString in ASP.NET. In some of our web apps I see a lot of this all over the site:
```
int val = 0;
if(Request.QueryString["someKey"] != null)
{
val = Convert.ToInt32(Request.QueryString["someKey"]);
}
```
What are some better ways to handle this grossness? | I tend to like the idea of abstracting them as properties.
For example:
```
public int age {
get
{
if (Request.QueryString["Age"] == null)
return 0;
else
return int.Parse(Request.QueryString["Age"]);
}
}
```
You could add more validation if you wanted to. But I tend to like wrapping all of my query string variables this way.
EDIT: ---
Also as another poster pointed out that you have to create these properties on every page. My answer is no you do not. You can create these properties in a single class that you can call "QueryStrings" or something. Then you can instantiate this class in every page where you want to access your query strings, then you can simply do something like
```
var queryStrings = new QueryStrings();
var age = queryStrings.age;
```
This way you can encapsulate all of the logic for accessing and handling each type of query variable in a single maintainable location.
EDIT2: ---
And because it is an instance of the class, you could also use dependency injection to inject the QueryStrings class in every place you are using it. [StructureMap](http://structuremap.github.io/) does a good job of that. This also allows you to mock up the QueryStrings class and inject that if you wanted to do automated unit testing. It is much easier to mock this up than ASP.Net's Request object. | One thing is you're not capturing blank values here. You might have a url like "<http://example.com?someKey=&anotherKey=12345>" and in this case the "someKey" param value is "" (empty). You can use string.IsNullOrEmpty() to check for both null and empty states.
I'd also change "someKey" to be stored in a variable. That way you're not repeating literal strings in multiple places. It makes this easier to maintain.
```
int val = 0;
string myKey = "someKey";
if (!string.IsNullOrEmpty(Request.QueryString[myKey]))
{
val = int.Parse(Request.QueryString[myKey]);
}
```
I hope that helps!
Ian | Converting/accessing QueryString values in ASP.NET | [
"",
"c#",
".net",
"asp.net",
""
] |
... or the other way around, is there any way to know if a php script is running inside a web server? | <http://www.php.net/manual/en/function.php-sapi-name.php>
```
function is_cli()
{
return php_sapi_name() === 'cli';
}
``` | Typically, when running in CLI mode, the superglobals `$argv` and `$argc` will be set, and many of the typical contents of `$_SERVER` (e.g. request method) won't be available. In addition, pre-defined console streams such as `STDIN`, `STDOUT` and `STDERR` will be set up. | Is there any way to know if a php script is running in cli mode? | [
"",
"php",
"command-line-interface",
""
] |
Let’s say the runtime environment (version 1.6.0\_01-b06) is already in place, but since I lack administrative privileges in this particular PC, the JDK can’t be installed. So, is there any portable JDK or standalone Java compiler for Windows that doesn’t require installation? | You might try taking the tools.jar file from the JDK (you would have to copy it over from another machine) and see if that worked.
javac is essentially a small exe that starts the VM with the specific class for the compiler.
Also, there is nothing (that I am aware of) about the JDK install that you couldn't do with a copy of it from another machine. So get on a machine you can install the JDK on, install it, and then copy the files to a place on the machine that you lack the rights to and it should work. | You don't need to install JDK. Just copy it over from another machine, and set PATH to %jdk%/bin and JAVA\_HOME to %jdk% (actually, only PATH is often enough). I do it all the time. | How can I compile Java code in Windows without installing the whole JDK? | [
"",
"java",
"compilation",
""
] |
Is there a way to do the following in Oracle:
```
SELECT *
FROM Tbl1
JOIN Tbl2
USING (col1)
AND ON Tbl1.col2 = Tbl2.col3
``` | In standard SQL, you can use either USING or ON but not both. If you could use both, you'd omit the AND from your example.
---
PMV commented (more accurately, asked - see also the poster's answer):
> My problem is I've got a bunch of tables, all with USING joins. If I try to add a table with different key names I get an ambiguous column error. Is there a graceful way to do this without converting all my joins to ON join?
Well, the best way to limit the damage imposed by the sadly misnamed columns is probably (and roughly - I've not debugged the SQL below):
```
SELECT *
FROM (SELECT *
FROM Tbl1
JOIN Tbl2 USING (col1, col2, col3, col4)
JOIN Tbl3 USING (col2, col4, col6, col23)
JOIN Tbl4 USING (col2, col8, col3, col23)
) AS SystematicNaming
JOIN Tbl5
ON SystematicNaming.Col1 = Tbl5.Col1
AND SystematicNaming.ColA = Tbl5.PoorlyNamedColA
AND SystematicNaming.ColB = Tbl5.PoorlyNamedColB
```
This preserves the convenient and systematic USING notation for as long as possible, while managing the join with Tbl5 in the way that it has to be managed given the non-uniform column names required to join with Tbl5.
I'm not sure that's the best query layout, though I think it is reasonable. | ```
SELECT * FROM TBL1 JOIN TBL2 ON TBL1.COL1 = TBL2.COL1 AND TBL1.COL2 = TBL2.COL3
```
Regards
K | Mixing ON and USING within one join | [
"",
"sql",
"oracle",
""
] |
I want to animate a scroll to the bottom of the viewport with jQuery. Is there a plugin available which isn't overkill (i.e. without a huge feature set for this small task);
Is there a plugin available or a way to do this natively with jQuery? | jQuery makes things like this so trivial that you just dont need a plugin. Example:
```
var x = 250; //insert your own formula to calculate where you want to scroll to in px
var t = 500; //arbitrary time in ms
$("html,body").animate({ scrollTop: x }, t);
```
Instead of `html,body` you can put any element which scrolls, like a div. `t` is the time in ms over which the animation will run and `x` is your position to scroll to in px. Note that this works with scrollLeft also but not scrollRight or scrollBottom (not a limitation of jQuery but JavaScript). | you can always do the following line to scroll an element to the bottom
```
$("body").attr({ scrollTop: $("body").attr("scrollHeight") });
``` | Does jQuery have any functions to scroll the client to the bottom of the view port? | [
"",
"javascript",
"jquery",
"viewport",
""
] |
### How do you name delegates, events and instance of events?
I use this:
```
delegate void OnSomethingHandler();
event OnSomethingHandler onSomething;
```
Is this an accepted way? Notice lower and upper cases
---
### Where do you place delegates and events?
I usually put delegates in an a namespace best reflecting them:
```
mynamespace.Def.SomethingLike
{
}
mynamespace.Def.SomethingElseLike
{
}
```
---
### Where do you define events?
I usually place them into the class that uses them.
I notice that a lot of people define delegates and events in the same class. How common is that? | Everything you have looks pretty standard - the only thing I would change is that the event name would be `Something` rather than `onSomething`. Following Microsofts convention you would end up with something more like this:
```
delegate void SomethingHandler();
event SomethingHandler Something;
protected void OnSomething()
{
if (this.Something != null)
this.Something();
}
```
And as a cool trick you can add an empty delegate to your `Something` event so that you don't have to check the event for null before you raise it:
```
delegate void SomethingHandler();
event SomethingHandler Something = delegate {};
protected void OnSomething()
{
this.Something();
}
``` | [MSDN on naming events](http://msdn.microsoft.com/en-us/library/ms229012.aspx):
> Events always refer to some action, either one that is happening or one that has occurred. Therefore, as with methods, events are named with verbs, and verb tense is used to indicate the time when the event is raised.
>
> √ **DO** name events with a verb or a verb phrase.
>
> Examples include `Clicked`, `Painting`, `DroppedDown`, and so on.
>
> √ **DO** give events names with a concept of before and after, using the present and past tenses.
>
> For example, a close event that is raised before a window is closed would be called `Closing`, and one that is raised after the window is closed would be called `Closed`.
>
> X **DO NOT** use "Before" or "After" prefixes or postfixes to indicate pre- and post-events. Use present and past tenses as just described.
>
> √ **DO** name event handlers (delegates used as types of events) with the "EventHandler" suffix, as shown in the following example:
>
> ```
> public delegate void ClickedEventHandler(object sender, ClickedEventArgs e);
> ```
>
> √ **DO** use two parameters named *sender* and *e* in event handlers.
>
> The sender parameter represents the object that raised the event. The sender parameter is typically of type `object`, even if it is possible to employ a more specific type.
>
> √ **DO** name event argument classes with the "EventArgs" suffix.
So, events should be named with a verb or verb phrase. Instead of `OnSomething`, use `Something`, assuming that `Something` is actually a verb, like `Close`, `Click`, or `ManagedPiplelineAbandoning` and `ManagedPiplelineAbandoned`.
The delegate for an event should be named with the `EventHandler` suffix, giving `CloseEventHandler`, `ClickEventHandler`, `ManagedPiplelineAbandoningHandler`, etc.
For delegates that aren't related to an event, use a noun, like `EventProcessor` or `ItemRetriever`, while an instance of that delegate is a verb, like `processEvent` or `retrieveItem`.
The casing of your delegate reference should be camel, unless the reference is not private. I can't think of a case where you'd have a non-private delegate field, though.
However, since it is suggested to use the conventional event handler signature (i.e. `object sender, EventArgs e)`), you should [use a generic event handler](http://msdn.microsoft.com/en-us/library/ms182178.aspx) instead of defining your own. That is, your event would be defined as something like this:
```
event EventHandler<SomethingEventArgs> Something;
``` | Naming, declaring and defining delegates and events conventions | [
"",
"c#",
".net",
"coding-style",
""
] |
I have some code to delete user profiles over the network using a service that runs on the client computers that looks like this:
```
public static void DeleteProfiles()
{
ConsoleWrapper.WriteLine("We're in DeleteProfiles()");
try
{
string[] users = GetUsers();
ConsoleWrapper.WriteLine("Users gotten");
if (users == null || users.Length == 0)
{
DeletingProfiles = false;
ConsoleWrapper.WriteLine("Null or no user loaded");
return;
}
DirectoryInfo oInfo = new DirectoryInfo("C:/Users");
if (!oInfo.Exists)
oInfo = new DirectoryInfo("C:/Documents and Settings");
ConsoleWrapper.WriteLine("Profile folder gotten.");
ConsoleWrapper.WriteLine("User Directory: " + oInfo.FullName);
ConsoleWrapper.WriteLine("\nDirectories to be deleted:");
DirectoryInfo[] SubDirectories = oInfo.GetDirectories();
foreach (DirectoryInfo oSubDir in SubDirectories)
{
bool match = false;
foreach (string user in users)
{
if (user == null)
continue;
if (oSubDir.Name.ToLower() == user.ToLower())
{
ConsoleWrapper.WriteLine("Matched: " + oSubDir.FullName);
match = true;
break;
}
}
if (match)
continue;
try
{
ConsoleWrapper.WriteLine(oSubDir.FullName);
DeletePath(oSubDir.FullName);
}
catch (Exception ex)
{
ConsoleWrapper.WriteLine(ex.StackTrace);
}
}
}
catch (Exception dirEx)
{
ConsoleWrapper.WriteLine(dirEx.Message);
}
}
```
The WriteLine method from the ConsoleWrapper actually appends data to a txt file, because that's the easiest way I can think of to debug on a different machine.
This exact code works when I use it in a command-line application, but when I try to use it in the Windows service, it simply writes "We're in DeleteProfiles()." As you'll notice, I've caught every "catchable" exception, but I still don't understand what's going on.
All the client computers are exhibiting this problem, but it works well on both my desktop and laptop. What am I doing wrong?
For the DeletePath code, see <http://www.vbdotnetforums.com/windows-services/16909-deletedirectory-throws-exception.html#post51470>. I practically lifted it and converted it to C# code. | What does GetUsers() do?
Can it potentially take a long time?
How are you calling DeleteProfiles() from the service?
If you are calling DeleteProfiles() directly from an override of ServiceBase.OnStart(), you need to know that OnStart() times out after 30 seconds. | If you caught every catchable exception and you're not seeing an entry in the log then it's very likely that an **un-catchable** exception is being thrown. This is typically in the form of a StackOverflowException. By default a process cannot catch such an exception.
If DeletePath is a recursive function, try making it iterative and see if that fixes the problem. | Execution stops without any exception | [
"",
"c#",
""
] |
What is the difference between these two file types. I see that my C++ app links against both types during the construction of the executable.
How to build .a files? links, references, and especially examples, are highly appreciated. | `.o` files are objects. They are the output of the compiler and input to the linker/librarian.
`.a` files are archives. They are groups of objects or static libraries and are also input into the linker.
**Additional Content**
I didn't notice the "examples" part of your question. Generally you will be using a makefile to generate static libraries.
```
AR = ar
CC = gcc
objects := hello.o world.o
libby.a: $(objects)
$(AR) rcu $@ $(objects)
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
```
This will compile `hello.c` and `world.c` into objects and then archive them into library. Depending on the platform, you may also need to run a utility called `ranlib` to generate the table of contents on the archive.
An interesting side note: `.a` files are technically *archive files* and not libraries. They are analogous to zip files without compression though they use a much older file format. The table of contents generated by utilities like `ranlib` is what makes an archive a *library*. Java archive files (`.jar`) are similar in that they are zip files that have some special directory structures created by the Java archiver. | A .o file is the result of compiling a single compilation unit (essentially a source-code file, with associated header files) while a .a file is one or more .o files packaged up as a library. | .o files vs .a files | [
"",
"c++",
"c",
"linux",
"gcc",
"build-process",
""
] |
Given the following code, will ixAdd do what you'd expect, i. e. return the value of ix before the increment, but increment the class member before leaving the function?
```
class myCounter {
private int _ix = 1;
public int ixAdd()
{
return _ix++;
}
}
```
I wasn't quite sure if the usual rules for post / pre increment would also apply in return statements, when the program leaves the stack frame (or whatever it is in Java) of the function. | The key part is that a post increment/decrement happens *immediately* after the expression is evaluated. Not only does it happen before the return occurs - it happens before any later expressions are evaluated. For instance, suppose you wrote:
```
class myCounter {
private int _ix = 1;
public int ixAdd()
{
return _ix++ + giveMeZero();
}
public int giveMeZero()
{
System.out.println(_ix);
return 0;
}
}
```
That would print out the incremented result as well, because the increment happens before `giveMeZero()` is called. | Well, let's look at the bytecode (use `javap -c <classname>` to see it yourself):
```
Compiled from "PostIncTest.java"
class myCounter extends java.lang.Object{
myCounter();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: aload_0
5: iconst_1
6: putfield #2; //Field _ix:I
9: return
public int ixAdd();
Code:
0: aload_0
1: dup
2: getfield #2; //Field _ix:I
5: dup_x1
6: iconst_1
7: iadd
8: putfield #2; //Field _ix:I
11: ireturn
}
```
As you can see, instructions 6 and 7 in `ixAdd()` handle the increment before the return. Therefore, as we would expect, the decrement operator does indeed have an effect when used in a return statement. Notice, however, that there is a `dup` instruction before these two appear; the incremented value is (of course) not reflected in the return value. | In Java, how does a post increment operator act in a return statement? | [
"",
"java",
"operators",
""
] |
On my laptop with Intel Pentium dual-core processor T2370 (Acer Extensa) I ran a simple multithreading speedup test. I am using Linux. The code is pasted below. While I was expecting a speedup of 2-3 times, I was surprised to see a **slowdown** by a factor of 2. I tried the same with gcc optimization levels -O0 ... -O3, but everytime I got the same result. I am using pthreads. I also tried the same with only two threads (instead of 3 threads in the code), but the performance was similar.
What could be the reason? The faster version took reasonably long - about 20 secs - so it seems is not an issue of startup overhead.
NOTE: This code is a lot buggy (indeed it does not make much sense as the output of serial and parallel versions would be different). The intention was just to "get" a speedup comparison for the same number of instructions.
```
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
class Thread{
private:
pthread_t thread;
static void *thread_func(void *d){((Thread *)d)->run();}
public:
Thread(){}
virtual ~Thread(){}
virtual void run(){}
int start(){return pthread_create(&thread, NULL, Thread::thread_func, (void*)this);}
int wait(){return pthread_join(thread, NULL);}
};
#include <iostream>
const int ARR_SIZE = 100000000;
const int N = 20;
int arr[ARR_SIZE];
int main(void)
{
class Thread_a:public Thread{
public:
Thread_a(int* a): arr_(a) {}
void run()
{
for(int n = 0; n<N; n++)
for(int i=0; i<ARR_SIZE/3; i++){ arr_[i] += arr_[i-1];}
}
private:
int* arr_;
};
class Thread_b:public Thread{
public:
Thread_b(int* a): arr_(a) {}
void run()
{
for(int n = 0; n<N; n++)
for(int i=ARR_SIZE/3; i<2*ARR_SIZE/3; i++){ arr_[i] += arr_[i-1];}
}
private:
int* arr_;
};
class Thread_c:public Thread{
public:
Thread_c(int* a): arr_(a) {}
void run()
{
for(int n = 0; n<N; n++)
for(int i=2*ARR_SIZE/3; i<ARR_SIZE; i++){ arr_[i] += arr_[i-1];}
}
private:
int* arr_;
};
{
Thread *a=new Thread_a(arr);
Thread *b=new Thread_b(arr);
Thread *c=new Thread_c(arr);
clock_t start = clock();
if (a->start() != 0) {
return 1;
}
if (b->start() != 0) {
return 1;
}
if (c->start() != 0) {
return 1;
}
if (a->wait() != 0) {
return 1;
}
if (b->wait() != 0) {
return 1;
}
if (c->wait() != 0) {
return 1;
}
clock_t end = clock();
double duration = (double)(end - start) / CLOCKS_PER_SEC;
std::cout << duration << "seconds\n";
delete a;
delete b;
}
{
clock_t start = clock();
for(int n = 0; n<N; n++)
for(int i=0; i<ARR_SIZE; i++){ arr[i] += arr[i-1];}
clock_t end = clock();
double duration = (double)(end - start) / CLOCKS_PER_SEC;
std::cout << "serial: " << duration << "seconds\n";
}
return 0;
}
```
---
See also: [What can make a program run slower when using more threads?](https://stackoverflow.com/questions/612860/what-can-make-a-program-run-slower-when-using-more-threads) | The times you are reporting are measured using the clock function:
> The [`clock()`](http://linux.die.net/man/3/clock) function returns an approximation of processor time used by the program.
```
$ time bin/amit_kumar_threads.cpp
6.62seconds
serial: 2.7seconds
real 0m5.247s
user 0m9.025s
sys 0m0.304s
```
The real time will be less for multiprocessor tasks, but the processor time will typically be greater.
When you use multiple threads, the work may be done by more than one processor, but the amount of work is the same, and in addition there may be some overhead such as contention for limited resources. `clock()` measures the total processor time, which will be the work + any contention overhead. So it should never be less than the processor time for doing the work in a single thread.
It's a little hard to tell from the question whether you knew this, and were surprised that the value returned by `clock()` was twice that for a single thread rather than being only a little more, or you were expecting it to be less.
Using [`clock_gettime()`](http://linux.die.net/man/3/clock_gettime) instead (you'll need the realtime library librt, `g++ -lrt` etc.) gives:
```
$ time bin/amit_kumar_threads.cpp
2.524 seconds
serial: 2.761 seconds
real 0m5.326s
user 0m9.057s
sys 0m0.344s
```
which still is less of a speed-up than one might hope for, but at least the numbers make some sense.
100000000\*20/2.5s = 800Hz, the bus frequency is 1600 MHz, so I suspect with a read and a write for each iteration (assuming some caching), you're memory bandwidth limited as tstenner suggests, and the `clock()` value shows that most of the time some of your processors are waiting for data. (does anyone know whether `clock()` time includes such stalls?) | The only thing your thread does is adding some elements, so your application should be IO-bound. When you add an extra thread, you have 2 CPUs sharing the memory bus, so it won't go faster, instead, you'll have cache misses etc. | Negative Speedup on Multithreading my Program | [
"",
"c++",
"multithreading",
"performance",
"multicore",
""
] |
I am new to C#. Here is a hard-coded thing I got working:
```
InputProperty grantNumber = new InputProperty();
grantNumber.Name = "udf:Grant Number";
grantNumber.Val = "571-1238";
Update update = new Update();
update.Items = new InputProperty[] { grantNumber };
```
Now I want to generalize this to support an indefinite number of items in the Update object and I came up with this but it fails to compile:
```
Update update = BuildMetaData(nvc); //call function to build Update object
```
and the function itself here:
```
private Update BuildMetaData(NameValueCollection nvPairs)
{
Update update = new Update();
InputProperty[] metaData; // declare array of InputProperty objects
int i = 0;
foreach (string key in nvPairs.Keys)
{
metaData[i] = new InputProperty(); // compiler complains on this line
metaData[i].Name = "udf:" + key;
foreach (string value in nvPairs.GetValues(key))
metaData[i].Val = value;
}
update.Items = metaData;
return update; // return the Update object
}
``` | Since the size of your Items collection can vary, you should use a collection type like `List<T>` or `Dictionary<K,V>` instead of an array. | For the current compiler error, you need to initialize the metaData array, like:
```
InputProperty[] metaData = new InputProperty[](nvPairs.Count);
```
Using linq you could:
```
private Update BuildMetaData(NameValueCollection nvPairs)
{
Update update = new Update();
update.Items = nvPairs.Keys
.Select(k=> new InputProperty
{
Name = "udf:" + k,
Val = nvPairs[k] // or Values = nvPairs.GetValues(k)
}
)
.ToArray();
return update; // return the Update object
}
``` | Populate array of objects from namevaluecollection in c# | [
"",
"c#",
"arrays",
"object",
"namevaluecollection",
""
] |
I am unable to use session variables on a page other than the one where they are set, IOW they act like non-session variables. I have found a similar question posted in half a dozen other similar fora, but the answer in those other cases always turns out not to apply.
Here are my files:
*sess1.php*
```
<?php
session_start();
session_register("userid");
session_register("textvar");
$_SESSION['userid'] = 10333 ;
$_SESSION['textvar'] = TextVariable ;
echo "<p>User ID is: " . $_SESSION['userid'] . "</p>" ;
echo "<p>Another variable is: " . $_SESSION['textvar'] . "</p>" ;
?>
<p>Go to the <a href="sess2.php">next page</a>.</p>
```
and,
*sess2.php*
```
<?php
session_start();
echo "<p>The userid session variable is: " . $_SESSION['userid'] . "</p>";
echo "<p>The other session variable is: " . $_SESSION['newvar']. "</p> ";
?>
```
The browser output in each case is:
*sess1.php*
> User ID is: 10333
>
> Another variable is: TextVariable
>
> Go to the [next page].
and,
*sess2.php*
> The userid session variable is:
>
> The other session variable is:
>
> Go to the [last page].
A few things it is NOT:
* I do have session\_start() at the top of both files.
* The variables directory is writable, and the session variables are showing up there. (I have about a hundred little files called sess\_b62, that have this inside: 'userid|i:10333;textvar|s:12:"TextVariable";'.)
* phpinfo() tells me that the php.ini file is being read correctly and the lifetime is set to the default, 0, i.e. until the browser is closed.
I'm at my wit's end. Any suggestions?
Thanks so much. | The session ID has to be carried along in some way in order that the same session can be used over several pages. In general this is done with a cookie (see [`session.use_cookies`](http://docs.php.net/manual/en/session.configuration.php#ini.session.use-cookies)) but it can also be done in the URL or in forms (see [`session.use_trans_sid`](http://docs.php.net/manual/en/session.configuration.php#ini.session.use-trans-sid)).
So first you have to make sure that the session ID is transmitted so that PHP can load the right session and session data.
See also [Is my understanding of PHP sessions correct?](https://stackoverflow.com/questions/523703/is-my-understanding-of-php-sessions-correct) | `session_register()` is not required and may be causing a problem here. Read the docs on `session_register()` - it is intended to assign session variables using existing variables.
and from [here](http://p2p.wrox.com/pro-php/1918-why-session_register-bad.html):
> Well, session\_register() tells PHP that a certain global variable should be considered a session variable. That means that at the end of the script's execution (which is when session data writes usually occur), the resulting value of that global variable will be written using the current enabled session handlers.
I think this is the problem that you are experiencing. At the end of the script execution the session variable gets over-written. | PHP Session Variables Not Preserved | [
"",
"php",
"session",
"session-variables",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.