Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Does anyone know why the following generates an error on VC9?
```
class Elem;
class ElemVec : public vector<Elem>
{
public:
void foo();
};
void ElemVec::foo()
{
BOOST_FOREACH(Elem& elem, *this)
{
// Do something with elem
}
return;
}
```
The error I get is:
```
error C2355: 'this' : can only be referenced inside non-static member functions
```
The only (hack) solution I have right now which compiles without error is:
```
void ElemVec::foo()
{
ElemVec* This = this;
BOOST_FOREACH(Elem& elem, *This)
{
// Do something with elem
}
return;
}
``` | Which compiler/Boost version are you using? I can compile the following without any problem (VS2005/Boost 1.38):
```
#include <boost/foreach.hpp>
using namespace std;
struct xxx : std::vector<int>
{
void test()
{
BOOST_FOREACH(int x, *this)
{
}
}
};
int main(void) {
xxx x;
x.test();
return 0;
}
```
Search the Boost [bugbase](https://svn.boost.org/trac/boost/search?ticket=on) if you want more details. | You shouldn't inherit from STL containers. These are not polymorphic classes and it's the reason `BOOST_FORACH` can't handle your derived class.
Try to use aggregation instead. | BOOST_FOREACH: What is the error on using this of a STL container? | [
"",
"c++",
"visual-c++",
"boost",
""
] |
How can I get Django 1.0 to write **all** errors to the console or a log file when running runserver in debug mode?
I've tried using a middleware class with process\_exception function as described in the accepted answer to this question:
[How do you log server errors on django sites](https://stackoverflow.com/questions/238081/how-do-you-log-server-errors-on-django-sites)
The process\_exception function is called for some exceptions (eg: assert(False) in views.py) but process\_exception is not getting called for other errors like ImportErrors (eg: import thisclassdoesnotexist in urs.py). I'm new to Django/Python. Is this because of some distinction between run-time and compile-time errors? But then I would expect runserver to complain if it was a compile-time error and it doesn't.
I've watched Simon Willison's fantastic presentation on Django debugging (<http://simonwillison.net/2008/May/22/debugging/>) but I didn't see an option that would work well for me.
In case it's relevant, I'm writing a Facebook app and Facebook masks HTTP 500 errors with their own message rather than showing Django's awesomely informative 500 page. So I need a way for **all** types of errors to be written to the console or file.
**Edit:** I guess my expectation is that if Django can return a 500 error page with lots of detail when I have a bad import (ImportError) in urls.py, it should be able to write the same detail to the console or a file without having to add any additional exception handling to the code. I've never seen exception handling around import statements.
Thanks,
Jeff | It's a bit extreme, but for debugging purposes, you can turn on the [`DEBUG_PROPAGATE_EXCEPTIONS`](http://docs.djangoproject.com/en/dev/ref/settings/#debug-propagate-exceptions) setting. This will allow you to set up your own error handling. The easiest way to set up said error handling would be to override [sys.excepthook](http://docs.python.org/library/sys.html#sys.excepthook). This will terminate your application, but it will work. There may be things you can do to make this not kill your app, but this will depend on what platform you're deploying this for. At any rate, never use this in production!
For production, you're pretty much going to have to have extensive error handling in place. One technique I've used is something like this:
```
>>> def log_error(func):
... def _call_func(*args, **argd):
... try:
... func(*args, **argd)
... except:
... print "error" #substitute your own error handling
... return _call_func
...
>>> @log_error
... def foo(a):
... raise AttributeError
...
>>> foo(1)
error
```
If you use log\_error as a decorator on your view, it will automatically handle whatever errors happened within it.
> The process`_`exception function is called for some exceptions (eg: assert(False) in views.py) but process`_`exception is not getting called for other errors like ImportErrors (eg: import thisclassdoesnotexist in urs.py). I'm new to Django/Python. Is this because of some distinction between run-time and compile-time errors?
In Python, all errors are run-time errors. The reason why this is causing problems is because these errors occur immediately when the module is imported before your view is ever called. The first method I posted will catch errors like these for debugging. You might be able to figure something out for production, but I'd argue that you have worse problems if you're getting ImportErrors in a production app (and you're not doing any dynamic importing).
A tool like [pylint](http://www.logilab.org/857) can help you eliminate these kinds of problems though. | > The process\_exception function is
> called for some exceptions (eg:
> assert(False) in views.py) but
> process\_exception is not getting
> called for other errors like
> ImportErrors (eg: import
> thisclassdoesnotexist in urs.py). I'm
> new to Django/Python. Is this because
> of some distinction between run-time
> and compile-time errors?
No, it's just because [process\_exception middleware is only called if an exception is raised in the view](http://docs.djangoproject.com/en/dev/topics/http/middleware/?#process-exception).
I think [DEBUG\_PROPAGATE\_EXCEPTIONS](http://docs.djangoproject.com/en/dev/ref/settings/#debug-propagate-exceptions) (as mentioned first by Jason Baker) is what you need here, but I don't think you don't need to do anything additional (i.e. sys.excepthook, etc) if you just want the traceback dumped to console.
If you want to do anything more complex with the error (i.e. dump it to file or DB), the simplest approach would be the [got\_request\_exception signal](http://docs.djangoproject.com/en/dev/ref/signals/#got-request-exception), which Django sends for any request-related exception, whether it was raised in the view or not.
The [get\_response](http://code.djangoproject.com/browser/django/trunk/django/core/handlers/base.py#L66) and [handle\_uncaught\_exception](http://code.djangoproject.com/browser/django/trunk/django/core/handlers/base.py#L136) methods of django.core.handlers.BaseHandler are instructive (and brief) reading in this area.
> without having to add any additional
> exception handling to the code. I've
> never seen exception handling around
> import statements.
Look around a bit more, you'll see it done (often in cases where you want to handle the absence of a dependency in some particular way). That said, it would of course be quite ugly if you had to go sprinkling additional try-except blocks all over your code to make a global change to how exceptions are handled! | Log all errors to console or file on Django site | [
"",
"python",
"django",
"facebook",
""
] |
Am using java to develop program that receives and processes SMS messages. I have been able to code the processing of the SMS Messages received and its working perfectly. Now the challenge i have is receiving the the SMS Messages from the CDMA network. When the application is about to go live, the CDMA network will setup a VPN connection which will enable my application to connect to its IN or its IN connect to my application to deliver the SMS Messages to my application over the VPN. Now, in what format will be SMS be sent to the application? Or will i just need to listen on the VPN and read data's when they become available? Thank you very much for your time.
Thanks. | I assume that by IN you mean [Intelligent Network](http://en.wikipedia.org/wiki/Intelligent_network)? Usually IN is not relevant for sending/receiving SMS messages - you need to connect to the [Short Message Service Center](http://en.wikipedia.org/wiki/Short_message_service_center) (SMSC) (or some proxy/gateway) in order to do that.
As also pointed out by Bombe, there are several protocols that you can use to connect to the mobile operators SMSC, it is all quite vendor-specific, due to historic reasons. Common protocols are:
* [SMPP](http://en.wikipedia.org/wiki/SMPP) (most popular, becoming the de-facto standard). There are two SMPP java libraries:
+ [SMPP API at SourceForge](http://sourceforge.net/projects/smppapi) - very stable and mature library, I have personally used it in several projects and can recommend it.
+ [Logica OpenSMPP](http://opensmpp.logica.com/) - library from the company that developed the SMPP specification. I have never used this, so I cannot comment on its maturity or stability.
* [UCP](http://en.wikipedia.org/wiki/Universal_Computer_Protocol) ([specification](http://www.nowsms.com/discus/messages/1/EMI%5FUCP%5FSpecification%5F40-8156.pdf)) - quite old standard. I'm not aware of any open java libraries for this protocol. However, as it is all ASCII-based, it is fairly easy to implement yourself (as long as you like messing with bytes :-)).
* [CIMD2](http://en.wikipedia.org/wiki/CIMD) - specification for communicating with Nokia SMSCs. It is becoming legacy, as I have heard that newer Nokia SMSC releases also support SMPP. No known open java libraries for this either.
* and finally, there are gazillions of custom protocols implemented to make it "easier" for 3rd-party developers to connect to SMSCs. These are usually based on HTTP and XML (SOAP, if you are lucky).
To sum up, the choice of protocol is not yours to make. It is usually dictated by the SMSC vendor or the mobile operator (in case they have developed some sort of "proxy/gateway", to shield their SMSC from potential programming errors that external developers can make).
P.S. in case you are not limited to java, you can also have a look at [Kannel - the Open Source WAP and SMS gateway](http://www.kannel.org/). I have not used it myself, but as far as I have heard, they should have all major protocols covered. | If the messages come into you over SMPP have a look at the SMPPAPI.
<http://smppapi.sourceforge.net/>
Talk to your mobile network they will tell you what format your messages will be delivered in. | Connecting to a CDMA network IN from Java | [
"",
"java",
"networking",
"sms",
"vpn",
""
] |
I've got a strange situation with some tables in my database starting its IDs from 0, even though TABLE CREATE has IDENTITY(1,1).
This is so for some tables, but not for others.
It has worked until today.
I've tried resetting identity column:
```
DBCC CHECKIDENT (SyncSession, reseed, 0);
```
But new records start with 0.
I have tried doing this for all tables, but some still start from 0 and some from 1.
Any pointers?
(i'm using SQL Server Express 2005 with Advanced Services) | From [DBCC CHECKIDENT](http://technet.microsoft.com/en-us/library/ms176057(SQL.90).aspx)
```
DBCC CHECKIDENT ( table_name, RESEED, new_reseed_value )
```
> If no rows have been inserted to the
> table since it was created, or all
> rows have been removed by using the
> TRUNCATE TABLE statement, the first
> row inserted after you run DBCC
> CHECKIDENT uses new\_reseed\_value as
> the identity. Otherwise, the next row
> inserted uses new\_reseed\_value + the
> current increment value.
So, this is expected for an empty or truncated table. | If you pass a reseed value the DB will start the identity from that new value:
```
DBCC CHECKIDENT (SyncSession, RESEED, 0); --next record should be 0 + increment
```
You don't have to pass the a value though, if you don't `IDENTITY(a,b)` will be used instead:
```
DBCC CHECKIDENT (SyncSession, RESEED); --next record should be the seed value 'a'
```
This is usually better practice, as it leaves the table closer to its initial created state. | SQL server identity column values start at 0 instead of 1 | [
"",
"sql",
"sql-server",
"sql-server-2005",
"identity",
"auto-increment",
""
] |
I am trying to create a `PredicateBuilder<T>` class which wraps an `Expression<Func<T, bool>>` and provides some methods to easily build up an expression with various `And` and `Or` methods. I thought it would be cool if I could use this `PredicateBuilder<T>` as an `Expression<Func<T, bool>>` directly, and thought this could be done by having an `implicit operator` method thing.
Stripped down version of the class looks like this:
```
class PredicateBuilder<T>
{
public Expression<Func<T, bool>> Predicate { get; protected set; }
public PredicateBuilder(bool initialPredicate)
{
Predicate = initialPredicate
? (Expression<Func<T, bool>>) (x => true)
: x => false;
}
public static implicit operator Expression<Func<T, bool>>(
PredicateBuilder<T> expressionBuilder)
{
return expressionBuilder.Predicate;
}
}
```
Then, just as a test, I have this extention method in a static class:
```
public static void PrintExpression<T>(this Expression<Func<T, bool>> expression)
{
Console.WriteLine(expression);
}
```
In my head, I should then be able to do these:
```
var p = new PredicateBuilder<int>(true);
p.PrintExpression();
PredicateExtensions.PrintExpression(p);
```
However none of them work. For the first one, the extension method is not found. And for the second, it says that
> The type arguments for method 'ExtravagantExpressions.PredicateHelper.PrintExpression(System.Linq.Expressions.Expression>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
So I tried the following, which worked:
```
PredicateExtensions.PrintExpression<int>(p);
```
Also, this works, of course:
```
((Expression<Func<int, bool>>) p).PrintExpression();
```
But yeah... why don't the others work? Have I misunderstood something about how this `implicit operator` thing works? | This is not specific to extension methods. C# won't implicitly cast an object to another type unless there is a clue about the target type. Assume the following:
```
class A {
public static implicit operator B(A obj) { ... }
public static implicit operator C(A obj) { ... }
}
class B {
public void Foo() { ... }
}
class C {
public void Foo() { ... }
}
```
Which method would you expect to be called in the following statement?
```
new A().Foo(); // B.Foo? C.Foo?
``` | No, you haven't, but C# compiler's type deduction isn't powerful enough to understand your code, and in particular, it doesn't look at implicit operators. You'll have to stick with `Expression<Func<T,bool>>` — why not have extension methods like `Or`, `And` directly on expressions? | C#: implicit operator and extension methods | [
"",
"c#",
"operator-overloading",
"extension-methods",
""
] |
I'm trying to call a function declared with ExternalInterface in a Flash swf, using JavaScript. It worked once, but all of a sudden, it stopped working.
I have a debug version of the Flash Player, but no errors occur in Flash. Not even a "Security Sandbox Error" or something. The only error I get is the following error in JavaScript `Error: Error in Actionscript. Use a try/catch block to find error.`
I'm using AS3, exporting for Flash Player 10 and testing on Firefox 3/Safari 4, on a Mac.
Any assistance would be greatly appreciated. | Check out [ExternalInterface.marshallExceptions](https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/external/ExternalInterface.html#marshallExceptions). It should allow you to see more details about the error. | Kinda tricky to help you solve something that 'worked once'. But using ExternalInterface is pretty straightforward -- here's what I do:
in AS3: something like
```
...
if (ExternalInterface.available) ExternalInterface.addCallback("search", jsSearch);
...
private function jsSearch(term:String):void
{
new Search(data);
}
```
in JS: something like
```
...
var term = $('input#search').val();
$("#swfobject").get(0).search(term);
....
``` | calling a Flash ExternalInterface with JavaScript | [
"",
"javascript",
"flash",
"actionscript-3",
"actionscript",
""
] |
I don't do a lot of coding with VB6, but I'm updating an existing app now and just encountered a snag.
I figured out the problem. In VB6, queries must use the **%** **wild card** when using **LIKE**, but in MS Access, you have to use the \*\*\*\*\* **wild card**.
I'm querying the same database - (it's in MS Access).
When querying from within MS Access, the following query works:
```
SELECT * FROM table WHERE field LIKE '*something*'
```
when I build that query in VB6, I have to do this:
```
SELECT * FROM table WHERE field LIKE '%something%'
```
What's happening? Is that normal? | Access used to have its own incompatible version of SQL, so I think it uses the \* for legacy reasons.
When you use VB6 you usually use ODBC and a more standardized SQL, so the more common wildcards apply. Remember that VB6 doesn't care which DB you use, so if you used something else (e.g., SQL server) it would probably only understand the percentage signs.
I am guessing that the Access-ODBC connector converts things for you. | Access will use a subset of ANSI-89 wildcards by default, VB6, connecting through ADO will use ANSI-92.
[Operator Comparison](http://oit.osu.edu/shortcourse/office2007/access_operators.htm)
[Changing the mode Access uses](http://office.microsoft.com/en-us/access/HP030704831033.aspx) | MS Access query: why does LIKE behave differently when being called from VB6 app? | [
"",
"sql",
"ms-access",
"vb6",
""
] |
Is it possible to extract information from an excel file (.xls) into c# on a computer **without excel** installed?
I've got the following code:
```
OleDbConnection objConn = new
OleDbConnection(CONNECTION_STRING.Replace("<FILENAME>", fileName));
try
{
objConnection.Open();
}
catch (Exception)
{}
```
It throws an IndexOutOfRangeException ("Cannot find table 0") when I try to open the OleDbConnection when run on a computer that does not have excel installed. The same code run on a computer with excel works just fine. I therefore very strongly suspect the lack of excel to be the culprit.
Is this the problem?
If this is, how can I extract data from the file? | Check out the open-source [NExcel](http://nexcel.sourceforge.net/). Last updated about 2 years ago, so it doesn't have support for the newer Excel 2007 .xlsx format, but will read Excel 07-Excel 2003. | There are two main methods without Excel installed
Use the Jet database drivers to open the file. This will give you access to the cell values in the rows, treating each sheet as a table. You will not have access to any of the meta-information (formatting, comments, etc).
Use [SpreadsheetGear.NET](http://www.spreadsheetgear.com/products/spreadsheetgear.net.aspx), which allows you to open, create, manipulate and save Excel binary files without Excel or any other dependencies. SpreadSheetGear can be downloaded for evaluation, but costs money to licence. | Is it possible to extract information from an excel file into c# on a computer without excel installed? | [
"",
"c#",
"excel",
""
] |
Anyone written or know of a decent PHP helper class written for Constant Contact's new REST API?
I've looked at their sample application... has a bunch of inline examples... helpful, but I'm thinking I want to either find or write a helper class to fully encapsulate the API so that all one has to do is interact with the PHP object. | I actually just started this project myself. It does almost everything the REST APIs allow. It will probably help you get off the ground with your integration.
<http://www.envoymediagroup.com/Code/CTCT-Web-Services-PHP-Library.html> | They have a PHP sample application:
<http://img.constantcontact.com/webservices/samples/PHPSample.zip> | Constant Contact - PHP wrapper for REST API? | [
"",
"php",
"email",
"constantcontact",
""
] |
I've read a lot of people discussing nested lists, but I was wondering how to iterate through an adjacancy list/tree in PHP.
I have a table with: id, title, parent\_id
And I've selected all records out into an array called $pages.
Then using this php:
```
function makeList($pages, $used) {
if (count($pages)) {
echo "<ul>";
foreach ($pages as $page) {
echo "<li>".$page['pag_title'];
$par_id = $page['pag_id'];
$subsql("SELECT * FROM pages WHERE pag_parent = ".$par_id."");
// running the new sql through an abstraction layer
$childpages = $dbch->fetchAll();
makeList($childpages, $used, $lastused);
echo "</li>";
}
echo "</ul>";
}
}
```
This sort of works but I end up with any sub menu being repeated e.g.
* Home
+ News
- Sub-news
+ Articles
- Article
* News
+ Sub-news
* Articles
+ Article
* Sub-news
* Article
I've tried adding the current id into an array that gets passed through the function, and then using in\_array to check if it's there, but I have had no joy doing that.
Any help would be much appreciated.
I need to parse the whole tree so choosing parent as 0 isn't an option | Since it already does the SQL, you dont have to do it outside before the first function call.
```
function makeList($par_id = 0) {
//your sql code here
$subsql("SELECT * FROM pages WHERE pag_parent = $par_id");
$pages = $dbch->fetchAll();
if (count($pages)) {
echo '<ul>';
foreach ($pages as $page) {
echo '<li>', $page['pag_title'];
makeList($page['pag_id']);
echo '</li>';
}
echo '</ul>';
}
}
```
For storing it more tree like you might want to look at this site: [Storing Hierarchical Data in a Database](http://www.sitepoint.com/article/hierarchical-data-database/). | If you create an array of pages grouped by parent id it is quite easy to recursively build the list. This will only require one database query.
```
<?php
//example data
$items = array(
array('id'=>1, 'title'=>'Home', 'parent_id'=>0),
array('id'=>2, 'title'=>'News', 'parent_id'=>1),
array('id'=>3, 'title'=>'Sub News', 'parent_id'=>2),
array('id'=>4, 'title'=>'Articles', 'parent_id'=>0),
array('id'=>5, 'title'=>'Article', 'parent_id'=>4),
array('id'=>6, 'title'=>'Article2', 'parent_id'=>4)
);
//create new list grouped by parent id
$itemsByParent = array();
foreach ($items as $item) {
if (!isset($itemsByParent[$item['parent_id']])) {
$itemsByParent[$item['parent_id']] = array();
}
$itemsByParent[$item['parent_id']][] = $item;
}
//print list recursively
function printList($items, $parentId = 0) {
echo '<ul>';
foreach ($items[$parentId] as $item) {
echo '<li>';
echo $item['title'];
$curId = $item['id'];
//if there are children
if (!empty($items[$curId])) {
makeList($items, $curId);
}
echo '</li>';
}
echo '</ul>';
}
printList($itemsByParent);
``` | Adjacency tree from single table | [
"",
"php",
"tree",
"hierarchy",
"adjacency-list",
""
] |
What are the differences between the two and when would you use an "object initializer" over a "constructor" and vice-versa? I'm working with C#, if that matters. Also, is the object initializer method specific to C# or .NET? | Object Initializers were something added to C# 3, in order to simplify construction of objects when you're using an object.
Constructors run, given 0 or more parameters, and are used to create and initialize an object *before* the calling method gets the handle to the created object. For example:
```
MyObject myObjectInstance = new MyObject(param1, param2);
```
In this case, the constructor of `MyObject` will be run with the values `param1` and `param2`. These are both used to create the new `MyObject` in memory. The created object (which is setup using those parameters) gets returned, and set to `myObjectInstance`.
In general, it's considered good practice to have a constructor require the parameters needed in order to completely setup an object, so that it's impossible to create an object in an invalid state.
However, there are often "extra" properties that could be set, but are not required. This could be handled through overloaded constructors, but leads to having lots of constructors that aren't necessarily useful in the majority of circumstances.
This leads to object initializers - An Object Initializer lets you set properties or fields on your object *after* it's been constructed, but *before* you can use it by anything else. For example:
```
MyObject myObjectInstance = new MyObject(param1, param2)
{
MyProperty = someUsefulValue
};
```
This will behave about the same as if you do this:
```
MyObject myObjectInstance = new MyObject(param1, param2);
myObjectInstance.MyProperty = someUsefulValue;
```
However, in *multi-threaded* environments the atomicity of the object initializer may be beneficial, since it prevents the object from being in a not-fully initialized state (see [this answer](https://stackoverflow.com/a/12842511/2822719 "Is there any benefit of using an Object Initializer? - Top answer") for more details) - it's either null or initialized like you intended.
Also, object initializers are simpler to read (especially when you set multiple values), so they give you the same benefit as many overloads on the constructor, without the need to have many overloads complicating the API for that class. | A constructor is a defined method on a type which takes a specified number of parameters and is used to create and initialize an object.
An object initializer is code that runs on an object after a constructor and can be used to succinctly set any number of fields on the object to specified values. The setting of these fields occurs **after** the constructor is called.
You would use a constructor without the help of an object initializer if the constructor sufficiently set the initial state of the object. An object initializer however must be used in conjunction with a constructor. The syntax requires the explicit or implicit use (VB.Net and C#) of a constructor to create the initial object. You would use an object initializer when the constructor does not sufficiently initialize the object to your use and a few simple field and/or property sets would. | What's the difference between an object initializer and a constructor? | [
"",
"c#",
".net",
"constructor",
"object-initializer",
""
] |
I have a Java project that currently has a lot of JARs in its libraries directory, which are all included in the resulting package when building. I know, however, that some of these libs are never referenced in the project.
Is there a tool that can search for libs that are not referenced within the project? I guess there must be something in that sense.
BTW, an Eclipse plugin would be awesome.
EDIT: I chose to go with ClassDep because it was the only suggestion that worked. However, I'm having some trouble with it: please check [this question](https://stackoverflow.com/questions/745574/classpath-problems-with-jini-classdep-javas-dependency-finder) | [ClassDep](http://java.sun.com/products/jini/2.0/doc/api/com/sun/jini/tool/ClassDep.html) (from Sun, in the Jini development kit) will do this for you. | Beware of the case that a class is loaded via Class.forName() and not specified as a dependency in the manifest file (there is a Depends-On: attribute that is for that, but many people don't specify it, which breaks tools like this, the bane of my existence when I worked on such a tool). | Tool to remove unnecessary dependencies in a Java project | [
"",
"java",
"dependencies",
""
] |
i have some regexp (like ^\w+[\w-.]*\@\w+((-\w+)|(\w*)).[a-z]{2,3}$, to match correct emails), but i cant figure out how to remove everything that doesn't match the regexp in my string.
Keeping the email example, i need a way to, given a sting like
```
$myString = "This is some text, the email is here example@example.com, and other things over here";
```
i need to return just 'example@example.com', or boolean false, if there is no email in the strings.
Of course, the email is just an example, some others times I'll need to remove everything except integer/floating numbers, etc...
I've googled around so much but didn't find anything. | If you surround your regex in parentheses and use [`preg_match`](http://www.php.net/preg_match) or [`preg_match_all`](http://www.php.net/preg_match_all) it will only return the part of the string that was matched by the regular expression:
```
$myString = "This is some text, the email is here example@example.com, and other things over here";
preg_match("/(\w+[\w-.]\@\w+((-\w+)|(\w)).[a-z]{2,3})/", $myString, $matches);
print_r($matches);
```
Note I also took off the beginning and end of string delimeters as in this case they are not needed. | Use the [`preg_match_all` function](http://docs.php.net/preg_match_all) to match all occurrences. The `preg_match_all` function itself returns the number of matches or *false* if an error occured.
So:
```
$myString = "This is some text, the email is here example@example.com, and other things over here";
if (($num = preg_match_all('/\w+[\w-.]\@\w+((-\w+)|(\w)).[a-z]{2,3}/', $myString, $matches)) !== false) {
echo $num.' matches have been found.';
var_dump($matches);
} else {
// error
}
``` | Regexp: how to remove everything except another regexp? | [
"",
"php",
"regex",
""
] |
I have the following method signature:
```
public void MyFunction(Object[,] obj)
```
I create this object:
```
List<List<Object>> obj = new List<List<Object>>;
```
Is there an easy way I can convert this to an `Object[,]`?
---
### UPDATE:
The fact is I like to use `List`s because I can easily add a new item. Is there a way I can declare my `List<>` object to fit this need? I know the number of columns in my `Object[,]` but not the number of rows. | No. In fact, these aren't necessarily compatible arrays.
`[,]` defines a multidimensional array. `List<List<T>>` would correspond more to a jagged array ( `object[][]` ).
The problem is that, with your original object, each `List<object>` contained in the list of lists can have a different number of objects. You would need to **make a multidimensional array of the largest length of the internal list, and pad with null values** or something along those lines to make it match. | You're not going to get a *very* simple solution for this (i.e. a few lines). LINQ/the `Enumerable` class isn't going to help you in this case (though it could if you wanted a jagged array, i.e. `Object[][]`). Plain nested iteration is probably the best solution in this case.
```
public static T[,] To2dArray(this List<List<T>> list)
{
if (list.Count == 0 || list[0].Count == 0)
throw new ArgumentException("The list must have non-zero dimensions.");
var result = new T[list.Count, list[0].Count];
for(int i = 0; i < list.Count; i++)
{
for(int j = 0; j < list[i].Count; j++)
{
if (list[i].Count != list[0].Count)
throw new InvalidOperationException("The list cannot contain elements (lists) of different sizes.");
result[i, j] = list[i][j];
}
}
return result;
}
```
I've included a bit of error handling in the function just because it might cause some confusing errors if you used it on a non-square nested list.
This method of course assumes that each `List<T>` contained as an element of the parent `List` is of the same length. (Otherwise you really need to be using a jagged array.) | How can I convert a list<> to a multi-dimensional array? | [
"",
"c#",
".net",
"arrays",
"list",
""
] |
My application is running on Google App Engine and most of requests constantly gets yellow flag due to high CPU usage. Using profiler I tracked the issue down to the routine of creating `jinja2.Environment` instance.
I'm creating the instance at module level:
```
from jinja2 import Environment, FileSystemLoader
jinja_env = Environment(loader=FileSystemLoader(TEMPLATE_DIRS))
```
Due to the Google AppEngine operation mode (CGI), this code can be run upon each and every request (their module import cache seems to cache modules for seconds rather than for minutes).
I was thinking about storing the environment instance in memcache, but it seems to be not picklable. `FileSystemLoader` instance seems to be picklable and can be cached, but I did not observe any substantial improvement in CPU usage with this approach.
Anybody can suggest a way to decrease the overhead of creating `jinja2.Environment` instance?
**Edit**: below is (relevant) part of profiler output.
```
222172 function calls (215262 primitive calls) in 8.695 CPU seconds
ncalls tottime percall cumtime percall filename:lineno(function)
33 1.073 0.033 1.083 0.033 {google3.apphosting.runtime._apphosting_runtime___python__apiproxy.Wait}
438/111 0.944 0.002 2.009 0.018 /base/python_dist/lib/python2.5/sre_parse.py:385(_parse)
4218 0.655 0.000 1.002 0.000 /base/python_dist/lib/python2.5/pickle.py:1166(load_long_binput)
1 0.611 0.611 0.679 0.679 /base/data/home/apps/with-the-flow/1.331879498764931274/jinja2/environment.py:10()
```
One call, but as far I can see (and this is consistent across all my GAE-based apps), the most expensive in the whole request processing cycle. | Armin suggested to pre-compile Jinja2 templates to python code, and use the compiled templates in production. So I've made a compiler/loader for that, and it now renders some complex templates 13 times faster, throwing away **all** the parsing overhead. The related discussion with link to the repository is [here](http://groups.google.com/group/google-appengine-python/browse_thread/thread/04d4bf3dd615ed1e/2907cdeff922710c). | OK, people, this is what I got today on #pocoo:
[20:59] zgoda: hello, i'd like to know if i could optimize my jinja2 environment creation process, the problem -> [Optimizing Jinja2 Environment creation](https://stackoverflow.com/questions/618827/optimizing-jinja2-environment-creation)
[21:00] zgoda: i have profiler output from "cold" app -> <http://paste.pocoo.org/show/107009/>
[21:01] zgoda: and for "hot" -> <http://paste.pocoo.org/show/107014/>
[21:02] zgoda: i'm wondering if i could somewhat lower the CPU cost of creating environment for "cold" requests
[21:05] mitsuhiko: zgoda: put the env creation into a module that you import
[21:05] mitsuhiko: like
[21:05] mitsuhiko: from yourapplication.utils import env
[21:05] zgoda: it's already there
[21:06] mitsuhiko: hmm
[21:06] mitsuhiko: i think the problem is that the template are re-compiled each access
[21:06] mitsuhiko: unfortunately gae is incredible limited, i don't know if there is much i can do currently
[21:07] zgoda: i tried with jinja bytecache but it does not work on prod (its on on dev server)
[21:08] mitsuhiko: i know
[21:08] mitsuhiko: appengine does not have marshal
[21:12] zgoda: mitsuhiko: thank you
[21:13] zgoda: i was hoping i'm doing something wrong and this can be optimized...
[21:13] mitsuhiko: zgoda: next release will come with improved appengine support, but i'm not sure yet how to implement improved caching for ae
It looks Armin is aware of problems with bytecode caching on AppEngine and has some plans to improve Jinja2 to allow caching on GAE. I hope things will get better over time. | Optimizing Jinja2 Environment creation | [
"",
"python",
"google-app-engine",
"jinja2",
""
] |
**Update**: In fact, the only acceptable solution for this problem would be sorting the array ascending and then reversing it.
Let **S** be the following sequence of events:
```
Event | Time
A | 0:00
B | 0:01
C | 0:01
D | 0:02
```
I have a simple Comparator to sort **S**, which sorts the elements according to the *time* value.
```
public int compare(Event e1, Event e2) {
// Reverse sorting.
// _sortOrder is set outside this method.
if(SORT_DESCENDING.equals(_sortOrder))
return e2.getTime() - e1.getTime(); /* time is long */
return e1.getTime() - e2.getTime();
}
```
The problem is: when the sort order is ascending, **S** is sorted correctly: A, B, C, D.
But when I use reverse sorting, **S** becomes D, B, C, A:
```
Event | Time
D | 0:02
B | 0:01 /* B and C should be reversed */
C | 0:01
A | 0:00
```
This happens because the default sorting algorithm keeps the original order for elements with the same *time* value.
So, how do I sort it reverse without keeping the original order?
**Note:** I know I can sort **S** ascending and further simply revert it, but unfortunately this is not an option in my case. | The sorting algorithm is correct: 0.01 is 0.01. Unless there's something you're not telling us. If however you want the exact reverse order of an ascending sort then sort them in ascending order and use [Collections.reverse()](http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#reverse(java.util.List)). By this I mean:
```
List<SomeObject> list = ...;
Collections.sort(list, myComparator);
Collections.reverse(list);
```
which will give you exactly what you want.
But if reversing isn't an option you only have two options left:
1. Make it so no two elements can be "equal". Either include another field or add a synthetic one (such as the current index or the primary key if it is a number). This will give you a reproducible, consistent and mirrored order; or
2. Implement your own sorting algorithm. This is not recommended as it's simply too error prone.
Now before you say you can't reverse (why?), let me ask you how you're sorting? if you're using `Collections.sort()` consider the source code (Java 6u10):
```
public static <T extends Comparable<? super T>> void sort(List<T> list) {
Object[] a = list.toArray();
Arrays.sort(a);
ListIterator<T> i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set((T)a[j]);
}
}
```
So it copies the collection into an array, sorts that array and then uses that to reorder the collection.
Are you sure you can't afford a reversal? | What are you using to sort? My guess is it's something which guarantees it's a [stable sort](http://en.wikipedia.org/wiki/Sorting_algorithm#Stability) - and you've got two equal values, as far as the comparison is concerned.
Is there any additional ordering you can impose in this case? Can you easily tell which event would come first in the ascending ordering? If so, just make the original comparison use that as well, and then your descending ordering will start to work naturally.
EDIT: As your data doesn't have any extra ordering information in it, I wouldn't be surprised if it were returned in different orders when you performed the same query again in Oracle. However, if you only care about the order in this one particular case, I suggest you add an extra field in your Java in-memory representation to store the original index in the loaded list - as you read the data, keep track of how many you've read and assign the field accordingly. Then you can use that when you sort. | Java: reverse sorting without keeping the order | [
"",
"java",
"algorithm",
"sorting",
"comparison",
""
] |
I tried to do several searches before posting this question. If this is a duplicate, please let me know and I will delete it.
My question revolves around the proper way to handle errors produced through our web application. We currently log everything through log4j. If an error happens, it just says "An error has occurred. The IT Department has been notified and will work to correct this as soon as possible" right on the screen. This tells the user nothing... but it also does not tell the developer anything either when we try to reproduce the error. We have to go to the error log folder and try finding this error. Let me also mention that the folder is full of logs from the past week. Each time there is an error, one log file is created for that user and email is sent to the IT staff assigned to work on errors. This email does not mention the log file name but it is a copy of the same error text written that is in the log file.
So if Alicia has a problem at 7:15 with something, but there are 10 other errors that happen that same minute, I have to go through each log file trying to find hers.
What I was proposing to my fellow co-workers is adding an Error Log table into the database. This would write a record to the table for each error, record who it is for, the error, what page it happened on, etc. The bonus of this would be that we can return the primary key value from the table (error\_log\_id) and show that on the page with a message like "Error Reference Id (1337) has been logged and the proper IT staff has been notified. Please keep this reference id handy for future use". When we get the email, it would tell us the id of the error for quick reference. Or if the user is persistent, they can contact us with the id and we can find the error rather quickly.
How do you setup your error logging? By the way, our system uses Java Servlets that connect to a SQL Server database. | I answered a similar question [here](https://stackoverflow.com/questions/618820/logging-vs-debugging/619020#619020), but I will adapt that answer to your question.
We use **requestID** for this purpose - assign a request ID to each incoming (HTTP) request, at the very beginning of processing (in filter) and then log that on every log line, so you can easily grep those logs later by that ID and find all relevant lines.
If you think it is very tedious to add that ID to every log statement, then you are not alone - java logging frameworks have made it transparent with the use of [Mapped Diagnostic Context](http://logback.qos.ch/manual/mdc.html) (MDC) (at least log4j and logback have this).
RequestID can also work as a handy reference number, to spit out, in case of errors (as you already suggested). However, as others have commented, it is not wise to load those details to database - better use file-system. Or, the simplest approach is to just use the requestID - then you do not need to do anything special at the moment error occurs. It just helps you to locate the correct logfile and search inside that file.
How would one requestID look like?
We use the following pattern:
> <instanceName>:<currentTimeInMillis>.<counter>
In consists of the following variables:
* *instanceName* uniquely identifies particular JVM in particular deployment environment / .
* *currentTimeInMillis* is quite self-explanatory. We chose to represent it in human-readable format "yyyyMMddHHmmssSSS", so it is easy to read request start time from it (beware: SimpleDateFormat is not thread-safe, so you need to either synchronize it or create a new one on each request).
* *counter* is request counter in that particular millisecond - in the rare case you might need to generate more than one request ID in one millisecond
As you can see, the ID format has been set up in such a way that *currentTimeInMillis.counter* combination is guaranteed to be unique in particular JVM and the whole ID is guaranteed to be globally unique (well, not in the true sense of "global", but it is global enough for our purposes), without the need to involve database or some other central node. Also, the use of *instanceName* variable gives you the possibility to limit the number of log files you later need to look in to find that request.
Then, the final question: *"that is fine and dandy in single-JVM solution, but how do you scale that to several JVMs, communicating over some network protocol?"*
As we use [Spring Remoting](http://static.springframework.org/spring/docs/2.0.x/reference/remoting.html) for our remoting purposes, we have implemented custom [RemoteInvocationFactory](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/remoting/support/RemoteInvocationFactory.html) (that takes request ID from context and saves it to [RemoteInvocation attributes](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/remoting/support/RemoteInvocation.html#addAttribute(java.lang.String,%20java.io.Serializable))) and [RemoteInvocationExecutor](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/remoting/support/RemoteInvocationExecutor.html) (that takes request ID from attributes and adds it to diagnostic context in the other JVM).
Not sure how you would implement it with plain-RMI or other remoting methods. | For the strategies of logging you can see the discussion [Logging best practices](https://stackoverflow.com/questions/576185/logging-best-practices). | How to properly handle error logs? | [
"",
"java",
"servlets",
"error-handling",
""
] |
What are the benefits of using multiple MySQL queries in a statement, other than to minimize code.
How do you execute, retrieve, and display the results of multiple MySQL queries sent in one statement using PHP (and preferably PDO). | Regardless of which database you are using, it can be more efficient to put multiple queries into one statement. If you perform the queries separately, you have to make a call to the database across the network (or at least, between processes if on the same machine), get a connection to it (including autheticating), pass in the query, return the resultset, and release the connection for each query.
Even if you use connection pooling, you are still passing more requests back and forth than is necessary.
So, for example, if you combine two queries into one, you have saved all of that extra calling back and forth for the second query. The more queries you combine, then, the more efficient your app can become.
For another example, many apps populate lists (such as for dropdownlists) when they start up. That can be a number of queries. Performing them all in one call can accelerate startup time. | mysql\_query() doesn't support multiple queries. However, there are some workarounds:
[<http://www.dev-explorer.com/articles/multiple-mysql-queries>](http://www.dev-explorer.com/articles/multiple-mysql-queries)
[<http://php.net/function.mysql-query>](http://php.net/function.mysql-query) | When and How to use Multiple MySQL Queries with PHP (PDO) | [
"",
"php",
"mysql",
"pdo",
""
] |
I have about 7 `textarea`s on a web page, all of them are rich text editors using TinyMCE. However at page load only 1 of them is visible and the rest of them hidden. The user can click a 'show' link which would display the remaining textareas one by one.
However, I have a weird problem. All the `textarea`s are setup like this:
```
<textarea cols="40" rows="20"></textarea>
```
However, only the `textarea` displayed on page load is the full size I want it to be. The remaining `textarea`s are really small when I show them. So I'm thinking that perhaps they aren't rendered because they are hidden on page load.
How can I remedy this? | Try adding some CSS to textareas that are hidden.
For example, use
```
<textarea cols="40" rows="20" style="width: 40em; height: 20em"></textarea>
```
I think I ran into this, where TinyMCE's CSS overrides some of the default CSS behaviour. I ended up having to "re-override" it, and eventually edited the TinyMCE's css pages. | I think this is an MCE bug, or at least a feature that MCE lacks.
Since I wanted to style my input box in CSS, not in HTML (yuck) I tried
```
visibility: hidden;
```
instead of
```
display: none;
```
and everything worked again.
I believe that the latter causes the element to take up no space, which trips up the MCE code which detects the width and height of the element. | Why is my TinyMCE hidden textarea acting up? | [
"",
"javascript",
"dom",
"tinymce",
"dhtml",
""
] |
I have an RTF file that I want to display inside a web page after tags have been replaced with user input.
I would like to be able to display the RTF file without having to convert it to something before displaying it.
Every time I try it now it gives me the popup open/save box even though I am telling it to display it inline with:
```
header("Content-type: application/msword");
header("Content-Disposition: inline; filename=mark.rtf");
header("Content-length: " . strlen($output));
echo $output;
``` | Most browsers won't reliably display RTF content. It IS possible to parse the RTF into HTML, and display the HTML content on your web page however.
You need some kind of program to parse RTF and convert it to HTML. I'm assuming it has to be free. I do not know of any reliable free RTF parsing or RTF to HTML libraries in PHP.
I recommend you use a command-line conversion program like RTF2HTML: <http://sageshome.net/?w=downloads/soft/RTF2HTML.html>
You would need to download and install this program on your webserver, allow the user to upload the file to a temp directory, and then call the command line application from PHP with shell\_exec():
```
$html_output_path = '/path/for/processing/files/'
$html_output_filename = $username . $timestamp;
if (is_uploaded_file($_FILES['userfile']['tmp_name'])
{
shell_exec('rtf2html ' .
escapeshellarg($_FILES['userfile']['tmp_name']) . " " .
$html_output_path . $html_output_filename);
}
$html_to_display = file_get_contents($html_output_path .
$html_output_filename);
```
Then, parse the results as HTML and display them. Not a bad strategy. Note that you will probably need to remove the head, body and possibly other tags if you're going to display the content inside another web page. | You might want to check out <https://github.com/tbluemel/rtf.js> for client-side RTF rendering. It's still in its early stages but it renders even embedded graphics. Support for rendering embedded WMF artwork is still very very limited, though, and requires browser support for the tag. | Is it possible to display an RTF file inside a web page using PHP? | [
"",
"php",
"document",
"rtf",
""
] |
If you were to have a naming system in your app where the app contains say 100 actions, which creates new objects, like:
```
Blur
Sharpen
Contrast
Darken
Matte
...
```
and each time you use one of these, a new instance is created with a unique editable name, like `Blur01`, `Blur02`, `Blur03`, `Sharpen01`, `Matte01`, etc. How would you generate the next available unique name, so that it's an O(1) operation or near constant time. Bear in mind that the user can also change the name to custom names, like `RemoveFaceDetails`, etc.
It's acceptable to have some constraints, like restricting the number of characters to 100, using letters, numbers, underscores, etc...
EDIT: You can also suggest solutions without "filling the gaps" that is without reusing the already used, but deleted names, except the custom ones of course. | I would create a static integer in action class that gets incremented and assigned as part of each new instance of the class. For instance:
```
class Blur
{
private static int count = 0;
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public Blur()
{
_name = "Blur" + count++.ToString();
}
}
```
Since count is static, each time you create a new class, it will be incremented and appended to the default name. O(1) time.
**EDIT**
If you need to fill in the holes when you delete, I would suggest the following. It would automatically queue up numbers when items are renamed, but it would be more costly overall:
```
class Blur
{
private static int count = 0;
private static Queue<int> deletions = new Queue<int>();
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
Delete();
}
}
private int assigned;
public Blur()
{
if (deletions.Count > 0)
{
assigned = deletions.Dequeue();
}
else
{
assigned = count++;
}
_name = "Blur" + assigned.ToString();
}
public void Delete()
{
if (assigned >= 0)
{
deletions.Enqueue(assigned);
assigned = -1;
}
}
}
```
Also, when you delete an object, you'll need to call .Delete() on the object.
**CounterClass Dictionary version**
```
class CounterClass
{
private int count;
private Queue<int> deletions;
public CounterClass()
{
count = 0;
deletions = new Queue<int>();
}
public string GetNumber()
{
if (deletions.Count > 0)
{
return deletions.Dequeue().ToString();
}
return count++.ToString();
}
public void Delete(int num)
{
deletions.Enqueue(num);
}
}
```
you can create a Dictionary to look up counters for each string. Just make sure you parse out the index and call .Delete(int) whenever you rename or delete a value. | I refer you to Michael A. Jackson's [Two Rules of Program Optimization](http://en.wikipedia.org/wiki/Optimization_(computer_science)#Quotes):
1. Don't do it.
2. For experts only: Don't do it yet.
Simple, maintainable code is far more important than optimizing for a speed problem that you think you *might* have later.
I would start simple: build a candidate name (e.g. "Sharpen01"), then loop through the existing filters to see if that name exists. If it does, increment and try again. This is O(N2), but until you get thousands of filters, that will be good enough.
If, sometime later, the O(N2) does become a problem, then I'd start by building a HashSet of existing names. Then you can check each candidate name against the HashSet, rather than iterating. Rebuild the HashSet each time you need a unique name, then throw it away; you don't need the complexity of maintaining it in the face of changes. This would leave your code easy to maintain, while only being O(N).
O(N) will be good enough. You do not need O(1). The user is not going to click "Sharpen" enough times for there to be any difference. | Generating the next available unique name in C# | [
"",
"c#",
".net",
"performance",
""
] |
I have a pretty simple SQL query but something is missing and I didn't find an answer for this problem yet.
The thing is that I select some fields with several ids and I want the result to be ordered in this particular order.
The query is the following
```
SELECT `content`.*
FROM `content`
WHERE (user_id = "1" AND ( id = "4" OR id = "7" OR id = "5" OR id = "8" ))
```
The default order is "id ASC" (id is my primary key), but I want the order to be 4,7,5,8 in this particular case.
Any ideas? | This will do what you want:
```
select *
from myTable
order by field(myID, 8, 7, 6) desc;
```
You can set the order of whatever ID's (or whatever) youwant to appear, and any others will follow after that. Hope that helps.
More on this @ <http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_field> | > ```
> ORDER BY CASE user_id
> WHEN "4" THEN 1
> WHEN "7" THEN 2
> WHEN "5" THEN 3
> WHEN "8" THEN 4
> ELSE 5
> END
> ```
If you want to generalize it, you can create a new table with two columns - "user\_id" and "order\_by\_val", join to it, and "ORDER BY order\_by\_val".
---
EDIT: Per @Tim, MySQL has a proprietary function - FIELD() - as noted in his post, if you aren't concerned about portability, or the issue that function return values are unoptimizable. | MySQL ORDER problem | [
"",
"sql",
"mysql",
""
] |
I'm creating a design document for a security subsystem, to be written in C++. I've created a class diagram and sequence diagrams for the major use cases. I've also specified the public attributes, associations and methods for each of the classes. But, I haven't drilled the method definitions down to the C++ level yet. Since I'm new to C++ , as is the other developer, I wonder if it might not make sense go ahead and specify to this level. Thoughts?
edit: Wow - completely against, unanimous. I was thinking about, for example, the whole business about specifying const vs. non-const, passing references, handling default constructor and assigns, and so forth. I do believe it's been quite helpful to spec this out to this level of detail so far. I definitely have gotten a clearer idea of how the system will work. Maybe if I just do a few methods, as an example, before diving into the code? | Since you're new, it probably makes sense *not* to drill down.
Reason: You're still figuring out the language and how things are best structured. That means you'll make mistakes initially and you'll want to correct them without constantly updating the documentation. | I wouldn't recommend going to this level, but then again you've already gone past where I would go in a design specification. My personal feeling is that putting a lot of effort into detailed design up-front is going to be wasted as you find out in developing code that your guesses as to how the code will work are wrong. I would stick with a high-level design and think about using TDD (test driven development) to guide the low-level design and implementation. | How specific to get on design document? | [
"",
"c++",
""
] |
If I would want to create a c# application that support multiple languages, how should I store them?
I'd probably use constants in the application as value holders.
Such as:
Console.Write(FILE\_NOT\_FOUND);
When compiled, it would change into the string determined by the language.
I'll probably stick to 3 languages (Danish, English, Deutsch), not that I think it matters though.
It seems to be a waste to have a class file for each language, which all is processed when the application is compiled. It would also mean that you'd have to re-compile and re-distribute the whole program every time you want to change a string.
As far as I know, hardcoded strings is a bad thing.
Maybe a text file?
English.txt
Line1: FILE\_NOT\_FOUND=File Not Found. Try Again
Line2
Line3
etc.
Danish.txt
Line1: FILE\_NOT\_FOUND=Filen blev ikke fundet. Prøv igen
Line2
Line3
etc.
and so on.
If the user selects English, it reads the text file and set the different constant values.
The last one I can think of is placing it in a SQL database.
Could you give me some input? :)
Also, I tried writing FILE \_ NOT \_ FOUND (without spaces, but the text editor wouldn't let me | Use a resource file. That's the standard way to handle localization.
For details, [see this tutorial.](http://www.codeproject.com/KB/dotnet/Localization.aspx)
--- EDIT ---
An alternative tutorial is [available here.](http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=211&printer=t) This one uses much better naming, so it may be more clear how it works. | I think your best option is to use the built in localization resources of the .NET Framework. You can read more about the mechanics of that [here](http://msdn.microsoft.com/en-us/library/f45fce5x(VS.80).aspx).
As for using a database to store your localised elements (text, images and the like) this is certainly a common option, but I think it's mostely because developers understand getting data from a database, more than working with satellite assemblies and the like. There a number of problems with using a database, so I'll name only a few: 1) added complexity of deployment of the application 2) addtional load on the database server, 3) where do you store the localized messages to say that the database is down :)
Using some sort of text file (likely XML) also carries with it some deployment issues, but more importanly the percieved flexibility of making text changes 'on the fly' is somewhat over rated. Apart of spelling mistakes and awkward wording you'll almost always be shipping a new build as the text of your app changes. | best way to store/use multiple languages | [
"",
"c#",
""
] |
In what seems to be random occurrences, **javascript files are not loading**.
I believe this diagnosis is correct because a) I have code to check, b) I've stepped through the code, and c) I get “'myfunction' is undefined” error when functions in those files are used.
Sometimes this doesn’t happen for an hour, sometimes it happens every time I load the page, sometimes it happens every other time I load the page. It seems like every time I identify a consistent behavior so I can repeat it and diagnose it, it changes!
Does anybody have any idea what might be causing this?
I'm using :
* IE version 7.0.5730.11 (had &
uninstalled IE8 Beta)
* VS2008
Right now, it appears to only be happening to my colleague and I on our development environments.
There is one script which appears to be missing more than any other. Here's the script tag.
```
<script language="javascript"
type="text/javascript"
src="js/Ajax.Utility.js?<%= ConfigurationManager.AppSettings["WebApp.JavaScript.FileVersion"].ToString() %>"></script>
```
Which evaluates to
```
<script language="javascript"
type="text/javascript"
src="js/Ajax.Utility.js?090324a"></script>
```
The version query string parameter doesn't appear to have any effect either since I've both had and not had the problem immediately after changing it. | Just an FYI for anybody having the same problem.
This was never resolved, but I now believe it had something to do with Visual Studio Development Server, and I question if this would have happened had I been using IIS. Unfortunately, I no longer work on that project, so I cannot test it. | I've had this problem twice before. It's always a syntax error in the Javascript code. Most probably an extra bracket or a missing one. All other browsers let it through but IE7 wasn't.
Trial and error (removing chunks and chunks of code) led me to finding the solution.
I hope this helps :-) | Why are my javascript files not loading 'consistently' in IE7? | [
"",
"internet-explorer",
"javascript",
"asp.net",
""
] |
I am a real noob when it comes to javascript/ajax, so any help will be very appreciated.
In reference to this question:
[Updating a MySql database using PHP via an onClick javascript function](https://stackoverflow.com/questions/638147/updating-a-mysql-database-using-php-via-an-onclick-javascript-function)
But mainly concerned with the answer left by [Phill Sacre](https://stackoverflow.com/users/7094/phill-sacre). I am wondering if someone could elaborate on how we are(if we can?) passing values/data through his example, using jquery.
The code example left by him is as follows:
```
function updateScore(answer, correct) {
if (answer == correct) {
$.post('updatescore.php');
}
}
...
<a onclick="updateScore(this, correct)" ...> </a>
```
Say for example, we are wanting to pass any number of values to the database with php, could someone give me a snippet example of what is required in the javascript function? Or elaborate on what is posted above please?
Thanks again all. | The simplest example I can think of is this. Make your AJAX call in your **if** block like this:
```
$.get('updatescore.php', {'score': '222'}, function(d) {
alert('Hello from PHP: ' + d);
});
```
On your "updatescore.php" script, just do that: **update the score**. And return a *plain text* stating wether the update operation was successful or not.
Good luck.
P.S.: You could also use **POST** instead of **GET**. | What you would do is on the php server side have a page lets say its update.php. This page will be visited by your javascript in an Ajax request, take the request and put it in a database.
The php might look something like this:
```
<?php
mysql_connect(...)
mysql_query("INSERT INTO table
(score) VALUES('$_GET["score"]') ")
```
Your javascript would simply preform an ajax request on update.php and send it the variables as get value "score". | Pass data to database using javascript Onclick | [
"",
"javascript",
"jquery",
"ajax",
""
] |
I've noticed a dramatic increase in GWT popularity during the past 6 months. More evidence can be seen here:
<http://www.indeed.com/jobtrends?q=gwt&l=>
Can someone explain the cause? | I would say jsight's answer is a pretty good explanation.
I have looked at Flex, Rails and GWT. All three inhabit the same space, with Flex producing Flash RIAs and GWT and Rails doing the same for HTML.
Having worked with Flex, there is a lot to like but some serious niggling problems, the main one for me being the difficulty integrating HTML into a Flex app - it's no trivial task and there are few projects that can avoid this.
GWT on the other hand is daunting initially because it's Java-based and does not come with the same kind of drag and drop editor that Flex provides in Flex Builder.
But GWT Designer (by Instantiations) is a pretty good equivalent to Flex Builder in the GWT world and for a Java programmer with Swing skills, the architecture of GWT doesn't take much figuring out.
Not to mention the sheer number of Java programmers around who can pitch GWT to their managers as a simple add-on their existing Java toolset.
Plus the Google brand doesn't hurt.
In terms of sellability within the enterprise, a Java tool is always going to be an easier sell than Actionscript or Ruby on Rails. It's hard to say for sure where things are headed but I would expect to see continued growth for all three. Everyone wants RIA these days. | I think there are basically three reasons for this:
1. Organic Growth - Have you ever used GWT? I don't know about most people, but for me, none of the marketing material on the GWT site was very convincing. Then I ran into a little small personal project that required integration with Google maps and app engine. I decided to try GWT since the tools made it so easy. Using it once, even for an extremely modest project has completely changed my mind. I suspect this means there has been a lot of word of mouth propagation of the framework over the past 6 months.
2. Maturity - The early versions weren't used by Google all that much (little dogfooding) and were a bit rough around the edges. The latest releases seem to have solved most of the growing pain issues (though compile times are still too high, imo) and have turned it into a solid, usable framework.
3. Styling - They've started including a set of default skins. I think this has helped their demos to look quite a bit more impressive for recent releases, whereas some people were confused in the past by the "no-styling out of the box" approach that the project had taken.
I'd be really shocked if any of these apply outside of Java shops, though. I haven't seen GWT making inroads into non-Java environments at all, and I think their current direction makes non-Java success even more unlikely. | Why might gwt be getting more popular? | [
"",
"java",
"apache-flex",
"gwt",
"ria",
""
] |
When you just want to do a try-except without handling the exception, how do you do it in Python?
Is the following the right way to do it?
```
try:
shutil.rmtree(path)
except:
pass
``` | ```
try:
doSomething()
except Exception:
pass
```
or
```
try:
doSomething()
except:
pass
```
The difference is that the second one will also catch `KeyboardInterrupt`, `SystemExit` and stuff like that, which are derived directly from `BaseException`, not `Exception`.
See documentation for details:
* [`try` statement](http://docs.python.org/reference/compound_stmts.html#try)
* [exceptions](http://docs.python.org/library/exceptions)
However, it is generally bad practice to catch every error - see [Why is "except: pass" a bad programming practice?](https://stackoverflow.com/questions/21553327/why-is-except-pass-a-bad-programming-practice) | It's generally considered best-practice to only catch the errors you are interested in. In the case of `shutil.rmtree` it's probably `OSError`:
```
>>> shutil.rmtree("/fake/dir")
Traceback (most recent call last):
[...]
OSError: [Errno 2] No such file or directory: '/fake/dir'
```
If you want to silently ignore that error, you would do:
```
try:
shutil.rmtree(path)
except OSError:
pass
```
Why? Say you (somehow) accidently pass the function an integer instead of a string, like:
```
shutil.rmtree(2)
```
It will give the error *"TypeError: coercing to Unicode: need string or buffer, int found"* - you probably don't want to ignore that, which can be difficult to debug.
If you *definitely* want to ignore all errors, catch `Exception` rather than a bare `except:` statement. Again, why?
Not specifying an exception catches *every* exception, including the `SystemExit` exception which for example `sys.exit()` uses:
```
>>> try:
... sys.exit(1)
... except:
... pass
...
>>>
```
Compare this to the following, which correctly exits:
```
>>> try:
... sys.exit(1)
... except Exception:
... pass
...
shell:~$
```
If you want to write ever better behaving code, the [`OSError`](http://docs.python.org/library/exceptions.html#exceptions.OSError) exception can represent various errors, but in the example above we only want to ignore `Errno 2`, so we could be even more specific:
```
import errno
try:
shutil.rmtree(path)
except OSError as e:
if e.errno != errno.ENOENT:
# ignore "No such file or directory", but re-raise other errors
raise
``` | How to properly ignore exceptions | [
"",
"python",
"exception",
"try-except",
""
] |
zend framework has many components/services I don't need, it has many includes.
All this I think slow down application.
Do you know how to speed up it? may be remove not used(what is common) components, or combine files to one file? | 1. [APC](http://www.php.net/manual/en/book.apc.php) or [eAccelerator](http://eaccelerator.net/) (*APC will be included by default in future releases, so I'd recommend using it, even though raw speed is slightly below of eAccelerator)*
2. [Two level cache](http://framework.zend.com/manual/en/zend.cache.backends.html#zend.cache.backends.twolevels) for configuration, full-page, partial views, queries, model objects:
* 1st level cache (in memory KV-store, [APC store](http://www.php.net/manual/en/function.apc-store.php) or [memcached](http://www.php.net/manual/en/book.memcached.php))
* 2nd level cache (persistent KV-store in [files](http://framework.zend.com/manual/en/zend.cache.backends.html#zend.cache.backends.file), [SQLite](http://framework.zend.com/manual/en/zend.cache.backends.html#zend.cache.backends.sqlite) or [dedicated KV-store](http://memcachedb.org/))
3. RDBMS connection pooling, if avaliable. | Before you start worrying about actively modifying things for more performance, you'll want to check the [Performance Guide](http://framework.zend.com/manual/en/performance.html) from the manual. One of the simplest steps you can do is to enable an opcode cache (such as APC) on your server - [an Opcode cache alone can give you a 3-4x boost](http://blog.digitalstruct.com/2007/12/23/php-accelerators-apc-vs-zend-vs-xcache-with-zend-framework/). | what is best way to improve performance of zend framework? | [
"",
"php",
"performance",
"zend-framework",
""
] |
I have a parent user control with a label. On the parent's OnInit, I dynamically load the child control. From the child control, I will need to set the parent's label to something.
Using the Parent property returns the immediate parent which is actually a PlaceHolder in my case. Theoretically, I can recursively loop to get the reference to the Parent User control. Am I heading in the right direction here? Is there a straightforward way of doing this? | Try getting the child's [NamingContainer](http://msdn.microsoft.com/en-us/library/system.web.ui.control.namingcontainer.aspx). | Or you could iterate through the parents until you find the desired control, such as with an extension method.
```
public static Control GetParentOfType(this Control childControl,
Type parentType)
{
Control parent = childControl.Parent;
while(parent.GetType() != parentType)
{
parent = parent.Parent;
}
if(parent.GetType() == parentType)
return parent;
throw new Exception("No control of expected type was found");
}
```
More details about this method here: <http://www.teebot.be/2009/08/extension-method-to-get-controls-parent.html> | Accessing parent control from child control - ASP.NET C# | [
"",
"c#",
"asp.net",
""
] |
I'm wanting to order Wordpress posts by the most recent comment. To the best of my knowledge this isn't possible using the WP\_Query object, and would require a custom $wpdb query, which I can easily write. However, I then don't know how to setup the loop to run off this object.
Can anyone help? | OK guys,
A lot of great answers here, but obviously nobody's taken the time to test them.
Hao Lian gets the credit for the first best original answer, but unfortunately his code doesn't show posts without comments.
Captain Keytar is on the right track, but his code will display every single post and attachment as a separate result.
Here is a modified version of Captain Keytar but it limits the results to the type 'post'.. that has been published (to avoid getting drafts!!)
```
select wp_posts.*,
coalesce(
(
select max(comment_date)
from $wpdb->comments wpc
where wpc.comment_post_id = wp_posts.id
),
wp_posts.post_date
) as mcomment_date
from $wpdb->posts wp_posts
where post_type = 'post'
and post_status = 'publish'
order by mcomment_date desc
limit 10
``` | Assign
```
select wp_posts.*, max(comment_date) as max_comment_date
from $wpdb->posts wp_posts
right join $wpdb->comments
on id = comment_post_id
group by ID
order by max_comment_date desc
limit 10
```
to some variable $query. You can fiddle around with the 10 or the query itself. (I'm no SQL optimization ninja.) Then your code will look something like
```
<?php
$results = $wpdb->get_results($query) or die('!');
foreach ($results as $result):
?>
[insert template here]
<?php endforeach ?>
```
This pattern is covered in more depth [by the Codex](http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query). | Ordering Wordpress posts by most recent comment | [
"",
"php",
"mysql",
"wordpress",
""
] |
`shared_ptr` is a reference counting smart pointer in the Boost library.
The problem with reference counting is that it cannot dispose of cycles. I am wondering how one would go about solving this in C++.
Please no suggestions like: "don't make cycles", or "use `weak_ptr`".
**Edit**
I don't like suggestions that say to just use a `weak_ptr` because obviously if you know you will create a cycle, then you wouldn't have a problem. You also cannot know you will have a cycle at compile time if you generate `shared_ptr`s at runtime.
So please, self delete answers that use `weak_ptr` in them because I specifically asked not to have those kind of answers... | I haven't found a much better method than drawing large UML graphs and looking out for cycles.
To debug, I use an instance counter going to the registry, like this:
```
template <DWORD id>
class CDbgInstCount
{
public:
#ifdef _DEBUG
CDbgInstCount() { reghelper.Add(id, 1); }
CDbgInstCount(CDbgInstCount const &) { reghelper.Add(id, 1); }
~CDbgInstCount() { reghelper.Add(id, -1); }
#else
#endif
};
```
I just ned to add that to the classes in question, and have a look at the registry.
(The ID, if given as e.g. 'XYZ!' will be converted to a string. Unfortunately, you can't specify a string constant as template parameter) | `shared_ptr` represents *ownership* relation. While `weak_ptr` represents *awareness*. Having several objects owning each other means you have problems with architecture, which is solved by changing one or more *own*'s into *aware of*'s (that is, `weak_ptr`'s).
I don't get why suggesting `weak_ptr` is considered useless. | How to detect cycles when using shared_ptr | [
"",
"c++",
"garbage-collection",
"shared-ptr",
"reference-counting",
""
] |
I am currently writing a C (not C++). It seems the Microsoft's C compiler requires all variables to be declared on top of the function.
For example, the following code will not pass compilation:
```
int foo(int x) {
assert(x != 0);
int y = 2 * x;
return y;
}
```
The compiler reports an error at the third line, saying
```
error C2143: syntax error : missing ';' before 'type'
```
If the code is changed to be like below it will pass compilation:
```
int foo(int x) {
int y;
assert(x != 0);
y = 2 * x;
return y;
}
```
If I change the source file name from `.c` to be `.cpp`, the compilation will also pass as well.
I suspect there's an option somewhere to turn off the strictness of the compiler, but I haven't found it. Can anyone help on this?
Thanks in advance.
I am using cl.exe that is shipped with Visual Studio 2008 SP1.
Added:
Thank you all for answering! It seems I have to live in C89 with Microsoft's cl.exe. | It looks like it's using C89 standard, which requires that all variables be declared before any code. You may initialize them with literals, etc., but not mix code and variables.
There should be a compiler flag to enable C99 somewhere, which will get you the behavior you're used to.
**EDIT:** quick Googling does not look promising for enabling C99. You may have to live with C89 (which ain't so bad) or find a better C compiler (which would be better). | Microsoft C compiler is C89 compilant, and isn't upgraded anymore, the standard C99 isn't afaik planned. For plain C in C99 (variables not on begin of block) use another compiler, or C++ extension. | Why does Microsoft's C compiler want the variables at the beginning of the function? | [
"",
"c++",
"c",
""
] |
It is a university task in my group to write a compiler of C-like language. Of course I am going to implement a small part of our beloved C++.
The exact task is absolutely stupid, and the lecturer told us it need to be self-compilable (should be able to compile itself) - so, he meant not to use libraries such as Boost and STL.
He also does not want us to use templates because it is hard to implement.
The question is - is it real for me, as I`m going to write this project on my own, with the deadline at the end of May - the middle of June (this year), to implement not only templates, but also nested classes, namespaces, virtual functions tables at the level of syntax analysis?
PS I am not noobie in C++ | Stick to doing a C compiler.
Believe me, it's hard enough work building a decent C compiler, *especially* if its expected to compile itself. Trying to support all the C++ features like nested classes and templates will drive you insane. Perhaps a group could do it, but on your own, I think a C compiler is more than enough to do.
If you are dead set on this, at least implement a C-like language first (so you have something to hand in). *Then* focus on showing off. | "The exact task is absolutely stupid" - I don't think you're in a position to make that judgment fairly. Better to drop that view.
"I`m going to write this project on my own" - you said it's a group project. Are you saying that your group doesn't want to go along with your view that it should morph into C++, so you're taking off and working on your own? There's another bit I'd recommend changing.
It doesn't matter how knowledgable you are about C++. Your ability with grammars, parsers, lexers, ASTs, and code generation seems far more germane.
Without knowing more about you or the assignment, I'd say that you'd be doing well to have the original assignment done by the end of May. That's three months away. Stick to the assignment. It might surprise you with its difficulty.
If you finish early, and fulfill your obligation to your team, I'd say you should feel free to modify what's produced to add C++ features.
I'll bet it took Bjarne Stroustrup more than three months to add objects to C. Don't overestimate yourself or underestimate the original assignment. | How can I make my own C++ compiler understand templates, nested classes, etc. strong features of C++? | [
"",
"c++",
"templates",
"compiler-development",
""
] |
We want to build a script that run every night (kills and restart a java process). For that we need to capture the process number (since there could be more than one java process running). The command below is basically what we will use to obtain the processes number, probably with a regexp at the end of the grep. Unless any better suggestions comes up.
```
root#ps -e |grep 'java'
18179 pts/0 00:00:43 java
```
We want to know how to parse the output above and get it into a shell variable so we can use the kill command as below.
```
kill -9 ${processid}
wait 10
```
Note1: The reason we cannot rely on the normal service stop command is because the processes sometimes does not want to die. And we have to use the kill command manually. | There are a couple of options to solve this. If you're using bash, then the shell variable '$!' will contain the PID of the last forked-off child process. So, after you start your Java program, do something like:
```
echo $! > /var/run/my-process.pid
```
Then, after your init script stops the Java process:
```
# Get the pidfile.
pid=$(cat /var/run/my-process.pid)
# Wait ten seconds to stop our process.
for count in $(1 2 3 4 5 6 7 8 9 10); do
sleep 1
cat "/proc/$pid/cmdline" 2>/dev/null | grep -q java
test $? -ne 0 && pid="" && break
done
# If we haven't stopped, kill the process.
if [ ! -z "$pid" ]; then
echo "Not stopping; terminating with extreme prejudice."
kill -9 $pid
fi
```
Make sure to remove the pidfile when you're done. | ```
ps aux | grep java | awk '{print $1}' | xargs kill -9
```
Here's an explanation:
`ps aux` gives you a listing of all processes
`grep java` gives you all of the processes whose names and command line arguments contain the string "java"
`awk '{print $1}'` parses the output of the grep command into columns by whitespace and re-prints only the first column
`xargs kill -9` passes each of the results of the awk command as parameters to a kill -9 command | How to capture the result of a system call in a shell variable? | [
"",
"java",
"linux",
"shell",
"scripting",
""
] |
Which is better (or faster), a C++ `for` loop or the `foreach` operator provided by Qt? For example, the following condition
```
QList<QString> listofstrings;
```
Which is better?
```
foreach(QString str, listofstrings)
{
//code
}
```
or
```
int count = listofstrings.count();
QString str = QString();
for(int i=0;i<count;i++)
{
str = listofstrings.at(i);
//Code
}
``` | It really doesn't matter in most cases.
The large number of questions on StackOverflow regarding whether this method or that method is faster, belie the fact that, in the vast majority of cases, code spends most of its time sitting around waiting for users to do something.
If you *are* really concerned, profile it for yourself and act on what you find.
But I think you'll most likely find that only in the most intense data-processing-heavy work does this question matter. The difference may well be only a couple of seconds and even then, only when processing huge numbers of elements.
Get your code working *first*. Then get it working *fast* (and only if you find an actual performance issue).
Time spent optimising before you've finished the functionality and can properly profile, is mostly wasted time. | First off, I'd just like to say I agree with Pax, and that the speed probably doesn't enter into it. foreach wins hands down based on readability, and that's enough in 98% of cases.
But of course the Qt guys have looked into it and actually done some profiling:
<http://blog.qt.io/blog/2009/01/23/iterating-efficiently/>
The main lesson to take away from that is: use const references in read only loops as it avoids the creation of temporary instances. It also make the purpose of the loop more explicit, regardless of the looping method you use. | 'for' loop vs Qt's 'foreach' in C++ | [
"",
"c++",
"performance",
"qt",
"foreach",
"for-loop",
""
] |
*If you have an answer that is not Java / SQLite related, I'd be pleased to read it.*
## The environment
I store items in a database with the following scheme :
```
###################
# Item #
###################
# _id # This is the primary key
# parent_id # If set, it the ID of the item containing this item
# date # An ordinary date
# geocontext_id # Foreign key to a pair of named coordinates
###################
###################
# Geocontext #
###################
# _id # This is the primary key
# name # Way for the user to label a pair of coordinates (e.g : "home", "work")
# x # One of the coordinate
# y # The other one
###################
```
## The problem
I must filter the items according to the geocontext and the date. It would be a easy job if items were all at the same level, but the trick is it's recursive. E.G :
```
root
|_item 1
|_item 2
| |_item 4
| |_item 5
| |_item 6
|_item 3
| |_item 8
| |_item 10
|_item 11
| |_item 12
|_item 7
```
There is no explicit limit to the recursive depth.
Now, if we are in any node and filter with the date "1st of April", we must see not only the items directly contained in the node that match the date, but **we must see the items that contain items matching the date as well**.
E.G : We are in "Items 2", if "item 6" matches the date, then we consider "item 5" matches the date too and we must keep it. If we are at the root, then item 2 must be displayed.
Same goes for the geocontext, but it's even harder because :
* It's stored in an other table.
* Matching the context is a costly mathematical computation.
Of course, brute forcing the matching would result in the software to be slow and a very poor user experience.
NOTE : **I don't need to display a tree**. I display a list of filtered data from a tree. We must see only a flat list of the top elements. The challenge is to decide whether to display each element or not, according to all the children hierachy.
## How I tried to solve it
I thought I could ease a bit the problem by using more tables to cache flat data :
```
###################
# Geocontex_cache #
###################
# item_id # I can Join the items table on this field
# child_id # I can delete / update a child, and so delete / update the cache
# geocontext_id # I can delete / update a geocontext, and so delete / update the cache
# x # Here, I can brute force :-)
# y #
###################
###################
# Date_cache #
###################
# item_id #
# child_id #
# date #
###################
```
This seems reasonable, but I haven't tried it yet. Nevertheless, it should the following drawbacks :
* I moved the costly process to the get
/ set / create / delete methods that
will have to manage the cached date.
That will be a troublesome code to
write and maintain. A five depth
level item will triger a process that
will hit recursively five parents.
* The size ot the data base could
become HUGE. A five de depth level
item store cached data for five
parents. Don't know if it's relevant,
since this a a mono-user app with a
manual input. I don't think anybody
would insert more thatn 1000 items
with more than 10 level of depth.
Now the good news is we go from the
bottom of the pyramid to the top, not
the other way, so it's not has
horrible as it seems. When I will
have to deal with parent item
deletion, it will be another nice
headache, but I save it for another
question ;-).
## Now my question
How would you store the data and process the filtering int the most optimal way ?
*Optional :*
Should I define an explicit recursive depth limit ?
Should I perform the filtering using SQL or Java ? SQL surely will be faster, but matching the geocontext is far easier to do in Java.
As I am working on the Android platform, I have the following constraints :
* Java is the only language available,
and not with the entire standard lib.
* SQLite is the only DBMS available.
* Performance and memory are important
issues. In case you have to choose,
battery life and therefore
performance is the priority.
* Exotics external libs may not be able
to be used.
P.S : I dug into SO and found some interesting pieces of information (espacially [What is the most efficient/elegant way to parse a flat table into a tree?](https://stackoverflow.com/questions/192220/what-is-the-most-efficientelegant-way-to-parse-a-flat-table-into-a-tree)). It's a hint, but not a problem solver. | **1)** First, let's look at simply putting everything in memory. This is simple, flexible, and above all, fast, solution. Drawbacks include the fact that you'll have to read everything into memory at startup (give the user a pretty loading bar and they won't even notice), and perhaps have to do a little extra work to ensure everything is reflected to disk when the user thinks it is, so that data isn't lost.
In this analysis I'm making some generic assumptions about Android/Dalvik I don't really know that much about, so hopefully it's somewhat accurate :) Remember the G1 has 192MB of RAM. Also, your assumption above was a max around 1000 items.
```
Object superclass ~ 8 bytes
parent/child pointer ~ 4 bytes
date (long) ~ 8 bytes
name (non interned string avg 32 chars) ~ 64 bytes
x point (int) ~ 4 bytes
y point (int) ~ 4 bytes
Total = 92 bytes + possible memory alignment + fudge factor = 128 bytes
1000 items = 125kB
10000 items = 1.22MB
```
Note: I realize that while a child can only have one pointer, a parent can have multiple children. However, the number of parent->child pointers is (elements - 1), so the average cost of parent->child pointer is (elements - 1)/elements ~ 1 element or 4 bytes. This assumes a child structure that doesn't allocate unused memory, such as a LinkedList (as opposed to an ArrayList)
**2)** The nerd in me says that this would be a fun place to profile a B+ tree, but I think that's overkill for what you want at the moment :) However, whatever solution you end up adopting, if you are not holding everything in memory, you will definitely want to cache as much of the top levels of the tree in memory as you can. This may cut down on the amount of disk activity drastically.
**3)** If you don't want to go all memory, another possible solution might be as follows. Bill Karwin suggests a rather elegant [RDBMS structure called a Closure Table](https://stackoverflow.com/questions/192220/what-is-the-most-efficient-elegant-way-to-parse-a-flat-table-into-a-tree/192462#192462) for optimizing tree based reads, while making writes more complex. Combining this with top level cache may give you performance benefits, although I would test this before taking my word on it:
When evaluating a view, use whatever you have in memory to evaluate as many children as you can. For those children that do not match, use an SQL join between the closure table and the flat table with an appropriate where clause to find out if there are any matching children. If so, you'll be displaying that node on your result list.
Hope this all makes sense and seems like it would work for what you need. | This might be offtopic but.. have you considered using serialization?
Google Protocol Buffers could be used to serialize the data in a very efficient manner (time and space), you'd have to then create a suitable tree structure (look in any CS book) to help with the searching.
I mentioned protocol buffers because being a Google library they may be available on Android.
Just a thought. | Recursive data processing performance using Java and SQLite | [
"",
"java",
"android",
"sqlite",
"recursion",
""
] |
Can anyone explain why the following code does not compile (on g++ (GCC) 3.2.3 20030502 (Red Hat Linux 3.2.3-49))?
```
struct X {
public:
enum State { A, B, C };
X(State s) {}
};
int main()
{
X(X::A);
}
```
The message I get is:
jjj.cpp: In function 'int main()':
jjj.cpp:10: 'X X::A' is not a static member of 'struct X'
jjj.cpp:10: no matching function for call to 'X::X()'
jjj.cpp:1: candidates are: X::X(const X&)
jjj.cpp:5: X::X(X::State)`
Is this bad code or a compiler bug?
Problem solved by Neil+Konrad. See the comments to Neil's answer below. | ```
X(X::A);
```
is being seen a s a function declaration. If you really want this code, use:
```
(X)(X::A);
``` | You've forgot the variable name in your definition:
```
int main()
{
X my_x(X::A);
}
```
Your code confuses the compiler because syntactically it can't distinguish this from a function declaration (returning `X` and passing `X::A` as an argument). When in doubt, the C++ compiler always disambiguates in favour of a declaration.
The solution is to introduce redundant parentheses around the `X` since the compiler forbids parentheses around types (as opposed to constructo calls etc.):
```
(X(X::A));
``` | C++ enum not properly recognized by compiler | [
"",
"c++",
"enums",
"constructor",
"temporary",
""
] |
How do you include a javascript or CSS file only on a certain article in Joomla?
I have one article which requires the jQuery UI and associated theme. Since this isn't being used on any other pages, I only want it for this particular article. Adding in the necessary `<script>` and `<link rel="stylesheet">` tags in the HTML of the article doesn't work, since they get stripped out when saved.
If there was a method to include certain files, or to stop the stripping of those tags, that'd be really good. | I ended up creating a plugin to do this for a site I maintain; I may release the code for it, but it's pretty simple to explain. You build a content plugin that searches for tags like `{css path/to/a/css/file.css}`, strips them out, then adds the files to the HTML `<head>`. Once you have the name of the CSS or JS file you want to include, here is the code you use to get it in the header:
```
$document =& JFactory::getDocument();
$document->addStyleSheet(JURI::base() . 'path/to/style.css');
$document->addScript(JURI::base() . 'path/to/script.js');
``` | For this job use the Joomla plugin "Sourcerer". You can put PHP and Javascript in articles with it and still have time left to bake a pie!
I just added the code to the article and it worked like a charm. Beware of evil editors that will strip parts of the code. Html Entities are your friend - you can use them.
Sample code:
```
{source}<?php
$doc =& JFactory::getDocument();
$doc->addStyleSheet( JURI::root( true ).'/example.css' );
$doc->addCustomTag( '<script src="/example.js" type="text/javascript"></script>' );
$doc->addScript( JURI::root( true ).'/example.js' );
?>{/source}
``` | Add page-specific javascript or CSS in Joomla | [
"",
"javascript",
"css",
"joomla",
""
] |
I've just designed a large database by playing around in MS Access. Now that I'm happy with the design, I need to be able to generate this same database (tables, relationships, etc.) from code.
Rather than hand-writing the SQL CREATE statements (which will be long, tedious, and error-prone process), I was wondering whether there was a shortcut. I seem to recall from my limited exposure to MySql that I was able to export an entire database as an SQL statement that can then be run in order to regenerate that database.
Do you know of a way to do this in MS Access, either through the GUI, or programmatically? | For free for 30 days (then $30) you can give [DBWScript](http://dbweigher.com/dbwscript.php) a go, looks like its what you are asking for, although not in native Access GUI or programmatically | I just found and tried out this tool: [jet-tool](https://github.com/himselfv/jet-tool). It seems to work well for Access 2010. | Automatically Generate SQL from existing MS Access table | [
"",
"sql",
"ms-access",
"schema",
""
] |
When does using pointers in any language require someone to use more than one, let's say a triple pointer. When does it make sense to use a triple pointer instead of just using a regular pointer?
For example:
```
char * * *ptr;
```
instead of
```
char *ptr;
``` | each star should be read as "which is pointed to by a pointer" so
```
char *foo;
```
is "char which is pointed to by a pointer foo". However
```
char *** foo;
```
is "char which is pointed to by a pointer which is pointed to by a pointer which is pointed to by a pointer foo". Thus foo is a pointer. At that address is a second pointer. At the address pointed to by that is a third pointer. Dereferencing the third pointer results in a char. If that's all there is to it. It's hard to make much of a case for that.
Its still possible to get some useful work done, though. Imagine we're writing a substitute for bash, or some other process control program. We want to manage our processes' invocations in an object oriented way...
```
struct invocation {
char* command; // command to invoke the subprocess
char* path; // path to executable
char** env; // environment variables passed to the subprocess
...
}
```
But we want to do something fancy. We want to have a way to browse all of the different sets of environment variables as seen by each subprocess. to do that, we gather each set of `env` members from the invocation instances into an array `env_list` and pass it to the function that deals with that:
```
void browse_env(size_t envc, char*** env_list);
``` | If you work with "objects" in C, you probably have this:
```
struct customer {
char *name;
char *address;
int id;
} typedef Customer;
```
If you want to create an object, you would do something like this:
```
Customer *customer = malloc(sizeof Customer);
// Initialise state.
```
We're using a pointer to a `struct` here because `struct` arguments are passed by value and we need to work with *one* object. (Also: Objective-C, an object-oriented wrapper language for C, uses internally but visibly pointers to `struct`s.)
If I need to store multiple objects, I use an array:
```
Customer **customers = malloc(sizeof(Customer *) * 10);
int customerCount = 0;
```
Since an array variable in C *points* to the first item, I use a pointer… again. Now I have double pointers.
But now imagine I have a function which filters the array and returns a new one. But imagine it can't via the return mechanism because it must return an error code—my function accesses a database. I need to do it through a by-reference argument. This is my function's signature:
```
int filterRegisteredCustomers(Customer **unfilteredCustomers, Customer ***filteredCustomers, int unfilteredCount, int *filteredCount);
```
The function takes an array of customers and returns a reference to an array of customers (which are pointers to a `struct`). It also takes the number of customers and returns the number of filtered customers (again, by-reference argument).
I can call it this way:
```
Customer **result, int n = 0;
int errorCode = filterRegisteredCustomers(customers, &result, customerCount, &n);
```
I could go on imagining more situations… This one is without the `typedef`:
```
int fetchCustomerMatrix(struct customer ****outMatrix, int *rows, int *columns);
```
Obviously, I would be a horrible and/or sadistic developer to leave it that way. So, using:
```
typedef Customer *CustomerArray;
typedef CustomerArray *CustomerMatrix;
```
I can just do this:
```
int fetchCustomerMatrix(CustomerMatrix *outMatrix, int *rows, int *columns);
```
If your app is used in a hotel where you use a matrix per level, you'll probably need an array to a matrix:
```
int fetchHotel(struct customer *****hotel, int *rows, int *columns, int *levels);
```
Or just this:
```
typedef CustomerMatrix *Hotel;
int fetchHotel(Hotel *hotel, int *rows, int *columns, int *levels);
```
Don't get me even started on an array of hotels:
```
int fetchHotels(struct customer ******hotels, int *rows, int *columns, int *levels, int *hotels);
```
…arranged in a matrix (some kind of large hotel corporation?):
```
int fetchHotelMatrix(struct customer *******hotelMatrix, int *rows, int *columns, int *levels, int *hotelRows, int *hotelColumns);
```
What I'm trying to say is that you can imagine crazy applications for multiple indirections. Just make sure you use `typedef` if multi-pointers are a good idea and you decide to use them.
(Does this post count as an application for a [SevenStarDeveloper](http://c2.com/cgi/wiki?ThreeStarProgrammer)?) | Uses for multiple levels of pointer dereferences? | [
"",
"c++",
"pointers",
""
] |
I've created a JavaScript script that can be pasted on someone's page to create an iFrame. I would like for the person to be able to paste the script where they would like the iFrame to appear.
However, I can't figure out how to append the DOM created iFrame to the location where the script has been pasted. It always appends it to the very bottom of the body.
How do I append in place? | Mm. You *could* do:
```
document.write("<div id='iframecontainer'></div>");
document.getElementById('iframecontainer').innerHTML = '...';
```
But that feels ugly/wrong in a lot of different levels. I am not aware of any other alternatives, though.
**EDIT**: Actually, a quick google search revealed [this artlcle](http://www.sitepoint.com/blogs/2007/07/11/insert-in-place-without-documentwrite/) which discusses why `document.write` is ugly and a nice alternative for the particular pickle you're in: Give your `script` tag an ID!
```
<script id="iframeinserter" src=".."></script>
```
And then you can get a reference to the script tag and insert the iframe before it:
```
var newcontent = document.createElement('iframe');
var scr = document.getElementById('iframeinserter');
scr.parentNode.insertBefore(newcontent, scr);
``` | Paulo's answer can also be done without the ID, by simply looking for the last <script> element. This must be the script block we're in, because JavaScript guarantees all content past the closing tag of the current script block has not yet been parsed(\*):
```
var scripts= document.getElementsByTagName('script');
var script= scripts[scripts.length-1];
script.parentNode.insertBefore(d, script);
```
This can be put in an onload/ready function if you like, but if so the ‘var script’ must be calculated at include-time and not in the ready function (when that executes, more <script>s will have been parsed).
(\*: except in the case of <script defer>.) | How can I append a new element in place in JavaScript? | [
"",
"javascript",
"dom",
""
] |
I recently created a site that simply has a variable and checks it against various possible values and gives an appropriate response. The program goes through using a lot of `else if` statements.
I'm sure there is a better method of doing this, but not sure what to use. I'm still learning PHP really.
Here's the source code to give you a better idea:
<http://github.com/r3morse/isitup/blob/a7a972bcf125d1f058a44406a467438d46aa4b16/functions.php> | Probably switch is what you're after, it is equivalent to if... else if... .
<http://be.php.net/switch> | Try [State](http://en.wikipedia.org/wiki/State_pattern) or [Chain-of-responsibility](http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern) | Looking for a better method of checking a variable repeatedly | [
"",
"php",
""
] |
I'm stuck with using a web service I have no control over and am trying to parse the XML returned by that service into a standard object.
A portion of the XML structure looks like this
```
<NO>
<L>Some text here </L>
<L>Some additional text here </L>
<L>Still more text here </L>
</NO>
```
In the end, I want to end up with one String property that will look like **"Some text here Some additional text here Still more text here "**
What I have for an initial pass is what follows. I think I'm on the right track, but not quite there yet:
```
XElement source = \\Output from the Webservice
List<IndexEntry> result;
result = (from indexentry in source.Elements(entryLevel)
select new IndexEntry()
{
EtiologyCode = indexentry.Element("IE") == null ? null : indexentry.Element("IE").Value,
//some code to set other properties in this object
Note = (from l in indexentry.Elements("NO").Descendants
select l.value) //This is where I stop
// and don't know where to go
}
```
I know that I could add a ToList() operator at the end of that query to return the collection. Is there an opertaor or technique that would allow me to inline the concatentation of that collection to a single string?
Feel free to ask for more info if this isn't clear.
Thanks. | LINQ to XML is indeed the way here:
```
// Note: in earlier versions of .NET, string.Join only accepts
// arrays. In more modern versions, it accepts sequences.
var text = string.Join(" ", topElement.Elements("L").Select(x => x.Value));
```
EDIT: Based on the comment, it looks like you just need a single-expression way of representing this. That's easy, if somewhat ugly:
```
result = (from indexentry in source.Elements(entryLevel)
select new IndexEntry
{
EtiologyCode = indexentry.Element("IE") == null
? null
: indexentry.Element("IE").Value,
//some code to set other properties in this object
Note = string.Join(" ", indexentry.Elements("NO")
.Descendants()
.Select(x => x.Value))
};
```
Another alternative is to extract it into a separate extension method (it has to be in a top-level static class):
```
public static string ConcatenateTextNodes(this IEnumerable<XElement> elements) =>
string.Join(" ", elements.Select(x => x.Value));
```
then change your code to:
```
result = (from indexentry in source.Elements(entryLevel)
select new IndexEntry
{
EtiologyCode = indexentry.Element("IE") == null
? null
: indexentry.Element("IE").Value,
//some code to set other properties in this object
Note = indexentry.Elements("NO")
.Descendants()
.ConcatenateTextNodes()
}
```
**EDIT: A note about efficiency**
Other answers have suggested using `StringBuilder` in the name of efficiency. I would check for evidence of this being the right way to go before using it. If you think about it, `StringBuilder` and `ToArray` do similar things - they create a buffer bigger than they need to, add data to it, resize it when necessary, and come out with a result at the end. The hope is that you won't need to resize too often.
The *difference* between `StringBuilder` and `ToArray` here is what's being buffered - in `StringBuilder` it's the entire contents of the string you've built up so far. With `ToArray` it's *just* references. In other words, resizing the internal buffer used for `ToArray` is likely to be cheaper than resizing the one for `StringBuilder`, *particularly* if the individual strings are long.
After doing the buffering in `ToArray`, `string.Join` is hugely efficient: it can look through *all* the strings to start with, work out *exactly* how much space to allocate, and then concatenate it without ever having to copy the actual character data.
This is in [sharp contrast to a previous answer I've given](https://stackoverflow.com/questions/585860/string-join-vs-stringbuilder-which-is-faster/585897#585897) - but unfortunately I don't think I ever wrote up the benchmark.
I certainly wouldn't expect `ToArray` to be significantly slower, and I think it makes the code simpler here - no need to use side-effects etc, aggregation etc. | I don't have experience with it myself, but it strikes me that [LINQ to XML](http://msdn.microsoft.com/en-us/library/bb387061.aspx) could vastly simplify your code. Do a select of XML document, then loop through it and use a StringBuilder to append the L element to some string. | Concatenate collection of XML tags to string with LINQ | [
"",
"c#",
"linq",
"linq-to-xml",
""
] |
I know a site can have many apps but all the examples I see have the site called "mysite". I figured the site would be the name of your site, like StackOverflow for example.
Would you do that and then have apps like "authentication", "questions", and "search"? Or would you really just have a site called mysite with one app called StackOverflow? | Django actually has 3 concepts here:
* **Project** (I think this is what you're calling site): This is the directory that contains all the apps. They share a common runtime invocation and can refer to each other.
* **App**: This is a set of views, models, and templates. Apps are often designed so they can be plugged into another project.
* **Site**: You can designate different behaviour for an app based on the site (ie: URL) being visited. This way, the same "App" can customize itself based on whether or not the user has visited 'StackOverflow.com' or 'RackOverflow.com' (or whatever the IT-targeted version will be called), even though it's the same codebase that's handling the request.
How you arrange these is really up to your project. In a complicated case, you might do:
```
Project: StackOverflowProject
App: Web Version
Site: StackOverflow.com
Site: RackOverflow.com
App: XML API Version
Site: StackOverflow.com
Site: RackOverflow.com
Common non-app settings, libraries, auth, etc
```
Or, for a simpler project that wants to leverage an open-source plugin:
```
Project: StackOverflowProject
App: Stackoverflow
(No specific use of the sites feature... it's just one site)
App: Plug-in TinyMCE editor with image upload
(No specific use of the sites feature)
```
Aside from the fact that there needs to be a Project, and at least one app, the arrangement is very flexible; you can adapt however suits best to help abstract and manage the complexity (or simplicity) of your deployment. | From the [Django documentation](http://docs.djangoproject.com/en/dev/intro/tutorial01/):
> ## Projects vs. apps
>
> What’s the difference between a project and an app? An app is a Web application that does something — e.g., a weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects.
From [this link](http://www.b-list.org/weblog/2006/sep/10/django-tips-laying-out-application/):
> ## Projects versus applications
>
> This is really more of a separate (though related) question, but understanding the distinction Django draws between a “project” and an “application” is a big part of good code layout. Roughly speaking, this is what the two terms mean:
>
> * An application tries to provide a single, relatively self-contained set of related functions. An application is allowed to define a set of models (though it doesn’t have to) and to define and register custom template tags and filters (though, again, it doesn’t have to).
> * A project is a collection of applications, installed into the same database, and all using the same settings file. In a sense, the defining aspect of a project is that it supplies a settings file which specifies the database to use, the applications to install, and other bits of configuration. A project may correspond to a single web site, but doesn’t have to — multiple projects can run on the same site. The project is also responsible for the root URL configuration, though in most cases it’s useful to just have that consist of calls to include which pull in URL configurations from inidividual applications.
>
> Views, custom manipulators, custom context processors and most other things Django lets you create can all be defined either at the level of the project or of the application, and where you do that should depend on what’s most effective for you; in general, though, they’re best placed inside an application (this increases their portability across projects). | What is the difference between a site and an app in Django? | [
"",
"python",
"django",
""
] |
I'm trying to use gluOrtho2D with glutBitmapCharacter so that I can render text on the screen as well as my 3D objects. However, when I use glOrtho2D, my 3D objects dissapear; I assume this is because I'm not setting the projection back to the OpenGL/GLUT default, but I'm not really sure what that is.
Anyway, this is the function I'm using to render text:
```
void GlutApplication::RenderString(Point2f point, void* font, string s)
{
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0.0, WindowWidth, 0.0, WindowHeight);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glDisable(GL_TEXTURE);
glDisable(GL_TEXTURE_2D);
glRasterPos2f(point.X, point.Y);
for (string::iterator i = s.begin(); i != s.end(); ++i)
{
glutBitmapCharacter(font, *i);
}
glEnable(GL_TEXTURE);
glEnable(GL_TEXTURE_2D);
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
}
```
And, the render function is similar to this:
```
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glLoadIdentity();
// Do some translation here.
// Draw some 3D objects.
glPopMatrix();
// For some reason, this stops the above from being rendered,
// where the camera is facing (I assume they are still being rendered).
Point2f statusPoint(10, 10);
RenderString(statusPoint, GLUT_BITMAP_9_BY_15, "Loading...");
``` | Your code looks okay. Most likely you've just messed up the matrix stack somewhere.
I suggest that you check if you forgot a `glPopMatrix` somewhere. To do so you can get the stack depth via `glGet(GL_MODELVIEW_STACK_DEPTH)`. Getters for the other matrix-stacks are available as well.
Also you can take a look at the current matrix. Call `glGetFloatv(GL_MODELVIEW_MATRIX, Pointer_To_Some_Floats)` to get it. You can print out the floats each time you've set up a modelview or projection matrix. That way you should be able to to find out which matrix erratically ends up as the current matrix.
That should give you enough clues to find the bug. | When I needed something similar I didn't try to push and pop the matrix states, I just set everything back from scratch each time:
```
void set2DMode()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, w, h, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void set3DMode()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(50.0, (float) w / h, 1, 1024);
gluLookAt(0, 0, 400, 0, 0, 0, 0.0, 1.0, 0.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void cb_display(void)
{
set3DMode();
// draw some stuff
set2DMode();
// draw some text
// and some more
}
``` | With OpenGL, how can I use gluOrtho2D properly with default projection? | [
"",
"c++",
"opengl",
""
] |
I have a script that displays a list of song names and when the user clicks a 'listen' button the filename is passed to a Flash player which loads and plays the mp3. This works fine for Safari and IE but not in Mozilla. Does anyone know of any issues around Mozilla and using Javascript to pass variables to flash and call functions in flash.
In my header file I have -
```
<script type="text/javascript">
var flash;
window.onload = function() {
if(navigator.appName.indexOf("Microsoft") != -1) {
flash = window.flashObject;
}else {
flash = window.document.flashObject;
}
}
```
AND
```
function PassFlash($preview_mp3){
if(navigator.appName.indexOf("Microsoft") != -1) {
window.flashObject.SetVariable("fileToPlay", $preview_mp3);
window.flashObject.updatePlayer();
}
else {
window.document.flashObject.SetVariable("fileToPlay", $preview_mp3);
window.document.flashObject.updatePlayer();
}
```
Then I embed the swf like so ...
```
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" name="flashObject" width="191" height="29" align="middle" id="flashObject">
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="preview.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<embed src="preview.swf" quality="high" bgcolor="#ffffff" width="191" height="29" name="flashObject" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
```
The swf is successfully loaded in all browsers (main ones) but in Firefox does not appear to receive the variables or function calls that javascript passes.
Many thanks in advance for any hints or tales of your own experience with this.
Stephen | +1 swfObject
I think what swfObject allows you to do is to write the Flashvars into the embed code, with the same result as if you were to hardcode the flashvars in. I think trying to change the hardcoded parts in your manner would be very similar to trying to change the flashvars during runtime, after the swf has already loaded. Firefox may well be loading the swf once it hits the html, not giving the javascript a chance to change the code.
also, read up on [ExternalInterface.addCallback](http://livedocs.adobe.com/flash/8/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00002200.html), that might be cool if you are compiling the swfs yourself. | When using javascript to communicate with Flash, I've always had the least difficulty using [swfObject](http://code.google.com/p/swfobject/). It's just a simple javascript lib that will embed the swf and make it easy to communicate back and forth. It works in all major browsers as well. | Mozilla Firefox problem with Javascript and Flash communication | [
"",
"javascript",
"flash",
"firefox",
"variables",
"communication",
""
] |
I'm looking to create a windows application in vb.net or c#.net that will capture the phone number of incoming calls. This would be a land line. What would the hardware requirements be? Which .Net libraries would be used? | You'll need a recent modem that supports Caller ID and is supported by Windows. Windows provides an API for talking to the modem called Telephony Application Programming Interface, a.k.a. TAPI. Unfortunately, this API [cannot easily be accessed from managed code](http://support.microsoft.com/kb/841712).
Your best bet for getting access to Caller ID in managed code would be to use one of the free or shareware TAPI OCX controls that sit on top of the TAPI API, most of them should have a simple API that would give you the incoming number. Google for something like 'TAPI OCX' or 'TAPI Caller ID' to see what's available. | If it's a landline you're talking about, all you would need would be a standard analog modem and a serial port to connect it to. You'd use standard AT-style commands to control the modem and monitor incoming data.
For specific commands and events, check out [the Wikipedia article on the Hayes AT command set](http://en.wikipedia.org/wiki/Hayes_command_set) | How to capture a Phone Number | [
"",
"c#",
".net",
"vb.net",
""
] |
So I've been using LINQ for a while, and I have a question.
I have a collection of objects. They fall into two categories based on their property values. I need to set a different property one way for one group, and one way for the other:
```
foreach(MyItem currentItem in myItemCollection)
{
if (currentItem.myProp == "CATEGORY_ONE")
{
currentItem.value = 1;
}
else if (currentItem.myProp == "CATEGORY_TWO")
{
currentItem.value = 2;
}
}
```
Alternately, I could do something like:
```
myItemCollection.Where(currentItem=>currentItem.myProp == "CATEGORY_ONE").ForEach(item=>item.value = 1);
myItemCollection.Where(currentItem=>currentItem.myProp == "CATEGORY_TWO").ForEach(item=>item.value = 2);
```
I would think the first one is faster, but figured it couldn't hurt to check. | Iterating through the collection only once (and not calling any delegates, and not using as many iterators) is likely to be slightly faster, but I very much doubt that it'll be significant.
Write the most readable code which does the job, and only worry about performance at the micro level (i.e. where it's easy to change) when it's a problem.
I think the first piece of code is more readable in this case. Less LINQy, but more readable. | How about doing it like that?
```
myItemCollection.ForEach(item => item.value = item.myProp == "CATEGORY_ONE" ? 1 : 2);
``` | LINQ Optimization Question | [
"",
"c#",
".net",
"linq",
"optimization",
""
] |
I am using google's perftools (<http://google-perftools.googlecode.com/svn/trunk/doc/cpuprofile.html>) for CPU profiling---it's a wonderful tool that has helped me perform a great deal of CPU-time improvements on my application.
Unfortunately, I have gotten to the point that the code is still a bit slow, and when compiled using g++'s -O3 optimization level, all I know is that a specific function is slow, but not which aspects of it are slow.
If I remove the -O3 flag, then the unoptimized portions of the program overtake this function, and I don't get a lot of clarity into the actual parts of the function that are slow. If I leave the -O3 flag in, then the slow parts of the function are inlined, and I can't determine which parts of the function are slow.
Any suggestions? Thanks for your help! | If you're on linux, use [oprofile](http://oprofile.sourceforge.net/about/).
If you're on Windows, use AMD's [CodeAnalyst](http://developer.amd.com/cpu/CodeAnalyst/Pages/default.aspx).
Both will give sample-based profiles down to the level of individual source lines or assembly instructions and you should have no problem identifying "hot spots" within functions. | For something like this, I've always used the "old school" way of doing it:
Insert into the routine you want to measure at various points statements which measure the current time (or cputime). Then simply print out or log the differences between them and you will know how long each section of code took. From there you can find out what is eating most of the time, and go in and get fine-grained timing within that section until you know what the problem is, and how to fix it.
If the overhead of the function calls is not the problem, you can also force inlining to be off with `-fno-inline-small-functions -fno-inline-functions -fno-inline-functions-called-once -fno-inline` (I'm not exactly sure how these switches interact with each other, but I think they are independent). Then you can use your ordinary profiler to look at the call graph profile and see what function calls are taking what amount of time. | c++ profiling/optimization: How to get better profiling granularity in an optimized function | [
"",
"c++",
"optimization",
"profiler",
""
] |
Is it possible to create a description for parameters used in an (asmx)-webservice?
I know I can set the description of the webmethod with the Description-property.
However is it also possible to add an attribute to the parameter to create description in the webservice for a given parameter
```
[WebMethod(Description = @"Get all approved friends <br />
where rownum >= StartPage * count AND rownum < (StartPage+1) * count")]
public Friend[] GetFriendsPaged(int startPage, int count){...}
```
For instance in the example given above, I would like to add documentation that the StartPage is 0-based.
Thanks in advance | There is no way to do this, and no standard for what to do with the information even if you could add it. It's true that a WSDL may contain annotations for any element, but there's no standard about, for instance, placing those annotations into comments in the generated proxy class. | I can't find any way of doing it. I guess you'd have to put the text into the Webmethod's description. | Description for Webservice parameters | [
"",
"c#",
"web-services",
""
] |
I have a very wierd problem happening to me during unit testing (MSTest in Visual Studio - .NET 3.5 SP1):
1. I click "Run All Tests in solution"
2. All tests passes, *except* for one particular class, where every tests throws the following exception: "System.IO.FileLoadException: Loading this assembly would produce a different grant set from other instances. (Exception from HRESULT: 0x80131401)."
3. I then go and set a breakpoint in the class. Result: all tests in the class passes (the same tests that failed before).
4. I click "Run All Tests in solution". All tests passes, except for *another* class.
5. I go set a breakpoint in the class. Result: All tests in the class passes
6. I click "Run All Tests in solution". All tests passes, except for the first testclass again.
7. etc.
As you can see the problem is very inconsistent, making it hard to debug.
I've tried using Fusion Log Viewer, but that gave me confusing results I didn't quite understand.
What should I be looking for? Has anyone else experienced this problem?
**Update:**
Some additional info was requested.
The tests has run fine for months - I think last time I ran them was thursday, and then they ran fine. I've been trying to examine the source control history, to see if something has changed, but nothing out of the ordinary.
I could track back and check out the project at different days back in time, but we're using Visual Source Safe (I know - not my descission :-( ) so I'm hesitating to do that.
The tests are regular unit tests, and I'm using Moq for mock-objects... But as I said - it has worked fine until recently.
I was just hoping for some advice on how to debug this issue. | We encountered this issue as well, though it only happened on our build server (where we have VS2008 installed in order to use MSTest with MSBuild), not locally. We installed [this hotfix](http://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=16827) in the version of VS2008 on the build server and that eliminated this problem. | Apparently it is a bug. No doubt you've already found this but just in case, here's a link.
<http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=95157>
Hope it helps. | Debugging assembly load issue | [
"",
"c#",
".net",
"visual-studio",
"mstest",
"fileloadexception",
""
] |
I'm writing a parallel evolutionary algorithm library using C++, MPI and CUDA. I need to extract the raw data from my object oriented design and stick it into a flat array (or std::vector using [stl-mpi](http://clustertech.com/index.php?Download:STL-MPI_Library)) for it to be sent across to nodes or the cuda device.
The complete design is quite complex with a lot of inheritance to keep the library flexible. But the classes of interest are:
**Genome class** - contains vector of data. e.g. floats or bools.
**Population class** - contains vector of Genome objects and is initailised with a genome object.
First a genome object is created, then a reference to it is passed to population class constructor which creates its own vector of genomes based on passed one. (Hope that makes sense!)
So I thought I would add another member vector, say `rawData` to the population class. But the type of rawData would need to depend on the type of data stored in the genomes (or the original genome object).
Here lies the problem, as far as I am aware there is no way to dynamically set the type passed to template.
my pseudo-code would be
```
class genome {
std::vector<bool> data;
}
template <class T>
class population {
std::vector<genome> population;
std::vector<T> rawData;
void PackDataIntoRawData();
};
```
then when i create the population (which is actually a member object of another class), I would call:
```
genome myBitGenome();
population<type of myBitGenome.data> pop(myBitGenome);
```
Is there anyway to do this, or can anyone suggest another way to implement this.
Thanks in advance | As far as dynamic typing is concerned, [boost::variant](http://www.boost.org/doc/html/variant.html) is a pretty powerful tool.
But your problem seems to be fairly simple, so i'd recommend doing something like this :
```
template<typename DataPiece>
class Genome {
typedef std::vector<DataPiece> Data;
Data data;
}
template <class T_Genome>
class Population {
std::vector<T_Genome> population;
typedef typename T_Genome::Data Data;
Data rawData;
void PackDataIntoRawData();
};
```
And then use it :
```
typedef Genome<bool> MyGenome;
MyGenome myBItGenome;
Population<MyGenome> pop( myBitGenome );
``` | I don't really understand the problem. Don't you just need to turn the "raw data" into a genome? Why do you need to store it? If you need special functions to deal with different kinds of raw data, you don't need templates, you can simply use function overloading. | C++ : variable template parameters (for genetic algorithm) | [
"",
"c++",
"templates",
"generics",
"oop",
""
] |
In my application I want to suspend a button event for some time so that I can fire another event after which the first button event will resume. In c# I am not getting how do I perform it using threads asynchronously. Please help. Thanks in advance.. | If you want to fire the second event and wait for it to finish before continuing, then why not just fire it *synchronously* from within the first event handler? That would be much simpler.
### EDIT:
If you want one button to trigger the code that's in another button's event handler, I would suggest instead that you move it out into a separate function, and just call that. In other words, do this:
```
private void button1_Click(object sender, EventArgs e)
{
DoButtonStuff();
}
private void button2_Click(object sender, EventArgs e)
{
DoButtonStuff();
}
private void DoButtonStuff()
{
// code that was originally in button2_Click()
}
```
If the buttons do the exact same thing, you could even just assign them the exact same handler.
But, if you really must programmatically "click" a button, then the easiest way is probably:
```
button2.PerformClick();
```
That'll raise a `Click` event. | This sounds like a design problem in your application and you're tackling it from the wrong end. | How to Suspend a button event in C#? | [
"",
"c#",
"multithreading",
"events",
"suspend",
""
] |
I've stumbled upon a bug in the Java Collections API, in Collections.java.
Here’s the code verbatim from the JDK’s source. Just so you know, the JavaDoc version tag reads "1.106, 04/21/06". The method is located in line 638.
```
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();
while (i.hasNext()) {
T next = i.next();
if (next.compareTo(candidate) > 0)
candidate = next;
}
return candidate;
}
```
If you take a second to analyse the method, you’ll quickly spot the bug: T candidate = i.next(). D’oh! Calling i.next() on an Iterator without checking hasNext() first? That’s just asking for an exception.
Surely something like that should've been spotted during coding? It means use of the API must check if the collection has at least two elements. | No - it means that it's invalid to try to find the maximal element of an empty collection. This is specified in the API docs:
```
Throws:
NoSuchElementException - if the collection is empty.
```
That's what `Iterator.next()` is documented to throw if there's no next element, so it's doing exactly what it's meant to.
Note that *after* the first call to next(), there's a call to hasNext() to check whether there's *more* than one element. | Hard to call it a bug since the exception is documented [here](http://java.sun.com/javase/6/docs/api/java/util/Collections.html#max(java.util.Collection))
Throws:
* ClassCastException if the collection contains elements that are not mutually comparable (for example, strings and integers).
* **NoSuchElementException if the collection is empty.** | Java Collections API Bug? | [
"",
"java",
"collections",
""
] |
I need to implement a couple of functions which comply with the following:
1. function genKey: given a string q (this may be a MD5 or SHA hash) and a seed string, the function must generate a new string p
2. function checkKey: this function must return true if a string p was generated from string q (using the previous function)
In seudo-code the above would be something lie this:
```
p=genKey(q,seed) ; // generate string p from q and seed
checkKey(p,q)==true ; // if p was generated from q, then this must return true. False otherwise.
```
Does anyone know about existing algorithms that do such thing??
I can implement the algorithms myself if there are no known implementations for PHP, so what I'm really asking is for the procedure to accomplish this. | For this discussion let p == hash(q)
You could then easily use OpenSSL with php to sign 'p' with a private key and keep that signature along side 'p'.
It is then simple to use the OpenSSL verify function to check 'p' against the signature using the public key that is paired with your private key. In this case 'p' would be the data to verify.
See [openssl\_sign](https://www.php.net/manual/en/function.openssl-sign.php) and [openssl\_verify](https://www.php.net/manual/en/function.openssl-verify.php) for info and examples of using OpenSSL in php to sign and verify data: | It sounds like you might be trying to describe a MAC.
A message authentication code takes a message digest, a secret, and message. The secret and data are hashed together, and the result is included with the message.
A message recipient who knows the secret can perform the same digest computation, and compare his MAC to the one that accompanied the received message. If they are equal, he can trust that the message was not altered.
---
Given your comments, I understand now that you are working with asymmetric keys, rather than a secret key, which would be used in a MAC.
However, there's still a little confusion. Normally, a private signature key is kept secret by its owner, which in this case seems to be the client. A client can cryptographically prove that they possess a private key that corresponds to a public key without disclosing the private key.
Using digital signatures, you can do something like this:
```
p = genKey(pvt, seed)
checkKey(pub, p)
```
Here, `pvt` is the server's private key, `pub` is its public key. The `seed` parameter is the data that gets signed. If I understand your application (which I doubt), `seed` should be the client identifier. Then `p` is a message format that bundles `seed` and its signature together. Your question is confusing because `q` is used both generating and verifying `p`—like a shared secret.
However, there's nothing in this scheme (or in the MAC scheme) to stop one client from using another's value of `p`. All you can do with such a technique is to ensure that the message content has not been altered. For example, if the message is something like "clientID=Alice,IPAddress=192.168.1.1", you can make sure that Mallory didn't substitute his own IP address for Alice's.
But if the message is just "clientID=Alice", you can't stop Alice from giving Bob her tamper-proof message (in return for splitting the cost of a license), and you can't control whether Mallory hacks into Alice's box and steals the message.
By the way, if message integrity really is all you need, and you can easily share a secret between the sender and a receiver, MACs have some nice advantages over public-key cryptography, such as much smaller message size and faster performance.
Outline the threats you are trying to defend against. Cryptography is hard. Devising untried schemes usually ends badly. | Simple cryptography problem to be implemented in PHP | [
"",
"php",
"cryptography",
""
] |
I have a list of objects that I want to filter by an integer parameter
```
List<testObject> objectList = new List<testObject>();
// populate objectList with testObjects
objectList.FindAll(GroupLevel0);
private static bool GroupLevel0(testObject item)
{ return item._groupLevel == 0; }
private class testObject
{
public string _FieldSQL = null;
public int _groupLevel;
}
```
What I'm looking to do is to make GroupLevel0 take in an integer as a parameter instead of hardcoding to 0. I'm working in .NET 2.0 so lambda expressions are a no-go. Is it even possible to pass a parameter into a predicate?
Thank you, | If you're stuck with C# 2.0, use an anonymous method - just a slightly clunkier lambda expression (ignoring expression trees):
```
List<testObject> objectList = new List<testObject>();
int desiredGroupLevel = 10;
objectList.FindAll(delegate (testObject item)
{
return item._groupLevel == desiredGroupLevel;
});
```
Or you could still use a method call to start with:
```
List<testObject> objectList = new List<testObject>();
int desiredGroupLevel = 10;
objectList.FindAll(CheckGroupLevel(desiredGroupLevel));
...
public Predicate<testItem> CheckGroupLevel(int level)
{
return delegate (testItem item)
{
return item._groupLevel == level;
};
}
```
If you're using Visual Studio 2008 but *targeting* .NET 2.0, however, you can still use a lambda expression. It's just a compiler trick which requires no framework support (again, ignoring expression trees). | ```
int groupLevel = 0;
objectList.FindAll(
delegate(testObject item)
{
return item._groupLevel == groupLevel;
});
```
This is an anonymous delegate, it closes over the lexical scope of its parent, so it can see "groupLevel".
Works in C# 2.0 and above. I'd recommend using a lambda if you move to .NET 3.5 in the future. | Adding a parameter to a FindAll for a Generic List in C# | [
"",
"c#",
"generics",
"predicate",
"findall",
""
] |
Every so often I find that I have accidentally broken data binding in my application. Either by renaming a property and not renaming it in the XAML or by a property throwing an exception for some reason.
By default data binding errors are logged to debug output and exceptions that are thrown are caught and suppressed.
Is there an easy way to have an exception thrown after the debug output is logged?
I want to know as soon as possible if data binding is broken (ideally picking it up in an automated test) and not risk the chance that it might go unnoticed until tested by a human. | After some procrastination I finally set about coding a solution to my original issue.
My solution uses a custom `TraceListener` (originally suggested by John) that logs to an output window. The output window is automatically displayed and bought to the foreground when an error occurs.
Here is my `TraceListener`:
```
public class ErrorLogTraceListener : TraceListener
{
public override void Write(string message)
{
...
}
public override void WriteLine(string message)
{
...
}
}
```
`TraceListener` is defined in System.Diagnostics.
The custom `TraceListener` must be hooked into the system to be used. The official way to do this is to set something in the registry and then use the `App.config` file to configure the `TraceListener`.
However I found that there is a much easier way to do this programmatically:
```
ErrorLogTraceListener listener = new ErrorLogTraceListener();
PresentationTraceSources.Refresh();
PresentationTraceSources.DataBindingSource.Listeners.Add(listener);
PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error;
```
`PresentationTraceSources` is also defined in `System.Diagnostics`.
For more information on trace sources see Mike Hillberg's [blog](http://blogs.msdn.com/mikehillberg/archive/2006/09/14/WpfTraceSources.aspx).
Bea Stollnitz has some useful info on her [blog](http://www.beacosta.com/blog/?p=52). | Have a look at [this blog article](https://web.archive.org/web/20101116194923/http://www.beacosta.com/blog/?p=52) which may help get around this issue. | How to propagate errors & exceptions that occur during WPF data binding? | [
"",
"c#",
"wpf",
"data-binding",
"xaml",
""
] |
I'm writing a Java web app using Spring MVC. I have a background process that goes through the database and finds notifications that must be e-mailed to my users. These e-mail messages need to include hyperlinks to the application. This seems like a fairly common pattern for a web app, but I'm having trouble.
How do I derive my application's fully qualified URL, with server name and context path? I don't have access to any of the methods in HttpServletRequest because I'm running this as a background process, not in response to a web request. The best I can do is get access to ServletContext.
Currently I'm putting the base URL into a configuration file and reading it at startup, but this application is going to be licensed and deployed to customers' application servers, and if possible I'd like them not to have to configure this manually. | It is not recommended to dynamically prepare the URL at run time, especially based on ServletRequest. This is primarily because you have no idea of the URL that users would be using to access the application - the application server could be behind a web server, a firewall or a load balancer. To keep it short, one cannot predict network topologies.
Your current technique of fetching the URL from the property file is good enough to resolve the said issue. Maybe you should look at providing an administrative console to manage the URL appearing in mails, especially if there is an admin console in place, or if there are related options that should go into one.
Edit: My last point echoes what Tony has spoken of. | Why just not have a setup web page that comes up the first time the application is run if the configuration file does not exist (in WEB-INF folder for example. Using ServletContext, you can call getRealPath and get the real path of a File and see if it exists(). If it does, redirect to the app start page, if it does not, open the admin page).
The best you cam do with ServletContext is read some settings from web.xml, and get the context path, only the HttpRequest can give you the FQ URL. | Finding your application's URL with only a ServletContext | [
"",
"java",
"jakarta-ee",
"spring-mvc",
""
] |
Im trying to run something like this:
```
<a href="login.php?logout=1" id="logout">logout</a>
<div id="main">
<?php require_once('getPhotos.php') ; ?>
<div id="response" class="hidden" />
</div><!-- end main-->
```
> But Im getting this error.
**Warning: require\_once(1) [function.require-once]: failed to open stream: No such file or directory in C:\wamp\www\myPhotosWebsite\index.php on line 17
Fatal error: require\_once() [function.require]: Failed opening required '1' (include\_path='.;C:\php5\pear') in C:\wamp\www\myPhotosWebsite\index.php on line 17**
> Any sugesstions...what iam doing wrong | * does the getPhotos.php exist?
* where is it?
* is it written exactly like that? | It can't find the file getPhotos.php in the folders c:\wamp\myPhotosWebsite\ or c:\php5\pear | function.require-once is giving error in my wamp server | [
"",
"php",
""
] |
**BACKGROUND:**
I use an offset into a file and the Filestream lock/unlock menthods to control read/write access. I am using the following code to test if a lock is currently held on the file
```
try
{
fs.Lock( RESERVED_BYTE, 1 );
fs.Unlock( RESERVED_BYTE, 1 );
rc = 1;
}
catch
{
rc = 0;
}
```
**QUESTION:**
My goal is to eliminate the try/catch block. Is there some better way to see if the lock exists?
**EDIT:**
Note: This question is not about if the file exists. I already know it does. It is about synchronizing write access. | You can call the [`LockFile` Windows API function](http://msdn.microsoft.com/en-us/library/aa365202%28v=vs.85%29.aspx) through the P/Invoke layer directly. You would use the handle returned by the SafeFileHandle property on the FileStream.
Calling the API directly will allow you to check the return value for an error condition as opposed to resorting to catching an exception.
---
[Noah](https://stackoverflow.com/users/12113/noah) asks if there is any overhead in making the call to the P/Invoke layer vs a try/catch.
The Lock file makes the same call through the P/Invoke layer and throws the exception if the call to LockFile returns 0. In your case, you aren't throwing an exception. In the event the file is locked, you will take less time because you aren't dealing with a stack unwind.
The actual P/Invoke setup is around seven instructions I believe (for comparison, COM interop is about 40), but that point is moot, since your call to LockFile is doing the same thing that the managed method does (use the P/Invoke layer). | Personally I would just catch a locked file when trying to open it. If it's unlocked now, it may be locked when you try to open it (even if it's just a few ms later). | Using C# is it possible to test if a lock is held on a file | [
"",
"c#",
"locking",
"filestream",
""
] |
I have to invoke a web service with a single parameter, a String in XML format.
I'm building this via an XSLT transformation. So far so good.
The problem is with this XSD fragment:
```
<xs:complexType name="Document">
<xs:sequence>
<xs:element name="title" type="xs:string" minOccurs="1"/>
<xs:element name="content" type="xs:base64Binary" minOccurs="1"/>
</xs:sequence>
</xs:complexType>
```
which translates (for example) into this XML:
```
<attachment>
<title>test title</title>
<content>
PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Inllc
yI/Pg0KPG1zZ3ByYXRpY2E+DQogICAgPHByYXRpY2E+DQogICAgICAgIDxwcm9jZXNzbz
4NCiAgICAgICAgICAgIDxjb2RQcm9jZXNzbz4xPC9jb2RQcm9jZXNzbz4NCiAgICAgICA
gICAgIDxjb2RJc3RhbnphUHJvY2Vzc28MzwvY29kSXN0YW56YVByb2Nlc3NvPg0KICAgI
CAgICAgICAgPGNvZFN0YXRvPjYwPC9jb2RTdGF0bz4NCiAgICAgICAgPC9wcm9jZXNzbz
4NCiAgICA8L3ByYXRpY2E+DQo8L21zZ3ByYXRpY2E+
</content>
</attachment>
```
Yes, you got it right: I have to insert a file content into the XML document in base 64 binary format.
I thought about inserting a placeholder with XSLT and then processing the XML document to replace it with the actual file content, but I'm wondering if there are any best practices for these occasions, maybe some fancy XSTL trick well beyond my knowledge or some Java tools which may come in handy.
How would you do that?
**NOTE**: I can't use *SOAP with attachment*, and I'm well aware that the aforementioned approach is prone to failure in case of huge attachments, but at the moment our counterpart will not budge. | **Probably the best way to do this is to read the file and encode its contents in base64 by the code that instantiates the XSLT transformation**. The base64 string can either be passed as a parameter to the transformation, or the transformation could request it via an extension method.
*In principle XSLT could be used to do the encoding to base64*, however some byte values, such as 0 (for XML 1.0 and XML 1.1), and 29 other codes below 0x20 (for XML 1.0) are forbidden as characters within an XML document and this makes such encoding in XSLT impossible.
( see: <http://projects.ischool.washington.edu/tabrooks/545/ContentManagement/PassingParameters.htm> ) | If your SOAP stack supports MTOM, turn that on. What that will then do is put a "reference" in the content element to a MIME attachment where the data would be placed. That data can be completely binary and not base64 encoded. | XML for Web Service: inline attachment | [
"",
"java",
"web-services",
"xslt",
"base64",
"attachment",
""
] |
What could be the deciding factor to use the methods asynchronously.
One factor i can understand is **independent** and parallel execution so as to save time and uses the available resources.
What could be the other factors ???
Any help is highly appreciated. | * Allow the user to do other tasks (or cancel) during the execution
* Allow the software to do other tasks during the execution
+ Eg. Using processor time while waiting for network or file system
+ Communication with external processes or devices which need immediate response to not run into a timeout. (Eg. Network response, external devices)
It's good praxis to not bind two different time consuming tasks synchronously together, eg. network communication and Database access.
On the other hand, software does not get faster if everything is asynchronous. It just allows using resources while waiting for others. | Providing responsiveness and feedback in the user interface, in order to keep the users happy and buying more software. | Deciding Factor for Asynchronous Programming | [
"",
"c#",
".net",
"asynchronous",
""
] |
URL is here: <http://www.thexsoft.com/DownloadFolder/download.php?file=P2PTransfer>
This page is basically a way for me to have set url to download a certain problem i published. This page should never ever be cached, but it seems to be caching still.
I have set the following items:
```
<meta http-equiv="expires" content="0" >
<meta http-equiv="cache-control" content="no-cache" >
<meta http-equiv="pragma" content="no-cache" >
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" >
```
The html code on the page validates 100% when i don't have the fastclick.net ad code in, but i keept it in now because it normally is in. | I checked your headers using [Firebug](http://www.getfirebug.com/):
```
Cache-Control: max-age=1209600
Expires: Tue, 28 Apr 2009 18:49:15 GMT
```
In PHP you can send HTTP headers with [header()](http://www.php.net/manual/en/function.header.php).
```
header('Pragma: no-cache');
header('Expires: -1');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
``` | Pragma: no-cache prevents caching only when used over a secure connection (https). A Pragma: no-cache META tag is treated identically to Expires: -1 if used in a non-secure page. The page will be cached but marked as immediately expired.
<http://support.microsoft.com/kb/234067>
```
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
``` | Html / php page being cached (client side) when it should not be | [
"",
"php",
"html",
""
] |
is there a way to create a standalone .exe from a python script.
Executables generated with py2exe can run only with pythonXX.dll.
I'd like to obtain a fully standalone .exe which does not require to install the python runtime library.
It looks like a linking problem but using static library instead the dynamic one and it would be also useful to apply a strip in order to remove the unused symbols.
Any idea ?
Thanks.
Alessandro | You can do this in the latest version of py2exe...
Just add something like the code below in your `setup.py` file (key part is 'bundle\_files': 1).
To include your TkInter package in the install, use the 'includes' key.
```
distutils.core.setup(
windows=[
{'script': 'yourmodule.py',
'icon_resources': [(1, 'moduleicon.ico')]
}
],
zipfile=None,
options={'py2exe':{
'includes': ['tkinter'],
'bundle_files': 1
}
}
)
``` | Due to how Windows' dynamic linker works you cannot use the static library if you use .pyd or .dll Python modules; DLLs loaded in Windows do not automatically share their symbol space with the executable and so require a separate DLL containing the Python symbols. | Create a standalone windows exe which does not require pythonXX.dll | [
"",
"python",
"windows",
"py2exe",
""
] |
My company created an application that can send large attachements from one mail recipient to another (because most mailboxes are very limited).
But we were wondering how we can prevent the uploading of warez?
For now all extentions are allowed, but we could restrict the extentions to zip and images.
But if you zip warez you can still upload these.
Are there any tools, methods or something like it to prevent the uploading of warez through our system?
Some more info:
This project is semi-public. It will mostly be used for the communication between customer and company. Therefore an email address of our company is always required (either within the receivers as that of the senders, but you all know how easy it is to manipulate this). | Define what "warez" is first.
I'm pretty sure you're going to have problems with that.
You can probably implement heuristics that figure out that you're sending applications and just ban that, but there's no way you're going to figure out that one application is a pirated copy and another isn't and allow the legal one while ban the pirated one.
If you control the server, and is afraid that people will upload pirated copies of applications onto your server and use it to spread it with, then I'm pretty sure your only option is to check with a lawyer what you're obligated to do.
I think it boils down to that you need a system where copyright owners can inform you of pirated copies being present and that you have a system to remove said content within a time frame. I think that's all that is required. | **EDIT**
If as you said in your edit, that this is for customers to send stuff to you, then I'd be very careful about the allowed email addresses. Is there anything to stop somebody putting in Distribution Email addresses. e.g. If some naughty person sent a large file to All@YourCompany.com, will it be distributed or will it be blocked
**ORIGINAL**
If this is an open/public system, then its going to be abused. There are ways to unpack zip files on the fly to check their contents, and even to check the file mimetype headers to perform more restrictions, but it doesn't change the fact that someone might want to legitimately send an AVI file of a presentation, while someone else whats to upload a pirated movie.
If this is for internal use in your company, I'd suggest restricting access in someway (tie the system into your Company LDAP/ADSI system and make users login to the system.
Also putting some file size restrictions in place might be necessary as theres nothing to stop some script kiddie just sending 1Gb Junk Text files around, just to be a nuisance and eating up your bandwidth | How to prevent the uploading of Warez. (asp.net, C#) | [
"",
"c#",
"asp.net",
"upload",
""
] |
Is there a way I can do a sleep in JavaScript before it carries out another action?
Example:
```
var a = 1 + 3;
// Sleep 3 seconds before the next action here.
var b = a + 4;
``` | You can use `setTimeout` to achieve a similar effect:
```
var a = 1 + 3;
var b;
setTimeout(function() {
b = a + 4;
}, (3 * 1000));
```
This doesn't really 'sleep' JavaScript—it just executes the function passed to `setTimeout` after a certain duration (specified in milliseconds). Although it is possible to write a sleep function for JavaScript, it's best to use `setTimeout` if possible as it doesn't freeze everything during the sleep period. | In case you really need a `sleep()` just to test something. But be aware that it'll crash the browser most of the times while debuggin - probably that's why you need it anyway. In production mode I'll comment out this function.
```
function pauseBrowser(millis) {
var date = Date.now();
var curDate = null;
do {
curDate = Date.now();
} while (curDate-date < millis);
}
```
Don't use `new Date()` in the loop, unless you want to waste memory, processing power, battery and possibly the lifetime of your device. | Sleep in JavaScript - delay between actions | [
"",
"javascript",
"sleep",
""
] |
I wish to upload from my Flash Application (AS3) to imageshacks XML API. I wish to know how I can do this.
"In Flash, we must POST the data using the UrlRequest and UrlLoader classes, however we run into a limitation of the Flash API. The data property of a UrlRequest can either be a UrlVariablesByteArray object. There is no easy way to send name value pairs along with the JPG byte array. This is a big problem, because most upload applications will require a filename and other headers to accompany the raw file data"
I was hoping if someone could help me overcome the above!
Thanks all
## Update
I have tried making use of this tutorial here:<http://www.mikestead.co.uk/2009/01/04/upload-multiple-files-with-a-single-request-in-flash/>
The problem is it's not for unsaved images, but it get images from your local machine and then uploads it to the server where the images has had a name already! | This was of great help to me: <http://kitchen.braitsch.io/upload-bitmapdata-snapshot-to-server-in-as3/>
You need to modify the URLRequestWrapper to insert field names and file names where needed. Here's what I've done:
```
bytes = 'Content-Disposition: form-data; name="' + $fieldName + '"; filename="';
```
It does the most formatting of headers so the server could understand it as a file upload.
By the way, if you have a BitmapData you might need to encode it to JPEG or PNG first.
Regards,
Artem | You can send your filename data and any other data you want along with the URLRequest:
```
var params:URLVariables = new URLVariables();
params.id = ride.id;
params.filename = ride.map_image;
params.path = 'maps/';
var req:URLRequest = new URLRequest( ModelLocator.SERVER_URL + "/php/uploadpic.php");
req.method = URLRequestMethod.GET;
req.data = params;
fileRef.upload(req);
```
on the server side in php you access the extra variables as:
$\_REQUEST['path'] and $\_REQUEST['filename'] etc | How to upload a BitmapData Object straight to my server? | [
"",
"php",
"xml",
"flash",
"actionscript-3",
"http",
""
] |
I'm working on a tool that parses files for CSS style declarations. It uses a very complicated regular expression that, besides the expected performance issues and a few minor bugs that aren't affecting me for now, is doing everything I'd like it to do except for one thing.
I have it matching all combinations of element names, classes, sub-classes, pseudo-classes, etc. However, when a line contains more than one declaration, I can only get it to match once. As an example, here is the kind of thing that is tripping me up at the moment:
```
td.class1, td.class2, td.class3
{
background-color: #FAFAFA;
height: 10px;
}
```
I can write an expression that will satisfy this for all of the three declarations, but since I am also capturing information after it (the actual style info within the brackets) I feel like this entire block of text is considered to be accounted for so the engine moves on to the next character following the whole block that just got processed.
Is there a way to accomplish this where each class will be a separate match and all will include the style info that follows as well? I know that I can modify my regex to match the whole line and then parse it for commas after I get my match, but I'd like to keep all my logic inside the expression itself if possible.
I can post the expression and/or the commented code I use to generate it if it's absolutely relevant to the answer, but the expression is huge/ugly (as all non-trivial regexes are) and the code is a bit lengthy. | Here's a regex that works with your sample data:
```
@"([^,{}\s]+(?:\s+[^,{}\s]+)*)(?=[^{}]*(\{[^{}]+\}))"
```
The first part matches and captures a selector (td.class1) in group #1, then the lookahead skips over any remaining selectors and captures the associated style rules in group #2. The next match attempt starts where the lookahead started the previous time, so it matches the next selector (td.class2) and the lookahead captures the same block of rules again.
This won't handle @-rules or comments, but it works fine on the sample data you provided. I even checked it out on some real-world stylesheets and it did remarkably well. | You need a CSS parser, not a regex. You should probably read [Is there a CSS Parser for C#](https://stackoverflow.com/questions/512720/is-there-a-css-parser-for-c). | Multi-line regex with overlapping matches | [
"",
"c#",
".net",
"css",
"regex",
""
] |
Following are the benefits of C++
* C++ provides the specific features they are asking about
* Their C compiler is almost certainly really a C++ compiler, so there are no software cost implications
* C++ is just as portable as C
* C++ code can be just as efficient as C (or more so, or less so)
Are there any concrete reasons and specific scenarios, where one has to use C over C++?
Reference to this question:[Library for generics in C](https://stackoverflow.com/questions/649649/library-for-generic-datatypes-in-c)
Not a duplicate, because this question is asking about language limitations and not about should/shouldn't learn one language over another.
**Peter Kirkham's post was for me the most informative, particularly with regard to C99 issues which I hadn't considered, so I've accepted it. Thanks to all others who took part.** | > This is prompted by a an answer I gave to a current question which asks about a generics library for C - the questioner specifically states that they do not want to use C++.
C is a complete programming language. C is not an arbitrary subset of C++. C is not a subset of C++ at all.
This is valid C:
```
foo_t* foo = malloc ( sizeof(foo_t) );
```
To make it compile as C++ you have to write:
```
foo_t* foo = static_cast<foo_t*>( malloc ( sizeof(foo_t) ) );
```
which isn't valid C any more. (you could use the C-style cast, it which case it would compile in C, but be shunned by most C++ coding standards, and also by many C programmers; witness the "don't cast malloc" comments all over Stack Overflow).
---
They are not the same language, and if you have an existing project in C you don't want to rewrite it in a different language just to use a library. You would prefer to use libraries which you can interface to in the language you are working in. (In some cases this is possible with a few `extern "C"` wrapper functions, depending on how template/inline a C++ library is.)
Taking the first C file in a project I'm working on, this is what happens if you just swap `gcc std=c99` for `g++`:
```
sandiego:$ g++ -g -O1 -pedantic -mfpmath=sse -DUSE_SSE2 -DUSE_XMM3 -I src/core -L /usr/lib -DARCH=elf64 -D_BSD_SOURCE -DPOSIX -D_ISOC99_SOURCE -D_POSIX_C_SOURCE=200112L -Wall -Wextra -Wwrite-strings -Wredundant-decls -Werror -Isrc src/core/kin_object.c -c -o obj/kin_object.o | wc -l
In file included from src/core/kin_object.c:22:
src/core/kin_object.h:791:28: error: anonymous variadic macros were introduced in C99
In file included from src/core/kin_object.c:26:
src/core/kin_log.h:42:42: error: anonymous variadic macros were introduced in C99
src/core/kin_log.h:94:29: error: anonymous variadic macros were introduced in C99
...
cc1plus: warnings being treated as errors
src/core/kin_object.c:101: error: ISO C++ does not support the ‘z’ printf length modifier
..
src/core/kin_object.c:160: error: invalid conversion from ‘void*’ to ‘kin_object_t*’
..
src/core/kin_object.c:227: error: unused parameter ‘restrict’
..
src/core/kin_object.c:271: error: ISO C++ does not support the ‘z’ printf length modifier
src/core/kin_object.c:271: error: ISO C++ does not support the ‘z’ printf length modifier
```
In total 69 lines of errors, four of which are invalid conversions, but mostly for features that exist in C99 but not in C++.
It's not like I'm using those features for the fun of it. It would take significant work to port it to a different language.
So it is plain wrong to suggest that
> [a] C compiler is almost certainly really a C++ compiler, so there are no software cost implications
There are often significant cost implications in porting existing C code to the procedural subset of C++.
So suggesting *'use the C++ std::queue class'* as an answer to question looking for an library implementation of a queue in C is dafter than suggesting *'use objective C'* and *'call the Java java.util.Queue class using JNI'* or *'call the CPython library'* - Objective C actually is a proper superset of C (including C99), and Java and CPython libraries both are callable directly from C without having to port unrelated code to the C++ language.
Of course you could supply a C façade to the C++ library, but once you're doing that C++ is no different to Java or Python. | I realize it's neither a professional nor a particular good answer, but for me it's simply because I really like C. C is small and simple and I can fit the whole language in my brain, C++ to me has always seemed like a huge sprawling mess with all kinds of layers I have a hard time grokking. Due to this I find that whenever I write C++ I end up spending far more time debugging and banging my head against hard surfaces than when I code C. Again I realize that a lot of this is largely a result of my own 'ignorance'.
If I get to choose I'll write all the high level stuff like the interface and database interaction in python (or possibly C#) and all the stuff that has to be fast in C. To me that gives me the best of all worlds. Writing everything in C++ feels like getting the worst of all worlds.
**Edit:**
I'd like to add that I think C with a few C++ features is largely a bad idea if you're going to be several people working on a project or if maintainability is priority. There will be disagreement as to what constitutes a 'a few' and which bits should be done in C and which bits in C++ leading eventually to a very schizophrenic codebase. | What would be C++ limitations compared C language? | [
"",
"c++",
"c",
""
] |
This question is related to [this one](https://stackoverflow.com/questions/763213/what-would-this-code-do-memory-management). Given this code:
```
char *p = new char[200];
delete[] p;
```
what would happen if you set `p[100] = '\0'` before deleting p?
I had some code where I got a debug error when I tried to delete a not null-terminated char array, something about deleting heap memory that's not assigned. It seemed to delete memory out of the array's bounds. | The code:
```
char *p = new char[200];
p[100] = '\0';
delete[] p;
```
is perfectly valid C++. delete does not know or care about null-terminated strings, so your error must have had some other cause. | Nothing special would happen. You would write at some place in the middle of the allocated memory (100 bytes apart from the start, 99 bytes before the end of the allocated memory).
Then you would free that allocated memory. The compiler will handle it exactly as we would expect. The memory allocated by that is completely unrelated to null terminated strings. You could stick everything you want into that memory. It's some "raw" chunk of storage, you could even create some arbitrary C++ object into that memory (placement new).
Your bug is somewhere else. For example, some common error is this one, where the constructor is called once, but the destructor is called twice, double-deleting something:
```
struct A { P *p; A() { p = new P; } ~A() { delete p; } };
A getA() { return A(); } int main() { A a = getA(); }
```
Now, what happens is that the default constructor is called once, and the created object is copied zero or more times. But the destructor is run for each copy that's created. Thus, you will call the destructor on the pointer more than once, leading to such strange bugs. The correct way to fix *that* is to use a smart pointer, like `shared_ptr`. As an exercise, you can also do it without, by writing proper copy constructors that copy the object over and allocate memory in the copy constructor, so that the copy and the respective original object keep distinct pointers. | Deleting a char array | [
"",
"c++",
"memory-management",
""
] |
I currently have an excel sheet with one of the columns being in the date format.
What I see when I open up the spreadsheet is something like 12/29/09 and the program sees 40176.
I figured out this is the value present when I change the column to general text.
My question is **how can I read the value 12/29/09** instead of 40176 or how can I change 40176 into a valid date?
*My program is in c# Must be read in in c#*
---
Here is sample code of my connection if it helps any.
```
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
string myPath = @"C:\Test.xls";
excelApp.Workbooks.Open(myPath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "t", false, false, 0, true, 1, 0);
Microsoft.Office.Interop.Excel.Sheets sheets = excelApp.Worksheets;
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
excelApp.Visible = true;
if(((Microsoft.Office.Interop.Excel.Range)excelApp.Cells[r, 1]).Value2 != null)
DateString = ((Microsoft.Office.Interop.Excel.Range)excelApp.Cells[r, 1]).Value2.ToString();
``` | You can use [DateTime.FromOADate()](http://msdn.microsoft.com/en-us/library/system.datetime.fromoadate.aspx) to convert the double into a DateTime value. | As Reed Copsey said, the `DateTime.FromOADate()` method will convert the value into a `DateTime`. If, however, you want 12/29/09 as a string, and don't want to manipulate it any further, you can use `cell.Text` instead. | Excel Date Field Conversion Problem | [
"",
"c#",
"excel",
""
] |
If I type:
```
void doThis(){
System.out.println("Hello Stackoverflow.");
}
```
what is the default scope of `doThis()`?
Public? Protected? Private? | The default scope is package-private. All classes in the same package can access the method/field/class. Package-private is stricter than protected and public scopes, but more permissive than private scope.
More information:
<http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html>
<http://mindprod.com/jgloss/scope.html> | Anything defined as package private can be accessed by the class itself, other classes within the same package, but not outside of the package, and not by sub-classes.
See [this page](http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html) for a handy table of access level modifiers... | What is the default scope of a method in Java? | [
"",
"java",
"scope",
""
] |
By design, Selenium makes a new copy of your Firefox profile each time a new test is run. I find this copy time is a considerable bottleneck, especially when running 100s of tests. (5-15 seconds to copy the profile anew).
Does anyone know of any override behavior for this? I'd prefer my Selenium server to just reuse the same firefox profile. I know this violates the "cleanly set up your test fixtures" philosophy, but it's a shortcut I'm willing to take, as my tests don't materially alter my firefox profile enough to jeopardize future tests. | I agree this is a problem. It's nice to have a new copy of a Firefox process each time, but a bit overkill to double the startup time by regenerating the Firefox profile. If you open a bug report on <http://jira.openqa.org> and email me at patrick@browsermob.com I'll be happy to make sure we get a solution in place.
PS: I've solved this problem as a one-off for myself. We use the same Firefox profile and just nuke out the cache and cookies DB. But I really should just patch that change back to the Selenium source. | It's simply a matter of moving the code below outside of your test setup and into the fixture setup and keeping a global of the selenium instance (code assumes NUnit.)
```
[TestFixtureSetUp()]
public void FixtureSetup()
{
selenium = New DefaultSelenium("localhost", 4444, "*firefox", "http://localhost/");
selenium.Start();
selenium.SetTimeout("30000");
selenium.Open("/");
}
```
Your test setup should then look something like this:
```
[SetUp()]
public void SetUpTest()
{
selenium.Open("default.aspx");
selenium.WaitForPageToLoad("30000");
}
``` | Is there any way to speed up the Selenium Server load time? | [
"",
"java",
"selenium",
""
] |
The title pretty much frames the question. I have not used CHAR in years. Right now, I am reverse-engineering a database that has CHAR all over it, for primary keys, codes, etc.
How about a CHAR(30) column?
Edit:
So the general opinion seems to be that CHAR if perfectly fine for certain things. I, however, think that you can design a database schema that does not have a need for "these certain things", thus not requiring fixed-length strings. With the bit, uniqueidentifier, varchar, and text types, it seems that in a well-normalized schema you get a certain elegance that you don't get when you use encoded string values. Thinking in fixed lenghts, no offense meant, seems to be a relic of the mainframe days (I learned RPG II once myself). I believe it is obsolete, and I did not hear a convincing argument from you claiming otherwise. | Where the nature of the data dictates the length of the field, I use CHAR. Otherwise VARCHAR. | I use char(n) for codes, varchar(m) for descriptions. Char(n) seems to result in better performance because data doesn't need to move around when the size of contents change. | Is the CHAR datatype in SQL obsolete? When do you use it? | [
"",
"sql",
"types",
"char",
""
] |
I have this class:
```
public class GenericEventArgs<T> : EventArgs
{
public GenericEventArgs() : this(default(T)) {}
public GenericEventArgs(T value) { Value = value; }
public T Value { get; private set; }
}
```
And this event handler delegate for it:
```
public delegate void GenericEventHandler<T>(object sender, GenericEventArgs<T> e);
```
I currently have these in the same file together in a namespace. Is that considered bad/messy/etc.? Cause, in general I would say that each file should contain only one class. So to have it clean I would prefer to have the `GenericEventArgs` class in the file alone. But then I have this `GenericEventHandler<T>` delegate that I am not sure where I should place. Should it have its own file? With just... that one line kind of? (and the namespace of course)
How do you usually do this? | Any reason for not using `EventHandler<TEventArgs>`? I thought there was an equivalent `EventArgs<T>` but I can't see it at the moment... Anyway, I'd put `GenericEventArgs` in `GenericEventArgs.cs`
Personally, when I want to introduce my own delegate types (which is increasingly rare, to be honest) I create a `Delegates.cs` file with all the appropriate delegates for the namespace in. Then I know where to find them without having a file for a single declaration. | When I wanted to create my own eventhandler delegates, I used to create one file which had the name of the EventArgs class that I used in my own eventhandler delegate.
For instance 'MyEventArgs.cs'.
That file contained the MyEventArgs class, and the MyEventHandler delegate that used this class.
Now however, I use the existing generic EventHandler (`EventHandler<T>`), and I only have to create my custom EventArgs class. So, this 'problem' doesn't exists anymore for me. :) | C#: Where should you place event handler delegates? | [
"",
"c#",
"event-handling",
"conventions",
""
] |
In a project that I'm working on I have to work with a rather weird data source. I can give it a "query" and it will return me a DataTable. But the query is not a traditional string. It's more like... a set of method calls that define the criteria that I want. Something along these lines:
```
var tbl = MySource.GetObject("TheTable");
tbl.AddFilterRow(new FilterRow("Column1", 123, FilterRow.Expression.Equals));
tbl.AddFilterRow(new FilterRow("Column2", 456, FilterRow.Expression.LessThan));
var result = tbl.GetDataTable();
```
In essence, it supports all the standard stuff (boolean operators, parantheses, a few functions, etc.) but the syntax for writing it is quite verbose and uncomfortable for everyday use.
I wanted to make a little parser that would parse a given expression (like `"Column1 = 123 AND Column2 < 456"`) and convert it to the above function calls. Also, it would be nice if I could add parameters there, so I would be protected against injection attacks. The last little piece of sugar on the top would be if it could cache the parse results and reuse them when the same query is to be re-executed on another object.
So I was wondering - are there any existing solutions that I could use for this, or will I have to roll out my own expression parser? It's not too complicated, but if I can save myself two or three days of coding and a heapload of bugs to fix, it would be worth it. | Try out [Irony](http://irony.codeplex.com/). Though the documentation is lacking, the samples will get you up and running very quickly. Irony is a project for parsing code and building abstract syntax trees, but you might have to write a little logic to create a form that suits your needs. The [DLR](http://dlr.codeplex.com/) may be the complement for this, since it can dynamically generate / execute code from abstract syntax trees (it's used for IronPython and IronRuby). The two should make a good pair.
Oh, and they're both first-class .NET solutions and open source. | Bison or JavaCC or the like will generate a parser from a grammar. You can then augment the nodes of the tree with your own code to transform the expression.
OP comments:
I really don't want to ship 3rd party executables with my soft. I want it to be compiled in my code.
Both tools generate *source code*, which you link with. | C#: How to parse arbitrary strings into expression trees? | [
"",
"c#",
".net",
"parsing",
"expression-trees",
""
] |
For example, given the string "2009/11/12" I want to get the regex ("\d{2}/d{2}/d{4}"), so I'll be able to match "2001/01/02" too.
Is there something that does that? Something similar? Any idea' as to how to do it? | There is [text2re](http://www.txt2re.com/), a free web-based "regex by example" generator.
I don't think this is available in source code, though. I dare to say there is no automatic regex generator that gets it right without user intervention, since this would require the machine knowing what you want.
---
Note that text2re uses a template-based, modularized and very generalized approach to regular expression generation. The expressions it generates work, but they are much more complex than the equivalent hand-crafted expression. It is not a good tool to *learn* regular expressions because it does a pretty lousy job at setting examples.
For instance, the string `"2009/11/12"` would be recognized as a `yyyymmdd` pattern, which is helpful. The tool transforms it into *this* 125 character monster:
```
((?:(?:[1]{1}\d{1}\d{1}\d{1})|(?:[2]{1}\d{3}))[-:\/.](?:[0]?[1-9]|[1][012])[-:\/.](?:(?:[0-2]?\d{1})|(?:[3][01]{1})))(?![\d])
```
The hand-made equivalent would take up merely two fifths of that (50 characters):
```
([12]\d{3})[-:/.](0?\d|1[0-2])[-:/.]([0-2]?\d|3[01])\b
``` | It's not possible to write a general solution for your problem. The trouble is that any generator probably wouldn't know what you want to check for, e.g. should "2312/45/67" be allowed too? What about "2009.11.12"?
What you could do is write such a generator yourself that is suited for your exact problem, but a general solution won't be possible. | Given a string, generate a regex that can parse *similar* strings | [
"",
"java",
"regex",
""
] |
In a program in c# I have 2 threads apart from the main thread.
When the user closes the form I want to terminate one of the threads from the main thread.
How do I go about doing so?. Please provide me with the code if possible. | Please *don't* use `Thread.Abort` as recommended by the other answers so far, unless you want your program to be in an unknown state (see articles by [Ian Griffiths](http://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation) and [Chris Sells](http://www.ondotnet.com/pub/a/dotnet/2003/02/18/threadabort.html) for more info). If closing the form should actually be killing the app, you're *probably* okay - but in that case I'd recommend just using background threads anyway, which will automatically die when all foreground threads have terminated.
From Joe Duffy's ["Concurrent Programming in Windows"](https://rads.stackoverflow.com/amzn/click/com/032143482X):
> There are two situations in which thread aborts are always safe:
>
> * The main purpose of thread aborts is to tear down threads during CLR
> AppDomain unloads. [...]
> * Synchronous thread aborts are safe, provided that callers expect
> an exception to be thrown from the method. [...]
>
> All other uses of thread aborts are questionable at best. [...]
> While thread aborts are theoretically safer than other thread termination
> mechanisms, they can still occur at inopportune times, leading to
> instability and corruption if used without care.
(Synchronous thread aborts are when the thread aborts itself, rather than being aborted by another thread.)
For *graceful* shutdown (without risking getting into odd states) use a flag which is set periodically from the form and checked from the other threads - taking the memory model into account (e.g. either making the flag volatile or using a lock each time you test or set it). See my [article on the topic](http://pobox.com/~skeet/csharp/threads/shutdown.shtml) for an example. | Killing threads from other threads is almost *always* a bad idea. The correct way to do it is to signal the thread to terminate and then wait for it.
That's because threads should be totally responsible for their own resources as much as practicable, and that includes their lifetime.
It doesn't need to be complicated, a simple variable which can be set by any thread and is read by another thread periodically will do (this isn't really in any language but you should get the idea if you know C):
```
int exitThread1 = false;
static void Thread1 (void) {
while (!exitThread1) {
// do stuff
}
}
static void mummyProc (void) {
int tid1 = startThread (Thread1);
// dum de dum de dum ...
exitThread1 = true;
joinThread (tid1);
}
``` | Manipulating a thread from a different thread | [
"",
"c#",
"multithreading",
""
] |
I am trying to use std::for\_each to output the contents of vectors, which may contain different types. So I wrote a generic output function like so:
```
template<typename T> void output(const T& val)
{
cout << val << endl;
}
```
which I would like to use with:
```
std::for_each(vec_out.begin(), vec_out.end(), output);
```
but the compiler complains with "could not deduce template argument" in the for\_each statement. Also complains with "A function template cannot be an argument to another function template".
Is this not possible? I would have thought the compiler would know the type of vec\_out (it's vector) and so should instantiate the function "output(const double& val)"?
If this doesn't work how can I get similar STL functionality without writing manual loops?
I am quite new to C++ and still learning the ropes :-) | Try:
```
std::for_each(vec_out.begin(), vec_out.end(), output<T>);
```
where `vec_out` is a container (`vector`) of type T.
Note: The [`for_each`](http://www.sgi.com/tech/stl/for_each.html) algorithm expects an unary functor for its last argument. See the link for an example using functors. | You have to pass an instantiation of the template. Something like `output<int>` if your vector is vector of integers.
For example:
```
template<typename T> void output(const T& val)
{
cout << val << endl;
}
void main(int argc,char *argv[])
{
std::vector<int> vec_out;
std::for_each(vec_out.begin(), vec_out.end(), output<int>);
}
``` | In C++ how can I use a template function as the 3rd parameter in std::for_each? | [
"",
"c++",
"templates",
"stl",
"foreach",
""
] |
I have an ATL application with a dialog containing a TAB control. The App uses a common controls manifest.
Under XP with visual styles, the tab control background is a different color than the dialog and the controls (mostly checkboxes), so it looks quite ugly.
[Screenshot](http://www.codeproject.com/script/Membership/Uploads/175/ATLTAB.png)
How can I fix that? | [Here](https://stackoverflow.com/questions/1042415/windows-xp-style-why-do-we-get-dark-grey-background-on-static-text-widgets) you could find answer to your question. | There is - apparently - one thing to do to get tab control pages colored correctly using XP visual styles.
In the WM\_INITDIALOG handler for each page, call the uxtheme API [`EnableThemeDialogTexture`](http://msdn.microsoft.com/en-us/library/bb773320(VS.85).aspx)
With the `ETDT_ENABLETAB` flag this automatically changes the background color of the dialog and all its child controls to paint appropriately on a tab.
The dialog pages do not need any kind of transparent flag, or indeed any style bit set differently from previously. If you have overridden `WM_ERASEBKGND` or `WM_CTLCOLORDLG` in your pages DialogProc you will need to revert to default handling (return `FALSE`). | TAB control background in ATL App, XP styles | [
"",
"c++",
"winapi",
"atl",
"xp-theme",
""
] |
I need to create a table in MS access database.
Consider, 'ConfigStructure.mdb' being my database name and i need to create a table in this database in C#.
How can i do this? I tried with the below code but its not working.
```
OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + frmMain.strFilePath + "\\ConfigStructure.mdb");
myConnection.Open();
string strTemp = " KEY Text, VALUE Text ";
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = myConnection;
myCommand.CommandText = "CREATE TABLE table1(" + strTemp + ")";
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
```
This is the error that i get,
```
"System.Data.OleDb.OleDbException: Syntax error in field definition
System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)\r\n at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)\r\n at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)\r\n at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)"
``` | Replace
```
string strTemp = " KEY Text, VALUE Text ";
```
with
```
string strTemp = " [KEY] Text, [VALUE] Text ";
```
I think the reason for this is that 'KEY' an 'VALUE' are reserved keywords in Access or SQL. | KEY and VALUE are both [reserved words](http://support.microsoft.com/kb/286335). Particularly it is probably getting hung up on "KEY" because you can specify `PRIMARY KEY` as a constraint in a `CREATE TABLE` command.
Try using different column names or surrounding them by brackets (e.g. [KEY]) if you *really* want to use them (not suggested). | How to create a table in a MS access database in C# | [
"",
"c#",
""
] |
I have into my main.py
```
from modules import controller
ctrl = controller
help(ctrl)
print(ctrl.div(5,2))
```
and the controllor.py is:
```
class controller:
def div(self, x, y):
return x // y
```
when I run my main I got the error:
```
Traceback (most recent call last):
File "...\main.py", line 8, in ?
print(ctrl.div(5,2))
AttributeError: 'module' object has no attribute 'div'
```
WHat is wrong? | When you execute following code
```
from modules import controller
ctrl = controller
```
**ctrl** variable becomes a pointer to **controller** class.
To create an instance of **controller** class you need to add parenthesis:
```
from modules import controller
ctrl = controller()
``` | This is very confusing as shown.
When you say
```
from modules import controller
```
You're making the claim that you have a module with a filename of `modules.py`.
OR
You're making the claim that you have a package named `modules`. This directory has an `__init__.py` file and a module with a filename of `controller.py`
You should clarify this to be precise. It looks like you have mis-named your files and modules in the the example code posted here.
When you say
```
from modules import controller
```
That creates a *module* (not a class) named `controller`.
When you say
```
ctrl = controller
```
That creates another name for the `controller` *module*, `ctrl`.
At no time to you reference the class (`controller.controller`). At no time did you create an instance of the class (`controller.controller()`). | Python class inclusion wrong behaviour | [
"",
"python",
""
] |
If I have an instance of an inner class, how can I access the outer class *from code that is not in the inner class*? I know that within the inner class, I can use `Outer.this` to get the outer class, but I can't find any external way of getting this.
For example:
```
public class Outer {
public static void foo(Inner inner) {
//Question: How could I write the following line without
// having to create the getOuter() method?
System.out.println("The outer class is: " + inner.getOuter());
}
public class Inner {
public Outer getOuter() { return Outer.this; }
}
}
``` | The bytecode of the `Outer$Inner` class will contain a package-scoped field named `this$0` of type `Outer`. That's how non-static inner classes are implemented in Java, because at bytecode level there is no concept of an inner class.
You should be able to read that field using reflection, if you really want to. I have never had any need to do it, so it would be best for you to change the design so that it's not needed.
Here is how your example code would look like when using reflection. Man, that's ugly. ;)
```
public class Outer {
public static void foo(Inner inner) {
try {
Field this$0 = inner.getClass().getDeclaredField("this$0");
Outer outer = (Outer) this$0.get(inner);
System.out.println("The outer class is: " + outer);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public class Inner {
}
public void callFoo() {
// The constructor of Inner must be called in
// non-static context, inside Outer.
foo(new Inner());
}
public static void main(String[] args) {
new Outer().callFoo();
}
}
``` | There is no way, by design. If you need to access the outer class through an instance of the inner one, then your design is backwards: the point of inner classes is generally to be used only within the outer class, or through an interface. | In Java, how do I access the outer class when I'm not in the inner class? | [
"",
"java",
"syntax",
"nested",
""
] |
Is there an AppDomain for every C# program even if we do not specifically create an AppDomain? Why is it required? I have read about third party assemblies crashing the entire application if we do not load them into separate AppDomain. I didn't get that point well. Can anyone explain this also. | `AppDomain` is pretty much like a process, it's an infrastructure that your application runs in. A .NET assembly needs to be loaded in an `AppDomain` in order to be run. It's not required to load third party assemblies into separate `AppDomains`, but if you do, it provides isolation between them (like two separate processes) and malfunction in one will not affect the other. Application domains can be unloaded independently.
As an example, SQL Server use `AppDomain`s to load CLR assemblies safely in its process. | > I have read about 3rd party assemblies causing crash if we do not make use of AppDomain
I think you are talking about loading other assemblies in to separate app domains. That way they can be isolated from your address space to prevent a crash in their code affecting you. The cost is that communicating with an assembly in a seperate app domain is more difficult and has a perf penalty as all calls need to be martialed across the app domain boundary.
This is a fairly advance topic, I'd recommend reading up in [Richter](http://www.microsoft.com/learning/en/us/Books/6522.aspx) (other books are avaialable). | Is there an AppDomain for every C# program? | [
"",
"c#",
".net",
"appdomain",
""
] |
I have a question concerning Python multiprocessing. I am trying to take a dataset, break into chunks, and pass those chunks to concurrently running processes. I need to transform large tables of data using simple calculations (eg. electrical resistance -> temperature for a thermistor).
The code listed below almost works as desired, but it doesn't seem to be spawning any new processes (or if so only one at a time).
```
from multiprocessing import Process
class Worker(Process):
# example data transform
def process(self, x): return (x * 2) / 3
def __init__(self, list):
self.data = list
self.result = map(self.process, self.data)
super(Worker, self).__init__()
if __name__ == '__main__':
start = datetime.datetime.now()
dataset = range(10000) # null dataset
processes = 3
for i in range(processes):
chunk = int(math.floor(len(dataset) / float(processes)))
if i + 1 == processes:
remainder = len(dataset) % processes
else: remainder = 0
tmp = dataset[i * chunk : (i + 1) * chunk + remainder]
exec('worker'+str(i)+' = Worker(tmp)')
exec('worker'+str(i)+'.start()')
for i in range(processes):
exec('worker'+str(i)+'.join()')
# just a placeholder to make sure the initial values of the set are as expected
exec('print worker'+str(i)+'.result[0]')
``` | No need to send the number of chunks to each process, just use get\_nowait() and handle the eventual Queue.Empty exception. Every process will get different amounts of CPU time and this should keep them all busy.
```
import multiprocessing, Queue
class Worker(multiprocessing.Process):
def process(self, x):
for i in range(15):
x += (float(i) / 2.6)
return x
def __init__(self, input, output):
self.input = input
self.output = output
super(Worker, self).__init__()
def run(self):
try:
while True:
self.output.put(self.process(self.input.get_nowait()))
except Queue.Empty:
pass
if name == 'main':
dataset = range(10)
processes = multiprocessing.cpu_count()
input = multiprocessing.Queue()
output = multiprocessing.Queue()
for obj in dataset:
input.put(obj)
for i in range(processes):
Worker(input, output).start()
for i in range(len(dataset)):
print output.get()
``` | You haven't overridden the `run` method. There are two ways with processes (or threads) to have it execute code:
1. Create a process specifying target
2. Subclass the process, overriding the `run` method.
Overriding `__init__` just means your process is all dressed up with nowhere to go. It should be used to give it attributes that it needs to perform what it needs to perform, but it shouldn't specify the task to be performed.
In your code, all the heavy lifting is done in this line:
```
exec('worker'+str(i)+' = Worker(tmp)')
```
and nothing is done here:
```
exec('worker'+str(i)+'.start()')
```
So checking the results with `exec('print worker'+str(i)+'.result[0]')` should give you something meaningful, but only because the code you want to be executed *has* been executed, but on process construction, not on process start.
Try this:
```
class Worker(Process):
# example data transform
def process(self, x): return (x * 2) / 3
def __init__(self, list):
self.data = list
self.result = []
super(Worker, self).__init__()
def run(self):
self.result = map(self.process, self.data)
```
EDIT:
Okay... so I was just flying based on my threading instincts here, and they were all wrong. What we both didn't understand about processes is that you can't directly share variables. Whatever you pass to a new process to start is read, copied, and gone forever. Unless you use one of the two standard ways to share data: [queues and pipes](http://docs.python.org/library/multiprocessing.html#exchanging-objects-between-processes). I've played around a little bit trying to get your code to work, but so far no luck. I think that will put you on the right track. | Dynamic processes in Python | [
"",
"python",
"multithreading",
"multiprocessing",
""
] |
Let's say I am tasked with coding some kind of an RPG. This means that, for example, I'll want to track a ~~`Character`~~ `GameCharacter` and stats thereof, like intelligence, damage bonuses or hitpoints.
I'm positively scared that by the end of the project I may end up with handling with very a high number of fields - and for each I would have to make sure they follow a very similar set of constraint and behaviours (for example, I want them to be bounded between a min and a max; I want to be able to distinguish between a "base value" and a "temporary bonus"; I want to be able to increment and decrement both without going through a setters and getters). Suddenly, for every field I would need one (two?) getter and four setters and maybe a couple resetters too! Even for 10 fields that means a LOT of methods all alike, eek.
For DRYness I have started encapsulating the logic of messing with those stats in `Field` classes, so that I could write code such as `intelligence.applyBonus(10)` or `hitpoints.get()` (which takes care the value returned is in range), etc. I have even gone to such a length to create classes to group those fields together, but that's not the point right now.
Now, I hit in this problem while "plugging" `Field` into `GameCharacter`: most Java textbooks say that each class should have private fields with public getters and setters. That sounds good in theory, and I've already built a whole class around an `int`; however, the idea doesn't sound as solid when you find yourself calling a getter to get... a getter:
```
thisCharacter.getIntelligence().get() //eeek
```
I'd much rather access the field directly. Maybe it's my Python/VB [1] "background", but for me it is cleaner, clearer and more straightforward:
```
thisCharacter.intelligence.get()
```
The (theoretical) problem with public fields is that I'm giving up all control on it; for example at some other point in the codebase, by misfortune, the following might happen:
```
thisCharacter.intelligence = somethingThatReallyIsNull;
```
Sounds like a subtle bug... but... I mean, should I really worry about that? I for one never plan to assign the `Field` directly [2], I have documented in the Javadoc that this is not something that should be done, but still I am new here so I'm a bit torn.
So I would like to hear what your take on this topic. Are the advantages of encapsulation so massive that I should go ahead and have getter getters and setter getters and so on... or should I take encapsulation in healthy measures and leave the `Field` as a `public` field?
---
[1] Yes, I know. I've been trying to forget. But we've just recently seen also a bit of C# and man, aren't properties sweet. Oh well.
[2] except in Constructors! And a getter won't save me from a faulty constructor. | My experience is that in situations where you need a *lot* of fields, the number, nature, naming, and types of fields are so flexible and likely to change throughout the lifetime of your project that you would likely need some sort of map instead of fields.
For example have an attribute map from keys to values.
Provide public calls for getting and setting the attributes, but don't let everybody use them (or make sure they don't). Instead, create classes to represent each attribute you are interested in, and that class provides all the functions for manipulating that attribute. For example, if you have Strength, you could have a "StrengthManipulation" class that is initialized to a specific Player object, and then provides getters, setters (All with appropriate validation and exceptions), and perhaps things like calculating strength with bonuses, etc.
One advantage of this is that you decouple the use of your attributes from your player class. So if you now add an Intelligence attribute, you don't have to deal and recompile everything that manipulates only strength.
As for accessing fields directly, it's a bad idea. When you access a field in VB (at least in old VBs), you usually call a property getter and setter and VB simply hides the () call for you. My view is that you have to adapt to the conventions of the language that you are using. In C, C++, Java and the like you have fields and you have methods. Calling a method should always have the () to make it clear that it is a call and other things may happen (e.g., you could get an exception). Either way, one of the benefits of Java is its more precise syntax and style.
VB to Java or C++ is like Texting to graduate school scientific writing.
BTW: Some usability research shows that it's better to not have parameters to constructors and rather construct and call all the setters if you need them. | Sounds like you're thinking in terms of `if(player.dexterity > monster.dexterity) attacker = player`. You need to think more like `if(player.quickerThan(monster)) monster.suffersAttackFrom(player.getCurrentWeapon())`. Don't mess around with bare stats, express your actual intention and then design your classes around what they're supposed to do. Stats are a cop-out anyway; what you really care about is whether a player can or cannot do some action, or their ability/capacity versus some reference. Think in terms of "is the player character strong enough" (`player.canOpen(trapDoor)`) instead of "does the character have at least 50 strength". | Java: how to handle a LOT of fields and their encapsulation cleanly? | [
"",
"java",
"encapsulation",
"getter",
""
] |
How do I retrieve the session ID value inside a JSF managed bean? | ```
FacesContext fCtx = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fCtx.getExternalContext().getSession(false);
String sessionId = session.getId();
``` | You try
```
{
String uuidFc = FacesContext.getCurrentInstance().getExternalContext().getSessionId(true);
}
```
This line return the facesContext sessionId value | Retrieving session ID value from a JSF request | [
"",
"java",
"session",
"jsf",
""
] |
How do I get the filename without the extension from a path in Python?
```
"/path/to/some/file.txt" → "file"
``` | ### Python 3.4+
Use [`pathlib.Path.stem`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.stem)
```
>>> from pathlib import Path
>>> Path("/path/to/file.txt").stem
'file'
>>> Path("/path/to/file.tar.gz").stem
'file.tar'
```
### Python < 3.4
Use [`os.path.splitext`](https://docs.python.org/3/library/os.path.html#os.path.splitext) in combination with [`os.path.basename`](https://docs.python.org/3/library/os.path.html#os.path.basename):
```
>>> os.path.splitext(os.path.basename("/path/to/file.txt"))[0]
'file'
>>> os.path.splitext(os.path.basename("/path/to/file.tar.gz"))[0]
'file.tar'
``` | Use [`.stem`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.stem) from [`pathlib`](https://docs.python.org/library/pathlib.html) in Python 3.4+
```
from pathlib import Path
Path('/root/dir/sub/file.ext').stem
```
will return
```
'file'
```
Note that if your file has multiple extensions `.stem` will only remove the last extension. For example, `Path('file.tar.gz').stem` will return `'file.tar'`. | How do I get the filename without the extension from a path in Python? | [
"",
"python",
"string",
"path",
""
] |
I have this ugly XML which has alot of namespaces on it, when I try to load it with simpleXML if i indicate the first namespace I'd get an xml object ,but following tags with other namespaces would not make it to the object.
How can I parse this XML ?
```
<?xml version="1.0" encoding="UTF-8"?>
<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
<soap-env:Header>
<eb:MessageHeader xmlns:eb="http://www.ebxml.org/namespaces/messageHeader" eb:version="1.0" soap-env:mustUnderstand="1">
<eb:From>
<eb:PartyId eb:type="URI">wscompany.com</eb:PartyId>
</eb:From>
<eb:To>
<eb:PartyId eb:type="URI">mysite.com</eb:PartyId>
</eb:To>
<eb:CPAId>something</eb:CPAId>
<eb:ConversationId>moredata.com</eb:ConversationId>
<eb:Service eb:type="compXML">theservice</eb:Service>
<eb:Action>theaction</eb:Action>
<eb:MessageData>
<eb:MessageId>a certain messageid</eb:MessageId>
<eb:Timestamp>2009-04-11T18:43:58</eb:Timestamp>
<eb:RefToMessageId>mid:areference</eb:RefToMessageId>
</eb:MessageData>
</eb:MessageHeader>
<wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/12/secext">
<wsse:BinarySecurityToken valueType="String" EncodingType="wsse:Base64Binary">an impresive binary security toekn</wsse:BinarySecurityToken>
</wsse:Security>
</soap-env:Header>
<soap-env:Body>
<SessionCreateRS xmlns="http://www.opentravel.org/OTA/2002/11" version="1" status="Approved">
<ConversationId>the goodbye token</ConversationId>
</SessionCreateRS>
</soap-env:Body>
</soap-env:Envelope>
```
im trying to parse it with the following code
```
<?php
$xml = simplexml_load_string($res,NULL,NULL,"http://schemas.xmlsoap.org/soap/envelope/");
?>
```
but the $xml object would only contain the following
```
SimpleXMLElement Object
(
[Header] => SimpleXMLElement Object
(
)
[Body] => SimpleXMLElement Object
(
)
)
``` | I think you need to register the namespacing and access with XPath. Something like the following should get you going (I haven't the facility to test this).
```
$xml = simplexml_load_string($res, NULL, NULL, "http://schemas.xmlsoap.org/soap/envelope/");
$xml->registerXPathNamespace('soap-env', 'http://schemas.xmlsoap.org/soap/envelope/');
$xml->registerXPathNamespace('eb', 'http://www.ebxml.org/namespaces/messageHeader');
$xml->registerXPathNamespace('wsse', 'http://schemas.xmlsoap.org/ws/2002/12/secext');
```
Then you can do something like:
```
foreach($xml->xpath('//eb:MessageHeader') as $header)
{
var_export($header->xpath('//eb:CPAId')); // Should output 'something'.
}
```
You may not need to register the namespacing, thinking about it, as they are alredy present in the XML. Not sure on this though, would need to test.
Hope this helps. | 1) Do not use `print_r` and friends to see what is "in" a SimpleXML object. See <https://github.com/IMSoP/simplexml_debug> for explanation and alternatives.
2) Namespace support in SimpleXML is provided by the [`->children()`](http://uk.php.net/manual/en/simplexmlelement.children.php) and [`->attributes()`](http://uk.php.net/manual/en/simplexmlelement.attributes.php) methods.
For example you could get the PartyId of the From node like this:
```
$from_party = (string)$xml->children('soap-env', true)->Header->children('eb', true)->MessageHeader->From->PartyId;
``` | parse an XML with SimpleXML which has multiple namespaces | [
"",
"php",
"soap",
"namespaces",
"simplexml",
""
] |
I am trying to use the isAuthorized() method to do a check for an admin flag, but the function never seems to be called. Even when I set the function to always return false, it allows any user. It just seems like it isn't being called.
Do I need to do something more than setting $this->Auth->authorize = 'controller' ?
from /app/app\_controller.php
```
class AppController extends Controller
{
var $components = array('Auth');
function beforeFilter()
{
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'pages', 'display' => 'home');
$this->Auth->logoutRedirect = '/';
$this->Auth->authorize = 'controller';
$this->Auth->userScope = array('User.active' => 1);
}
function isAuthorized()
{
if (strpos($this->action, "admin_") != false)
{
if ($this->Auth->user('isAdmin') == '0')
{
return false;
}
}
return true;
}
}
``` | You should check if you're overriding your Auth settings in your other controller.
First, to verify that `isAuthorized()` is being called, try putting a simple `debug($this); die;` in it.
If it is not dying, you're probably overriding it in some other controller (you're missing the `parent::isAuthorized()` call).
If it's not that, then you're probably doing that same thing with `beforeFilter()`. | Additional to the Answer of dr Hannibal Lecter, there is another possible reason if you experience this problem (as i did ...):
If your controller is named **tests\_controller**, the startUp method of the Auth-Component aborts without starting the authentication (at least in cakePHP 1.3.10 - haven't checked 2.x). So be sure that you **never name a Controller tests\_controller**...
Excerpt from cake\libs\controller\components\auth.php
```
function startup(&$controller) {
$isErrorOrTests = (
strtolower($controller->name) == 'cakeerror' ||
(strtolower($controller->name) == 'tests' && Configure::read() > 0)
);
if ($isErrorOrTests) {
return true;
}
...
``` | cakephp isAuthorized() not being called | [
"",
"php",
"authentication",
"cakephp",
""
] |
I have the following data as input (sorted by first column):
```
foo 1 2
foo 3 3
bar 10 11
```
I want to create a Map of Vector with first column as key of the map
such that we have:
```
foo = {1,2,3,3}
bar = {10,11}
```
But why my code below doesn't work as expected?
```
#include <vector>
#include <map>
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main ( int arg_count, char *arg_vec[] ) {
if (arg_count !=2 ) {
cerr << "expected one argument" << endl;
return EXIT_FAILURE;
}
string line;
ifstream acemblyfile (arg_vec[1]);
map <string, vector<int> > myMapOfVec;
vector <string> myVec;
string KEY = "" ;
if (acemblyfile.is_open())
{
while (getline(acemblyfile,line) )
{
stringstream ss(line);
string KEY_TEMP;
int VAL1;
int VAL2;
ss >> KEY_TEMP >> VAL1 >> VAL2;
MyVec.push_back(VAL1);
MyVec.push_back(VAL2);
if (KEY_TEMP != KEY) {
myMapOfVec[KEY] = MyVec;
KEY = KEY_TEMP;
MyVec.clear();
}
}
acemblyfile.close();
}
else {
cout << "Unable to open file";
}
for( map<string, vector<int> >::iterator iter = myMapOfVec.begin(); iter != myMapOfVec.end(); ++iter ) {
vector <int> tempVec = (*iter).second;
string Key = (*iter).first;
for (unsigned i =0; i<tempVec.size(); i++) {
cout << Key << " " << tempVec[i] << endl;
}
}
return 0;
}
``` | As Mykola said, you should use the vector in the map instead of creating one yourself. I changed your whole code so it works for me. Note that you wrote some of the variable names with wrong case (MyMapOfVec instead of myMapOfVec) and this led to compiler errors.
Also be sure you don't have a newline at the end of your input file because this will result in repeating the last line.
```
#include <vector>
#include <map>
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main ( int arg_count, char *arg_vec[] ) {
if (arg_count !=2 ) {
cerr << "expected one argument" << endl;
return EXIT_FAILURE;
}
string line;
ifstream acemblyfile (arg_vec[1]);
map <string, vector<int> > myMapOfVec;
string KEY;
if (acemblyfile.is_open())
{
while (getline(acemblyfile, line) )
{
stringstream ss(line);
int VAL1;
int VAL2;
ss >> KEY >> VAL1 >> VAL2;
myMapOfVec[KEY].push_back(VAL1);
myMapOfVec[KEY].push_back(VAL2);
}
acemblyfile.close();
}
else {
cout << "Unable to open file";
}
for( map<string, vector<int> >::iterator iter = myMapOfVec.begin(); iter != myMapOfVec.end(); ++iter ) {
vector<int> tempVec = (*iter).second;
string Key = (*iter).first;
cout << Key;
for (unsigned i = 0; i < tempVec.size(); i++) {
cout << " " << tempVec[i];
}
cout << endl;
}
return 0;
}
```
For your example, this gives the output
```
bar 10 11
foo 1 2 3 3
``` | Don't add check for KEY\_TEMP != KEY. Because in your case they are equal as foo goes two times one by one. Just
```
myMapOfVec[KEY].push_back( VAL1 );
myMapOfVec[KEY].push_back( VAL2 );
``` | Howto Create Map of Vector From Sorted Data | [
"",
"c++",
"data-structures",
"vector",
"dictionary",
""
] |
Does anyone know a way to access the text of stored procedures using LINQ to SQL? I'd like to audit a set of stored procedures to check that they contain all contain some common code.
It feels like there should be a nice way of opening them through a LINQ to SQL data context but I don't know how. Any suggestions? | You could try something along these lines:
```
string results = db.ExecuteQuery<string>
(@"EXEC sp_helptext '{0}'", procedure_name);
```
or use this query in you LINQ:
```
SELECT text
FROM syscomments
WHERE id = (SELECT id FROM sysobjects WHERE name = 'procedure_name')
ORDER BY colid
``` | I guess you are using SQL Server.
To retrieve the text of an stored procedure you will need to execute the [sp\_helptext](http://technet.microsoft.com/en-us/library/ms176112.aspx) system stored procedure.
To know how to execute an stored procedure from Linq you can see [this](http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx). | Using LINQ to SQL to read stored procedures | [
"",
"c#",
"linq-to-sql",
"stored-procedures",
""
] |
What's the easy way to render a shape in Java to its "actual size". For example, I have a tube with a diameter of 1" and I want to depict it on screen as the outline of a 1" circle. The Graphics2D method drawOval(int x, int y, int width, int height) takes a height and width in pixels. What are the steps to translate a pixel size into the size rendered on screen?
Thanks in advance. | The getNormalizingTransform() method of the class GraphicsConfiguration looks like it has some potential
<http://java.sun.com/javase/6/docs/api/java/awt/GraphicsConfiguration.html#getNormalizingTransform()> | The `java.awt.Toolkit` will tell you the [size of a pixel,](http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Toolkit.html#getScreenResolution()) and the [pixel dimensions of the screen.](http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Toolkit.html#getScreenSize()) This is based on information from the underlying system, however, which may sometimes be misconfigured.
So, to draw a 1" circle, you'd use a diameter of `1.0 * tk.getScreenResolution()`, a 2.5" circle is `2.5 * tk.getScreenResolution()`, etc. | Shape at "Actual Size" | [
"",
"java",
""
] |
I am storing a list of classes through (`Classname.class`) and would like to instantiate one? Is this possible?
`newInstance` seems to the method I am after but it doesn't support a constructor? | You cannot construct new classes this way.
If you have the name of a class you can use Class.forName(className) to load/reference a class.
If you have the byte code for a class you want to create you can have a class loader load the byte code and give you the class. This is likely to be more advanced than you intended. | You can use [Class.getConstructors](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getConstructors()) (or Class.getConstructor) to get a list of available constructors, and invoke any of them with [Constructor.newInstance](http://java.sun.com/javase/6/docs/api/java/lang/reflect/Constructor.html#newInstance(java.lang.Object...)), which does accept parameters. | Can I Instantiate a class using the class object? What about Constructors? | [
"",
"java",
"reflection",
""
] |
How do I produce Qt-style documentation (Trolltech's C++ Qt or Riverbank's PyQt docs) with Doxygen? I am documenting Python, and I would like to be able to improve the default function brief that it produces.
In particular, I would like to be able to see the return type (which can be user specified) and the parameters in the function brief.
For example:
```
Functions:
int getNumber(self)
str getString(self)
tuple getTuple(self, int numberOfElements=2)
Function Documentation:
int getNumber(self)
gets the number of items within a list as specified...
Definition at line 63 of ....
etc...
```
If this isn't possible without modifying the source, maybe there is another tool other than Doxygen that handles Python documentation in this kind of way? | Then just use Doxygen? [This will get you started](https://engtech.wordpress.com/2007/03/20/automatic_documentation_python_doxygen/):
> This is a guide for automatically
> generating documentation off of Python
> source code using Doxygen.
Obviously, since Python is not strongly typed, specifying the return type and the expected type of the parameters will be up to you, the documentation writer. That's just best practices anyway. | If you're doing anything documentation related when it comes to Python I recommend [Sphinx](http://sphinx.pocoo.org/ "Sphinx"). It's what the developers of python use for their documentation. | Qt-style documentation using Doxygen? | [
"",
"python",
"documentation",
"doxygen",
""
] |
I've implemented a kind of 'heartbeat solution' and I'd like to see what happen when the network 'goes down', in real conditions, specially if it happens when there is no traffic on the socket.
Problems:
- I've got only one computer;
- I'm on windows/java;
I guess that simply unplugging the network cable/deactivating the network card won't affect the two processes, as they are running on the same box; Is there a programmatic solution to that? A kind of way to force close a socket ? | I use [TCPView](http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx) to right click and close sockets. | if you are using Eclipse, there is a TCP/IP Monitor,
WIndow -> Show View -> Other -> type filter text = TCP/IP
and create a new forwarding tcp/ip
you can monitor and stop that in the middle. | How can I simulate a socket disconnection (on windows) between a client and a server? | [
"",
"java",
"windows",
"tcp",
"sockets",
"system",
""
] |
How do you store a file that was uploaded by an ASP.net webform into a sql server 2005 varbinary(max) field?
Here is what I have so far:
```
protected void btnUpload_Click(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++)
{
StoreFile(Request.Files[i]);
}
}
private void StoreFile(HttpPostedFile file)
{
// what do i do now?
}
```
A plain old ado.net example would be good. So would a linq to sql example.
Thanks | There's nice tutorial on how to upload a file directly into the database
at [4GuysFromRolla](https://web.archive.org/web/20210304133428/https://www.4guysfromrolla.com/articles/120606-1.aspx) | Here's how I did this using Linq To Sql:
```
FilesDataContext db = new FilesDataContext();
protected void btnUpload_Click(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++)
{
StoreFile(Request.Files[i]);
}
db.SubmitChanges();
}
private void StoreFile(HttpPostedFile file)
{
byte[] data = new byte[file.ContentLength];
file.InputStream.Read(data, 0, file.ContentLength);
File f = new File();
f.Data = data;
f.Filename = file.FileName;
db.Files.InsertOnSubmit(f);
}
``` | ASP.NET Store uploaded file sql server table | [
"",
"c#",
"asp.net",
"sql-server",
"sql-server-2005",
"varbinary",
""
] |
Is it possible to embed a scrollable text box to output text on my web page, in HTML or JavaScript?
I am trying not to use any Java libraries if possible. | ```
<textarea></textarea>
``` | ```
<style type="text/css" media="screen">
#messages{
border : solid 2px #ff0000; background : #D5D5D5; padding : 4px; width : 500px; height : 350px; overflow : auto;
}
</style>
<div id='messages'>
</div>
```
to scroll down with jquery:
```
$('#messages').scrollTop( $('#messages')[0].scrollHeight );
``` | How can I embed a scrollable text box to output text on my web page? | [
"",
"javascript",
"html",
""
] |
Is there anything wrong with pushing back a vector of vectors? like
```
typedef vector<Point> Polygon;
vector<Polygon> polys;
polys.push_back(some_poly);
```
All the elements in some\_poly will be *copied* right?
I have a bug in my code and I can't seem to figure out what's wrong with it. | Yes, that should work fine, as long as you have defined a copy constructor and assignment operator for your Point class (and ensured they're doing the right thing etc). std::vector will push just fine, so the bug must be elsewhere - obviously we'd need more details to help further.
There are performance implications if you're going to push a vector of things, but don't worry about that until it's working (and then only if it becomes a problem). | Right, the vector is copied like expected. There is a good software called [geordi](http://www.xs4all.nl/~weegen/eelis/geordi/) which can show this:
```
{
using namespace tracked;
typedef vector<B> poly_t;
poly_t poly(3); // contains 3 B's
vector<poly_t> v;
v.push_back(poly);
}
```
It tracks creation/copies of `tracked::B`. Here is the output:
```
B0* B1*(B0) B2*(B0) B3*(B0) B0~ B4*(B1) B5*(B2) B6*(B3) B4~ B5~ B6~ B1~ B2~ B3~
```
This is output when we only track `v.push_back`:
```
B4*(B1) B5*(B2) B6*(B3)
```
As you see, first B0 is created as the default argument of the vector constructor. Then that object is copied into 3 B's and after that B0 is destroyed again as the constructor comes back. poly then is created. Then, we push\_back it into a vector of polygons. The argument, poly, is copied into a new vector which is created within the vector of polygons and managed by that.
If it crashes, the problem probably lies within another part of your program. Checks that the copy constructor/constructor and destructor work correctly and that they don't delete things twice if you use dynamic memory allocation. | Pushing vector of vectors | [
"",
"c++",
"stl",
"vector",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.