Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I've got a bit of code that I've been working on for a friend for the past few days. At a high level it parses a text file and writes to an MDB. To cut a long story short, I've got a nested couple of loops doing some processing on the items. The inner loop only gets called in certain cases, but when it does, it's doing some strange things.
```
ArrayList CaseRecordItems = new ArrayList(); // this is created earlier
string baseTif = "sometext_"; // this is created earlier
CaseRecord cr = new CaseRecord(); (this gets populated with "stuff")
char increment = 'A';
for (int i = 0; i < FirstNames.Count; i++)
{
cr.Firstname = (string)FirstNames[i];
cr.Lastname = (string)LastNames[i];
if (FirstNames.Count > 1)
{
cr.Tif = baseTif + increment.ToString();
increment++;
}
CaseRecordItems.Add(cr);
}
```
The loop runs for example two times and should set the value of cr.Tif to sometext\_A and sometext\_B. This works correctly, but once the second item is added to the collection, the value of the first is changed to match it.
I suspect this is due to a lack of my understanding how these objects are being instantiated and passed around. Any insight would be appreciated.
**EDIT:**
Based on the awesome feedback (and my numb-nutzery) the issue has been resolved. Thanks to Dan's answer I made a couple of changes to the code that I had tried before utilizing the clone function (yes, beach I had actually tried that :P).
The new block looks like this:
ArrayList CaseRecordItems = new ArrayList(); // this is created earlier
string baseTif = "sometext\_"; // this is created earlier
CaseRecord cr = new CaseRecord(); // this gets populated with "stuff")
char increment = 'A';
```
for (int i = 0; i < FirstNames.Count; i++)
{
CaseRecord cr2 = new CaseRecord();
cr2 = cr.Clone(); // preserves the data from outside
cr2.Firstname = (string)FirstNames[i];
cr2.Lastname = (string)LastNames[i];
if (FirstNames.Count > 1)
{
cr2.Tif = baseTif + increment.ToString();
increment++;
}
CaseRecordItems.Add(cr2);
}
```
Thanks everyone for the super-quick responses! | I assume cr is an object. You're not creating a new cr each time, and so you have the same reference in the arraylist twice, thus when you modify it the second time you're actually working on the same object. | You are changing the value of the `cr` instance inside the loop. Each iteration through the loop is using the same instance of `cr` so when you change it, they all change. To resolve this, an appropriate method is to use a local instance inside the loop:
```
for (int i = 0; i < FirstNames.Count; i++)
{
CaseRecord cr=new CaseRecord();
...
CaseRecordItems.Add(cr);
}
``` | Collection Values Changing in for loop | [
"",
"c#",
"collections",
"loops",
"for-loop",
""
] |
I have a collection of objects of one type that I'd like to convert to a different type. This can be done easily with foreach, but I'd like to figure out how to use Linq's aggregate function to do it.
The problem is all the Aggregate examples use types line string or int, which support the '+' operator. I'd like to have the accumulator type be a list, which doesn't support '+' semantics.
Here's a quick example:
```
public class DestinationType
{
public DestinationType(int A, int B, int C) { ... }
}
var set = from item in context.Items
select new { item.A, item.B, item.C };
var newSet = set.Aggregate( new List<DestinationType>(),
(list, item) => list.Add(new DestinationType(item.A, item.B, item.C)) );
```
The problem is that List<>.Add returns void. The return type of the second parameter to Aggregate needs to be a List.
If I had a list type that supported '+' type semantics I could just make the second parameter
```
list + item
```
However I can't find any collection type that supports this kind of thing.
Seems like this should be easily possible in Linq. Is there a way? Also, if I'm missing an entirely easier way, I'd love to learn about that too. Thanks! | I think a call to [Select](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.select.aspx) combined with [ToList()](http://msdn.microsoft.com/en-us/library/bb342261.aspx) might be what you need here. For example:
```
context.Items
.Select(item => new DestinationType(item.A, item.B, item.C))
.ToList();
``` | Assuming this is LINQ to Objects, try...
```
var newSet = set.Aggregate(new List<DestinationType>(),
(list, item) =>
{
list.Add(new DestinationType(item.A, item.B, item.C));
return list;
});
``` | How to add to a list using Linq's aggregate function C# | [
"",
"c#",
"linq",
"aggregate",
""
] |
Is there a modulo function in the Python `math` library?
Isn't `15 % 4`, 3? But `15 mod 4` is 1, right? | There's the `%` sign. It's not just for the remainder, it is the modulo operation. | you can also try [`divmod(x, y)`](https://docs.python.org/3/library/functions.html#divmod) which returns a tuple `(x // y, x % y)` | How to calculate a mod b in Python? | [
"",
"python",
""
] |
I need to send e-mails from a servlet running within Tomcat. I'll always send to the same recipient with the same subject, but with different contents.
What's a simple, easy way to send an e-mail in Java?
### Related:
> [How do you send email from a Java app using GMail?](https://stackoverflow.com/questions/46663/how-do-you-send-email-from-a-java-app-using-gmail) | Here's my code for doing that:
```
import javax.mail.*;
import javax.mail.internet.*;
// Set up the SMTP server.
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", "smtp.myisp.com");
Session session = Session.getDefaultInstance(props, null);
// Construct the message
String to = "you@you.com";
String from = "me@me.com";
String subject = "Hello";
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText("Hi,\n\nHow are you?");
// Send the message.
Transport.send(msg);
} catch (MessagingException e) {
// Error.
}
```
You can get the JavaMail libraries from Sun here: <http://java.sun.com/products/javamail/> | JavaMail can be a bit of a pain to use. If you want a simpler, cleaner, solution then have a look at the Spring wrapper for JavaMail. The reference docs are here:
<http://static.springframework.org/spring/docs/2.5.x/reference/mail.html>
However, this does mean you need Spring in your application, if that isn't an option then you could look at another opensource wrapper such as simple-java-mail:
[simplejavamail.org](http://www.simplejavamail.org)
Alternatively, you can use JavaMail directly, but the two solutions above are easier and cleaner ways to send email in Java. | How do I send an e-mail in Java? | [
"",
"java",
"email",
"tomcat",
"servlets",
""
] |
I have some div on page loaded from server by ajax, but in the scenario google and other search engine don't index the content of this div. The only solution I see, it's recognize when page get by search robot and return complete page without ajax.
1) Is there more simple way?
2) How distinguish humans and robots? | Google gets antsy if you are trying to show different things to you users than to crawlers. I suggest simply caching your query or whatever it is that needs AJAX and then using AJAX to replace only what you need to change. You still haven't really explained what's in this div that only AJAX can provide. If you can do it without AJAX then you should be, not just for SEO but for braille readers, mobile devices and people without javascript. | You could also provide a link to the non-ajax version in your sitemap, and when you serve that file (to the robot), you make sure to have included a canonical link-element to the "real" page you want users to see:
```
<html>
<head>
[...]
<link rel="canonical" href="YOUR_CANONICAL_URL_HERE" />
[...]
</head>
<body>
[...]
YOUR NON_AJAX_CONTENT_HERE
</body>
</html>
```
edit: if this solution is not appropriate (some comments below points out that that this solution is non-standard and only supported by the "big-three"), you might have to re-think whether you should make the non-ajax version the standard solution, and use JavaScript to hide/show the information instead of fetching it via AJAX. If it is business critical information that is fetched, you have to realize that not all users have JavaScript enabled, and thus they won't be able to see this information. A progressive enhancement approach might be more appropriate in this case. | Ajax page part load and Google | [
"",
"javascript",
"ajax",
"search-engine",
""
] |
Is it possible to do the following in a DataGridView:
In the same column I want to change the control type of each row between DataGridViewTextBoxColumn and DataGridViewComboBoxColumn?
(this is because sometimes I want to display a drop down list and other times I just want the user to enter a freehand value).
Thanks,
P.S. I am using C# | You could create your own class inherited from DataGridViewCell, and override the adequate virtual members (InitializeEditingControls, EditType, maybe a few others). You can then create a DataGridViewColumn with an instance of this class as the cell template | I've recently had a similar usecase, and ended up writing something like the below code:
Write a custom Cell and Column class, and override the EditType and InitializeEditingControl methods on the cell, to return different controls as appropriate (here I'm just databinding to a list of a custom class with .useCombo field indicating what control to use):
```
// Define a column that will create an appropriate type of edit control as needed.
public class OptionalDropdownColumn : DataGridViewColumn
{
public OptionalDropdownColumn()
: base(new PropertyCell())
{
}
public override DataGridViewCell CellTemplate
{
get
{
return base.CellTemplate;
}
set
{
// Ensure that the cell used for the template is a PropertyCell.
if (value != null &&
!value.GetType().IsAssignableFrom(typeof(PropertyCell)))
{
throw new InvalidCastException("Must be a PropertyCell");
}
base.CellTemplate = value;
}
}
}
// And the corresponding Cell type
public class OptionalDropdownCell : DataGridViewTextBoxCell
{
public OptionalDropdownCell()
: base()
{
}
public override void InitializeEditingControl(int rowIndex, object
initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
{
// Set the value of the editing control to the current cell value.
base.InitializeEditingControl(rowIndex, initialFormattedValue,
dataGridViewCellStyle);
DataItem dataItem = (DataItem) this.OwningRow.DataBoundItem;
if (dataItem.useCombo)
{
DataGridViewComboBoxEditingControl ctl = (DataGridViewComboBoxEditingControl)DataGridView.EditingControl;
ctl.DataSource = dataItem.allowedItems;
ctl.DropDownStyle = ComboBoxStyle.DropDownList;
}
else
{
DataGridViewTextBoxEditingControl ctl = (DataGridViewTextBoxEditingControl)DataGridView.EditingControl;
ctl.Text = this.Value.ToString();
}
}
public override Type EditType
{
get
{
DataItem dataItem = (DataItem)this.OwningRow.DataBoundItem;
if (dataItem.useCombo)
{
return typeof(DataGridViewComboBoxEditingControl);
}
else
{
return typeof(DataGridViewTextBoxEditingControl);
}
}
}
}
```
Then just add a column to your DataGridView of this type, and the correct edit control should be used. | Windows Forms DataGridView control have different control types in the same column | [
"",
"c#",
"winforms",
"datagridview",
""
] |
How do I pass this instance as a parameter into a function?
```
class
{
public:
void foo();
} bar;
```
Do I have to name the class?
It is copyable since I haven't made the class's copy ctor private.
So how is it possible if at all? | Maybe it would be better if you explicit what you want to do. Why do you want to create an unnamed class? Does it conform to an interface? Unnamed classes are quite limited, they cannot be used as parameters to functions, they cannot be used as template type-parameters...
Now if you are implmenting an interface then you can pass references to that interface:
```
class interface {
public:
virtual void f() const = 0;
};
void function( interface const& o )
{
o.f();
}
int main()
{
class : public interface {
public:
virtual void f() const {
std::cout << "bar" << std::endl;
}
} bar;
function( bar ); // will printout "bar"
}
```
NOTE: For all those answers that consider template arguments as an option, unnamed classes cannot be passed as template type arguments.
C++ Standard. 14.3.1, paragraph 2:
> 2 A local type, a type with no
> linkage, an unnamed type or a type
> compounded from any of these types
> shall not be used as a
> template-argument for a template
> type-parameter.
If you test with [comeau](http://www.comeaucomputing.com/tryitout/) compiler (the link is for the online tryout) you will get the following error:
> error: a template argument may not
> reference an unnamed type
As a side note, comeau compiler is the most standard compliant compiler I know of, besides being the one with the most helpful error diagnostics I have tried.
NOTE: Comeau and gcc (g++ 4.0) give an error with the code above. Intel compiler (and from other peoples comments MSVS 2008) accept using unnamed classes as template parameters, against the standard. | Why should you create an anonymous class when you want to pass it to a function?
Just explicitly declare the class:
```
class Foo {
// ...
};
void Method(Foo instance);
int main() {
Foo bar;
Method(bar);
}
```
The 2nd possibility would be using a template-function, so the compiler would infer the type (Note that this is not standard-compatible!)
```
#include <iostream>
using namespace std;
template <typename T>
void SayFoo(T& arg) {
arg.Foo();
}
int main() {
class {
public:
void Foo() { cout << "Hi" << endl; }
} Bar;
Bar.Foo();
SayFoo(Bar);
return 0;
}
```
There is no problem with copying the class since the compiler generated the copy constructor automatically and you can use tools like [boost::typeof](http://www.boost.org/doc/libs/1_35_0/doc/html/typeof.html) in order to avoid referring to the type explicitly.
```
BOOST::AUTO(copy, Bar);
```
Another approch is using (relatively slow) runtime-polymorphism (interfaces/inheritance). | Passing unnamed classes through functions | [
"",
"c++",
"oop",
"class",
""
] |
Currently I'm programming a database class which makes a little bit use of PHP's PDO class, but I'd like to add some simple features for making programming a certain application a bit easier.
Now In the following piece of pseudo code you can see where I'm going. The only problem in this example is that the $result variable is an object, which cannot be used for comparisation of some stuff I'm doing further on in the script:
```
<?php
class Database
{
public function FetchRow ( $query )
{
// .. do some stuff, and make a $result variable
return DatabaseStatement ( $result );
}
}
class DatabaseStatement
{
private $result;
public function __construct ( $query )
{
// .. save result in property etc.
}
public function __get ( $column )
{
// .. check result item
return $this -> result [ $column ];
}
}
$db = new Database;
$result = $db -> Query ( 'SELECT * FROM users WHERE id = 1;' );
if ( $result != null ) // Here $result should be an array OR null in case no rows are returned
{
echo $result -> username; // Here $result should call the __get method
echo '<pre>' , print_r ( $result ) , '</pre>'; // Here $result should be the array, cause it wasn't null just yet
}
```
As you can see the $result variable should not be an object when I'm doing a comparisation, I know it can be made to a string using \_\_toString. But I'd like it to be some other type, mostly an array or null.
How do I get something like that working if it's possible (should be possible I think with too much hassle)?
So can somebody point me in the right direction, or possibly give a piece of code that should work or I can change to fit in my current class? | I think you'll have to do this in the same place you create the DatabaseStatement. So for instance:
```
public function FetchRow($query)
{
// ... do some stuff, and make a $result variable.
$ds = DatabaseStatement($result);
if ($ds) {
return $ds;
}
else {
return null;
}
}
``` | It seems to me that you just need to add some methods that do what you want. Instead of forcing the $result object to be an array or null to check whether it's empty, why don't you just create and call a method `isEmpty ()` that tells you what you want to know?
And if you need an array, create a method `toArray ()` that returns what you want. OR, even better, make your object implement Iterator and/or ArrayAccess from the [Standard PHP Library](http://www.php.net/~helly/php/ext/spl/). | PHP Object return value | [
"",
"php",
"class",
"object",
"return",
""
] |
Excuse the long question!
We have two database tables, e.g. Car and Wheel. They are related in that a wheel belongs to a car and a car has multiple wheels. The wheels, however, can be changed without affecting the "version" of the car. The car's record can be updated (e.g. paint job) without affecting the version of the wheels (i.e. no cascade updating).
For example, Car table currently looks like this:
```
CarId, CarVer, VersionTime, Colour
1 1 9:00 Red
1 2 9:30 Blue
1 3 9:45 Yellow
1 4 10:00 Black
```
The Wheels table looks like this (this car only has two wheels!)
```
WheelId, WheelVer, VersionTime, CarId
1 1 9:00 1
1 2 9:40 1
1 3 10:05 1
2 1 9:00 1
```
So, there's been 4 versions of this two wheeled car. It's first wheel (WheelId 1) hasn't changed. The second wheel was changed (e.g. painted) at 10:05.
How do I efficiently do as of queries that can be joined to other tables as required? Note that this is a new database and we own the schema and can change it or add audit tables to make this query easier. We've tried one audit table approach (with columns: CarId, CarVersion, WheelId, WheelVersion, CarVerTime, WheelVerTime), but it didn't really improve our query.
Example query: Show the Car ID 1 as it was, including its wheel records as of 9:50. This query should result in these two rows being returned:
```
WheelId, WheelVer, WheelVerTime, CarId, CarVer, CarVerTime, CarColour
1 2 9:40 1 3 9:45 Yellow
2 1 9:00 1 3 9:45 Yellow
```
The best query we could come up with was this:
```
select c.CarId, c.VersionTime, w.WheelId,w.WheelVer,w.VersionTime,w.CarId
from Cars c,
( select w.WheelId,w.WheelVer,w.VersionTime,w.CarId
from Wheels w
where w.VersionTime <= "12 Jun 2009 09:50"
group by w.WheelId,w.CarId
having w.WheelVer = max(w.WheelVer)
) w
where c.CarId = w.CarId
and c.CarId = 1
and c.VersionTime <= "12 Jun 2009 09:50"
group by c.CarId, w.WheelId,w.WheelVer,w.VersionTime,w.CarId
having c.CarVer = max(c.CarVer)
```
And, if you wanted to try this then the create table and insert record SQL is here:
```
create table Wheels
(
WheelId int not null,
WheelVer int not null,
VersionTime datetime not null,
CarId int not null,
PRIMARY KEY (WheelId,WheelVer)
)
go
insert into Wheels values (1,1,'12 Jun 2009 09:00', 1)
go
insert into Wheels values (1,2,'12 Jun 2009 09:40', 1)
go
insert into Wheels values (1,3,'12 Jun 2009 10:05', 1)
go
insert into Wheels values (2,1,'12 Jun 2009 09:00', 1)
go
create table Cars
(
CarId int not null,
CarVer int not null,
VersionTime datetime not null,
colour varchar(50) not null,
PRIMARY KEY (CarId,CarVer)
)
go
insert into Cars values (1,1,'12 Jun 2009 09:00', 'Red')
go
insert into Cars values (1,2,'12 Jun 2009 09:30', 'Blue')
go
insert into Cars values (1,3,'12 Jun 2009 09:45', 'Yellow')
go
insert into Cars values (1,4,'12 Jun 2009 10:00', 'Black')
go
``` | This kind of table is known as a valid-time state table in the literature. It is universally accepted that each row should model a period by having a start date and an end date. Basically, the unit of work in SQL is the row and a row should completely define the entity; by having just one date per row, not only do your queries become more complex, your design is compromised by splitting sub atomic parts on to different rows.
As mentioned by Erwin Smout, one of the definitive books on the subject is:
Richard T. Snodgrass (1999). [Developing Time-Oriented Database Applications in SQL](http://www.cs.arizona.edu/people/rts/tdbbook.pdf)
It's out of print but happily is available as a free download PDF (link above).
I have actually read it and have implemented many of the concepts. Much of the text is in ISO/ANSI Standard SQL-92 and although some have been implemented in proprietary SQL syntaxes, including SQL Server (also available as downloads) I found the conceptual information much more useful.
Joe Celko also has a book, 'Thinking in Sets: Auxiliary, Temporal, and Virtual Tables in SQL', largely derived from Snodgrass's work, though I have to say where the two diverge I find Snodgrass's approaches preferable.
I concur this stuff is hard to implement in the SQL products we currently have. We think long and hard before making data temporal; if we can get away with merely 'historical' then we will. Much of the temporal functionality in SQL-92 is missing from SQL Server e.g. INTERVAL, OVERLAPS, etc. Some things as fundamental as sequenced 'primary keys' to ensure periods do not overlap cannot be implemented using CHECK constraints in SQL Server, necessitating triggers and/or UDFs.
Snodgrass's book is based on his work for SQL3, a proposed extension to Standard SQL to provide much better support for temporal databases, though sadly this seems to have been effectively shelved years ago :( | As-of queries are easier when each row has a start and an end time. Storing the end time in the table would be most efficient, but if this is hard, you can query it like:
```
select
ThisCar.CarId
, StartTime = ThisCar.VersionTime
, EndTime = NextCar.VersionTime
from Cars ThisCar
left join Cars NextCar
on NextCar.CarId = ThisCar.CarId
and ThisCar.VersionTime < NextCar.VersionTime
left join Cars BetweenCar
on BetweenCar.CarId = BetweenCar.CarId
and ThisCar.VersionTime < BetweenCar.VersionTime
and BetweenCar.VersionTime < NextCar.VersionTime
where BetweenCar.CarId is null
```
You can store this in a view. Say the view is called vwCars, you can select a car for a particular date like:
```
select *
from vwCars
where StartTime <= '2009-06-12 09:15'
and ('2009-06-12 09:15' < EndTime or EndTime is null)
```
You could store this in a table valued stored procedure, but that might have a steep performance penalty. | How to effectively do database as-of queries? | [
"",
"sql",
"database",
"database-design",
""
] |
I've got two tables, one for openings and the other for bookings. An entry in the bookings table always refers to an opening and there may be multiple bookings for each opening. I would like to extract all the openings that have bookings different from `bookingType 'C'`.
> E.g.
>
> 1. if an opening has 3 bookings of type A, B and C, it should NOT show up
> in the result
> 2. if an opening has only bookings of type A and B, it should show up in the
> result
The following is what I've tried but it is not correct as it fails for the example 1:
```
select op.id, bo.id
from opening op
left join booking bo on bo.openingId = op.id
where bo.bookingType != 'C';
```
Here is the complete query referring to time intervals:
```
select op.id, bo.id
from opening op
left join booking bo on bo.openingId = op.id
where ((bo.arrivalDate < '2009/06/20' AND bo.departureDate <= '2009/06/20') OR
(bo.arrivalDate >= '2009/06/27' AND bo.departureDate > '2009/06/27'))
```
What I used to call `bookingType` was actually a time interval defined through the two columns `arrivalDate` and `departureDate`: in the example above I need all the openings that DO NOT have a booking between the `20th June 2009` and the `27th June 2009`. | ```
SELECT op.id
FROM opening op
WHERE op.id NOT IN
(SELECT b.openingid
FROM booking b
WHERE b.bookingtype='C')
```
with the date change:
```
SELECT op.id
FROM opening op
WHERE op.id NOT IN
(SELECT b.openingid
FROM booking b
WHERE (b.arrivalDate BETWEEN '2009/06/20' AND '2009/06/27')
OR
(b.departureDate BETWEEN '2009/06/20' and '2009/06/27')
)
``` | Here's an easy version without joins, you don't even need the Openings table:
```
select openingId, id
from booking
where openingId not in (
select openingId
from booking
where bookingType = 'C'
)
``` | SQL Query - Where am I going wrong? | [
"",
"sql",
""
] |
not sure it is possible but I am looking for a solution that will queue email messages.
Is there any way to write some sort of web app that will run and send certain amounts of emails to email server for delivery even after I submit my message and close webpage. May be some sort of daemon? | A **local email server** will do exactly that. Once you setup a local email relay server (make sure it will only accept email from the localhost), then just sent email to it and let it handle actually delivering the email.
It will be tons more reliable and configurable than anything you could write. Depending on the platform, you should be able to tune rates of delivery and any other parameters you'd like.
Windows: [IIS SMTP Server](http://www.cmsconnect.com/praetor/webhelpg2/Chapter_2_-_Pre-installation_considerations/Configuring_the_SMTP_Server.htm)
Linux: [Postfix](http://www.postfix.org/) | You can always build a **Windows service** that connects to a webservice in your web-app which provides the e-mails that are in the queue. That way you can close your browser and the windows-service just grabs an amount of emails for delivery every run.
After delivery you can use a different webservice call to tell the web-app that certain e-mails have been delivered or delayed, so the webapp can control a proper queue.
The reason that **i would not recommend using a local mailserver** is that it is nearly impossible to get status feedback from sent/bounced/delayed e-mails. If mails bounce or get delayed the local mailserver will reply that to the e-mail address of the sender, and not to your web-app. You would have to build a POP-client to check for bounces, which makes the overall solution more complex than it should have to be. Building a custom polling/sending mechanism does provide status updates on all your e-mails, which imho is especially important if the e-mails are a critical feature of your app. | email queueing with c# | [
"",
"c#",
""
] |
We would like to make our C++ brace style more consistent. Right now, our code contains a mix of:
```
if (cond)
{
// ...
}
else
{
// ...
}
```
...and:
```
if (cond) {
// ...
} else {
// ...
}
```
We want to use the latter style exclusively.
However, we **don't** want to change the indentation of our code. I've tried using astyle, bcpp, GNU indent and Uncrustify (and I've looked at the command-line options for GreatCode). Unfortunately, each of these tools insists on reindenting our code, and most of them mangle C++ constructor initializer lists and preprocessor macros pretty badly.
Are there any C++ code beautifiers which can fix braces while leaving indentation alone? It doesn't have to be a pre-existing tool--if you know how to do this using some crazy Perl one-liner, that's also good. Thank you!
**Update:** Yes, we aware that this will make it hard to read diffs against older code. This is a long-postponed code cleanup, and we've decided that the day-to-day advantages of consistent formatting outweigh any version-control difficulties. | Here's a Perl one-liner that should do what you want.
```
perl -pi.bak -e 'BEGIN { undef $/; } s/\s*?(\s?\/\/.*)?\r?\n\s*{/ {\1/g; s/}(\s?\/\/.*)?\r?\n\s*else\b(.*)/} else\2\1/g;'
```
It turns this:
```
int main(int argc, char *argv[])
{
int something = 0;
if (something) // 5-12-2007
{
printf("Hi!\n");
}
else // 5-13-2007
{
printf("Bye\n");
}
return 0;
}
```
into this:
```
int main(int argc, char *argv[]) {
int something = 0;
if (something) { // 5-12-2007
printf("Hi!\n");
} else { // 5-13-2007
printf("Bye\n");
}
return 0;
}
``` | You really should think twice, and probably thrice, before doing this. It will completely destroy your source code control system's revision history at the point of change. You are using a source code control system, aren't you? | Reformat C++ braces without changing indentation? | [
"",
"c++",
"formatting",
"coding-style",
"indentation",
"curly-braces",
""
] |
This is a Windows application using C#. I want to capture a screen shot with a timer. The timer is set to a 5000 ms interval. As the timer is started, the desktop screen should be captured with the source window caption.
```
try
{
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Tick += new EventHandler(timer2_Tick);
timer.Interval = (100) * (50);
timer.Enabled = true;
timer.Start();
ScreenShots sc = new ScreenShots();
sc.pictureBox1.Image = system_serveillance.CaptureScreen.GetDesktopImage();
while(sc.pictureBox1.Image != null)
{
sc.pictureBox1.Image.Save("s"+".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
sc.pictureBox1.Image = null;
}
```
This code is not working properly. How can I make it work? | The timer isn't firing because you're not handling the tick event. Pete has also pointed out your file will be overwritten on each tick.
It needs to look something more like the following. This isn't the exact code but it should give you an idea.
```
private Int32 pictureCount = 0;
public Form1()
{
timer1.Tick += new EventHandler(this.timer1_Tick);
timer1.Interval = (100) * (50);
timer1.Enabled = true;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
/* Screen capture logic here */
sc.pictureBox1.Image.Save(pictureCount.ToString() + ".jpg", ImageFormat.Jpeg);
pictureCount++;
}
``` | You've started your timer, but your screen save routine doesn't appear to be in your timer tick code (unless you've omitted the code from the post. Similarly, you will be overwriting s.jpg everytime, and I assume this isn't what you want. The use of a while clause is also odd here because you only need to perform an if test. | How to capture screen with timer using C#? | [
"",
"c#",
"winforms",
""
] |
I have a code, and I do not understand it. I am developing an application which precision is very important. but it does not important for .NET, why? I don't know.
```
double value = 3.5;
MessageBox.Show((value + 1 * Math.Pow(10, -20)).ToString());
```
but the message box shows: 3.5
Please help me, Thank you. | You can have precision, but it depends on what else you want to do. If you put the following in a Console application:
```
double a = 1e-20;
Console.WriteLine(" a = {0}", a);
Console.WriteLine("1+a = {0}", 1+a);
decimal b = 1e-20M;
Console.WriteLine(" b = {0}", b);
Console.WriteLine("1+b = {0}", 1+b);
```
You will get
```
a = 1E-20
1+a = 1
b = 0,00000000000000000001
1+b = 1,00000000000000000001
```
But Note that The `Pow` function, like almost everything in the Math class, only takes doubles:
```
double Pow(double x, double y);
```
So you cannot take the Sine of a decimal (other then by converting it to double)
Also see [this question](https://stackoverflow.com/questions/803225/when-should-i-use-double-instead-of-decimal). | If you're doing anything where precision is very important, you need to be aware of the limitations of floating point. A good reference is [David Goldberg's "What Every Computer Scientist Should Know About Floating-Point Arithmetic"](http://docs.sun.com/source/806-3568/ncg_goldberg.html).
You may find that floating-point doesn't give you enough precision and you need to work with a decimal type. These, however, are always much slower than floating point -- it's a tradeoff between accuracy and speed. | Double Precision | [
"",
"c#",
"double",
"precision",
""
] |
I'm updating some old code to grab some binary data from a URL instead of from a database (the data is about to be moved out of the database and will be accessible by HTTP instead). The database API seemed to provide the data as a raw byte array directly, and the code in question wrote this array to a file using a BufferedOutputStream.
I'm not at all familiar with Java, but a bit of googling led me to this code:
```
URL u = new URL("my-url-string");
URLConnection uc = u.openConnection();
uc.connect();
InputStream in = uc.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
final int BUF_SIZE = 1 << 8;
byte[] buffer = new byte[BUF_SIZE];
int bytesRead = -1;
while((bytesRead = in.read(buffer)) > -1) {
out.write(buffer, 0, bytesRead);
}
in.close();
fileBytes = out.toByteArray();
```
That seems to work most of the time, but I have a problem when the data being copied is large - I'm getting an OutOfMemoryError for data items that worked fine with the old code.
I'm guessing that's because this version of the code has multiple copies of the data in memory at the same time, whereas the original code didn't.
Is there a simple way to grab binary data from a URL and save it in a file without incurring the cost of multiple copies in memory? | Instead of writing the data to a byte array and then dumping it to a file, you can directly write it to a file by replacing the following:
```
ByteArrayOutputStream out = new ByteArrayOutputStream();
```
With:
```
FileOutputStream out = new FileOutputStream("filename");
```
If you do so, there is no need for the call `out.toByteArray()` at the end. Just make sure you close the `FileOutputStream` object when done, like this:
```
out.close();
```
See the documentation of [FileOutputStream](http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileOutputStream.html) for more details. | If you need the Content-Length and your web-server is somewhat standard conforming, then it should provide you a "Content-Length" header.
URLConnection#getContentLength() should give you that information upfront so that you are able to create your file. (Be aware that if your HTTP server is misconfigured or under control of an evil entity, that header may not match the number of bytes received. In that case, why dont you stream to a temp-file first and copy that file later?)
In addition to that: A ByteArrayInputStream is a horrible memory allocator. It always doubles the buffer size, so if you read a 32MB + 1 byte file, then you end up with a 64MB buffer. It might be better to implement a own, smarter byte-array-stream, like this one:
<http://source.pentaho.org/pentaho-reporting/engines/classic/trunk/core/source/org/pentaho/reporting/engine/classic/core/util/MemoryByteArrayOutputStream.java> | Copy binary data from URL to file in Java without intermediate copy | [
"",
"java",
"file",
"url",
"copy",
""
] |
Let's say you don't want other sites to "frame" your site in an `<iframe>`:
```
<iframe src="http://example.org"></iframe>
```
So you insert anti-framing, frame busting JavaScript into all your pages:
```
/* break us out of any containing iframes */
if (top != self) { top.location.replace(self.location.href); }
```
Excellent! Now you "bust" or break out of any containing iframe automatically. Except for one small problem.
As it turns out, **your frame-busting code can be busted**, [as shown here](http://coderrr.wordpress.com/2009/02/13/preventing-frame-busting-and-click-jacking-ui-redressing/):
```
<script type="text/javascript">
var prevent_bust = 0
window.onbeforeunload = function() { prevent_bust++ }
setInterval(function() {
if (prevent_bust > 0) {
prevent_bust -= 2
window.top.location = 'http://example.org/page-which-responds-with-204'
}
}, 1)
</script>
```
This code does the following:
* increments a counter every time the browser attempts to navigate away from the current page, via the `window.onbeforeunload` event handler
* sets up a timer that fires every millisecond via `setInterval()`, and if it sees the counter incremented, changes the current location to a server of the attacker's control
* that server serves up a page with HTTP status code **204**, which does not cause the browser to navigate anywhere
My question is -- and this is more of a JavaScript puzzle than an actual *problem* -- how can you defeat the frame-busting buster?
I had a few thoughts, but nothing worked in my testing:
* attempting to clear the `onbeforeunload` event via `onbeforeunload = null` had no effect
* adding an `alert()` stopped the process let the user know it was happening, but did not interfere with the code in any way; clicking OK lets the busting continue as normal
* I can't think of any way to clear the `setInterval()` timer
I'm not much of a JavaScript programmer, so here's my challenge to you: **hey buster, can you bust the frame-busting buster?** | I'm not sure if this is viable or not - but if you can't break the frame, why not just display a warning. For example, If your page isn't the "top page" create a setInterval method that tries to break the frame. If after 3 or 4 tries your page still isn't the top page - create a div element that covers the whole page (modal box) with a message and a link like...
> You are viewing this page in a unauthorized frame window - (Blah blah... potential security issue)
>
> **click this link to fix this problem**
Not the best, but I don't see any way they could script their way out of that. | FWIW, most current browsers [support](http://en.wikipedia.org/wiki/Clickjacking#X-Frame-Options) the [X-Frame-Options: deny](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options) directive, which works even when script is disabled.
IE8:
<http://blogs.msdn.com/ie/archive/2009/01/27/ie8-security-part-vii-clickjacking-defenses.aspx>
Firefox (3.6.9)
<https://bugzilla.mozilla.org/show_bug.cgi?id=475530>
<https://developer.mozilla.org/en/The_X-FRAME-OPTIONS_response_header>
Chrome/Webkit
<http://blog.chromium.org/2010/01/security-in-depth-new-security-features.html>
<http://trac.webkit.org/changeset/42333> | Frame Buster Buster ... buster code needed | [
"",
"javascript",
"html",
"iframe",
"framebusting",
""
] |
I am currently trying out [Json.NET](http://json.codeplex.com/), and it seems to work well.
Any other good JSON libraries for .NET? | [Jayrock](http://jayrock.berlios.de/) works well and transparently turns your objects to and from JSON objects providing they have a public constructor. It also creates the script for you so you can just call your web service like a Javascript class.
### Example:
```
public class Person
{
public string Name { get;set;}
public int Age { get;set; }
public Person() { }
}
public class MyService : JsonRpcHandler
{
[JsonRpcMethod("getBob")]
public Person GetBob()
{
return new Person() { Name="Bob",Age=20};
}
}
```
And the Javascript:
```
var service = new MyService();
var result = service.getBob();
alert(result.name); // JSON objects are camel-cased.
``` | There is the [JavascriptSerialiser](http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx) which is used by asp.net mvc and asp.net ajax. Also there is the [DataContractJsonSerialiser](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx) used by WCF. The only problem I have encountered with the JavascriptSerialiser is that it uses funny way to serialise dates, which I do not think will parse into a javascript date. But this is easyly solved by this snippet
```
public double MilliTimeStamp()
{
DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = DateTime.UtcNow;
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
return ts.TotalMilliseconds;
}
``` | Good .NET libraries for working with JSON data? | [
"",
"javascript",
".net",
"json",
""
] |
When a user hover overs one of the items such as Research, Brand Strategy, Audience Engagement the background colour in the bottom section changes via a inline style.
<http://www.odopod.com/work/tags/strategy/>
I was wondering, how it is done or which Jquery plugin they were using?
Many thanks! | This isn't a plugin, this is done through good old plain jQuery:
```
<div class='something'>my text goes here blah blah blah</div>
<div class='somethingelse'>my background color goes here</div>
```
Then with jQuery:
```
$(function() {
$('div.something').hover(function() {
$(this).next('div.somethingelse').css('background-color','red');
}, function() {
$(this).next('div.somethingelse').css('background-color','blue');
});
});
```
Depending on what you want you could set up the HTML in many different ways. You would then use whatever [DOM traversing](http://docs.jquery.com/Traversing) function is appropriate to find the associated DIV and manipulate it's CSS accordingly. | To animate a background color using jQuery, use the [color plugin](http://plugins.jquery.com/project/color). | What Jquery plugin is this? | [
"",
"javascript",
"jquery",
""
] |
I know that pointers store the address of the value that they point to, but if you display the value of a pointer directly to the screen, you get a hexadecimal number. If the number is exactly what the pointer stores, then when saying
```
pA = pB; //both are pointers
```
you're copying the address. Then wouldn't there be a bigger overhead to using pointers when working with very small items like `int`s and `bool`s? | A pointer is essentially just a number. It stores the address in RAM where the data is. The pointer itself is pretty small (probably the same size as an `int` on 32 bit architectures, `long` on 64 bit).
You are correct though that an `int *` would not save any space when working with `int`s. But that is not the point (no pun intended). Pointers are there so you can have *references* to things, not just use the *things* themselves. | Memory addresses.
That is the locations in memory where other stuff *is*.
Pointers are generally the word size of the processor, so they can generally be moved around in a single instruction cycle. In short, they are fast. | What exactly do pointers store? (C++) | [
"",
"c++",
"pointers",
"overhead",
""
] |
I have a situation where, in javascript, I need to compare the contents of one string to see if it contains the exact same number in another string that could contain multiple numbers.
For example.
Source: "1234"
Comparison: "1000 12345 112345 1234 2000"
It should only match on the 1234 and not on the 12345 or 112345, etc.
It also needs to match if the source occurs at the beginning or end of the line.
How would I go about doing that? | Use regex:
```
"1000 12345 112345 1234 2000".match("\\b1234\\b")
``` | What about using the word boundary to match the number:
```
var p = /\b1234\b/;
var match = p.exec("1000 12345 112345 1234 2000")
``` | How do I match a specific number in javascript? | [
"",
"javascript",
"validation",
""
] |
**The Problem:** I am trying to extract a valid game mode for Defense of the Ancients (DotA) from a game name using C++.
**Details:**
* Game names can be, at most, 31 characters long
* There are three game mode categories: primary, secondary, and miscellaneous
+ There can only be 1 primary game mode selected
+ Certain primary game modes are incompatible with some secondary game modes
+ Certain secondary game modes are incompatible with other secondary game modes
+ Miscellaneous game modes can be combined with all other game modes
Here are a list of the various game modes, with a chart showing which secondary modes each mode is compatible with (X means incompatible):
```
// Only 1 primary allowed
static char *Primary[] = {
// Compatible with > | dm | rv | mm | du | sh | aa | ai | as | id | em | np | sc | om | nt | nm | nb | ro | mo | sp |
"ap", // All Pick | | | | | | | | | | | | | | | | | | | |
"ar", // All Random | | X | | | | | | | | | | | | | | | | | |
"tr", // Team Random | X | X | | | | | | | | | | | | | | | | | |
"mr", // Mode Random | X | X | | | X | X | X | X | | | | | | | | | X | X | |
"lm", // League Mode | X | X | X | X | X | X | X | X | X | X | X | X | X | X | X | X | X | X | |
"rd", // Random Draft | X | X | X | | X | X | X | X | | | | | | | | | X | X | |
"vr", // Vote Random | X | X | X | | X | X | X | X | | | | | | | | | X | X | |
"el", // Extended League | X | X | X | X | X | X | X | X | X | X | X | X | X | X | X | X | X | X | |
"sd", // Single Draft | X | X | X | | X | X | X | X | | | | | | | | | X | X | |
"cm", // Captains Mode | X | X | X | X | X | X | X | X | X | X | X | X | X | X | X | X | X | X | X |
"cd" // Captains Draft | X | X | X | | X | X | X | X | | | | | | | | | X | X | |
};
static char *Secondary[] = {
// Compatible with > | dm | rv | mm | du | sh | aa | ai | as | id | em | np | sc | om | nt | nm | nb | ro | mo | sp |
"dm", // Death Match | | X | X | | X | X | X | X | | | | | | | | | X | X | |
"rv", // Reverse Mode | X | | | | X | | | | | | | | | | | | | | |
"mm", // Mirror Match | X | | | | X | | | | | | | | | | | | | | |
"du", // Duplicate Mode | | | | | | | | | | | | | | | | | | | |
"sh", // Same Hero | X | X | X | | | | | | | | | | | | | | | | |
"aa", // All Agility | X | | | | | | X | X | | | | | | | | | | | |
"ai", // All Intelligence | X | | | | | X | | X | | | | | | | | | | | |
"as", // All Strength | X | | | | | X | X | | | | | | | | | | | | |
"id", // Item Drop | | | | | | | | | | | | | | | | | | | |
"em", // Easy Mode | | | | | | | | | | | | | | | | | | | |
"np", // No Powerups | | | | | | | | | | | | | | | | | | | |
"sc", // Super Creeps | | | | | | | | | | | | | | | | | | | |
"om", // Only Mid | | | | | | | | | | | | | | | | | | | |
"nt", // No Top | | | | | | | | | | | | | | | | | | | |
"nm", // No Middle | | | | | | | | | | | | | | | | | | | |
"nb", // No Bottom | | | | | | | | | | | | | | | | | | | |
"ro", // Range Only | X | | | | | | | | | | | | | | | | | X | |
"mo", // Melee Only | X | | | | | | | | | | | | | | | | X | | |
"sp" // Shuffle Players | | | | | | | | | | | | | | | | | | | |
};
// These options are always available
static char *Misc[] = {
"ns", // No Swap
"nr", // No Repick
"ts", // Terrain Snow
"pm", // Pooling Mode
"oi", // Observer Info
"mi", // Mini Heroes
"fr", // Fast Respawn
"so" // Switch On
};
```
**Examples:** Here are some example input, with the desired output:
"DotA v6.60 -RDSOSP USA/CA LC!" -> "rdsosp"
"DOTA AREMDM USA LC" -> "aremdm"
"DotA v6.60 -ApEmDuSpId USA BL" -> "apemduspid"
**Notes:** The solution doesn't necessarily have to provide actual code, pseudo-code and even just an explanation of how you would handle it is acceptable and preferred. Also, the solution needs to be flexible enough to where I can add another game mode fairly easily. It is also safe to assume that within the game name, the game mode will always start with a primary game mode.
---
**Result:**
```
#include <cstdarg>
#include <algorithm>
#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include <vector>
std::map<std::string, std::vector<std::string> > ModeCompatibilityMap;
static const unsigned int PrimaryModesCount = 11;
static char *PrimaryModes[] = {
"ap", "ar", "tr", "mr", "lm", "rd", "vr", "el", "sd", "cm", "cd"
};
static const unsigned int SecondaryModesCounts = 19;
static char *SecondaryModes[] = {
"dm", "rv", "mm", "du", "sh", "aa", "ai", "as", "id", "em", "np",
"sc", "om", "nt", "nm", "nb", "ro", "mo", "sp"
};
static const unsigned int MiscModesCount = 8;
static char *MiscModes[] = {
"ns", "nr", "ts", "pm", "oi", "mi", "fr", "so"
};
std::vector<std::string> Vectorize( int count, ... ) {
std::vector<std::string> result;
va_list vl;
va_start( vl, count );
for ( int i = 0; i < count; ++i ) {
char *buffer = va_arg( vl, char * );
result.push_back( buffer );
}
va_end( vl );
return result;
}
void InitializeModeCompatibilityMap() {
// Primary
ModeCompatibilityMap["ar"] = Vectorize( 1, "rv" );
ModeCompatibilityMap["tr"] = Vectorize( 2, "dm", "rv" );
ModeCompatibilityMap["mr"] = Vectorize( 8, "dm", "rv", "sh", "aa", "ai", "as", "ro", "mo" );
ModeCompatibilityMap["lm"] = Vectorize( 18, "dm", "rv", "mm", "du", "sh", "aa", "ai", "as", "id", "em", "np", "sc", "om", "nt", "nm", "nb", "ro", "mo" );
ModeCompatibilityMap["rd"] = Vectorize( 9, "dm", "rv", "mm", "sh", "aa", "ai", "as", "ro", "mo" );
ModeCompatibilityMap["vr"] = Vectorize( 9, "dm", "rv", "mm", "sh", "aa", "ai", "as", "ro", "mo" );
ModeCompatibilityMap["el"] = Vectorize( 18, "dm", "rv", "mm", "du", "sh", "aa", "ai", "as", "id", "em", "np", "sc", "om", "nt", "nm", "nb", "ro", "mo" );
ModeCompatibilityMap["sd"] = Vectorize( 9, "dm", "rv", "mm", "sh", "aa", "ai", "as", "ro", "mo" );
ModeCompatibilityMap["cm"] = Vectorize( 19, "dm", "rv", "mm", "du", "sh", "aa", "ai", "as", "id", "em", "np", "sc", "om", "nt", "nm", "nb", "ro", "mo", "sp" );
ModeCompatibilityMap["cd"] = Vectorize( 9, "dm", "rv", "mm", "sh", "aa", "ai", "as", "ro", "mo" );
// Secondary
ModeCompatibilityMap["dm"] = Vectorize( 8, "rv", "mm", "sh", "aa", "ai", "as", "ro", "mo" );
ModeCompatibilityMap["rv"] = Vectorize( 2, "dm", "sh" );
ModeCompatibilityMap["mm"] = Vectorize( 2, "dm", "sh" );
ModeCompatibilityMap["sh"] = Vectorize( 3, "dm", "rv", "mm" );
ModeCompatibilityMap["aa"] = Vectorize( 3, "dm", "ai", "as" );
ModeCompatibilityMap["ai"] = Vectorize( 3, "dm", "aa", "as" );
ModeCompatibilityMap["as"] = Vectorize( 3, "dm", "aa", "ai" );
ModeCompatibilityMap["ro"] = Vectorize( 2, "dm", "mo" );
ModeCompatibilityMap["mo"] = Vectorize( 2, "dm", "ro" );
}
std::vector<std::string> Tokenize( const std::string &string ) {
std::vector<std::string> tokens;
std::string token;
std::stringstream ss( string );
while ( ss >> token ) {
tokens.push_back( token );
}
return tokens;
}
void SanitizeString( std::string &in ) {
std::transform( in.begin(), in.end(), in.begin(), tolower );
for ( size_t i = 0; i < in.size(); ++i ) {
if ( in[i] < 'a' || in[i] > 'z' ) {
in.erase( i--, 1 );
}
}
}
std::vector<std::string> SplitString( const std::string &in, int count ) {
std::vector<std::string> result;
if ( in.length() % count != 0 ) {
return result;
}
for ( std::string::const_iterator i = in.begin(); i != in.end(); i += count ) {
result.push_back( std::string( i, i + count ) );
}
return result;
}
bool IsPrimaryGameMode( const std::string &in ) {
for ( int i = 0; i < PrimaryModesCount; ++i ) {
if ( strcmp( PrimaryModes[i], in.c_str() ) == 0 ) {
return true;
}
}
return false;
}
bool IsSecondaryGameMode( const std::string &in ) {
for ( int i = 0; i < SecondaryModesCounts; ++i ) {
if ( strcmp( SecondaryModes[i], in.c_str() ) == 0 ) {
return true;
}
}
return false;
}
bool IsMiscGameMode( const std::string &in ) {
for ( int i = 0; i < MiscModesCount; ++i ) {
if ( strcmp( MiscModes[i], in.c_str() ) == 0 ) {
return true;
}
}
return false;
}
bool IsValidGameMode( std::string in, std::string &out ) {
// 1. Strip all non-letters from the string and convert it to lower-case
SanitizeString( in );
// 2. Confirm that it is a multiple of 2
if ( in.length() == 0 || in.length() % 2 != 0 ) {
return false;
}
// 3. Split the string further into strings of 2 characters
std::vector<std::string> modes = SplitString( in, 2 );
// 4. Verify that each game mode is a valid game mode and is compatible with the others
bool primaryModeSet = false;
for ( size_t i = 0; i < modes.size(); ++i ) {
if ( IsPrimaryGameMode( modes[i] ) || IsSecondaryGameMode( modes[i] ) ) {
if ( IsPrimaryGameMode( modes[i] ) ) {
if ( primaryModeSet ) {
return false;
}
primaryModeSet = true;
}
if ( ModeCompatibilityMap.count( modes[i] ) > 0 ) {
std::vector<std::string> badModes = ModeCompatibilityMap[modes[i]];
for ( size_t j = 0; j < badModes.size(); ++j ) {
for ( size_t k = 0; k < modes.size(); ++k ) {
if ( badModes[j] == modes[k] ) {
return false;
}
}
}
}
} else if ( !IsMiscGameMode( modes[i] ) ) {
return false;
}
}
// 5. Assign the output variable with the game mode and return true
out = in;
return true;
}
std::string ExtractGameMode( const std::string &gameName ) {
std::vector<std::string> tokens = Tokenize( gameName );
std::string gameMode;
for ( size_t i = 0; i < tokens.size(); ++i ) {
if ( IsValidGameMode( tokens[i], gameMode ) ) {
return gameMode;
}
}
return "";
}
int main( int argc, char *argv[] ) {
InitializeModeCompatibilityMap();
std::string gameName = "DotA v6.60 -RDEM USA/CA LC";
std::string gameMode = ExtractGameMode( gameName );
std::cout << "Name: " << gameName << std::endl;
std::cout << "Mode: " << gameMode << std::endl;
return 0;
}
```
**Output:**
> Name: DotA v6.60 -RDEM USA/CA LC
>
> Mode: rdem
---
If anyone would like to review this code and let me know what they would change, that would be appreciated.
Thanks. | Extracting the game type from the host's game name will be difficult without more rules in place. If you **really** want to avoid giving the end user more rules you could try the following...
* ToLower() the entire game name string.
* Split the game name using a space ' ' delimiter.
* Analyse each word, do the following. If anything fails, go to next word.
---
* taking [0] and determining if it has an ascii value of 97-122 (making sure it's a letter). If it's not within those values, go the next character, and so on until it does (without exceeding the array bounds obviously). This removes any user formatting like a hyphen -apem.
* strcmp() the next 2 characters with each of primary game types until you reach a match. Otherwise failing and moving onto next word.
* With the remaining characters, strcmp each next pair of characters with each secondary or misc gametype. If any don't match fail out to next word, or if there is only 1 character left over fail out to next word
That should extract the game type, or you can blame the user for using a bad game name.
---
Now for the harder part, verifying if the gametypes are compatible with each other. I suggest that you make a struct that holds a data structure of booleans representing each of the secondary game types. A std::map, or a single boolean array that could be accessed using a enum.
Now you're going to need a data object to represent each primary game type **as well** as each secondary game type.
Then just make an array of every gametype, both primary and secondary. Refer to code sample:
```
map<const char*, bool> mapSecondaryCompatibility;
struct tGameType
{
char szName[3];
mapSecondaryCompatibility m_compat;
}
```
As you see, there technically isn't a difference between your primary and secondary game types, they both have the same restriction... may not be compatible with another secondary game type.
With this I'm sure you can figure out the rest. I hope it helps, I gotta get back to work :)
Oh and I'm a big fan of DotA... keep up the good work! | Create bool arrays which replicate the tables you've put into comments. Except instead of an "X" or blank put "true" or "false" (so "true" means the combination of modes is valid and "false" means invalid).
Use this table to lookup whether the combination is valid:
```
bool IsSecondaryValidWithPrimary(unsigned int primaryIndex, unsigned int secondaryIndex)
{
static bool secondaryValidWithPrimary[numPrimaryModes][numSecondaryModes] = {...}
if (primaryIndex < numPrimaryModes && secondaryIndex < numSecondaryModes)
{
return secondaryValidWithPrimary[primaryIndex][secondaryIndex]
}
else
{
//... this should never happen, throw your favorite exception
}
}
```
Naturally this requires you to convert each 2 character string to the correct array index to be tested. Loop over every possible combination and check to see if its valid. I doubt you seriously care about performance in this setup, so this should work nicely.
Do the same for the other validity check (secondary with another secondary) or any other combination of modes for which you have compatibility rules. | C++ - How can I extract a valid string within a string? | [
"",
"c++",
"string",
"parsing",
"extract",
""
] |
Goal is to replace a integer value that is returned in a SQL query with the char value that the number represents. For example:
A table attribute labeled ‘Sport’ is defined as a integer value between 1-4. 1 = Basketball, 2 = Hockey, etc. Below is the database table and then the desired output.
**Database Table:**
```
Player Team Sport
--------------------------
Bob Blue 1
Roy Red 3
Sarah Pink 4
```
**Desired Outputs:**
```
Player Team Sport
------------------------------
Bob Blue Basketball
Roy Red Soccer
Sarah Pink Kickball
```
What is best practice to translate these integer values for String values? Use SQL to translate the values prior to passing to program? Use scripting language to change the value within the program? Change database design? | The database should hold the values and you should perform a join to another table which has that data in it.
So you should have a table which has say a list of people
> ID Name FavSport
> 1 Alex 4
> 2 Gnats 2
And then another table which has a list of the sports
> ID Sport
> 1 Basketball
> 2 Football
> 3 Soccer
> 4 Kickball
Then you would do a join between these tables
```
select people.name, sports.sport
from people, sports
where people.favsport = sports.ID
```
which would give you back
> Name Sport
> Alex Kickball
> Gnat Football
You could also use a case statement eg. just using the people table from above you could write something like
```
select name,
case
when favsport = 1 then 'Basketball'
when favsport = 2 then 'Football'
when favsport = 3 then 'Soccer'
else 'Kickball'
end as "Sport"
from people
```
But that is certainly not best practice. | MySQL has a `CASE` statement. The following works in SQL Server:
```
SELECT
CASE MyColumnName
WHEN 1 THEN 'First'
WHEN 2 THEN 'Second'
WHEN 3 THEN 'Third'
ELSE 'Other'
END
``` | SQL select replace integer with string | [
"",
"sql",
"database",
"database-design",
""
] |
In the .net CLR Object is the base for all class objects, but not basic types (e.g. int, float etc). How can I use basic types like Object?
I.e. Like [Boost.Variant](http://www.boost.org/doc/libs/1_39_0/doc/html/variant.html)?
E.g. *like* :-
```
object intValue( int(27) );
if (intValue is Int32)
...
object varArray[3];
varArray[0] = float(3.141593);
varArray[1] = int(-1005);
varArray[2] = string("String");
``` | `object`, via boxing, is the effective (root) base-class of all .NET types. That should work fine - you just need to use `is` or `GetType()` to check the types...
```
object[] varArray = new object[3];
varArray[0] = 3.141593F;
varArray[1] = -1005;
varArray[2] = "String";
``` | Since you mentioned you're in C++/CLI, you should be able to do:
```
array<Object^>^ varArray = gcnew array<Object^>(3);
varArray[0] = 3.141593;
varArray[1] = -1005;
varARray[2] = "String";
double val = *reinterpret_cast<double^>(varArray[0]);
``` | How can I implement variant types in the CLR/Managed C++? | [
"",
"c#",
"clr",
"managed-c++",
"variant",
""
] |
Does anyone know of a utility to preprocess a C# source file without compiling it, in a similar fashion to using the -E flag in GCC? I tried using GCC - it successfully processes `#if` directives, but it chokes on any `#region` directives...
Ideally, I'd like to be able to run the tool over a .cs file to remove any `#if` blocks that evaluate to false, and optionally be able to flag whether to remove/leave intact comments, `#region`, `#pragma` directives etc.
To put this in context, I want to be able to a publish some source code that is part of a (much) larger project, whilst removing portions that are only relevant to the larger project. As an example, there are chunks of code that look like this:
```
#if (SUBPROJECT)
namespace SubProject
#else
namespace CompleteProject
#endif
{
public class SomeClass()
{
#if (!SUBPROJECT)
// This might call a method contained in an assembly that potentially
// won't be available to the sub-project, or maybe a method that hooks
// into a C library via P/Invoke...
string result = CallSomeCleverMethod();
#else
// This might call a method that performs a simplified version of the
// above, but does so without the above's assembly or P/Invoke
// dependencies...
string result = CallSomeSimpleMethod();
#endif
}
}
```
Please remember I'm not trying to do builds here - this is purely about publishing only a subset of a larger project's source code.
Any ideas/help appreciated. | It turns out using the GNU C preprocessor (cpp) directly (rather than via gcc) provides more control over the output. Using this, I was able to process the source files in a suitable fashion...
Here's an example:
```
cpp -C -P -DSUBPROJECT Input.cs Output.cs
```
I tried to get the C/C++ compiler provided with Visual Studio to do something similar, but gave up after a while... | I do not believe that there are any flags for the csc or msc (mono compiler) to output the preprocessed files.
If I had to do this, and it was a small subset I would compile and then use [Reflector](http://www.red-gate.com/products/reflector/) to decompile back to C# and export the files. If you have a lot of files, there is an [Reflector Add-In](http://www.codeplex.com/reflectoraddins) called [FileGenerator for Reflector](http://www.codeplex.com/FileGenReflector).
Unfortunately this will not be a true copy of your codebase -- it will reformat all of the code and you will lose all of the comments. | Does a C# preprocessing tool exist? | [
"",
"c#",
"c-preprocessor",
""
] |
Assuming PHP version >= 5.2, which is a better solution for managing includes:
```
require_once DEFPATH . 'config.inc.php';
```
or
```
if (!defined('FOOBAR')) require DEFPATH . 'config.inc.php';
```
or something entirely different?
Site does not use a front controller or autoloader. Typical number of files needed to be included is 3 - 8.
I've heard, here and elsewhere, that `require_once` adds overhead and does not play nice with caching. But I've also heard that a small number of `require_once` statements is OK in practice in later versions of PHP.
There must also be some overhead associated with checking if something is defined, but that may be less of an issue.
In general, which is the better practice and why? | Yes, require\_once() comes with CPU and memory overhead, but not in any way significant to performance. In fact, it's a very efficient operation because PHP just does one hashtable lookup to decide whether that file has already been parsed or not. Don't give yourself any unnecessary headaches with hacks like your !defined('FOOBAR') example, because it does the same thing only with less elegance.
What takes time during a PHP request is the file path lookup and then the subsequent parsing step. The amount of resources needed for the runtime to determine whether you've already parsed the file before is negligible.
There are a few things you can do to make your request run faster:
* avoid unecessarily long search path in include() and require()
* use absolute include paths were possible
* include stuff only as needed
* cache large output fragments
* cache complex query results
* write terse code, offload seldom-used functionality to included-on-demand source files
If you're using a code cache or some kind of runtime optimizer, read the manual - they have different strategies that can actually hurt performance or introduce bugs depending on your code.
One final advice: beware premature optimization! Requests taking between 0 and 50 miliseconds on the server are practically not distinguishable on the user side. | I would use require\_once in your case. Even if it adds overhead, you can neglect it, especially when you only have to include max 8 files. The require\_once is a lot less error prone and more 'clean'... | Which is better: require_once? or if (!defined('FOOBAR')) require? or something entirely different? | [
"",
"php",
""
] |
I see this in the standard C++ libraries for my system, as well as some of the headers in a library I'm using.
What are the semantics of these two definitions? Is there a good reference for #defines like this other than the source itself? | `__STDC_LIMIT_MACROS` and `__STDC_CONSTANT_MACROS` are a workaround to allow C++ programs to use `stdint.h` macros specified in the C99 standard that aren't in the C++ standard. The macros, such as `UINT8_MAX`, `INT64_MIN`, and `INT32_C()` may be defined already in C++ applications in other ways. To allow the user to decide if they want the macros defined as C99 does, many implementations require that `__STDC_LIMIT_MACROS` and `__STDC_CONSTANT_MACROS` be defined before `stdint.h` is included.
This isn't part of the C++ standard, but it has been adopted by more than one implementation. | The above issue has vanished. C99 is an old standard, so this has been explicitly overruled in the C++11 standard, and as a consequence C11 has removed this rule.
More details there:
* <https://sourceware.org/bugzilla/show_bug.cgi?id=15366> | What do __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS mean? | [
"",
"c++",
"stl",
"macros",
""
] |
I'm trying to implement Steven Sanderson's WinsorControllerFactory from his pro Asp.Net MVC Framework book (great book, btw) and I'm stumbling into an issue. I'm not sure what else you'll need to know in order to formulate a response but I greatly appreciate any help in this. Thanks!
Here's the code:
**WindsorControllerFactory**
```
public class WindsorControllerFactory : DefaultControllerFactory
{
private WindsorContainer _container;
public WindsorControllerFactory()
{
_container= new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
where typeof (IController).IsAssignableFrom(t)
select t;
foreach(Type t in controllerTypes)
{
_container.AddComponentLifeStyle(t.FullName, t, LifestyleType.Transient);
}
}
protected override IController GetControllerInstance(Type controllerType)
{
return (IController)_container.Resolve(controllerType);
}
}
```
**Web.Config**
```
<castle>
<components>
<component id="MenuRepository"
service="****.IMenuRepository, ****.Model"
type="****.FakeMenuRepository, ****.Model">
</component>
<component id="NewsRepository"
service="****.INewsRepository, ****.Model"
type="****.FakeNewsRepository, ****.Model">
</component>
</components>
</castle>
```
**NewsArticleController**
```
public class NewsArticleController : Controller
{
private INewsRepository _repository { get; set; }
public NewsArticleController(INewsRepository repository)
{
_repository = repository;
}
```
**Global.asax**
```
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory((new WindsorControllerFactory()));
}
```
**ERROR MESSAGE**
No component for supporting the service \*\*\*\*.NewsArticleController was found
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
```
Exception Details: Castle.MicroKernel.ComponentNotFoundException: No component for supporting the service ****.NewsArticleController was found
Source Error:
Line 29: protected override IController GetControllerInstance(Type controllerType)
Line 30: {
Line 31: return (IController)_container.Resolve(controllerType);
Line 32: }
Line 33: }
``` | The S#arpArchitecture project has a decent implentation of using Windsor as a DI framework (for controllers or anything else), with little or no need to add web.config sections - <http://code.google.com/p/sharp-architecture/>
Code examples:
CastleWindsor/ComponentRegistrar.cs:
```
public class ComponentRegistrar
{
public static void AddComponentsTo(IWindsorContainer container) {
AddGenericRepositoriesTo(container);
AddCustomRepositoriesTo(container);
container.AddComponent("validator",
typeof(IValidator), typeof(Validator));
}
private static void AddCustomRepositoriesTo(IWindsorContainer container) {
container.Register(
AllTypes.Pick()
.FromAssemblyNamed("Northwind.Data")
.WithService.FirstNonGenericCoreInterface("Northwind.Core"));
}
private static void AddGenericRepositoriesTo(IWindsorContainer container) {
container.AddComponent("entityDuplicateChecker",
typeof(IEntityDuplicateChecker), typeof(EntityDuplicateChecker));
container.AddComponent("repositoryType",
typeof(IRepository<>), typeof(Repository<>));
container.AddComponent("nhibernateRepositoryType",
typeof(INHibernateRepository<>), typeof(NHibernateRepository<>));
container.AddComponent("repositoryWithTypedId",
typeof(IRepositoryWithTypedId<,>), typeof(RepositoryWithTypedId<,>));
container.AddComponent("nhibernateRepositoryWithTypedId",
typeof(INHibernateRepositoryWithTypedId<,>), typeof(NHibernateRepositoryWithTypedId<,>));
}
}
```
Global.asax (primary initialization method for di):
```
protected virtual void InitializeServiceLocator() {
IWindsorContainer container = new WindsorContainer();
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));
container.RegisterControllers(typeof(HomeController).Assembly);
ComponentRegistrar.AddComponentsTo(container);
ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
}
``` | MvcContrib offers some extension methods for registering controllers in Windsor, example:
```
windsorContainer.RegisterControllers(Assembly.GetExecutingAssembly());
```
Mannish's code uses the same extension method. | Need help with Castle.Windsor as an Asp.Net MVC ControllerFactory please | [
"",
"c#",
"asp.net-mvc",
"castle-windsor",
""
] |
111111111111111111111111111111111111111111111111111111111111
when i take this as input , it appends an L at the end like this
111111111111111111111111111111111111111111111111111111111111L
thus affecting my calculations on it .. how can i remove it?
```
import math
t=raw_input()
l1=[]
a=0
while (str(t)!="" and int(t)!= 0):
l=1
k=int(t)
while(k!= 1):
l=l+1
a=(0.5 + 2.5*(k %2))*k + k % 2
k=a
l1.append(l)
t=raw_input()
a=a+1
for i in range(0,int(a)):
print l1[i]
```
this is my code and it works for every test case except 111111111111111111111111111111111111111111111111111111111111
so i guess something is wrong when python considers such a huge number | It looks like there are two distinct things happening here. First, as the other posters have noted, the L suffix simply indicates that Python has converted the input value to a long integer. The second issue is on this line:
```
a=(0.5 + 2.5*(k %2))*k + k % 2
```
This implicitly results in a floating point number for the value of `(0.5 + 2.5*(k %2))*k`. Since floats only have 53 bits of precision the result is incorrect due to rounding. Try refactoring the line to avoid floating point math, like this:
```
a=(1 + 5*(k %2))*k//2 + k % 2
``` | It's being input as a Long Integer, which should behave just like any other number in terms of doing calculations. It's only when you display it using [`repr`](http://docs.python.org/library/functions.html#repr) (or something that invokes `repr`, like printing a list) that it gets the 'L'.
What exactly is going wrong?
**Edit**: Thanks for the code. As far as I can see, giving it a long or short number makes no difference, but it's not really clear what it's supposed to do. | an error in taking an input in python | [
"",
"python",
""
] |
By defining an attribute that implements IContactBehavior and IWsdlExportExtension and set that attribute on your service contract, you can easily add **Soap Headers to your wsdl** (see <http://wcfextras.codeplex.com/> for more information)
But now I need to set a Soap Header contract in the wsdl on all Operationcontracts and this time I cannot set an attribute.
Following code (called from IWsdlExportExtension.ExportEndPoint) doesn't work, but does work when called from the SoapHeaderAttributes (that executes an IWsdlExportExtension.ExportContract)
```
foreach (OperationDescription operationDescription in context.ContractConversionContext.Contract.Operations)
{
AddSoapHeader(operationDescription, "SomeHeaderObject", typeof(SomeHeaderObject), SoapHeaderDirection.InOut);
}
internal static void AddSoapHeader(OperationDescription operationDescription, string name, Type type, SoapHeaderDirection direction)
{
MessageHeaderDescription header = GetMessageHeader(name, type);
bool input = ((direction & SoapHeaderDirection.In) == SoapHeaderDirection.In);
bool output = ((direction & SoapHeaderDirection.Out) == SoapHeaderDirection.Out);
foreach (MessageDescription msgDescription in operationDescription.Messages)
{
if ((msgDescription.Direction == MessageDirection.Input && input) ||
(msgDescription.Direction == MessageDirection.Output && output))
msgDescription.Headers.Add(header);
}
}
internal static MessageHeaderDescription GetMessageHeader(string name, Type type)
{
string headerNamespace = SoapHeaderHelper.GetNamespace(type);
MessageHeaderDescription messageHeaderDescription = new MessageHeaderDescription(name, headerNamespace);
messageHeaderDescription.Type = type;
return messageHeaderDescription;
}
```
Anyone has an idea how to apply this code on all operations (without using attributes) and by doing this, adding the contract of the header to the wsdl ? | The IEndpointBehavior has the following interface:
```
ApplyDispatchBehavior(ServiceEndpoint endPoint, EndPointDispatcher endpointDispatcher);
```
You can add Soap Headers to the wsdl for operations by iterating over the endpoint.Contract.Operations in the ApplyDispatchBehavior.
Here you have the complete solution that worked for me:
```
void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
foreach (OperationDescription operationDescription in endpoint.Contract.Operations)
{
foreach (MessageDescription msgDescription in operationDescription.Messages)
{
AddSoapHeader(operationDescription, "SomeHeaderObject", typeof(SomeHeaderObject), SoapHeaderDirection.InOut);
}
}
}
internal static void AddSoapHeader(OperationDescription operationDescription, string name, Type type, SoapHeaderDirection direction)
{
MessageHeaderDescription header = GetMessageHeader(name, type);
bool input = ((direction & SoapHeaderDirection.In) == SoapHeaderDirection.In);
bool output = ((direction & SoapHeaderDirection.Out) == SoapHeaderDirection.Out);
foreach (MessageDescription msgDescription in operationDescription.Messages)
{
if ((msgDescription.Direction == MessageDirection.Input && input) ||
(msgDescription.Direction == MessageDirection.Output && output))
msgDescription.Headers.Add(header);
}
}
internal static MessageHeaderDescription GetMessageHeader(string name, Type type)
{
string headerNamespace = SoapHeaderHelper.GetNamespace(type);
MessageHeaderDescription messageHeaderDescription = new MessageHeaderDescription(name, headerNamespace);
messageHeaderDescription.Type = type;
return messageHeaderDescription;
}
```
The SoapHeaderHelper can be found in the [WcfExtras](http://wcfextras.codeplex.com/). | You might want to have a look at the [WCFExtras](http://www.codeplex.com/WCFExtras) project on CodePlex - it has some support for custom SOAP headers and stuff like that. Not 100% sure if it's capable of filling your need, but check it out!
Marc
UPDATE: have you looked into creating a WCF extension, e.g. something like a message inspector, on both the client and the server side?
The client side IClientMessageInspector defines two methods `BeforeSendRequest` and `AfterReceiveReply` while the server side IDispatchMessageInspector has the opposite methods, i.e. `AfterReceiveRequest` and `BeforeSendReply`.
With this, you could add headers to every message going across the wire (or selectively only to a few).
Here's a snippet from a IClientMessageInspector implementor we use to automagically transmit the locale information (language and culture info) across from the clients to the server - should give you an idea how to get started:
```
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
International intlHeader = new International();
intlHeader.Locale = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
MessageHeader header = MessageHeader.CreateHeader(WSI18N.ElementNames.International, WSI18N.NamespaceURI, intlHeader);
request.Headers.Add(header);
return null;
}
``` | WCF WSDL Soap Header on all operations | [
"",
"c#",
"wcf",
"wsdl",
""
] |
Do you have a step in your deployment process that minifies JS? Do you have any sort of preprocessor for your JavaScript that allows you to leave in comments and console.logs and then have them automatically stripped out? Is your JavaScript machine generated by GWT or Script#? Do you use ANT or another tool to automate deployment?
I see a lot of JavaScript that looks like it comes right out of the editor, complete with lots of white space and comments. How much of that is due to not caring about the state of the deployed code, and how much is due to the spirit of the open web? | My steps include:
1. I write Javascript using TextMate with the Javascript Tools bundle installed. This JSLint's my files on every save and notifies me when errors occur.
2. I use [Sprockets](http://getsprockets.org/) to automatically concatenate my various Javascript files.
3. I run the resulting concatenation through jsmin to generate a minified version.
I end up with a concatenated lib.js file and a minified lib.min.js file. One I use for development, one for production. TextMate commands help automate it all.
I'm still looking for a good solution to actually (unit) test my scripts. | I usually check it out with [JSLint](http://www.jslint.com) to make sure it is bug-free, then pack it/encode it with [YUI compressor](http://developer.yahoo.com/yui/compressor/). | What do you do to your JavaScript code before deployment? | [
"",
"javascript",
"deployment",
"release-management",
"minify",
""
] |
I don't know why every time I try to include my header using PHP’s `include` there's a top margin. I checked it using Firebug and it says there's a 22px offset margin on the top. Is anybody experiencing this problem? I think it's a CSS propiety: top: 22px. But nothing can change it even if I write h1 style="top: 0px; margin-top: 0px;". I think it's a php-CSS mystery that will never be solved.
edit: The only way to get rid of that top margin offset or whatever it is, is to add the follow properties to the H1: top: 0px;
position: absolute;
Will those properties generate more problems in the future?
**is there a better way to solve this top margin-offset problem?**
edit2: I think there's a problem with the encoding. Is there a conflict between the encoding of the included file (header.html) and the index file?
My index goes like this:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
<link rel="stylesheet" type="text/css" href="style2.css" />
</head>
<body>
<div id="page-wrap">
<?php include_once("header2.html"); ?>
</div>
</body>
</html>
```
With this CSS:
```
* {
padding: 0px;
margin: 0px;
}
```
My *header.html* (the one that’s being included):
```
<h1>Header 2</h1>
```
And that’s the output:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
<link rel="stylesheet" type="text/css" href="style2.css" />
</head>
<body>
<div id="page-wrap">
<h1>Header 2</h1> </div>
</body>
</html>
```
* God its so simple that I really dont know where the top margin is coming from (in all browsers).
* It only happens when I use php includes.
* The source code looks the same as when I dont use php include. | This is pretty weird, but I copied & pasted your output HTML into Notepad++, and there was a strange character just prior to the h1. When pasting it into Notepad, the h in the h1 was subscripted.
Therefore, it looks to me like you may have an erroneous (or unexpected for PHP) character in your included HTML (or in the PHP including it). My suspicion? The dreaded UTF-8 BOM. Try to change the encoding of your included HTML file to eliminate the BOM (which I've always had problems with when dealing with PHP).
Edit: Yep. Just verified with a hex editor. There's a byte-order mark at the beginning of your included HTML. I don't know which editor you use, but you should have the option to change your text encoding settings.
See [this](http://bugs.php.net/bug.php?id=22108) for more info about PHP & the BOM. | You ought to post your *generated* HTML, like by copying what you see when you select "View Source" from your web browser. Oftentimes, I've seen mysterious blank lines in PHP-generated HTML because PHP is configured to output errors and warnings. Even if this is not caused by that, we can more-easily diagnose the problem if we see the outputted HTML. | Php include annoying top margin | [
"",
"php",
"css",
"include",
"margin",
""
] |
Let's say I have the following table with three columns:
```
id | start_block | end_block
-----------------------------
01 | 00000000001 | 00000000005
02 | 00000000006 | 00000000011
03 | 00000000012 | 00000000018
04 | 00000000025 | 00000000031
05 | 00000000032 | 00000000043
```
Each row was a "Start Block" and an "End Block". If the data was perfect, each start block would be one more than the end block before it. So, for row id == 02, the start block is 6 while the end block for the row before it 5.
I need to query this data (it's tens of thousands of row) and find any missing rows. According to my sample data, there should be a row in between 03 and 04 that has a start block of 19 and an end block of 24.
I'm trying to build a report in JSP to reconcile this data and find the missing rows. The ugly way to do this would be to pull the whole recordset into an array and do something like on every row:
```
if ((arry(i,1) + 1) != (arry(i+1),1)( {
print("Bad Row!\n");
}
```
But, I would really like to be able to query the recordset directly and return what I need. Is that possible? If not, could someone point me in the right direction of creating a stored proc that does what I need? | Sure wouldn't hurt to give it a try
```
CREATE TABLE #t (startz INT, zend INT)
insert into #t (startz, zend) values (1,5)
insert into #t (startz, zend) values (6,11)
insert into #t (startz, zend) values (12,18)
insert into #t (startz, zend) values (25,31)
insert into #t (startz, zend) values (32,43)
select * from #t ta
LEFT OUTER JOIN #t tb ON tb.startz - 1 = ta.zend
WHERE tb.startz IS NULL
```
The last result is a false positive. But easy to eliminate. | You could try:
```
SELECT t.ID, t.Start_Block, t.End_Block
FROM [TableName] t
JOIN [TableName] t2 ON t.ID = t2.ID+1
WHERE t.Start_Block - t2.End_Block > 1
``` | Can I use SQL to find missing numbers in the example table I give below? | [
"",
"sql",
"sql-server",
"database",
"algorithm",
""
] |
What is the difference between using a BufferedReader around the StringReader in the following code vs using the StringReader only? By loading up the DOM in line 2 of both examples, it seems like the BufferedReader is not necessary?
```
InputSource is = new InputSource(new StringReader(html));
Document dom = XMLResource.load(is).getDocument();
```
VS
```
InputSource is = new InputSource(new BufferedReader(new StringReader(html)));
Document dom = XMLResource.load(is).getDocument();
``` | In this particular case, I see no benefit. In general there are two benefits:
* The oh-so-handy [`readLine()`](http://java.sun.com/javase/6/docs/api/java/io/BufferedReader.html#readLine()) method is only defined in `BufferedReader` rather than `Reader` (irrelevant here)
* `BufferedReader` reduces IO where individual calls to the underlying reader are potentially expensive (i.e. fewer chunky calls are faster than lots of little ones) - again, irrelevant for `StringReader`
Cut and paste fail? | EDIT: My original answer below. The below *isn't* relevant in this case, since the buffered reader is wrapping a StringReader, which wraps a String. So there's no buffering to be performed, and the BufferedReader appears to be redundant. You *could* make an argument for using best/consistent practises, but it would be pretty tenuous.
Possibly the result of a copy/paste, or perhaps an IDE-driven refactor too far!
BufferedReader will attempt to read in a more optimal fashion.
That is, it will read larger chunks of data in one go (in a configurable amount), and then make available as required. This will reduce the number of reads from disk (etc.) at the expense of some memory usage.
To quote from the Javadoc:
> In general, each read request made of
> a Reader causes a corresponding read
> request to be made of the underlying
> character or byte stream. It is
> therefore advisable to wrap a
> BufferedReader around any Reader whose
> read() operations may be costly, such
> as FileReaders and InputStreamReaders | Why use BufferedReader in this case? | [
"",
"java",
"xml",
"bufferedreader",
""
] |
I'm running wampserver and can't seem to use php files in the CLI. Supposedly there are two modes of running php, CGI and CLI. I can't figure out how to enable CLI since I don't see php-cli.exe in /wamp/bin/php/php5.2.6. When I try and execute php scripts they wont run. Does anyone know how to get the CLI running php scripts using wampserver 2?
Im basically trying to call a bake.php script to open a cake console. | You should have a file php.exe, which is the CLI version. So you can do
```
php.exe -f phpfile.php
```
to run a file using the command line. | If your having a problem with environmental variables, here is some steps to fix it:
1. Go to My Computer properties
2. Click advanced tab
3. Click environmental variables
4. Edit "path" under system variables
with the paths to the php and cake
console folders
Example: `C:\wamp\bin\php\php5.2.9-2;C:\wamp\www\cake\cake\console;`
NOTE: You will have to change the paths to match yours, also make sure you have ; seperating each path | Wamp PHP CLI | [
"",
"php",
"cakephp",
"wampserver",
""
] |
How to refresh the auto refresh div inside the div theres is php
The following code dont work?
```
var refresh = setInterval(function() { $("#recent_activity").html(); }, 1);
``` | Based on x0n's comment, which I think is a fair guess, I am guessing that you want to automatically refresh a `<div>` with content from the server every X seconds. In your example, your second argument to the `setInterval` function is 1. This is a really bad idea, as the delay is in milliseconds, so you would be firing off 1000 requests a second (not that the browser would let you, but still).
Anyhow, if that's what you want, you would need to do this:
```
var timer;
var seconds = 30; // how often should we refresh the DIV?
function startActivityRefresh() {
timer = setInterval(function() {
$('#recent_activity').load('recent_activity_ajax.php');
}, seconds*1000)
}
function cancelActivityRefresh() {
clearInterval(timer);
}
```
Your server-side script (`recent_activity_ajax.php` in the example) would then need to return whatever you want the `<div>` to be populated with - just that, not the headers or footers or anything else. If you wanted this to start when the page loads, you would simply call `startActivityRefresh`:
```
$(function() {
startActivityRefresh();
});
```
If this is not at all what you meant by refreshing the `<div>`, you're going to need to clarify. :)
**EDIT**:
In response to your comment: you can't make Javascript "refresh" the contents of the dynamic PHP code. This just isn't possible as the browser can't really execute a server side language like PHP. You have to call the server again. In order to make this cleanest you should probably move the code that fills the contents of `#recent_activity` to a function, call that once when the page loads and have a different file that simply outputs that code to be able to refresh it dynamically. You should probably look into MVC patterns from here, but I'm not sure if you're quite ready for that... | You can write a function something like this and call it on 'document.ready'
```
function refreshMyDiv()
{
$("myDiv").fadeOut("slow");
//Code to refresh the content goes here
//could be a AJAX call
$("myDiv").fadeIn("slow");
setTimeout("refreshMyDiv();", 60000);
}
``` | How to refresh <DIV> | [
"",
"javascript",
"jquery",
"html",
""
] |
Is there an elegant and pythonic way to trap the first and last item in a for loop which is iterating over a generator?
```
from calendar import Calendar
cal = Calendar(6)
month_dates = cal.itermonthdates(year, month)
for date in month_dates:
if (is first item): # this is fake
month_start = date
if (is last item): # so is this
month_end = date
```
This code is attempting to get the first day of the week the month ends on, and the last day of the week the month ends on. Example: for June, month-start should evaluate to 5/31/09. Even though it's technically a day in May, it's the first day of the week that June begins on.
Month-dates is a generator so i can't do the [:-1] thing. What's a better way to handle this? | I would just force it into a list at the beginning:
```
from calendar import Calendar, SUNDAY
cal = Calendar(SUNDAY)
month_dates = list(cal.itermonthdates(year, month))
month_start = month_dates[0]
month_end = month_dates[-1]
```
Since there can only be 42 days (counting leading and tailing context), this has negligible performance impact.
Also, using SUNDAY is better than a magic number. | Richie's got the right idea. Simpler:
```
month_dates = cal.itermonthdates(year, month)
month_start = month_dates.next()
for month_end in month_dates: pass # bletcherous
``` | Getting the first and last item in a python for loop | [
"",
"python",
"for-loop",
""
] |
in my webapplications whihc runs on tomcat on widows i want to send email to many different people
for example whenever a new tutials is uploaded on my site an email shold go to all the registed user on my site.
simlarly whenever some other event occors i need to send the email to some selected users whose emailid are picked up from database.
I want a jar which can be used to send such messages.
I wil pass a array of receipienst to it.
are there some free jars available for this ??
jars shold me able to queue the msgs and send to the recipients
let me explain in detail | You need [JavaMail](http://java.sun.com/products/javamail/) | Check out [commons email](http://commons.apache.org/email/) | jars for mass email sending | [
"",
"java",
"email",
"jsp",
""
] |
how do I select special attributes like 'user:name' or 'city:id' using jQuery?
```
<div user:name="Ropstah"></div>
<span city:id="4"></div>
```
Javascript
```
//this works:
alert($('div').attr("user:name")); // alerts 'Ropstah'
//this doesn't work:
alert($('div[user:name]').attr("user:name")); //error
alert($('div[user\\:name]').attr("user:name")); //error even with special character escaping...
``` | [This is a bug in jQuery](http://dev.jquery.com/ticket/3729).
You have two options:
* Get rid of the `:` and using "non standard" attributes (honestly, it's not a big deal)
* Get more verbose, or use a plugin to get the functionality anyways:
Initially, you might have to do this:
```
$('div').filter(function() {
return $(this).attr('user:name') !== undefined;
}).whateverElse();
```
Speed wise this should be fairly close to jQuery's `[]` selector as that's what it's doing inside the library anyways. It is, of course, more to type every time you want to find an element that has an attribute, so you could write a plugin for it, since jQuery is awesome and lets you do this sort of thing:
```
$.fn.hasattr = function(attr) {
return this.filter(function() {
return $(this).attr(attr) !== undefined;
});
};
```
Which would then let you do a much simpler:
```
$('div').hasattr('user:name').whateverElse();
```
Or if you wanted to check if the attribute was equal to something, the plugin might be:
```
$.fn.cmpattr = function(attr, value) {
return this.filter(function() {
return $(this).attr(attr) == value;
});
};
```
And you could then do:
```
$('div').cmpattr('user:name', 'Ropstah').whateverElse();
``` | Fix it:
```
jQuery.expr.match.ATTR = /\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+|\w+:\w+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/;
// ^^^^^^^^
```
---
**EDIT**: This is not an official fix, it appears to work quite well though.
I've had quite a few headaches caused by jQuery and its inner-workings... sometimes, I think, it's okay to get stuck in there and fix it yourself. :) | How to select special attributes (prefix:name="")? | [
"",
"javascript",
"jquery",
"attributes",
""
] |
I'm sure that I'm missing something simple here, but in Visual Studio 2008 on my current project only List.Contains(T) is present. Being able to use List.Contains(T, IEqualityComparer(T)) would save me a lot of grief. Any quick thoughts on this? Thanks.
\*edit:
using System.Linq is not available to me. Is is possible that my project is stuck in .net 2.0 or something along those lines? Anyway to check & fix? | Make sure to reference System.Linq and include it (using System.Linq) in your namespaces.
The second call you are referring to is actually [Enumerable.Contains](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.contains.aspx) in System.Linq.
---
Edit in response to comments:
You could make your own version:
```
public void ContainedInList(IEnumerable<T> list, T value, IEqualityComparer<T> comparer)
{
foreach(T element in list)
{
if (comparer.Equals(element, value))
return true;
}
return false;
}
``` | To check to see if your target framework is 2.0, go to **Project>Properties**, on the **Application tab** you will see **"Target Framework"**
Set it to **.NET Framework 3.5**.
If this is set, `System.Linq` should be available to you. | List<T>.Contains not showing overload | [
"",
"c#",
"linq",
"generics",
""
] |
Factory Girl is a handy framework in rails for easily creating instances of models for testing.
From the [Factory Girl home page](http://www.thoughtbot.com/projects/factory_girl/):
> factory\_girl allows you to quickly define prototypes for each of your models and ask for instances with properties that are important to the test at hand.
An example (also from the home page):
```
Factory.sequence :email do |n|
"somebody#{n}@example.com"
end
# Let's define a factory for the User model. The class name is guessed from the
# factory name.
Factory.define :user do |f|
# These properties are set statically, and are evaluated when the factory is
# defined.
f.first_name 'John'
f.last_name 'Doe'
f.admin false
# This property is set "lazily." The block will be called whenever an
# instance is generated, and the return value of the block is used as the
# value for the attribute.
f.email { Factory.next(:email) }
end
```
if I need a user a can just call
```
test_user = Factory(:user, :admin => true)
```
which will yield a user with all the properties specified in the factory prototype, *except* for the admin property which I have specified explicitly. Also note that the email factory method will yield a different email each time it is called.
I'm thinking it should be pretty easy to implement something similar for Java, but I don't want to reinvent the wheel.
P.S: I know about both JMock and EasyMoc, however I am not talking about a mocking framework here. | One possible library for doing this is [Usurper](http://www.org-libs.org/org-lib-usurper/).
However, if you want to specify properties of the objects you are creating, then Java's static typing makes a framework pointless. You'd have to specify the property names as strings so that the framework could look up property accessors using reflection or Java Bean introspection. That would make refactoring much more difficult.
It's much simpler to just new up the objects and call their methods. If you want to avoid lots of boilerplate code in tests, the [Test Data Builder](http://c2.com/cgi/wiki?TestDataBuilder) pattern can help. | I also looked for a Java equivalent of Factory Girl, but never found anything like it. Instead, I created a solution from scratch. A factory for generating models in Java: [Model Citizen](https://github.com/mguymon/model-citizen).
Inspired by Factory Girl, it uses field annotations to set defaults for a Model, [a simple example from the wiki](https://github.com/mguymon/model-citizen/wiki/Simple-Example):
```
@Blueprint(Car.class)
public class CarBlueprint {
@Default
String make = "car make";
@Default
String manufacturer = "car manufacturer";
@Default
Integer mileage = 100;
@Default
Map status = new HashMap();
}
```
This would be the Blueprint for the Car model. This is registered into the ModelFactory, than new instances can be created as follows:
```
ModelFactory modelFactory = new ModelFactory();
modelFactory.registerBlueprint( CarBlueprint.class );
Car car = modelFactory.createModel(Car.class);
```
You can override the values of the Car model by passing in an instance of Car instead of the Class and setting values as needed:
```
Car car = new Car();
car.setMake( "mustang" );
car = modelFactory.createModel( car );
```
The [wiki](https://github.com/mguymon/model-citizen/wiki) has more complex examples ([such as using @Mapped](https://github.com/mguymon/model-citizen/wiki/Complex-example)) and details for a few more bells and whistles. | Does a framework like Factory Girl exist for Java? | [
"",
"java",
"ruby-on-rails",
"unit-testing",
"factory",
"factory-bot",
""
] |
I need to detect when the user moves the mouse over the Form and all its child controls and also when it leaves the Form. I tried the `MouseEnter` and `MouseLeave` events of the Form, I tried the `WM_MOUSEMOVE` & `WM_MOUSELEAVE` and `WM_NCMOUSEMOVE` & `WM_NCMOUSELEAVE` pairs of windows messages but none seem to work as I want...
Most of my Form is occupied by child controls of many sorts, there's not much client area visible. This means that if I move the mouse very quickly the mouse movement will not be detected, although the mouse is inside the Form.
For instance, I have a TextBox that is docked at the bottom and between the desktop and the TextBox, there's only a very small border. If I quickly move the mouse from the bottom into the TextBox, the mouse movement won't be detected, but the mouse is inside the TextBox, therefore, inside the Form.
How can I achieve what I need? | You can hook the main message loop and preprocess/postprocess any (WM\_MOUSEMOVE) message what you want.
```
public class Form1 : Form {
private MouseMoveMessageFilter mouseMessageFilter;
protected override void OnLoad(EventArgs e) {
base.OnLoad( e );
this.mouseMessageFilter = new MouseMoveMessageFilter();
this.mouseMessageFilter.TargetForm = this;
Application.AddMessageFilter(this.mouseMessageFilter);
}
protected override void OnClosed(EventArgs e) {
base.OnClosed(e);
Application.RemoveMessageFilter(this.mouseMessageFilter);
}
private class MouseMoveMessageFilter : IMessageFilter {
public Form TargetForm { get; set; }
public bool PreFilterMessage( ref Message m ) {
int numMsg = m.Msg;
if ( numMsg == 0x0200 /*WM_MOUSEMOVE*/)
this.TargetForm.Text = string.Format($"X:{Control.MousePosition.X}, Y:{Control.MousePosition.Y}");
return false;
}
}
}
``` | How about this: In your form's OnLoad, recursively go through all of the child controls (and their children) and hook up the MouseEnter event.
Then whenever the mouse enters any descendant, the event handler will be called. Similarly, you could hook up MouseMove and/or MouseLeave events.
```
protected override void OnLoad()
{
HookupMouseEnterEvents(this);
}
private void HookupMouseEnterEvents(Control control)
{
foreach (Control childControl in control.Controls)
{
childControl.MouseEnter += new MouseEventHandler(mouseEnter);
// Recurse on this child to get all of its descendents.
HookupMouseEnterEvents(childControl);
}
}
``` | How to detect if the mouse is inside the whole form and child controls? | [
"",
"c#",
"winforms",
"mouseevent",
"detection",
""
] |
Encouraged by [this](http://www.javamex.com/tutorials/regular_expressions/splitting_tokenisation_performance.shtml), and the fact I have billions of string to parse, I tried to modify my code to accept *StringTokenizer* instead of *String[]*
The only thing left between me and getting that delicious x2 performance boost is the fact that when you're doing
```
"dog,,cat".split(",")
//output: ["dog","","cat"]
StringTokenizer("dog,,cat")
// nextToken() = "dog"
// nextToken() = "cat"
```
How can I achieve similar results with the StringTokenizer? Are there faster ways to do this? | Are you only actually tokenizing on commas? If so, I'd write my own tokenizer - it may well end up being even more efficient than the more general purpose StringTokenizer which can look for multiple tokens, and you can make it behave however you'd like. For such a simple use case, it can be a simple implementation.
If it would be useful, you could even implement `Iterable<String>` and get enhanced-for-loop support with strong typing instead of the `Enumeration` support provided by `StringTokenizer`. Let me know if you want any help coding such a beast up - it really shouldn't be too hard.
Additionally, I'd try running performance tests on your actual data before leaping too far from an existing solution. Do you have any idea how much of your execution time is *actually* spent in `String.split`? I know you have a lot of strings to parse, but if you're doing anything significant with them afterwards, I'd expect that to be much more significant than the splitting. | After tinkering with the [`StringTokenizer`](http://java.sun.com/javase/6/docs/api/java/util/StringTokenizer.html) class, I could not find a way to satisfy the requirements to return `["dog", "", "cat"]`.
Furthermore, the `StringTokenizer` class is left only for compatibility reasons, and the use of `String.split` is encouaged. From the API Specification for the `StringTokenizer`:
> `StringTokenizer` is a legacy class
> that is retained for compatibility
> reasons although its use is
> discouraged in new code. It is
> recommended that anyone seeking this
> functionality use the `split` method
> of `String` or the `java.util.regex`
> package instead.
Since the issue is the supposedly poor performance of the [`String.split`](http://java.sun.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)) method, we need to find an alternative.
*Note: I am saying "supposedly poor performance" because it's hard to determine that every use case is going to result in the `StringTokenizer` being superior to the `String.split` method. Furthermore, in many cases, unless the tokenization of the strings are indeed the bottleneck of the application determined by proper profiling, I feel that it will end up being a premature optimization, if anything. I would be inclined to say write code that is meaningful and easy to understand before venturing on optimization.*
Now, from the current requirements, probably rolling our own tokenizer wouldn't be too difficult.
**Roll our own tokenzier!**
The following is a simple tokenizer I wrote. I should note that there are no speed optimizations, nor is there error-checks to prevent going past the end of the string -- this is a quick-and-dirty implementation:
```
class MyTokenizer implements Iterable<String>, Iterator<String> {
String delim = ",";
String s;
int curIndex = 0;
int nextIndex = 0;
boolean nextIsLastToken = false;
public MyTokenizer(String s, String delim) {
this.s = s;
this.delim = delim;
}
public Iterator<String> iterator() {
return this;
}
public boolean hasNext() {
nextIndex = s.indexOf(delim, curIndex);
if (nextIsLastToken)
return false;
if (nextIndex == -1)
nextIsLastToken = true;
return true;
}
public String next() {
if (nextIndex == -1)
nextIndex = s.length();
String token = s.substring(curIndex, nextIndex);
curIndex = nextIndex + 1;
return token;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
```
The `MyTokenizer` will take a `String` to tokenize and a `String` as a delimiter, and use the `String.indexOf` method to perform the search for delimiters. Tokens are produced by the `String.substring` method.
I would suspect there could be some performance improvements by working on the string at the `char[]` level rather than at the `String` level. But I'll leave that up as an exercise to the reader.
The class also implements [`Iterable`](http://java.sun.com/javase/6/docs/api/java/lang/Iterable.html) and [`Iterator`](http://java.sun.com/javase/6/docs/api/java/util/Iterator.html) in order to take advantage of the `for-each` loop construct that was introduced in Java 5. `StringTokenizer` is an `Enumerator`, and does not support the `for-each` construct.
**Is it any faster?**
In order to find out if this is any faster, I wrote a program to compare speeds in the following four methods:
1. Use of `StringTokenizer`.
2. Use of the new `MyTokenizer`.
3. Use of `String.split`.
4. Use of precompiled regular expression by [`Pattern.compile`](http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html#compile(java.lang.String)).
In the four methods, the string `"dog,,cat"` was separated into tokens. Although the `StringTokenizer` is included in the comparison, it should be noted that it will not return the desired result of `["dog", "", "cat]`.
The tokenizing was repeated for a total of 1 million times to give take enough time to notice the difference in the methods.
The code used for the simple benchmark was the following:
```
long st = System.currentTimeMillis();
for (int i = 0; i < 1e6; i++) {
StringTokenizer t = new StringTokenizer("dog,,cat", ",");
while (t.hasMoreTokens()) {
t.nextToken();
}
}
System.out.println(System.currentTimeMillis() - st);
st = System.currentTimeMillis();
for (int i = 0; i < 1e6; i++) {
MyTokenizer mt = new MyTokenizer("dog,,cat", ",");
for (String t : mt) {
}
}
System.out.println(System.currentTimeMillis() - st);
st = System.currentTimeMillis();
for (int i = 0; i < 1e6; i++) {
String[] tokens = "dog,,cat".split(",");
for (String t : tokens) {
}
}
System.out.println(System.currentTimeMillis() - st);
st = System.currentTimeMillis();
Pattern p = Pattern.compile(",");
for (int i = 0; i < 1e6; i++) {
String[] tokens = p.split("dog,,cat");
for (String t : tokens) {
}
}
System.out.println(System.currentTimeMillis() - st);
```
**The Results**
The tests were run using Java SE 6 (build 1.6.0\_12-b04), and results were the following:
```
Run 1 Run 2 Run 3 Run 4 Run 5
----- ----- ----- ----- -----
StringTokenizer 172 188 187 172 172
MyTokenizer 234 234 235 234 235
String.split 1172 1156 1171 1172 1156
Pattern.compile 906 891 891 907 906
```
So, as can be seen from the limited testing and only five runs, the `StringTokenizer` did in fact come out the fastest, but the `MyTokenizer` came in as a close 2nd. Then, `String.split` was the slowest, and the precompiled regular expression was slightly faster than the `split` method.
As with any little benchmark, it probably isn't very representative of real-life conditions, so the results should be taken with a grain (or a mound) of salt. | Replicating String.split with StringTokenizer | [
"",
"java",
"performance",
"string",
"split",
"stringtokenizer",
""
] |
I'm building a C# app that will likely contain a couple resource files to store strings for use in language translation. I'm trying to come up with a naming convention for the Keys in my resouce files. Has anyone tackled this before me? | Just use Pascal naming convention. Dont attribute the key to a module or the class. Generalize it so that it can be reused.
Eg: ReadWriteWarningMessage
The dot separated convention works fine for menu items. But what about strings that are generated dynamically or user messages. | See <https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-resources>. As @bobbyalex has said, this includes using PascalCasing, since the generated resource designer file does implement the resources as properties.
> ✔️ DO use PascalCasing in resource keys.
>
> ✔️ DO provide descriptive rather than short identifiers.
>
> ❌ DO NOT use language-specific keywords of the main CLR languages.
>
> ✔️ DO use only alphanumeric characters and underscores in naming resources.
>
> ✔️ DO use the following naming convention for exception message resources.
>
> The resource identifier should be the exception type name plus a short identifier of the exception:
>
> `ArgumentExceptionIllegalCharacters` `ArgumentExceptionInvalidName` `ArgumentExceptionFileNameIsMalformed` | Resource (.resx) file Key naming conventions? | [
"",
"c#",
"resources",
"naming-conventions",
"translation",
""
] |
I have a vector that stores pointers to many objects instantiated dynamically, and I'm trying to iterate through the vector and remove certain elements (remove from vector and destroy object), but I'm having trouble. Here's what it looks like:
```
vector<Entity*> Entities;
/* Fill vector here */
vector<Entity*>::iterator it;
for(it=Entities.begin(); it!=Entities.end(); it++)
if((*it)->getXPos() > 1.5f)
Entities.erase(it);
```
When any of the Entity objects get to xPos>1.5, the program crashes with an assertion error...
Anyone know what I'm doing wrong?
I'm using VC++ 2008. | You need to be careful because [`erase()`](http://en.cppreference.com/w/cpp/container/vector/erase) will invalidate existing iterators. However, it will return a new valid iterator you can use:
```
for ( it = Entities.begin(); it != Entities.end(); ) {
if( (*it)->getXPos() > 1.5f ) {
delete * it;
it = Entities.erase(it);
}
else {
++it;
}
}
``` | The "right" way to do this is using an algorithm:
```
#include <algorithm>
#include <functional>
// this is a function object to delete a pointer matching our criteria.
struct entity_deleter
{
void operator()(Entity*& e) // important to take pointer by reference!
{
if (e->GetXPos() > 1.5f)
{
delete e;
e = NULL;
}
}
// now, apply entity_deleter to each element, remove the elements that were deleted,
// and erase them from the vector
for_each(Entities.begin(), Entities.end(), entity_deleter());
vector<Entity*>::iterator new_end = remove(Entities.begin(), Entities.end(), static_cast<Entity*>(NULL));
Entities.erase(new_end, Entities.end());
```
Now I know what you're thinking. You're thinking that some of the other answers are shorter.
But, (1) this method typically compiles to faster code -- try comparing it, (2) this is the "proper" STL way, (3) there's less of a chance for silly errors, and (4) it's easier to read once you can read STL code. It's well worth learning STL programming, and I suggest you check Scott Meyer's great book "Effective STL" which has loads of STL tips on this kind of stuff.
Another important point is that by not erasing elements until the end of the operation, the elements don't need to be shuffled around. GMan was suggesting to use a list to avoid this, but using this method, the entire operation is O(n). Neil's code above, in contrast, is O(n^2), since the search is O(n) and removal is O(n). | How to erase & delete pointers to objects stored in a vector? | [
"",
"c++",
"visual-c++",
"vector",
"iterator",
"erase",
""
] |
I am making a small project for myself that deals with gps and some other cool stuff on WM6 in C#. I am just wondering, is it better to read from a file when you need to access the data or is it better to just read the whole file into the program and deal with it then? Mainly, I am talking about locations that I will save within some type of file/database, not quite sure which one yet. These locations will need to be looped over frequently and that's why I think I should read the whole file in and then write back to it later, but how much data becomes too much? Are there any efficiency issues that could arise from reading in lots of data from a file opposed to the obvious efficiency issues from reading the next value from a file as needed?
It doesn't really make too much difference at this stage since I will probably never get lots and lots of data, but it is good to think about scalability at some stage I suppose.
Cheers | Shane is right on the mark, store the data in a SQLCE database and use paramatized querys to access what you need from there.
As for memory usage, WM6 (and 6.5) is based on WinCE 5.something
WinCE 5.\* has this annoying design where there is no concept of virtual memory, memory is split up into 32mb slots and applications are only allocated a single slot - in effect your application can only use 32mb of memory. Sure there are hacks out there to get around this but this is still a fundamental limit.
You really dont need to be too concerned about using too much memory - always call dispose, only keep around what you need to keep around, and learning how to use '.NETCF Remote Performance Monitor' which has saved my a$$ on ocassion. | I would recommend some sort of database. No matter what the platform, it just makes things easier.
I can look into [SQL Server Compact](http://www.microsoft.com/Sqlserver/2005/en/us/compact.aspx) or Windows Mobile [EDB](http://msdn.microsoft.com/en-us/library/aa916024.aspx) database api. The SQL Server Compact is most likely to be easier to use in C#. | Best way to handle data within windows mobile 6 program | [
"",
"c#",
"windows-mobile",
""
] |
I have these data transfer objects:
```
public class Report
{
public int Id { get; set; }
public int ProjectId { get; set; }
//and so on for many, many properties.
}
```
I don't want to write
```
public bool areEqual(Report a, Report b)
{
if (a.Id != b.Id) return false;
if (a.ProjectId != b.ProjectId) return false;
//Repeat ad nauseum
return true;
}
```
Is there a faster way to test if two object with only properties have the same values (something that doesn't require one line of code or one logical expression per property?)
Switching to structs is not an option. | How about some reflection, perhaps using `Expression.Compile()` for performance? (note the static ctor here ensures we only compile it once per `T`):
```
using System;
using System.Linq.Expressions;
public class Report {
public int Id { get; set; }
public int ProjectId { get; set; }
static void Main() {
Report a = new Report { Id = 1, ProjectId = 13 },
b = new Report { Id = 1, ProjectId = 13 },
c = new Report { Id = 1, ProjectId = 12 };
Console.WriteLine(PropertyCompare.Equal(a, b));
Console.WriteLine(PropertyCompare.Equal(a, c));
}
}
static class PropertyCompare {
public static bool Equal<T>(T x, T y) {
return Cache<T>.Compare(x, y);
}
static class Cache<T> {
internal static readonly Func<T, T, bool> Compare;
static Cache() {
var props = typeof(T).GetProperties();
if (props.Length == 0) {
Compare = delegate { return true; };
return;
}
var x = Expression.Parameter(typeof(T), "x");
var y = Expression.Parameter(typeof(T), "y");
Expression body = null;
for (int i = 0; i < props.Length; i++) {
var propEqual = Expression.Equal(
Expression.Property(x, props[i]),
Expression.Property(y, props[i]));
if (body == null) {
body = propEqual;
} else {
body = Expression.AndAlso(body, propEqual);
}
}
Compare = Expression.Lambda<Func<T, T, bool>>(body, x, y)
.Compile();
}
}
}
```
---
Edit: updated to handle fields too:
```
static class MemberCompare
{
public static bool Equal<T>(T x, T y)
{
return Cache<T>.Compare(x, y);
}
static class Cache<T>
{
internal static readonly Func<T, T, bool> Compare;
static Cache()
{
var members = typeof(T).GetProperties(
BindingFlags.Instance | BindingFlags.Public)
.Cast<MemberInfo>().Concat(typeof(T).GetFields(
BindingFlags.Instance | BindingFlags.Public)
.Cast<MemberInfo>());
var x = Expression.Parameter(typeof(T), "x");
var y = Expression.Parameter(typeof(T), "y");
Expression body = null;
foreach(var member in members)
{
Expression memberEqual;
switch (member.MemberType)
{
case MemberTypes.Field:
memberEqual = Expression.Equal(
Expression.Field(x, (FieldInfo)member),
Expression.Field(y, (FieldInfo)member));
break;
case MemberTypes.Property:
memberEqual = Expression.Equal(
Expression.Property(x, (PropertyInfo)member),
Expression.Property(y, (PropertyInfo)member));
break;
default:
throw new NotSupportedException(
member.MemberType.ToString());
}
if (body == null)
{
body = memberEqual;
}
else
{
body = Expression.AndAlso(body, memberEqual);
}
}
if (body == null)
{
Compare = delegate { return true; };
}
else
{
Compare = Expression.Lambda<Func<T, T, bool>>(body, x, y)
.Compile();
}
}
}
}
``` | **Originally answered at ([question 1831747](https://stackoverflow.com/questions/1831747/is-there-a-better-way-to-implment-equals-for-object-with-lots-of-fields))**
Check out my [MemberwiseEqualityComparer](http://www.freakcode.com/projects/memberwiseequalitycomparer) to see if it fits your needs.
It's really easy to use and quite efficient too. It uses IL-emit to generate the entire Equals and GetHashCode function on the first run (once for each type used). It will compare each field (private or public) of the given object using the default equality comparer for that type (EqualityComparer.Default). We've been using it in production for a while and it seems stable but I'll leave no guarantees =)
It takes care of all those pescy edge-cases that you rarely think of when you're rolling your own equals method (ie, you can't comparer your own object with null unless you've boxed it in an object first and lot's off more null-related issues).
I've been meaning to write a blog post about it but haven't gotten around to it yet. The code is a bit undocumented but if you like it I could clean it up a bit.
```
public override int GetHashCode()
{
return MemberwiseEqualityComparer<Foo>.Default.GetHashCode(this);
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
return Equals(obj as Foo);
}
public override bool Equals(Foo other)
{
return MemberwiseEqualityComparer<Foo>.Default.Equals(this, other);
}
```
The MemberwiseEqualityComparer is released under the [MIT license](http://en.wikipedia.org/wiki/MIT_License) meaining you can do pretty much whatever you want with it, including using it in proprietary solutions without changing you licensing a bit. | How to quickly check if two data transfer objects have equal properties in C#? | [
"",
"c#",
"equals",
"dto",
""
] |
I have a multithreaded app that has to read some data often, and occasionally that data is updated. Right now a mutex keeps access to that data safe, but it's expensive because I would like multiple threads to be able to read simultaneously, and only lock them out when an update is needed (the updating thread could wait for the other threads to finish).
I think this is what `boost::shared_mutex` is supposed to do, but I'm not clear on how to use it, and haven't found a clear example.
Does anyone have a simple example I could use to get started? | It looks like you would do something like this:
```
boost::shared_mutex _access;
void reader()
{
// get shared access
boost::shared_lock<boost::shared_mutex> lock(_access);
// now we have shared access
}
void writer()
{
// get upgradable access
boost::upgrade_lock<boost::shared_mutex> lock(_access);
// get exclusive access
boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
// now we have exclusive access
}
``` | 1800 INFORMATION is more or less correct, but there are a few issues I wanted to correct.
```
boost::shared_mutex _access;
void reader()
{
boost::shared_lock< boost::shared_mutex > lock(_access);
// do work here, without anyone having exclusive access
}
void conditional_writer()
{
boost::upgrade_lock< boost::shared_mutex > lock(_access);
// do work here, without anyone having exclusive access
if (something) {
boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock);
// do work here, but now you have exclusive access
}
// do more work here, without anyone having exclusive access
}
void unconditional_writer()
{
boost::unique_lock< boost::shared_mutex > lock(_access);
// do work here, with exclusive access
}
```
Also Note, unlike a shared\_lock, only a single thread can acquire an upgrade\_lock at one time, even when it isn't upgraded (which I thought was awkward when I ran into it). So, if all your readers are conditional writers, you need to find another solution. | Example for boost shared_mutex (multiple reads/one write)? | [
"",
"c++",
"multithreading",
"boost",
"mutex",
"boost-thread",
""
] |
Why can't we have static method in a non-static inner class?
```
public class Foo {
class Bar {
static void method() {} // Compiler error
}
}
```
If I make the inner class static it works. Why?
```
public class Foo {
static class Bar { // now static
static void method() {}
}
}
```
In Java 16+, both of these are valid. | Because an instance of an inner class is implicitly associated with an instance of its outer class, it cannot define any static methods itself. Since a static nested class cannot refer directly to instance variables or methods defined in its enclosing class, it can use them only through an object reference, it's safe to declare static methods in a static nested class. | There's not much point to allowing a static method in a non-static inner class; how would you access it? You cannot access (at least initially) a non-static inner class instance without going through an outer class instance. There is no purely static way to create a non-static inner class.
For an outer class `Outer`, you can access a static method `test()` like this:
```
Outer.test();
```
For a static inner class `Inner`, you can access its static method `innerTest()` like this:
```
Outer.Inner.innerTest();
```
However, if `Inner` is not static, there is now no purely static way to reference the method `innertest`. Non-static inner classes are tied to a specific instance of their outer class. A function is different from a constant, in that a reference to `Outer.Inner.CONSTANT` is guaranteed to be unambiguous in a way that a function call `Outer.Inner.staticFunction();` is not. Let's say you have `Inner.staticFunction()` that calls `getState()`, which is defined in `Outer`. If you try to invoke that static function, you now have an ambiguous reference to the Inner class. That is, on which instance of the inner class do you invoke the static function? It matters. See, there is no truly static way to reference that static method, due to the implicit reference to the outer object.
Paul Bellora is correct that the language designers could have allowed this. They would then have to carefully disallow any access to the implicit reference to the outer class in static methods of the non-static inner class. At this point, what is the value to this being an inner class if you cannot reference the outer class, except statically? And if static access is fine, then why not declare the whole inner class static? If you simply make the inner class itself static, then you have no implicit reference to the outer class, and you no longer have this ambiguity.
If you actually **need** static methods on a non-static inner class, then you probably need to rethink your design. | Why can't we have static method in a (non-static) inner class (pre-Java 16)? | [
"",
"java",
"class",
"static",
"inner-classes",
""
] |
This first script gets called several times for each user via an AJAX request. It calls another script on a different server to get the last line of a text file. It works fine, but I think there is a lot of room for improvement but I am not a very good PHP coder, so I am hoping with the help of the community I can optimize this for speed and efficiency:
**AJAX POST Request made to this script**
```
<?php session_start();
$fileName = $_POST['textFile'];
$result = file_get_contents($_SESSION['serverURL']."fileReader.php?textFile=$fileName");
echo $result;
?>
```
**It makes a GET request to this external script which reads a text file**
```
<?php
$fileName = $_GET['textFile'];
if (file_exists('text/'.$fileName.'.txt')) {
$lines = file('text/'.$fileName.'.txt');
echo $lines[sizeof($lines)-1];
}
else{
echo 0;
}
?>
```
I would appreciate any help. I think there is more improvement that can be made in the first script. It makes an expensive function call (file\_get\_contents), well at least I think its expensive! | This script should limit the locations and file types that it's going to return.
Think of somebody trying this:
<http://www.yoursite.com/yourscript.php?textFile=../../../etc/passwd> (or something similar)
Try to find out where delays occur.. does the HTTP request take long, or is the file so large that reading it takes long.
If the request is slow, try caching results locally.
If the file is huge, then you could set up a cron job that extracts the last line of the file at regular intervals (or at every change), and save that to a file that your other script can access directly. | [readfile](http://www.php.net/readfile) is your friend here
it reads a file on disk and streams it to the client.
script 1:
```
<?php
session_start();
// added basic argument filtering
$fileName = preg_replace('/[^A-Za-z0-9_]/', '', $_POST['textFile']);
$fileName = $_SESSION['serverURL'].'text/'.$fileName.'.txt';
if (file_exists($fileName)) {
// script 2 could be pasted here
//for the entire file
//readfile($fileName);
//for just the last line
$lines = file($fileName);
echo $lines[count($lines)-1];
exit(0);
}
echo 0;
?>
```
This script could further be improved by adding caching to it. But that is more complicated.
The **very** basic caching could be.
script 2:
```
<?php
$lastModifiedTimeStamp filemtime($fileName);
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
$browserCachedCopyTimestamp = strtotime(preg_replace('/;.*$/', '', $_SERVER['HTTP_IF_MODIFIED_SINCE']));
if ($browserCachedCopyTimestamp >= $lastModifiedTimeStamp) {
header("HTTP/1.0 304 Not Modified");
exit(0);
}
}
header('Content-Length: '.filesize($fileName));
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 604800)); // (3600 * 24 * 7)
header('Last-Modified: '.date('D, d M Y H:i:s \G\M\T', $lastModifiedTimeStamp));
?>
``` | How can I optimize this simple PHP script? | [
"",
"php",
"optimization",
"file",
"performance",
""
] |
I am thinking of using [wxMathPlot](http://wxmathplot.sourceforge.net/index.shtml) for plotting/graphing some data that arrives continuously. I want to draw "Real-time" plot/graph using it. Is that possible?
I.E. I don't want just a static graph of a one-time read of a file - I want the streaming data plotted and continued out to the right of the graph - (and let the left side fall off/scroll out of view)
EDIT
I still have not gotten an answer for this. There is an interesting class in the wxmathPlot library called mpFXYVector but that appears just to draw one plot from a vector of data. What I want is something that can be fed a stream and scroll the graph horizontally (and also resize the scale if needed) | I think mpFXYVector is the way to go.
The simplest way to deal with this might be to write a wrapper class for mpFXYVector which holds a FIFO buffer of recent data points. Each time a new datapoint arrives, add it to the FIFO buffer, which will drop the oldest point, then load mpFXYVector with the updated buffer. The wxMathPlot class mpWindow will look after the rest of what you need.
A more elegant approach would be a specialization of mpFXYVector which implements the FIFO buffer, using the simple vectors in mpFXYVector. The advantage of this would be that you are holding just one copy of the display data. Unless you are displaying many thousands of points, I doubt the advantage is worth the extra trouble of inheriting from mpFXYVector, rather than simply using the mpFXYVector documented interface.
After looking at the details, the only tricky bit is to replace mpFXYVector::SetData() with a new method Add() to add data points as they arrive. The new method needs to manage the mpFXYVector vectors as FIFO buffers, and to re-implement the code to update the bounding box ( which unfortunately was not written with inheritance in mind ).
The result is that specialization gives a solution with a smaller memory requirement and more flexibility than using a wrapper. | Thanks ravenspoint...!! I did what you said.. It works flawless!
here is my AddData() function:
```
void mpFXYVector::AddData(float x, float y, std::vector<double> &xs, std::vector<double> &ys)
{
// Check if the data vectora are of the same size
if (xs.size() != ys.size()) {
wxLogError(_("wxMathPlot error: X and Y vector are not of the same length!"));
return;
}
//Delete first point if you need a filo buffer (i dont need it)
//xs.erase(xs.begin());
//xy.erase(xy.begin());
//Add new Data points at the end
xs.push_back(x);
ys.push_back(y);
// Copy the data:
m_xs = xs;
m_ys = ys;
// Update internal variables for the bounding box.
if (xs.size()>0)
{
m_minX = xs[0];
m_maxX = xs[0];
m_minY = ys[0];
m_maxY = ys[0];
std::vector<double>::const_iterator it;
for (it=xs.begin();it!=xs.end();it++)
{
if (*it<m_minX) m_minX=*it;
if (*it>m_maxX) m_maxX=*it;
}
for (it=ys.begin();it!=ys.end();it++)
{
if (*it<m_minY) m_minY=*it;
if (*it>m_maxY) m_maxY=*it;
}
m_minX-=0.5f;
m_minY-=0.5f;
m_maxX+=0.5f;
m_maxY+=0.5f;
}
else
{
m_minX = -1;
m_maxX = 1;
m_minY = -1;
m_maxY = 1;
}
}
```
in the Main() you only have to:
```
m_Vector->AddData(xPos,yPos,vectorX, vectorY);
m_plot->Fit();
``` | How can I make "real-time" plots with wxMathPlot? | [
"",
"c++",
"wxwidgets",
"plot",
"graphing",
"wxmathplot",
""
] |
im trying to resize bufferdImage in memory in java but to keep the aspect ratio of the image
im have something like this but this is not good
```
int w = picture.getWidth();
int h = picture.getWidth();
int neww=w;
int newh=h;
int wfactor = w;
int hfactor = h;
if(w > DEFULT_PICTURE_WIDTH || h > DEFULT_PICTURE_HIGHT)
{
while(neww > DEFULT_PICTURE_WIDTH)
{
neww = wfactor /2;
newh = hfactor /2;
wfactor = neww;
hfactor = newh;
}
}
picture = Utils.resizePicture(picture,neww,newh);
``` | You may have a look at [perils-of-image-getscaledinstance.html](https://community.oracle.com/docs/DOC-983611 "perils-of-image-getscaledinstance.html") that explains why `getScaledInstance()`, used in some of the answers, should be avoided.
The article also provides alternative code. | Adding to Erik's point about getScaledInstance, if you moved away from it to using the recommended scaling mechanisms in Java2D, you might have noticed that your images look noticeably worse.
The reason for that is when the Java2D discouraged use of getScaledInstance and AreaAveragingScaleFilter, they didn't replace it with anything *as easy* to use in the API, instead we were left to our own devices using Java2D APIs directly. Fortunately, Chris Campbell (from the J2D team) followed up with the recommendation of using an incremental scaling technique that gives similar looking results to AreaAveragingScaleFilter and runs faster; unfortunately the code is of a decent size and doesn't address your original question of honoring proportions.
About 6 months ago I saw all these questions on SO again and again about "scaling images in Java" and eventually collected all the advice, did all the digging and research I could, and compiled all of into a single "best practices" [image scaling library](https://github.com/thebuzzmedia/imgscalr).
The API is dead simple as it is only 1 class and a bunch of static methods. Basic use looks like this:
```
BufferedImage img = ImageIO.read(...); // load image
BufferedImage scaledImg = Scalr.resize(img, 320);
```
This is the [simplest call](http://www.thebuzzmedia.com/downloads/software/imgscalr/javadoc/com/thebuzzmedia/imgscalr/Scalr.html#resize%28java.awt.image.BufferedImage,%20int%29) where the library will make a best-guess at the quality, honor your image proportions, and fit the result within a 320x320 bounding box. NOTE, the bounding box is just the maximum W/H used, since your image proportions are honored, the resulting image would still honor that, say 320x200.
If you want to override the automatic mode and force it to give you the best-looking result and even apply a very mild anti-alias filter to the result so it looks even better (especially good for thumbnails), that call would look like:
```
BufferedImage img = ImageIO.read(...); // load image
BufferedImage scaledImg = Scalr.resize(img, Method.QUALITY,
150, 100, Scalr.OP_ANTIALIAS);
```
These are all just examples, the API is broad and covers everything from super-simple use cases to very specialized. You can even pass in your own BufferedImageOps to be applied to the image (and the library automatically fixes the 6-year BufferedImageOp JDK bug for you!)
There is a lot more to scaling images in Java successfully that the library does for you, for example always keeping the image in one of the best supported RGB or ARGB image types while operating on it. Under the covers the Java2D image processing pipeline falls back to an inferior software pipeline if the image type used for any image operations is poorly supported.
If all that sounded like a lot of headache, it sort of is... that's why I wrote the library and open sourced it, so folks could just resize their images and move on with their lives without needing to worry about it. | Resize image while keeping aspect ratio in Java | [
"",
"java",
"image",
"resize",
""
] |
I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z
and incrementing a counter?
**Update** (in reference to [Anthony's answer](https://stackoverflow.com/questions/991350/counting-repeated-characters-in-a-string-in-python/991372#991372)): Whatever you have suggested till now I have to write 26 times. Is there an easier way? | My first idea was to do this:
```
chars = "abcdefghijklmnopqrstuvwxyz"
check_string = "i am checking this string to see how many times each character appears"
for char in chars:
count = check_string.count(char)
if count > 1:
print char, count
```
This is not a good idea, however! This is going to scan the string 26 times, so you're going to potentially do 26 times more work than some of the other answers. You really should do this:
```
count = {}
for s in check_string:
if s in count:
count[s] += 1
else:
count[s] = 1
for key in count:
if count[key] > 1:
print key, count[key]
```
This ensures that you only go through the string once, instead of 26 times.
**Also, Alex's answer is a great one - I was not familiar with the collections module. I'll be using that in the future. His answer is more concise than mine is and technically superior. I recommend using his code over mine.** | ```
import collections
d = collections.defaultdict(int)
for c in thestring:
d[c] += 1
```
A `collections.defaultdict` is like a `dict` (subclasses it, actually), but when an entry is sought and not found, instead of reporting it doesn't have it, it makes it and inserts it by calling the supplied 0-argument callable. Most popular are `defaultdict(int)`, for counting (or, equivalently, to make a multiset AKA bag data structure), and `defaultdict(list)`, which does away forever with the need to use `.setdefault(akey, []).append(avalue)` and similar awkward idioms.
So once you've done this `d` is a dict-like container mapping every character to the number of times it appears, and you can emit it any way you like, of course. For example, most-popular character first:
```
for c in sorted(d, key=d.get, reverse=True):
print '%s %6d' % (c, d[c])
``` | Counting repeated characters in a string in Python | [
"",
"python",
""
] |
I am attempting to call into a native .dll from c# using p/invoke. I'm able to make the call (no crash, the function returns a value), but the return code indicates "A pointer parameter does not point to accessible memory." I've resorted to trial and error in order to solve this, but I haven't made any progress so far.
Here's the signature of the native function I'm calling:
```
LONG extern WINAPI MyFunction ( LPSTR lpszLogicalName, //input
HANDLE hApp, //input
LPSTR lpszAppID, //input
DWORD dwTraceLevel, //input
DWORD dwTimeOut, //input
DWORD dwSrvcVersionsRequired, //input
LPWFSVERSION lpSrvcVersion, //WFSVERSION*, output
LPWFSVERSION lpSPIVersion, //WFSVERSION*, output
LPHSERVICE lphService //unsigned short*, output
);
```
Here's the imported signature in C#:
```
[DllImport("my.dll")]
public static extern int MyFunction( [MarshalAs(UnmanagedType.LPStr)]
string logicalName,
IntPtr hApp,
[MarshalAs(UnmanagedType.LPStr)]
string appID,
int traceLevel,
int timeout,
int srvcVersionsRequired,
[Out] WFSVersion srvcVersion,
[Out] WFSVersion spiVersion,
[Out] UInt16 hService
);
```
Here's the C definition of WFSVERSION:
```
typedef struct _wfsversion
{
WORD wVersion;
WORD wLowVersion;
WORD wHighVersion;
CHAR szDescription[257];
CHAR szSystemStatus[257];
} WFSVERSION, * LPWFSVERSION;
```
Here's the C# definition of WFSVersion:
```
[StructLayout(LayoutKind.Sequential)]
public class WFSVersion
{
public Int16 wVersion;
public Int16 wLowVersion;
public Int16 wHighVersion;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 257)]
public char[] szDescription;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 257)]
public char[] szSystemStatus;
}
```
Here's the call to MyFunction from C#:
```
WFSVersion srvcVersionInfo = new WFSVersion();
WFSVersion spiVersionInfo = new WFSVersion();
UInt16 hService = 0;
IntPtr hApp = IntPtr.Zero;
string logicalServiceName = tbServiceName.Text;
int openResult = MyFunction(logicalServiceName, hApp, null, 0,
XFSConstants.WFS_INDEFINITE_WAIT,
0x00000004, srvcVersionInfo, spiVersionInfo,
hService);
```
As I said, this call returns, but the return value is an error code indicating "A pointer parameter does not point to accessible memory." I must be doing something wrong with parameters 1,3,7,8, or 9. However, I've made successful calls to other functions in this .dll which required WFSVERSION\* as parameters, so I don't think parameters 7 or 8 are the issue here.
I would appreciate any thoughts you might have about the cause of this issue, or any constructive criticisms of my code. This is my first experience with P/Invoke, so I'm not sure where to begin. Is there any way to narrow down the issue, or is trial an error my only option? | You have two obvious errors here. In your struct definition you should be using byte[] instead of char[] for szDescription and szSystemStatus.
Also the last parameter in your pInvoke call is not a pointer. When you make your call to MyFunction hService is zero and therefore an invalid pointer as far as the function is concerned. [Out] is a Marshaling directive telling the runtime when and where to copy data not an indicator that the parameter is a pointer. What you need is to change [Out] to out or ref this tells the runtime that hService is a pointer:
```
[DllImport("my.dll")]
public static extern int MyFunction( [MarshalAs(UnmanagedType.LPStr)]
string logicalName,
IntPtr hApp,
[MarshalAs(UnmanagedType.LPStr)]
string appID,
int traceLevel,
int timeout,
int srvcVersionsRequired,
[Out] WFSVersion srvcVersion,
[Out] WFSVersion spiVersion,
out UInt16 hService);
``` | Some ideas:
* The C# WFSVersion class should probably be a `struct`. I don't know if the P/Invoke marshaller cares, but I've always seen structs used.
* Character size might be an issue.
C's CHAR is 8 bits wide (ANSI), and .Net's System.Char is 16 bits wide (Unicode). To give the marshaller as much info as possible so it does the correct conversion, try adding "CharSet = CharSet.Ansi" to the DllImport and StructLayout attributes, and changing the string declarations in WFSVersion:
```
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 257)]
public string szDescription;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 257)]
public string szSystemStatus;
```
* Another issue could be data alignment in the structs. If no alignment was specified when the C struct was compiled, the data elements in the struct were probably aligned on a one or two byte boundary. Try using `Pack` in WFSVersion's StructLayout attribute:
```
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
// Try pack values of 2, 4 and 8 if 1 doesn't work.
```
And some questions:
* Was MyFunction intended to be called from non-C code? The original author may have written code that assumes the data passed in is allocated with the C runtime memory manager.
* Does code in the C DLL use the pointers passed to it for later processing after MyFunction has returned? If so - and assuming it's possible/wise/sane to go forward with such a situation - it may be necessary to "pin" the structs passed to MyFunction using the `fixed` keyword. Plus there are probably security issues to deal with. | c# p/invoke difficulties marshalling pointers | [
"",
"c#",
"pointers",
"interop",
"pinvoke",
""
] |
I need to get a reference to the FORM parent of an INPUT when I only have a reference to that INPUT. Is this possible with JavaScript? Use jQuery if you like.
```
function doSomething(element) {
//element is input object
//how to get reference to form?
}
```
This doesn't work:
```
var form = $(element).parents('form:first');
alert($(form).attr("name"));
``` | Native DOM elements that are inputs also have a `form` attribute that points to the form they belong to:
```
var form = element.form;
alert($(form).attr('name'));
```
According to [w3schools](http://www.w3schools.com/jsref/dom_obj_text.asp), the `.form` property of input fields is supported by IE 4.0+, Firefox 1.0+, Opera 9.0+, which is even more browsers that jQuery guarantees, so you should stick to this.
If this were a different type of element (not an `<input>`), you could find the closest parent with [`closest`](http://docs.jquery.com/Traversing/closest):
```
var $form = $(element).closest('form');
alert($form.attr('name'));
```
Also, see this MDN link on the `form` property of `HTMLInputElement`:
* <https://developer.mozilla.org/en/DOM/HTMLInputElement#Properties> | Every input has a `form` property which points to the form the input belongs to, so simply:
```
function doSomething(element) {
var form = element.form;
}
``` | How to get the containing form of an input? | [
"",
"javascript",
"jquery",
"forms",
"input",
""
] |
Possibly similar question:
[[Do you ever use the volatile keyword in Java?](https://stackoverflow.com/questions/106591/)](https://stackoverflow.com/questions/106591/)
---
Today I was debugging my game; It had a very difficult threading problem that would show up every few minutes, but was difficult to reproduce. So first I added the `synchronized` keyword to each of my methods. That didn't work. Then I added the `volatile` keyword to every field. The problem seemed to just fix itself.
After some experimentation I found that the field responsible was a `GameState` object which kept track of my game's current state, which can be either playing or busy. When busy, the game ignores user input. What I had was a thread that constantly changed the `state` variable, while the Event thread reads the `state` variable. However, after one thread changes the variable, it takes several seconds for the other thread to recognize the changes, which ultimately causes the problem.
It was fixed by making the state variable `volatile`.
Why aren't variables in Java `volatile` by default and what's a reason not to use the `volatile` keyword? | To make a long story short, volatile variables--be they in Java or C#--are never cached locally within the thread. This doesn't have much of an implication unless you're dealing with a multiprocessor/multicore CPU with threads executing on different cores, as they'd be looking at the same cache. When you declare a variable as volatile, all reads and writes come straight from and go straight to the actual main memory location; there's no cache involved. This has implications when it comes to optimization, and to do so unnecessarily (when most variables don't need to be volatile) would be inflicting a performance penalty (paltry as it may or may not be) for a relatively small gain. | Volatiles are really only needed when you're trying to write low-level thread-safe, lock-free code. Most of your code probably shouldn't be *either* thread-safe *or* lock-free. In my experience, lock-free programming is only worth attempting after you've found that the simpler version which *does* do locking is incurring a significant performance hit due to the locking.
The more pleasant alternative is to use other building blocks in `java.util.concurrent`, some of which are lock-free but don't mess with your head quite as much as trying to do it all yourself at a low level.
Volatility has its own performance costs, and there's no reason why *most* code should incur those costs. | Why aren't variables in Java volatile by default? | [
"",
"java",
"multithreading",
"volatile",
""
] |
I'm writing a service monitoring ASP .NET app and I'm having issues particularly with getting the service descriptions. My current method (reading from registry) is not going to work due to registry read permissions on the production server.
For example:
```
Microsoft.Win32.RegistryKey system, currentControlSet, services, service;
system = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("System");
currentControlSet = system.OpenSubKey("CurrentControlSet");
services = currentControlSet.OpenSubKey("Services");
service = services.OpenSubKey(scTemp.ServiceName, true);
row["service_description"] = service.GetValue("Description");
```
Produces:
> System.Security.SecurityException: Requested registry access is not allowed.
My question is:
Is there a work-around with another .NET class (maybe under System.ServiceProcess namespace?) or will it always end with a security exception error?
I have no issues getting Service names and states with the System.ServiceProcess namespace but I can't find any classes contained to get descriptions which is why I resorted to reading from registry. | I think this should work.
EDIT: I should read questions closer. The code below gets the description for the first service in the array.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
using System.Management;
namespace ServiceNames
{
class Program
{
static void Main(string[] args)
{
ServiceController[] services = ServiceController.GetServices();
string serviceName = services[0].ServiceName;
string objPath = string.Format("Win32_Service.Name='{0}'", serviceName);
using (ManagementObject service = new ManagementObject(new ManagementPath(objPath)))
{
Console.WriteLine(service["Description"]);
}
Console.Read();
}
}
}
``` | The previous answer showing the WMI solution is a good alternative and worth trying first.
--
I am not aware of a .NET Framework class that exposes the service description.
The first thing I would consider is requiring authenticated connections (e.g. NTLM) and impersonate the caller. As long as you don't do a double-hop (i.e. make a remote call with your impersonated credentials) you may find that you are able to successfully make the registery read.
If that is not possible then making a P/Invoke call may work.
If the credentials your web service has the SERVICE\_QUERY\_CONFIG permission you could do the following:
1. Find the service you are interested in using the ServiceController class
2. Using the ServiceHandle property make a P/Invoke call to QueryServiceConfig2 using the SERVICE\_CONFIG\_DESCRIPTION info level passing in null for the buffer and 0 for the lenght, reading the required buffer length from pcbBytesNeeded.
3. Allocate the proper buffer length and call QueryServiceConfig2 a second time getting the service description.
Obviously reading from the registery is a little more straight-forward (and in the end the permissions issues may be similar in both cases) - but using a supported API seems like a less fragile solution. | Get Windows Service Description ASP .NET | [
"",
"c#",
"asp.net",
""
] |
I was having a nice look at my STL options today. Then I thought of something.
It seems a linked list (a std::list) is only of limited use. Namely, it only really seems
useful if
* The sequential order of elements in my container matters, and
* I need to erase or insert elements in the middle.
That is, if I just want a lot of data and don't care about its order, I'm better off using an std::set (a balanced tree) if I want O(log n) lookup or a std::unordered\_map (a hash map) if I want O(1) expected lookup or a std::vector (a contiguous array) for better locality of reference, or a std::deque (a double-ended queue) if I need to insert in the front AND back.
OTOH, if the order does matter, I am better off using a std::vector for better locality of reference and less overhead or a std::deque if a lot of resizing needs to occur.
So, am I missing something? Or is a linked list just not that great? With the exception of middle insertion/erasure, why on earth would someone want to use one? | Any sort of insertion/deletion is O(1). Even std::vector isn't O(1) for appends, it approaches O(1) because most of the time it is, but sometimes you are going to have to grow that array.
It's also very good at handling bulk insertion, deletion. If you have 1 million records and want to append 1 million records from another list (concat) it's O(1). Every other structure (assuming stadard/naive implementations) are at least O(n) (where n is the number of elements added). | Order is important very often. When it is, linked lists are good. If you have a growing collection, you have the option of linked lists, array lists (`vector` in C++) and double-ended queues (`deque`). Use linked lists if you want to modify (add, delete) elements anywhere in the list often. Use array lists if fast retrieval is important. Use double-ended queues if you want to add stuff to both ends of the data structure and fast retrieval is important. For the `deque` vs `vector` question: use `vector` unless inserting/removing things from the beginning is important, in which case use `deque`. See [here](http://www.codeproject.com/KB/stl/vector_vs_deque.aspx) for an in-depth look at this.
If order isn't important, linked lists aren't normally ideal. | Is the linked list only of limited use? | [
"",
"c++",
"language-agnostic",
"container-data-type",
""
] |
I need to write a Windows XP/Vista application, main requirements:
* Just one .exe file, without extra runtime, like Air, .Net; posstibly a couple of dlls.
* **Very small file size**.
The application is for network centric usage, similar to ICQ or Gtalk clients. | It depends, I think, how much UI you require. The benefit of frameworks such as MFC is it wraps a lot of boiler plate code for you. However.. if executable size & dependencies are the major constraint, it can be quite fun to build a tiny app.
It's quite possible to build a Windows application with bare essentials (a dialog, etc) and make use of common dialog resources which will already be installed (e.g commdlg.dll).
To keep it as small as possible I'd recommend writing It with C++, preferably with the MSVC runtime for ease. The Win32 API is pretty easy to pick up in terms of the essential steps, e.g. registering windows and creating a message proc.
Can you be a bit more specific with what you'd like to know more about? | You can try: C++ w/ MFC. That's really going to be the only way you can seriously control the 'size' of your application (though why is that a constraint?).
If you want even lighterweight, you can try the [Windows Template Library](http://en.wikipedia.org/wiki/Windows_Template_Library) with C++. | Language to write a Windows application that doesn't take up a lot of space | [
"",
"c++",
"windows",
"user-interface",
"mfc",
"windows-xp",
""
] |
I need to generate random names which I'll be using to create temporary files in a directory. Currently I am using C standard function tempnam() for this. My code is in C++ and would like to use C++ equivalent for doing the same task. The code needs to work on Solaris as well as on Windows.
Is anyone aware of such thing in C++? Any pointer on this would be highly appreciated. | Try `std::tempnam` in the `cstdio` header. ;)
The C standard library is still available in C++ code. For convenience, they provide C++ wrappers (in headers with the 'c' prefix, and no extension), and available in the std namespace.
You can also use the plain C version (stdio.h and tempnam in the global namespace, but you did ask for the C++ version ;))
The C++ standard library only provides new functions when there's actually room for improvement. It has a string class, because a string class is an improvement over char pointers as C has. It has a vector class, because, well, it's useful.
For something like `tempnam`, what would C++ be able to bring to the party, that we didn't already have from C? So they didn't do anything about it, other than making the old version available. | I know this doesn't answer your question but as a side note, according to the man page:
> Although tempnam(3) generates names
> that are difficult to guess, it is
> nevertheless possible that between the
> time that tempnam(3) returns a
> pathname, and the time that the
> program opens it, another program
> might create that pathname using
> open(2), or create it as a symbolic
> link. This can lead to security
> holes. To avoid such possibilities,
> use the open(2) O\_EXCL flag to open
> the pathname. **Or better yet, use
> mkstemp(3) or tmpfile(3)**. | tempnam equivalent in C++ | [
"",
"c++",
"c",
""
] |
I have this string that I get back from Adobe Presenter 7. It's called suspend\_data and is of type CMIString4096 [(by the docs)](http://www.chrisfoster.com.au/blog/wp-content/uploads/2008/10/scorm.pdf)
> CMIString4096 A set of ASCII characters with a maximum length
> of 4096 characters.
This is the string:
> aG1111111000000000BB001EC%2EacC%7E%24GS%2AayjHm110BKCBBB0B0EBAB1B1ED%2EicC%7E%24GS%2AlfkHm110BKDBCB0B0EBBB0B0EBAB1B1EE%2EwcC%7E%24GS%2ACBlHm100BKDB2BCBCDB1BABBDB0BBBADF%2E7cC%7E%24GS%2A4GmHm110BKBB0Ebl%C3%A1rRbl%C3%A1r%3Bgr%C3%A6nn%3Brau%C3%B0urB
It looks like base64 with some urlencoded characters. When i urldecode() the string, the last few characters resemble some data but it's in utf8, then i utf8\_decode it and see this.
```
aG1111111000000000BB001EC.acC~$GS*ayjHm110BKCBBB0B0EBAB1B1ED.icC~$GS*
lfkHm110BKDBCB0B0EBBB0B0EBAB1B1EE.wcC~$GS*CBlHm100BKDB2BCBCDB1BABBDB0BBBADF.
7cC~$GS*4GmHm110BKBB0EblárRblár;grænn;rauðurB
```
Ok i'm closer to some data (at the end), but it still looks like it's a mess. When i base64\_decode() it i get some binary mess, but i don't know what on earth it is.
Does anyone know what this data is and how i can get some sense out of it? I'm using PHP btw so only functions within it are applicable. | The data stored in the cmi.suspend\_data field is simply a bucket of data that the SCO (the the content) can use to persist its current state. There is no semantic meaning or defined structure to the data. In many cases, the meaning of the data can be guessed at or reversed engineered, but that does not appear to be the case in with content produced by Adobe Presenter.
The suspend\_data field is limited to 4096 ASCII characters. For some SCOs this doesn't provide enough storage to fully persist the current state. In many cases, a content developer faced with this predicament will apply a compression algorithm to the state data in order to squeeze it into the limited size. It looks like that is what Adobe Presenter is doing here. My guess is that they compressed their data to the unencoded state that you found, then applied url encoding to ensure that all of the resulting characters were safe to send to the LMS.
The string of 1's and 0's at the start of the suspend data might be something meaningful. It could likely correspond to which of the slides in the course have been previously viewed by the learner. To verify this, it might be helpful to run the course through a tool like SCORM TestTrack (freely available at [scorm.com](http://www.scorm.com)) and use the generated debug logs to watch how the suspend data changes as the user progresses through the course.
SCORM provides quite a few other data model elements which do have a specific meaning relating to the current status of the course. Here is a [list of all available data model elements](http://www.scorm.com/scorm-explained/technical-scorm/run-time/run-time-reference/). The SCORM TestTrack debug logs will also show you which of those data model elements Adobe Presented content uses. | I don't think that SCORM defines what the suspend\_data field contains or in what format it is.
This is entirely up to the content/lesson (Adobe Presenter in your case), but it can only be text and is limited to 4096 characters.
This field can be used by the content to store any kind of state which should be passed back to the content the next time it is started. | What is CMIString4096 and how can I extract the data within it? | [
"",
"php",
"decode",
"scorm",
""
] |
I know that *interfaces cannot contain operators*, but is there a way I can **require** / tell the compiler that the + and / operators **will be** implemented by a certain class?
I want to do something like this:
```
public class AutoAverage<T> where T:(overloads + and /)
{
private List<T> history ; // 10-20 values
public T NextAvg( T newValue )
{
// implementation wants to push newValue
// into history, then sum
// values in history and return an average
}
}
``` | Unfortunately, that isn't currently possible in C#. | In cases like this, sometimes I will pass lambdas to the constructor:
```
public class AutoAverage<T>
{
public AutoAverage(Func<T, T, T> sum, Func<T, T, T> divide) { ...
```
And in usage:
```
var autoAverage = new AutoAverage((x, y) => x + y, (x, y) => x / y);
// ... use it ...
```
It's a bit ugly when you're doing binary operations like this (I've more often used it for single-argument functions, e.g. unit conversions), but it has the advantage of simplicity.
Whether that's a good solution in your case will depend, among other things, on how often you construct AutoAverage. If you only create it one or two places (for each T), then passing the lambdas wouldn't be that bad. If you construct it a whole bunch of places, the lambdas would be duplicated too much for comfort. | C# requiring operator overloading | [
"",
"c#",
""
] |
When is using a std::set more efficient (w.r.t. time) than using a std::vector along with `make_heap/push_/pop_` for the priority queue in an A\* operation? My guess is that if the vertices in the open list are small, using a vector is a better option. But does anyone have experience with this? | If i had to venture a guess? I'd guess that the vector version is probably a good choice because once it grows to a certain size, there won't be very many allocs.
But I don't like guessing. I prefer hard numbers. Try both, profile! | Use a priority queue. A binary heap based one is fine (like the vector based std priority queue). You can build the heap in O(n) time and all relevent operations take O(logn). In addition to that you can implement the decrease key operation which is useful for a\*. It might be tricky to implement for the std queue however. The only way to do that with a set is to remove the element and reinsert it with a different priority.
Edit: you might want to look into using
```
std::make_heap
```
(and related functions). That way you get access to the vector and can easily implement decrease\_key.
Edit 2: I see that you were intending on using make heap, so all you'd have to do is implement decrease key. | c++ set versus vector + heap operations for an A* priority queue | [
"",
"c++",
"stl",
"containers",
"a-star",
""
] |
I have a priority queue of events, but sometimes the event priorities change, so I'd like to maintain iterators from the event requesters into the heap. If the priority changes, I'd like the heap to be adjusted in log(n) time. I will always have exactly one iterator pointing to each element in the heap. | I'm happy to report that Boost has now added a [Boost.Heap library](http://www.boost.org/doc/libs/1_49_0/doc/html/heap.html) with some [stellar data structures](http://www.boost.org/doc/libs/1_49_0/doc/html/heap/data_structures.html).
The advantage of this is that Fibonacci heaps support changing priority in constant amortized time.
Unfortunately, all of the mutable heaps are node-based (in other words, they have extra indirection as suggested by @wilx). @Feruccio's answer of Boost's “mutable heaps” has code that allows one to write vector-based mutable heaps if you're willing to have pointers to handles contained in your value type. | Take a look at Boost's [mutable heaps](http://www.boost.org/doc/libs/1_39_0/boost/pending/mutable_heap.hpp). | Is there a heap class in C++ that supports changing the priority of elements other than the head? | [
"",
"c++",
"stl",
"boost",
"heap",
"priority-queue",
""
] |
Is there a way to tell if a thread has exited normally or because of an exception? | As mentioned, a wrapper around the Thread class could catch that state. Here's an example.
```
>>> from threading import Thread
>>> class MyThread(Thread):
def run(self):
try:
Thread.run(self)
except Exception as err:
self.err = err
pass # or raise err
else:
self.err = None
>>> mt = MyThread(target=divmod, args=(3, 2))
>>> mt.start()
>>> mt.join()
>>> mt.err
>>> mt = MyThread(target=divmod, args=(3, 0))
>>> mt.start()
>>> mt.join()
>>> mt.err
ZeroDivisionError('integer division or modulo by zero',)
``` | You could set some global variable to 0 if success, or non-zero if there was an exception. This is a pretty standard convention.
However, you'll need to protect this variable with a mutex or semaphore. Or you could make sure that only one thread will ever write to it and all others would just read it. | Python thread exit code | [
"",
"python",
"multithreading",
"exit-code",
""
] |
How do I format this date so that the alert displays the date in MM/dd/yyyy format?
```
<script type="text/javascript">
var date = new Date();
alert(date);
</script>
``` | You prototype a method so you never have to do this irritating task again:
```
Date.prototype.toFormattedString = function (f)
{
var nm = this.getMonthName();
var nd = this.getDayName();
f = f.replace(/yyyy/g, this.getFullYear());
f = f.replace(/yy/g, String(this.getFullYear()).substr(2,2));
f = f.replace(/MMM/g, nm.substr(0,3).toUpperCase());
f = f.replace(/Mmm/g, nm.substr(0,3));
f = f.replace(/MM\*/g, nm.toUpperCase());
f = f.replace(/Mm\*/g, nm);
f = f.replace(/mm/g, String(this.getMonth()+1).padLeft('0',2));
f = f.replace(/DDD/g, nd.substr(0,3).toUpperCase());
f = f.replace(/Ddd/g, nd.substr(0,3));
f = f.replace(/DD\*/g, nd.toUpperCase());
f = f.replace(/Dd\*/g, nd);
f = f.replace(/dd/g, String(this.getDate()).padLeft('0',2));
f = f.replace(/d\*/g, this.getDate());
return f;
};
```
*(and yes you could chain those replaces, but it's not here for readability before anyone asks)*
---
As requested, additional prototypes to support the above snippet.
```
Date.prototype.getMonthName = function ()
{
return this.toLocaleString().replace(/[^a-z]/gi,'');
};
//n.b. this is sooo not i18n safe :)
Date.prototype.getDayName = function ()
{
switch(this.getDay())
{
case 0: return 'Sunday';
case 1: return 'Monday';
case 2: return 'Tuesday';
case 3: return 'Wednesday';
case 4: return 'Thursday';
case 5: return 'Friday';
case 6: return 'Saturday';
}
};
String.prototype.padLeft = function (value, size)
{
var x = this;
while (x.length < size) {x = value + x;}
return x;
};
```
and usage example:
```
alert((new Date()).toFormattedString('dd Mmm, yyyy'));
``` | You have to get old school on it:
```
Date.prototype.toMMddyyyy = function() {
var padNumber = function(number) {
number = number.toString();
if (number.length === 1) {
return "0" + number;
}
return number;
};
return padNumber(date.getMonth() + 1) + "/"
+ padNumber(date.getDate()) + "/" + date.getFullYear();
};
``` | How do I format a Javascript Date? | [
"",
"javascript",
"date",
""
] |
How to use stored procedure in ADO.NET Entity Framework?
My Table : MyCustomer
```
Columns:
CustomerID PK int
Name nvarchar(50)
SurName nvarchar(50)
```
My stored procedure
```
ALTER procedure [dbo].[proc_MyCustomerAdd]
(@Name nvarchar(50),
@SurName nvarchar(50)
)
as
begin
insert into dbo.MyCustomer([Name], SurName) values(@name,@surname)
end
```
My C# code
```
private void btnSave_Click(object sender, EventArgs e)
{
entityContext.MyCustomerAdd(textName.Text.Trim(), textSurName.Text.Trim());
entityContext.SaveChanges();
}
```
The error:
> The data reader is incompatible with the specified
> 'TestAdonetEntity2Model.MyCustomer'. A
> member of the type, 'CustomerID', does
> not have a corresponding column in the
> data reader with the same name.
Error occured below the last code line (call to ExecuteFunction):
```
global::System.Data.Objects.ObjectParameter surNameParameter;
if ((surName != null))
{
surNameParameter = new global::System.Data.Objects.ObjectParameter("SurName", surName);
}
else
{
surNameParameter = new global::System.Data.Objects.ObjectParameter("SurName", typeof(string));
}
<b>return base.ExecuteFunction<MyCustomer>("MyCustomerAdd", nameParameter, surNameParameter);</b>
```
Added is ok. Every added process is ok. But after editing, above error occurs. | I think what you need to do it a function import with the EF tooling and calling the imported function like
```
DataContext.MyFunctionName(storedProcedureParamer1, storedProcedureParamer2)
```
[How to: Import a Stored Procedure](http://msdn.microsoft.com/en-us/library/bb896231.aspx) | Just a wild guess (I haven't used EF with stored procs): wouldn't the name of the function used in "ExecuteFunction" have to be the same as the stored proc's name??
```
return base.ExecuteFunction("MyCustomerAdd", nameParameter, surNameParameter);
ALTER procedure [dbo].[proc_MyCustomerAdd]
```
Can you try to use:
```
return base.ExecuteFunction("proc_MyCustomerAdd", nameParameter, surNameParameter);
```
Does that make any difference?
Marc | How do I run a stored procedure in ADO.NET Entity Framework? | [
"",
"c#",
".net",
"linq-to-sql",
"entity-framework",
""
] |
I need to force the initiation of download of a .sql file, when user clicks a button in my ASP .NET (C#) based web application.
As in, when the button is clicked, a save as dialog should open at the client end...
How do I do this?
**EDIT**
This is the code I am using
```
string sql = "";
using (System.IO.StreamReader rdr = System.IO.File.OpenText(fileName))
{
sql = rdr.ReadToEnd();
}
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", "attachment; filename=Backup.sql");
Response.Write(sql);
Response.End();
```
This is the error that I'm getting...
[alt text http://img40.imageshack.us/img40/2103/erroro.gif](http://img40.imageshack.us/img40/2103/erroro.gif)
What's wrong? | Create a separate HTTP Handler (DownloadSqlFile.ashx):
```
<%@ WebHandler Language="C#" Class="DownloadHandler" %>
using System;
using System.Web;
public class DownloadHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
var fileName = "myfile.sql";
var r = context.Response;
r.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
r.ContentType = "text/plain";
r.WriteFile(context.Server.MapPath(fileName));
}
public bool IsReusable { get { return false; } }
}
```
Then make the button in your ASP.NET page navigate to `DownloadSqlFile.ashx`. | You need to tell the browser that what you are sending is not html and shouldn't be displayed as such in the browser. The following code can be used to return some text in your server-side code and it will present the save dialog to the user as you wanted:
```
Response.Clear(); //eliminates issues where some response has already been sent
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.sql", filename));
Response.Write(yourSQL);
Response.End();
```
`filename`: the name you wish to give it
`yourSQL`: the content of the sql file | Force download of a file on web server - ASP .NET C# | [
"",
"c#",
"asp.net",
"download",
""
] |
In my java project, almost every non-static method I've written is `synchronized`. I've decided to fix up some code today, by removing most of the `synchronized` keywords. Right there I created several threading issues that took quite a while to fix, with no increase in performance. In the end I reverted everything.
I don't see anyone else writing code with "`synchronized`" everywhere. So is there any reason I *shouldn't* have "`synchronized`" everywhere?
What if I don't care too much about performance (ie. the method isn't called more than once every few seconds)? | Of course - performance. Monitors have a cost.
The answer is neither removing nor adding synchronization in a random fashion. Better to read something like Brian Goetz' "Java Concurrency In Practice" or Doug Lea's "Java Threads" books to understand how to do it properly. And learn the new concurrent packages well, of course.
Multithreading is a lot more than the synchronized keyword. | If you indiscriminately synchronize, you also run the risk of creating a [deadlock](http://en.wikipedia.org/wiki/Dining_philosophers_problem).
Suppose I have two classes, `Foo` and `Bar`, both having a synchronized method `doSomething()`. Suppose further that each class has a synchronized method taking an instance of the other class as a parameter.
```
public class Foo {
synchronized void doSomething() {
//code to doSomething
}
synchronized void doSomethingWithBar(Bar b) {
b.doSomething();
}
}
public class Bar {
synchronized void doSomething() {
//code to doSomething
}
synchronized void doSomethingWithFoo(Foo f) {
f.doSomething();
}
}
```
You can see that if you have an instance of `Foo` and an instance of `Bar`, both trying to execute their `doSomethingWith*` methods on each other at the same time, a deadlock can occur.
To force the deadlock, you could insert a sleep in both the `doSomethingWith*` methods (using `Foo` as the example):
```
synchronized void doSomethingWithBar(Bar b) {
try {
Thread.sleep(10000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
b.doSomething();
}
```
In your main method, you start two threads to complete the example:
```
public static void main(String[] args) {
final Foo f = new Foo();
final Bar b = new Bar();
new Thread(new Runnable() {
public void run() {
f.doSomethingWithBar(b);
}
}).start();
new Thread(new Runnable() {
public void run() {
b.doSomethingWithFoo(f);
}
}).start();
}
``` | Any reason NOT to slap the 'synchronized' keyword everywhere? | [
"",
"java",
"multithreading",
"synchronization",
""
] |
I'm looking for a **built-in** method that combines two associative arrays or objects into one. Using webkit in Adobe Air if that makes a difference. But basically I have two objects or associative arrays if you will:
```
var obj1 = { prop1: "something", prop2 "anotherthing" };
var obj2 = { prop3: "somethingelse" };
```
and I want to do merge them and create an object that has all the combined keys and values of the above two objects:
```
var obj3 = obj1.merge( obj2 ); //something similar to array's concat maybe?
alert(obj3.prop1); //alerts "something"
alert(obj3.prop2); //allerts "anotherthing"
alert(obj3.prop3); //alerts "somethingelse"
```
Any built in function that does this or do I have to manually do it? | Like tryptych said, except that his example code (was dangerous and wrong, until he edited it). something a little more like the following would be better.
```
mylib = mylib || {};
//take objects a and b, and return a new merged object o;
mylib.merge = function(a, b) {
var i, o = {};
for(i in a) {
if(a.hasOwnProperty(i)){
o[i]=a[i];
}
}
for(i in b) {
if(b.hasOwnProperty(i)){
o[i]=b[i];
}
}
return o;
}
//take objects a and b, and modify object a to have b's properties
mylib.augment = function(a, b) {
var i;
for(i in b) {
if(b.hasOwnProperty(i)){
a[i]=b[i];
}
}
return a;
}
```
edit re: ferocious. Deep copy is a different, and orthogonal function to this, but just for you, here's my personal deep copy function
```
function clone(o) {
var t,i;
if (o === undefined) {
return undefined;
}
if (o === null) {
return null;
}
if (o instanceof Function) {
return o;
}
if (! (o instanceof Object)) {
return o;
} else {
t = {};
for (i in o) {
/* jslint complains about this, it's correct in this case. I think. */
t[i] = clone(o[i]);
}
return t;
}
}
``` | There is no built-in method. Several libraries provide a method to do what you describe.
Writing one yourself is straightforward:
```
var merge = function(dest, source){
// This will resolve conflicts by using the source object's properties
for (prop in source){
dest[prop] = source[prop];
}
}
// Use like so
merge(obj1, obj2);
```
edit: no longer modifying Object.prototype, which is dangerous and generally frowned upon. | Is there a built in method to merge the properties of two objects into a single object? | [
"",
"javascript",
"merge",
"webkit",
"air",
""
] |
I'm building a website and one of the requirements is for users to export their contacts from their email client to import them into the site.
Because each email client exports their contacts in a slightly different format this has got my head scratching has to the best way to approach it. As I don't know what the fields are, or what the delimiter is.
I'm only looking to target the main email client/address books (outlook, apple mail, entourage, thunderbird). All of these have an entirely different format. Entourage uses tab as a delimiter where as the rest use a comma etc. I only need to pluck out the email address and (if available) a name. The name gets trickier as some clients have separate fields for first name / last name.
Using [FileHelpers](http://www.filehelpers.com) would be ideal, but it seems I need to know the structure of the csv before I can hook up a solution. I'd rather not go writing my own csv parser if possible.
Here's my thoughts for the collective hive mind:
### Plan A
* Read the first line of the csv file (all of the formats have a heading as the first row) and count the number of tabs vs commas. Determine from this the delimiter.
* Use some type of csv reader such as [Lumenworks](http://www.codeproject.com/KB/database/CsvReader.aspx) to give me basic csv reading capabilities for the rest of the file.
* Perform a Regex match on each field to determine the email column.
* No idea on how to figure out the name of the user...
### Plan B
* Prompt user for type of email client, and individually code it up for each different client <- seems really clunky.
### Plan C
....Use / purchase an existing component that already does this?! (I sure can't find one!!)
Thoughts? | I would go with Plan B (and I disagree that it is clunky).
IMHO, the best way would be to ask the user what kind of email client he/she needs to export from. Accordingly, you can identify the separator character. You yourself have found that although different clients use different separators, a single client will always use the same separator (unless they decide to bring out a non-backward compatible version) Consequently, tt should not be difficult to create an object-oriented class that accepts the separator as a parameter and accordingly parses input (the logic should remain almost the same, irrespective of the separator).
Even if the logic in parsing each type of export file differs significantly, it seems to be that you could create an abstract base class that holds all the common functionality and derived classes that simply override the client-specific functionality.
Even if you use a custom library such as FileHelpers, you should be able to accomplish it by passing the type of separator.
I feel that you should not rely on the relative count of the possible separators to identify what the actual separator is (as in Plan A).
**Edit:** Another option that just came to mind would be to provide a sort of options interface like MS Excel does. You get to choose the separator character with a live preview of how data will be parsed according to the choice. | I would first look at how the competition does it.
**Google:** *"We support importing contacts in the CSV file format (Comma Separated Values). For best results, please use a CSV file produced by Outlook, Outlook Express, Yahoo!, or Hotmail. For Apple Address Book, there is a useful utility called "A to G"."*
So I guess they go for your plan A, and have checks in place for the above stated CSV files.
**Live mail/hotmail:** They go for your option B, and support: *Microsoft Outlook (using CSV), Outlook Express (using CSV), Windows Contacts, Windows Live Hotmail, Yahoo! Mail (using Outlook CSV format and comma separated), Gmail (using Outlook CSV format)*
**Facebook:** They let you type in your email address, and if they know it (yahoo, gmail, hotmail etc) they will ask you for your password, and retrieve your contacts automatically. (option D) If they don't support your email provider you can still upload a CSV file from either Outlook or other formats (kind of your option B).
I guess the facebook version is really cool. But if that is too much you can go for option A for supported CSV formats (you have to check the different CSV files), and otherwise if you don't recognize it, prompt the user for meaning of the different columsn you recognized. | Import CSV file into c# | [
"",
"c#",
"asp.net",
"csv",
""
] |
While looking through the Spring MVC framework I noticed that, unless I misunderstand, its developers favor throws Exception instead of throwing multiple exceptions.
I realize that at the core of this question is the checked versus unchecked exceptions debate, avoiding that religious war, is it a good practice to use throws generic exception? | What makes sense for a library such as Spring MVC, which needs to be open enough to fit all sorts of different use cases, does not necessarily make sense for you to follow when writing a specific application. This is one of those cases.
If you are referring to classes such as the `Controller` interface which as a method signature such as
```
handleRequest(HttpServletRequest request, HttpServletResponse response)
throws Exception
```
This is likely because, from the perspective of the Spring classes which call into your Controller (such as `DispatcherServlet`), they don't care what type of Exception your code calls - library code such as `DispatcherServlet` only needs to know that this class may throw an Exception and therefore is capable of handling Exception in the general case.
In other words, `DispatcherServlet` doesn't need to know what specific type(s) of Exception your Controller may throw - it's going to treat any of them as an "error". This is why the method signature is `throws Exception`.
Now, the API authors could have made the signature use a custom exception type as `SpringMvcException`, but that would only have the effect of forcing you to handle any checked exception types in your `handleRequest` method and simply wrap them, which is tedious make-work boilerplate code. So, since pretty much everything with Spring is designed to make it as easy and lightweight for you to integrate with as possible, it's easier for them to specify that the interface method merely `throws Exception`. | No, absolutely not. You should specify what exceptions you're going to throw so the caller can do the right thing with each one. If you don't, "throws Exception" gets passed up the chain, and the best the callers can do is printStackTrace() and die.
Update: To counter some of the "what if I override the method" objections, I'd go a bit further and say that any time you have a package that throws exceptions (as opposed to passing up an exception from a caller), you should declare an exception class in that package. Thus, if you're overriding my "addToSchedule() throws ScheduleConflictException", you're perfectly able to subclass ScheduleConflictException to do what you need. | In Java, is using throws Exception instead of throwing multiple specific exceptions good practice? | [
"",
"java",
"exception",
""
] |
description like `<a href="myexample.com"></a>` should return blank | If you want to replace url's from dynamic content, you can do this with regular expressions, or an easier method like using [phpQuery](http://code.google.com/p/phpquery/) which will allow you to use a much method of looking up links within HTML, and replacing their HREF attribute.
```
phpQuery::newDocument("externalPage.html");
pq("a")->href("");
```
I've not used phpQuery for a while, but I believe that would do the trick. Also, if the links you are trying to remove are navigation, rss feeds, etc, you can use phpQuery to return only a particular portion of the externalPage, meaning you would no longer have to remove the links that are not within the portion you want.
For example, if you are trying to get an article from the external page that exists within a DIV having an ID of "articleBox", you could do this:
```
pq("div#articleBox");
```
That would return only that particular element, and the contents within it.
You may find that [PHPSimpleHTMLDOMParser](http://simplehtmldom.sourceforge.net/) is easier to work with. Here's an example of how to use it against slashdot to scrape parts of the main page:
```
// Create DOM from URL
$html = file_get_html('http://slashdot.org/');
// Find all article blocks
foreach($html->find('div.article') as $article) {
$item['title'] = $article->find('div.title', 0)->plaintext;
$item['intro'] = $article->find('div.intro', 0)->plaintext;
$item['details'] = $article->find('div.details', 0)->plaintext;
$articles[] = $item;
}
print_r($articles);
``` | Use the php strip\_tags function (<https://www.php.net/manual/en/function.strip-tags.php>), it will remove all html tags from a string, so:
```
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
```
Would output "Test paragraph. Other text", and the example you gave would return blank. Note that you can also specify some tags you want to allow, if there are some you still want to use. | Remove/Edit Links within Dynamically-loaded Markup | [
"",
"php",
""
] |
So, here's my problem:
I have a message driven bean X and would like to make use of Logger in X's onMessage() method. Lets presume that I have a single instance of the bean running in my app server, hence, I would initialize log4j in ejbCreate(). This would mean I would have to do something like this:
```
public void ejbCreate() {
PropertyConfigurator.configure(Classloader.getResourceAsStream("xyz_log4j.properties"));
}
```
However, this doesn't help. No matter what I do I always get my stream as null, I tried other versions : this.getClass().getStream() and ResourceBundle.
I jar'ed my properties file in to test.jar and added it under EAR libraries (I am using RAD7) and it got reflected in my manifest.mf.
Did anyone face this issue before? If yes, how did you solve it?
Appreciate your help... | I would not recommend configuring log4j in the EJB create method. Multiple EJBeans can be activated / passivated at the containers whim per the J2EE specification. So there is a possibility you end up configuring log4j multiple times. Recommend using startup beans which are guaranteed to be invoked only 1 time. | If you're getting this from inside a JAR file, then you're missing an iniitial `/`:
```
Classloader.getResourceAsStream("/xyz_log4j.properties")
```
And depending on what directory contains the properties file, you have to specify a path to that directory relative to the top of the class hierarchy. For example, if this properties file is in the same directory as `net.mine.Program`, then you would do this:
```
Classloader.getResourceAsStream("/net/mine/xyz_log4j.properties")
```
I don't believe you can read from the META-INF directory using `getResourceAsStream()`, but I've never tried so perhaps there's a way to do it. | Log4j for Message Driven Beans | [
"",
"java",
"logging",
"jakarta-ee",
"log4j",
"message-driven-bean",
""
] |
I have a Map keyed by Integer. Using EL, how can I access a value by its key?
```
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
```
I thought this would work but it doesn't (where map is already in the request's attributes):
```
<c:out value="${map[1]}"/>
```
**Follow up:** I tracked down the problem. Apparently `${name[1]}` does a map lookup with the number as a `Long`. I figured this out when I changed `HashMap` to `TreeMap` and received the error:
```
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
```
If I change my map to be:
```
Map<Long, String> map = new HashMap<Long, String>();
map.put(1L, "One");
```
then `${name[1]}` returns "One". What's with that? Why does `<c:out>` treat a number as a long. Seems counterintuitive to me (as int is more commonly used than long).
So my new question is, is there a EL notation to access a map by an `Integer` value? | Initial answer (EL 2.1, May 2009)
As mentioned in [this java forum thread](http://forums.sun.com/thread.jspa?messageID=9702932#9702932):
> Basically autoboxing puts an Integer object into the Map.
> ie:
```
map.put(new Integer(0), "myValue")
```
EL (Expressions Languages) evaluates 0 as a Long and thus goes looking for a Long as the key in the map.
ie it evaluates:
```
map.get(new Long(0))
```
As a `Long` is never equal to an `Integer` object, it does not find the entry in the map.
That's it in a nutshell.
---
## Update since May 2009 (EL 2.2)
[Dec 2009 saw the introduction of EL 2.2 with JSP 2.2 / Java EE 6](https://stackoverflow.com/a/4812883/6309), with a [few differences compared to EL 2.1](https://stackoverflow.com/a/7209200/6309).
It seems ("[EL Expression parsing integer as long](https://stackoverflow.com/a/18269163/6309)") that:
> **you can call the method `intValue` on the `Long` object self inside EL 2.2**:
```
<c:out value="${map[(1).intValue()]}"/>
```
That could be a good workaround here (also mentioned below in [Tobias Liefke](https://stackoverflow.com/users/4371659/tobias-liefke)'s [answer](https://stackoverflow.com/a/27533414/6309))
---
Original answer:
EL uses the following wrappers:
```
Terms Description Type
null null value. -
123 int value. java.lang.Long
123.00 real value. java.lang.Double
"string" ou 'string' string. java.lang.String
true or false boolean. java.lang.Boolean
```
JSP page demonstrating this:
```
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page import="java.util.*" %>
<h2> Server Info</h2>
Server info = <%= application.getServerInfo() %> <br>
Servlet engine version = <%= application.getMajorVersion() %>.<%= application.getMinorVersion() %><br>
Java version = <%= System.getProperty("java.vm.version") %><br>
<%
Map map = new LinkedHashMap();
map.put("2", "String(2)");
map.put(new Integer(2), "Integer(2)");
map.put(new Long(2), "Long(2)");
map.put(42, "AutoBoxedNumber");
pageContext.setAttribute("myMap", map);
Integer lifeInteger = new Integer(42);
Long lifeLong = new Long(42);
%>
<h3>Looking up map in JSTL - integer vs long </h3>
This page demonstrates how JSTL maps interact with different types used for keys in a map.
Specifically the issue relates to autoboxing by java using map.put(1, "MyValue") and attempting to display it as ${myMap[1]}
The map "myMap" consists of four entries with different keys: A String, an Integer, a Long and an entry put there by AutoBoxing Java 5 feature.
<table border="1">
<tr><th>Key</th><th>value</th><th>Key Class</th></tr>
<c:forEach var="entry" items="${myMap}" varStatus="status">
<tr>
<td>${entry.key}</td>
<td>${entry.value}</td>
<td>${entry.key.class}</td>
</tr>
</c:forEach>
</table>
<h4> Accessing the map</h4>
Evaluating: ${"${myMap['2']}"} = <c:out value="${myMap['2']}"/><br>
Evaluating: ${"${myMap[2]}"} = <c:out value="${myMap[2]}"/><br>
Evaluating: ${"${myMap[42]}"} = <c:out value="${myMap[42]}"/><br>
<p>
As you can see, the EL Expression for the literal number retrieves the value against the java.lang.Long entry in the map.
Attempting to access the entry created by autoboxing fails because a Long is never equal to an Integer
<p>
lifeInteger = <%= lifeInteger %><br/>
lifeLong = <%= lifeLong %><br/>
lifeInteger.equals(lifeLong) : <%= lifeInteger.equals(lifeLong) %> <br>
``` | Just another helpful hint in addition to the above comment would be when you have a string value contained in some variable such as a request parameter.
In this case, passing this in will also result in JSTL keying the value of say "1" as a sting and as such no match being found in a Map hashmap.
One way to get around this is to do something like this.
```
<c:set var="longKey" value="${param.selectedIndex + 0}"/>
```
This will now be treated as a Long object and then has a chance to match an object when it is contained withing the map Map or whatever.
Then, continue as usual with something like
```
${map[longKey]}
``` | EL access a map value by Integer key | [
"",
"java",
"jsp",
"jstl",
"el",
""
] |
My regex skill is... bad. I have this email body.
```
Hello World
[cid:image002.png@01C9DEDD.67C237D0]
Hello World
[cid:image002.png@01C9DEDD.67C237D0] [cid:image002.png@01C9DEDD.67C237D0]
Hello World
```
And what I need is an array of the filenames.
```
preg_match_all("/\[cid:(.*)\@/", $string, $matches);
echo "<pre>";
print_r($matches);
echo "</pre>";
```
And I get the first filename fine. But not the 2nd and 3rd.
```
[0] => image002.png
[1] => image002.png@01C9DEDD.67C237D0] [cid:image002.png
```
How can I change this regex so it works for any embedded file in an email body? | I think you can just change the expression to this:
```
"/\[cid:(.*?)\@/"
```
To make the match non-greedy.
Here are a couple of tools you can use to test your expressions:
* <http://gskinner.com/RegExr/>
* <http://www.rexv.org/> | Try:
```
preg_match_all("/\[cid:([^@]*)/", $string, $matches);
```
EDIT: Original post had a bug - apologies! I was trying to short circuit the greediness in an incorrect manner. | How to extract the embedded attachment name from this email? | [
"",
"php",
"regex",
"email",
""
] |
I'm looking for open source applications, built with winforms in C#. Specifically, i'm looking for applications using new and real world techniques. Like nerddinner and oxite for asp.net.
Thanks | [SharpDevelop](http://www.icsharpcode.net/OpenSource/SD/) is an excellent example IMO
Another one *was* [Paint.net](http://www.getpaint.net/index.html), but it's no longer open source, see comments. | Look to [codeplex](http://codeplex.com/), [SourceForge](http://sourceforge.net/) and [Code Google](http://code.google.com/). There is lot of applications :)
Next resource is [CodeProject](http://www.codeproject.com/).
---
Paint.Net is nice example.
[Here](http://www.afterdawn.com/software/source%5Fcodes/paint.net.cfm) is source code. | Open Source Winforms applications? | [
"",
"c#",
"winforms",
"open-source",
""
] |
First time reader, first time poster (woo!)
So I've been implementing my login scripts for an informal website. Not likely to be compromised, but just to be safe, I'd like to ask if there's a security risk in having my MySQL database login stored in plaintext in the php code.
As far as I know, the code itself is parsed by Apache, so the end-user doesn't see it (just the output), which would mean it should be safe to keep... but I'd like a second opinion.
Summary:
Accessing database through mysql\_connect, mysql\_select\_db, mysql\_query. Login info stored in local variables defined at each iteration of the script, and (I think) dumped once script terminates.
Security vulnerability? | You could also consider moving the username/password combination to a seperate configuration file that lives outside the webroot. Make sure that place is not directly accessible from the webserver side.
That way, if for some reason the webserver decides not to execute PHP files anymore you don't lose the account information to the database server.
As an added bonus, if you use anything that makes a copy of the .php file (editors, SVN or whatever) in the webroot, you don't risk anyone getting around the .php execution. | That's very standard procedure for web applications that talk to a database.
I recommend taking read permissions away from the file for users other than the web server and yourself - if you have other users on your box that can spy on the file, they'll be able to access your mysql server.
Also, you should adjust the executable permission on the top directory as it'll prevent unauthorized users from even entering it.
Harden your mysql user's allowed host, so that only the boxes you need can connect to it.
Of course if your box is compromised and an attacker gains root access, there's little that will protect you. | Security risk in storing SQL login info in PHP code? | [
"",
"php",
"mysql",
"security",
"plaintext",
""
] |
Scenario
Consider the following code snippet.
```
string s = "S";
string s1 = "S";
string s2 = string.Empty;
switch (s)
{
case "S":
s1 = "StringComparison";
break;
default:
break;
}
switch (s[0])
{
case'S':
s2 = "StringCOmpare2";
break;
default:
break;
}
```
the first switch case, results in a stringcomparison within IL.
But the second switch case, does not result in a stringcomparison within IL.
Can anyone justify this? | You're accessing the string via its [indexer](http://en.csharp-online.net/ECMA-334:_17.8_Indexers) which returns a char and so lets you use the string as if it was an array of chars.
So whar you're doing is a char comparison. Using the apostrophe for the 'S' also tells you that you're using 'S' as a char and not as a string. | Because on the second switch you're are not doing a String comparison, you're doing a Char comparison. | String Comparison | [
"",
"c#",
"string",
""
] |
I just wondering why this works (in Java):
```
byte b = 27;
```
but being method declared like this:
```
public void method(byte b){
System.out.println(b);
}
```
This doesn't work:
```
a.method(27);
```
Gives a Compiler error as follows:
```
`The method method(byte) in the type App is not applicable for the arguments (int)`
```
Reading [this](http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html) doesn't give me any clue (probably i am missunderstanding something).
Thanks in advance. | The reason the assignment
```
byte b = 27;
```
works is due to [section 5.2 of the Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.2) (assignment conversion), which includes:
> In addition, if the expression is a constant expression (§15.28) of type
> `byte`, `short`, `char` or `int` :
>
> A narrowing primitive conversion may
> be used if the type of the variable is
> `byte`, `short`, or `char`, and the value of
> the constant expression is
> representable in the type of the
> variable.
In other words, the language has special provision for this case with assignments. Normally, there's no implicit conversion from `int` to `byte`.
Interestingly, C# works differently in this respect (despite being like Java in so many other aspects of core functionality) - the method call is valid in C#. | Simple answer - a byte is 1 byte of memory, and an integer is typically 4 bytes.
Without explicitly trying to cast the int to a byte, there is no implied coercion because an integer of size say 10790 would lose information if truncated down to one byte. | Conversions and Promotions | [
"",
"java",
""
] |
I'm reading/writing data off of a named pipe. On the writing side it says that it's writing a constant 110 bytes. On the Reading side for the majority of time it says that it's reading 110 bytes which is correct, but other times it says its reading 220 bytes or 330 bytes. Which is right in the fact that when I print it out it's printing out the same message two or three times in a row within the same read(). In the code below for reading am I doing something wrong with the memset to clear the char? I can't think of any other way it's reading more then is being written unless something is left over in the buffer.
```
int fd1, numread;
char bufpipe[5000];
while(1)
{
fd1 = open("/tmp/testPipe", O_RDONLY);
numread = read(fd1,bufpipe, 5000);//->this should always be 110
if(numread > 1)
{
printf("READ: %i", numread);
bufpipe[numread+1] = '\0';
memset(bufpipe,'\0',5001);
close(fd1);
}
}
``` | This:
```
memset(bufpipe,'\0',5001);
```
is overwriting by one byte, because you have only 5000 bytes.
But the main "problem" is that `read(..., 5000)` will always read as much as it can up to 5000 bytes - you seem to be assuming that it will read only as much as was written in one go by the writer, which is not true. If the writer writes two packets of 110 bytes between two reads, then it's quite correct that the reader reads 220 bytes.
If you need to read only a single packet at a time, you have to make your packets self-describing. So for instance, the first four bytes contain the number of bytes to follow. Then you can read a single packet by reading four bytes, converting that to an integer, then reading that number of data bytes. | Your assumption that a `read` will execute immediately after a `write` is not true. The writer process might write to the pipe a couple of times before a read is encountered. Written data will be added to the end of buffer. Put it differently, read and write are not packet oriented. They are stream oriented. It means that `write` just adds data to the buffer and `read` just gets anything available to it. | unistd.h read() is reading more data then being written | [
"",
"c++",
"unix",
"named-pipes",
"memset",
"unistd.h",
""
] |
I'd like to close a dialog that pops up automatically, but I'm having some trouble getting it to work. My Win32 programming is a bit rusty after several years of limited usage.
I'm using FindWindowEx to get handles to the dialog and the button I want to click. I was under the impression that sending a WM\_COMMAND to the dialog, with the button handle in the wParam parameter would do the trick.
```
Window window = Window.FindWindow("TSomeDialog", null);
Window cancelButton = Window.FindWindow("TButton", "Cancel", window);
Message message = Message.Create(window.HWnd, 0x0111, cancelButton.HWnd, IntPtr.Zero);
PostMessage(message);
public void PostMessage(Message message)
{
// Win32 API import
PostMessage(message.HWnd, message.Msg, message.WParam, message.LParam);
}
```
Window is a class that implements IWin32Window and wraps some Win32 API calls. I have inlined the constant for WM\_COMMAND (0x111).
What am I doing wrong? :) | Well, according to the documentation for WM\_COMMAND, lParam should be the handle to the control's window (it looks like you're passing it in wParam).
wParam should have its high order word equal to BN\_CLICKED and its low order word equal to the control's identifier.
(You can use GetWindowLong with GWL\_ID to retrieve this, but presumably its IDCANCEL.) | Why not just send a WM\_SYSCOMMAND message with a SC\_CLOSE parameter? That should close the window. | Simulate clicking a button in another window in C# | [
"",
"c#",
"winapi",
"button",
"sendmessage",
""
] |
Inside [.vcproj files](http://msdn.microsoft.com/en-us/library/2208a1f2.aspx) There is a list of all source files in your project.
How can we use a macro to specify the path to a source file?
If we do this:
```
<File
RelativePath="$(Lib3rdParty)\Qt\qtwinmigrate-2.5-commercial\src\qmfcapp.cpp">
</File>
```
The compiler cannot find the folder:
```
qmfcapp.cpp
c1xx : fatal error C1083: Cannot open source file: '.\$(lib3rdparty)\qt\qtwinmigrate- 2.5-commercial\src\qmfcapp.cpp': No such file or directory
```
As you can see, our project compiles in several source files from QT. QT lives inside a folder of external libraries, and we don't want hardcode the path from our project to that folder (we have a very large solution) | Try setting an environment variable for 'Lib3rdParty' to the appropriate relative path snippet. | The normal solution is to include the 3rd party includes, libs and source in source control with your own source, so you can track changes to your 3rd party dependencies with your source.
If this is the case, you should be able to use a relative path from each project to the 3rd party source files.
However if your solution is big, and it has project complicated settings you should look at [CMake](http://www.cmake.org), even if you are only building on windows. CMake enables you to describe your build environment with common settings specified in only one place. More complicated cases can be handled with variables and macros. Then it generates your visual studio projects, or makefiles from this description. We introduced it to support a unix port, and now I use it for windows only development too.
VS projects are really clunky to use, opening and closing dialog boxes, setting things for debug and release. Each project with its own copy of the settings, but mostly the same as all the other projects. | Use a "User Macro" in .vcproj RelativePath | [
"",
"c++",
"include",
"visual-c++",
""
] |
I need some help with creating a regex for my php script. Basically, I have an associative array containing my data, and I want to use preg\_replace to replace some place-holders with real data. The input would be something like this:
```
<td>{{address}}</td><td>{{fixDate}}</td><td>{{measureDate}}</td><td>{{builder}}</td>
```
I don't want to use str\_replace, because the array may hold many more items than I need.
If I understand correctly, preg\_replace is able to take the text that it finds from the regex, and replace it with the value of that key in the array, e.g.
```
<td>{{address}}</td>
```
get replaced with the value of *$replace['address']*. Is this true, or did I misread the php docs?
If it is true, could someone please help show me a regex that will parse this for me (would appreciate it if you also explain how it works, since I am not very good with regexes yet).
Many thanks. | Use [`preg_replace_callback()`](https://www.php.net/preg_replace_callback). It's incredibly useful for this kind of thing.
```
$replace_values = array(
'test' => 'test two',
);
$result = preg_replace_callback('!\{\{(\w+)\}\}!', 'replace_value', $input);
function replace_value($matches) {
global $replace_values;
return $replace_values[$matches[1]];
}
```
Basically this says find all occurrences of {{...}} containing word characters and replace that value with the value from a lookup table (being the global $replace\_values). | For well-formed HTML/XML parsing, consider using the [Document Object Model (DOM)](https://www.php.net/book.dom) in conjunction with [XPath](https://www.php.net/manual/en/class.domxpath.php). It's much more fun to use than regexes for that sort of thing. | PHP regex templating - find all occurrences of {{var}} | [
"",
"php",
"regex",
"templates",
""
] |
I have several arrays in Javascripts, e.g.
a\_array[0] = "abc";
b\_array[0] = "bcd";
c\_array[0] = "cde";
I have a function which takes the array name.
```
function perform(array_name){
array_name = eval(array_name);
alert(array_name[0]);
}
perform("a_array");
perform("b_array");
perform("c_array");
```
Currently, I use eval() to do what I want.
Is there any method not to use eval() here? | You can either pass the array itself:
```
function perform(array) {
alert(array[0]);
}
perform(a_array);
```
Or access it over `this`:
```
function perform(array_name) {
alert(this[array_name][0]);
}
perform('a_array');
``` | Instead of picking an array by `eval`'ing its name, store your arrays in an object:
```
all_arrays = {a:['abc'], b:['bcd'], c:['cde']};
function perform(array_name) {
alert(all_arrays[array_name][0]);
}
``` | Javascript using variable as array name | [
"",
"javascript",
""
] |
As part of the requirement we need to process nearly 3 million records and associate them with a bucket. This association is decided on a set of rules (comprising of 5-15 attributes, with single or range of values and precedence) which derive the bucket for a record.
Sequential processing of such a big number is clearly out of scope.
Can someone guide us on the approach to effectively design a solution? | 3 million records isn't really that much from a volume-of-data point of view (depending on record size, obviously), so I'd suggest that the easiest thing to try is parallelising the processing across multiple threads (using the java.util.concurrent.Executor framework). As long as you have multiple CPU cores available, you should be able to get near-linear performance increases. | It depends on the data source. If it is a single database, you will spend most of the time retrieving the data anyway. If it is in a local file, then you can partition the data into smaller files or you can pad the records to have equal size - this allows random access to a batch of records.
If you have a multi-core machine, the partitioned data can be processed in parallel. If you determined the record-bucket assignment, you can write back the information into the database using the PreparedStatement's batch capability.
If you have only a single core machine, you can still achieve some performance improvements by designing a data retrieval - data processing - batch writeback separation to take advantage of the pause times of the I/O operations. | Process huge volume of data using Java | [
"",
"java",
"database",
""
] |
I'm trying to add/change images in my project, using Microsoft Visual Studio 2008 C#. Along with it, Devexpress components are also included.
What I did, I copied an image (.png file) and paste it it in my "PrintRibbonControllerResources.resx" and then after that I have to open again the MainForm.cs right click on the form and click on the Run Designer. It will open the Ribbon Control Designer. From there, I can add the image.
Do you think its ok? It's my first time to do this, and I don't have any experience & I'm learning it by doing.
Thanks
===
it seems I don't see the add function under resource tab | I generally add an image to the project itself. (Add/Existing item) I do this so I can use SourceControl to check in/out the image file. The resx then links to these files.
Basically, my philosophy is: if it works, don't fix it.
If this solution works for you, it's fine. At least, until you discover a situation where it fails. | If you go in the properties of your project, and select the resources tab, you can add it directly from there and it will be accessible in the default resource file of your project, which might be more convenient. | adding images in my project | [
"",
"c#",
"image",
""
] |
I'm working on an application that has to process audio files. When using mp3 files I'm not sure how to handle data (the data I'm interested in are the the audio bytes, the ones that represent what we hear).
If I'm using a wav file I know I have a 44 bytes header and then the data. When it comes to an mp3, I've read that they are composed by frames, each frame containing a header and audio data. Is it possible to get all the audio data from a mp3 file?
I'm using java (I've added MP3SPI, Jlayer, and Tritonus) and I'm able to get the bytes from the file, but I'm not sure about what these bytes represent or how to handle then. | From the [documentation for MP3SPI](https://web.archive.org/web/20210118201557/http://www.javazoom.net/mp3spi/documents.html):
```
File file = new File(filename);
AudioInputStream in= AudioSystem.getAudioInputStream(file);
AudioInputStream din = null;
AudioFormat baseFormat = in.getFormat();
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
16,
baseFormat.getChannels(),
baseFormat.getChannels() * 2,
baseFormat.getSampleRate(),
false);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
```
You then just read data from `din` - it will be the "raw" data as per `decodedFormat`. (See the [docs for `AudioFormat`](http://java.sun.com/javase/6/docs/api/javax/sound/sampled/AudioFormat.html) for more information.)
(Note that this sample code doesn't close the stream or anything like that - use appropriate try/finally blocks as normal.) | The data that you want are the actual samples, while MP3 represents the data differently. So, like what everyone else has said - you need a library to decode the MP3 data into actual samples for your purpose. | How to get audio data from a MP3? | [
"",
"java",
"audio",
"mp3",
"extract",
""
] |
I wanted to know how to go about implementing semaphores, locks and condition variables in C/C++. I am learning OS concepts but want to get around implementing the concepts in C.
Any tutorials? | Semaphores, locks, condition variables etc. are operating system concepts and must typically be implemented in terms of features of the operating system kernel. It is therefore not generally possible to study them in isolation - you need to consider the kernel code too. Probably the best way of doing this is to take a look at the Linux Kernel, with the help of a book such as [Understanding The Linux Kernel](http://oreilly.com/catalog/9780596000028/). | Semaphore at the very simplest is just a counter you can add and subtract from with a single atomic operation. Wikipedia has an easy to understand explanation that pretty much covers your question about them:
<http://en.wikipedia.org/wiki/Semaphore_(programming)> | Implementing Semaphores, locks and condition variables | [
"",
"c++",
"c",
"operating-system",
""
] |
1. Is there a performance or code maintenance issue with using `assert` as part of the standard code instead of using it just for debugging purposes?
Is
```
assert x >= 0, 'x is less than zero'
```
better or worse than
```
if x < 0:
raise Exception('x is less than zero')
```
2. Also, is there any way to set a business rule like `if x < 0 raise error` that is always checked without the `try/except/finally` so, if at anytime throughout the code `x` is less than 0 an error is raised, like if you set `assert x < 0` at the start of a function, anywhere within the function where `x` becomes less then 0 an exception is raised? | To be able to automatically throw an error when x become less than zero throughout the function. You can use [class descriptors](http://docs.python.org/reference/datamodel.html#implementing-descriptors). Here is an example:
```
class LessThanZeroException(Exception):
pass
class variable(object):
def __init__(self, value=0):
self.__x = value
def __set__(self, obj, value):
if value < 0:
raise LessThanZeroException('x is less than zero')
self.__x = value
def __get__(self, obj, objType):
return self.__x
class MyClass(object):
x = variable()
>>> m = MyClass()
>>> m.x = 10
>>> m.x -= 20
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "my.py", line 7, in __set__
raise LessThanZeroException('x is less than zero')
LessThanZeroException: x is less than zero
``` | Asserts should be used to test conditions that *should never happen*. The purpose is to crash early in the case of a corrupt program state.
Exceptions should be used for errors that can conceivably happen, and **you should almost always create your own Exception classes**.
---
For example, if you're writing a function to read from a configuration file into a `dict`, improper formatting in the file should raise a `ConfigurationSyntaxError`, while you can `assert` that you're not about to return `None`.
---
In your example, if `x` is a value set via a user interface or from an external source, an exception is best.
If `x` is only set by your own code in the same program, go with an assertion. | Best practice for using assert? | [
"",
"python",
"assert",
"assertion",
"raise",
""
] |
How do you remove a value out of a string in SQL Server? | This is done using the [REPLACE](http://msdn.microsoft.com/en-us/library/ms186862.aspx) function
To strip out "somestring" from "SomeColumn" in "SomeTable" in the SELECT query:
```
SELECT REPLACE([SomeColumn],'somestring','') AS [SomeColumn] FROM [SomeTable]
```
To update the table and strip out "somestring" from "SomeColumn" in "SomeTable"
```
UPDATE [SomeTable] SET [SomeColumn] = REPLACE([SomeColumn], 'somestring', '')
``` | Use the "REPLACE" string function on the column in question:
```
UPDATE (yourTable)
SET YourColumn = REPLACE(YourColumn, '*', '')
WHERE (your conditions)
```
Replace the "\*" with the character you want to strip out and specify your WHERE clause to match the rows you want to apply the update to.
Of course, the REPLACE function can also be used - as other answerer have shown - in a SELECT statement - from your question, I assumed you were trying to update a table.
Marc | How do you strip a character out of a column in SQL Server? | [
"",
"sql",
"sql-server",
""
] |
Given my generic select below, is there a way to get the number of records returned from a query with Zend Framework? $row++ in a loop is not acceptable for my solution as I am using paging (though its not in my sample).
I also DO NOT want to add another query with "Count(\*)".
```
$query = "Select * from Users where active = 1";
$stmt = $db->query($query);
$noOfRows = ???;
while ($row = $stmt->fetch())
{
// processing
}
``` | Use fetchAll()
fetchAll returns an array, so you can do something like this:
```
$rows = $db->fetchAll("select ...");
$numRows = sizeof($rows);
foreach ($rows as $row)
{
// process each row
}
``` | It still requires another query, but with MySQL there is a SELECT parameter `SQL_CALC_FOUND_ROWS` - it stores a value in your connection that you can then `SELECT FOUND_ROWS()`
Note - the performance of your initial query will go down, because the limit will be processed later, but it may be faster than a separate COUNT().
[FOUND\_ROWS()](http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows)
```
$query = "Select SQL_CALC_FOUND_ROWS * from Users where active = 1 limit 20";
$stmt = $db->query($query);
while ($row = $stmt->fetch())
{
// processing
}
$count = $db->fetchOne('SELECT FOUND_ROWS()');
``` | Is there a way to get the number of records from a query with Zend-framework? | [
"",
"php",
"zend-framework",
"zend-db",
""
] |
I know that it's a good idea to make as much of the interface of a class non-member non-friend as possible, and I've just realised that for my 3D vector class, 'Vector3', I can move the +=, -= and so on operators out of the class, leaving just constructors and the copy assignment operator.
The question is: what should this operator look like? I've seen canonical forms of plenty of other operators and have followed their advice, but I haven't seen canonical forms of these operators. I've given what I think it should be below.
The secondary question is: what are these operators even called? Arithmetic assignment operators?
The (relevant) code before:
```
class Vector3 {
public:
Vector3& operator+=(const Vector3& rhs);
float x, y, z;
};
Vector3& Vector3::operator+=(const Vector3 &rhs) {
x += rhs.x;
y += rhs.y;
z += rhs.z;
return *this;
}
```
What I've changed it to so far:
```
class Vector3 {
public:
float x, y, z;
};
Vector3& operator+=(Vector3& lhs, const Vector3& rhs) {
lhs.x += rhs.x;
lhs.y += rhs.y;
lhs.z += rhs.z;
return lhs;
}
``` | What you have looks good to me.
By the way, when you come to the operator+, it is common to implement that in terms of +=. (create a copy of lhs, and then call lhs += rhs and return the result)
Don't know if you're already aware of this trick, but since you're concerned about canonical ways to implement these operators, it can't hurt to mention it. :) | What you have looks good.
The basic way to think about this, intuitively, is to think about what you'd like code to look like when you write it. If, in this case, you can write
```
Vector v, w;
v += w;
w += v;
```
and so on, you're on the right track.
There are a lot of good rules of thumb to help; see [this entry](http://www.parashift.com/c++-faq/operator-overloading.html) in the C++ FAQ for lots on it. | Canonical form of += operator for classes | [
"",
"c++",
"operators",
"canonical-form",
""
] |
I'm trying to delete a file, after writing something in it, with `FileOutputStream`. This is the code I use for writing:
```
private void writeContent(File file, String fileContent) {
FileOutputStream to;
try {
to = new FileOutputStream(file);
to.write(fileContent.getBytes());
to.flush();
to.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
```
As it is seen, I flush and close the stream, but when I try to delete, `file.delete()` returns false.
I checked before deletion to see if the file exists, and: `file.exists()`, `file.canRead()`, `file.canWrite()`, `file.canExecute()` all return true. Just after calling these methods I try `file.delete()` and returns false.
Is there anything I've done wrong? | It was pretty odd the trick that worked. The thing is when I have previously read the content of the file, I used `BufferedReader`. After reading, I closed the buffer.
Meanwhile I switched and now I'm reading the content using `FileInputStream`. Also after finishing reading I close the stream. And now it's working.
The problem is I don't have the explanation for this.
I don't know `BufferedReader` and `FileOutputStream` to be incompatible. | Another bug in Java. I seldom find them, only my second in my 10 year career. This is my solution, as others have mentioned. I have nether used `System.gc()`. But here, in my case, it is absolutely crucial. Weird? YES!
```
finally
{
try
{
in.close();
in = null;
out.flush();
out.close();
out = null;
System.gc();
}
catch (IOException e)
{
logger.error(e.getMessage());
e.printStackTrace();
}
}
``` | file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true | [
"",
"java",
"file",
"fileoutputstream",
""
] |
I have a rather large (several MLOC) application at hand that I'd like to split up into more maintainable separate parts. Currently the product is comprised of about 40 Eclipse projects, many of them having inter-dependencies. This alone makes a continuous build system unfeasible, because it would have to rebuild very much with each checkin.
Is there a "best practice" way of how to
* identify parts that can immediately be separated
* document inter-dependencies visually
* untangle the existing code
* handle "patches" we need to apply to libraries (currently handled by putting them in the classpath before the actual library)
If there are (free/open) tools to support this, I'd appreciate pointers.
Even though I do not have any experience with Maven it seems like it forces a very modular design. I wonder now whether this is something that can be retrofitted iteratively or if a project that was to use it would have to be layouted with modularity in mind right from the start.
**Edit 2009-07-10**
We are in the process of splitting out some core modules using [Apache Ant/Ivy](http://ant.apache.org/ivy). Really helpful and well designed tool, not imposing as much on you as maven does.
I wrote down some more general details and personal opinion about why we are doing that on my blog - too long to post here and maybe not interesting to everyone, so follow at your own discretion: [www.danielschneller.com](http://www.danielschneller.com/2009/07/modularizing-software-with-antivy-and.html) | Using [OSGi](http://www.osgi.org/Main/HomePage) could be a good fit for you. It would allow to create modules out of the application. You can also organize dependencies in a better way. If you define your interfaces between the different modules correctly, then you can use continuous integration as you only have to rebuild the module that you affected on check-in.
The mechanisms provided by OSGi will help you untangle the existing code. Because of the way the classloading works, it also helps you handle the patches in an easier way.
[Some concepts of OSGi that seem to be a good match for you, as shown from wikipedia:](http://en.wikipedia.org/wiki/OSGi)
The framework is conceptually divided into the following areas:
* Bundles - Bundles are normal jar components with extra manifest headers.
* Services - The services layer connects bundles in a dynamic way by offering a publish-find-bind model for plain old Java objects(POJO).
* Services Registry - The API for management services (ServiceRegistration, ServiceTracker and ServiceReference).
* Life-Cycle - The API for life cycle management (install, start, stop, update, and uninstall bundles).
* Modules - The layer that defines encapsulation and declaration of dependencies (how a bundle can import and export code).
* Security - The layer that handles the security aspects by limiting bundle functionality to pre-defined capabilities. | First: good luck & good coffee. You'll need both.
I once had a similiar problem. Legacy code with awful circular dependencies, even between classes from different packages like org.example.pkg1.A depends on org.example.pk2.B **and** vice versa.
I started with maven2 and fresh eclipse projects. First I tried to identify the most common functionalities (logging layer, common interfaces, common services) and created maven projects. Each time I was happy with a part, I deployed the library to the central nexus repository so that it was almost immediately available for other projects.
So I slowly worked up through the layers. maven2 handled the dependencies and the m2eclipse plugin provided a helpful dependency view. BTW - it's usually not too difficult to convert an eclipse project into a maven project. m2eclipse can do it for you and you just have to create a few new folders (like src/main/java) and adjust the build path for source folders. Takes just a minute or two. But expect more difficulties, if your project is an eclipse plugin or rcp application and you want maven not only to manage artifacts but also to build and deploy the application.
To opinion, eclipse, maven and nexus (or any other maven repository manager) are a good basis to start. You're lucky, if you have a good documentation of the system architecture **and** this architecture is really implemented ;) | How to modularize a (large) Java App? | [
"",
"java",
"maven-2",
"refactoring",
"modularity",
""
] |
I'm currently working on a TCP socket server in C++; and I'm trying to figure out how I can ignore all browser connections made to my server. Any idea's?
Thanks. | Need more details to give good feedback.
Are you going to be listening on port 80 but want to avoid all HTTP traffic? Or will your protocol be HTTP-based? Do you need to listen on 80 or can you pick any port?
If it's your own custom protocol (HTTP or not) you could just look at the first line sent up and if it's not to your liking just close() the socket.
# EDIT:
Since you're going to be listening on a custom port, you probably won't get any browser traffic anyhow. Further, since you're going to be writing your own protocol, just require a handshake which establishes your client speaks your custom protocol and then ignore (close()) everything else.
Bonus points: depending on your goal, send back an HTTP error message which can be displayed to the user. | You can't stop a web-browser initiated tcp-session from connecting to your tcp server. You can (as stated above) close the connection once you've detected the client is trying to talk http to you (or any other unwanted application-layer protocol). | How to ignore certain socket requests | [
"",
"c++",
"tcp",
"sockets",
""
] |
We recently came across some sample code from a vendor for hashing a secret key for a web service call, their sample was in VB.NET which we converted to C#. This caused the hashing to produce different input. It turns out the way they were generating the key for the encryption was by converting a char array to a string and back to a byte array. This led me to the discovery that VB.NET and C#'s default encoder work differently with some characters.
C#:
```
Console.Write(Encoding.Default.GetBytes(new char[] { (char)149 })[0]);
```
VB:
```
Dim b As Char() = {Chr(149)}
Console.WriteLine(Encoding.Default.GetBytes(b)(0))
```
The C# output is 63, while VB is the correct byte value of 149.
if you use any other value, like 145, etc, the output matches.
Walking through the debugging, both VB and C# default encoder is SBCSCodePageEncoding.
Does anyone know why this is?
I have corrected the sample code by directly initializing a byte array, which it should have been in the first place, but I still want to know why the encoder, which should not be language specific, appears to be just that. | If you use ChrW(149) you will get a different result- 63, the same as the C#.
```
Dim b As Char() = {ChrW(149)}
Console.WriteLine(Encoding.Default.GetBytes(b)(0))
```
Read [the documentation](http://msdn.microsoft.com/en-us/library/613dxh46.aspx) to see the difference- that will explain the answer | The VB Chr function takes an argument in the range 0 to 255, and converts it to a character using the current default code page. It will throw an exception if you pass an argument outside this range.
ChrW will take a 16-bit value and return the corresponding System.Char value without using an encoding - hence will give the same result as the C# code you posted.
The approximate equivalent of your VB code in C# without using the VB Strings class (that's the class that contains Chr and ChrW) would be:
```
char[] chars = Encoding.Default.GetChars(new byte[] { 149 });
Console.Write(Encoding.Default.GetBytes(chars)[0]);
``` | Why Encoding.Default.GetBytes() returns different results in VB.NET and C#? | [
"",
"c#",
"vb.net",
"encoding",
""
] |
I wish to make a simple GET request to another script on a different server. How do I do this?
In one case, I just need to request an external script without the need for any output.
```
make_request('http://www.externalsite.com/script1.php?variable=45'); //example usage
```
In the second case, I need to get the text output.
```
$output = make_request('http://www.externalsite.com/script2.php?variable=45');
echo $output; //string output
```
To be honest, I do not want to mess around with CURL as this isn't really the job of CURL. I also do not want to make use of http\_get as I do not have the PECL extensions.
Would fsockopen work? If so, how do I do this without reading in the contents of the file? Is there no other way?
Thanks all
## Update
I should of added, in the first case, I do not want to wait for the script to return anything. As I understand file\_get\_contents() will wait for the page to load fully etc? | `file_get_contents` will do what you want
```
$output = file_get_contents('http://www.example.com/');
echo $output;
```
Edit: One way to fire off a GET request and return immediately.
Quoted from <http://petewarden.typepad.com/searchbrowser/2008/06/how-to-post-an.html>
```
function curl_post_async($url, $params)
{
foreach ($params as $key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$post_params[] = $key.'='.urlencode($val);
}
$post_string = implode('&', $post_params);
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($post_string)."\r\n";
$out.= "Connection: Close\r\n\r\n";
if (isset($post_string)) $out.= $post_string;
fwrite($fp, $out);
fclose($fp);
}
```
What this does is open a socket, fire off a get request, and immediately close the socket and return. | This is how to make Marquis' answer work with both POST and GET requests:
```
// $type must equal 'GET' or 'POST'
function curl_request_async($url, $params, $type='POST')
{
foreach ($params as $key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$post_params[] = $key.'='.urlencode($val);
}
$post_string = implode('&', $post_params);
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
// Data goes in the path for a GET request
if('GET' == $type) $parts['path'] .= '?'.$post_string;
$out = "$type ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($post_string)."\r\n";
$out.= "Connection: Close\r\n\r\n";
// Data goes in the request body for a POST request
if ('POST' == $type && isset($post_string)) $out.= $post_string;
fwrite($fp, $out);
fclose($fp);
}
``` | How do I make an asynchronous GET request in PHP? | [
"",
"php",
"http",
"curl",
"asynchronous",
""
] |
In C++ I would like to define some strings that will be used within a class but the values will be common over all instances. In C I would have used `#define`s. Here is an attempt at it:
```
#include <string>
class AskBase {
public:
AskBase(){}
private:
static std::string const c_REQ_ROOT = "^Z";
static std::string const c_REQ_PREVIOUS = "^";
static std::string const c_REQ_VERSION = "?v";
static std::string const c_REQ_HELP = "?";
static std::string const c_HELP_MSG = " ? - Help\n ?v - Version\n ^^ - Root\n ^ - Previous\n ^Z - Exit";
};
int main(){AskBase a,b;}
```
If C++0x is needed that is acceptable. | You will have to define them separately in a single translation unit (source file), like so:
```
//header
class SomeClass
{
static const std::string someString;
};
//source
const std::string SomeClass::someString = "value";
```
I believe the new C++1x standard will fix this, though I'm not entirely sure. | When I need string constants within a class, I never put them in the class itself, but either:
1) If they need to be exposed in the header, I put them outside of the class (in a namespace if appropriate), like this:
```
const char * const c_REQ_ROOT = "^Z";
...
```
2) If not, I put them in the cpp file, in an anonymous namespace.
You can then even group strings constant from several related components in the same header file.
It may be not the most "academic" way, but the code is simpler and easier to refactor. I never found any actual advantage of defining string constant as static class members.
I'm really interested by the opinion of other programmers here, so do not hesitate to leave your comments. | C++ Class Common String Constants | [
"",
"c++",
"c++11",
""
] |
I would like to produce nicely formatted tabular text from arbitrary dataset object models. Is there a good library to do this in Java?
Specifically, I want output that is formatted like command line data management tools such as the CLI for mysql. Example:
```
+---------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| name | varchar(100) | YES | | NULL | |
| release | year(4) | YES | | NULL | |
| studio | varchar(50) | YES | | NULL | |
| review | varchar(50) | YES | | NULL | |
| gross | int(11) | YES | | NULL | |
+---------+--------------+------+-----+---------+-------+
```
One main challenge is that I won't automatically know the maximum column widths before I start traversing the data. Also, there are plenty of edge cases, such as dealing with very large value lengths and large numbers of rows and columns.
If I have to build this myself, I imagine I would make use of String.format, and I'd need to pre-analyze the full dataset before starting the output. That's a very low level of coding though, so I'd love to find a good library that has already solved this problem. | Check out [TableFormatter](https://github.com/iNamik/Java-Text-Table-Formatter): it appears to do what you want for formatting tabular data. Source code is also available. You can append rows and cells to a table using a fluent interface approach. An example follows:
```
TableFormatter tf = new SimpleTableFormatter(true) // true = show border
.nextRow()
.nextCell()
.addLine("Field")
.nextCell()
.addLine("Type")
```
So it will build up the cells in the correct format and adjust whitespace accordingly. It also will allow you to do basic alignment of text within the cell (center, top, bottom) | trac.inamik.com/trac/jtable\_format is under GPL license, not suitable in some cases.
Another option (Apache 2 license):
<http://sourceforge.net/projects/texttablefmt/> | How to format tabular data as text in Java? | [
"",
"java",
"text",
"formatting",
""
] |
I'm having problem regarding max and sqrt
If I include math.h it coudn't find sqrt.
So I view the cmath header file and inside it includes math.h, but when I try to open math.h it says that file is not found. SO ithink my math.h is missing in Linux. | Sorry I found the answer.
I just need to write it this way:
std::max
std::sqrt
But Why does it work without "std::" under Windows OS? | NB:
in C++ you should #include <cmath> not #include <math.h>
NB:
also specifying the namespace is a good practice | C++ math functions problem (under Linux) | [
"",
"c++",
"linux",
"math",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.