Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
What is the best way to embed a truetype font within the application i'm developing? Basically i want to make sure a particular font is available to my application when installed on another machine. I have the \*.ttf font file and just need a way of embedding it or automatically installing it when the application is run.
Do i need to set the installation program to install the font during installation or can i dynamically load the font during runtime of the application? In fact both would be nice to know.
The application is being developed in C# using .NET 2.0. | This [blog post](http://www.siao2.com/2005/11/20/494829.aspx) should help you.
Basically you add the font as an embedded resource then load it into a [PrivateFontCollection](http://msdn.microsoft.com/en-us/library/system.drawing.text.privatefontcollection.aspx) object. | Here's Will's answer, translated to C# (untested):
```
PrivateFontCollection pfc = new PrivateFontCollection();
using (Stream fontStream = GetType().Assembly.GetManifestResourceStream("Alphd___.ttf"))
{
if (null == fontStream)
{
return;
}
int fontStreamLength = (int) fontStream.Length;
IntPtr data = Marshal.AllocCoTaskMem(fontStreamLength);
byte[] fontData = new byte[fontStreamLength];
fontStream.Read(fontData, 0, fontStreamLength);
Marshal.Copy(fontData, 0, data, fontStreamLength);
pfc.AddMemoryFont(data, fontStreamLength);
Marshal.FreeCoTaskMem(data);
}
```
along with their Paint() method:
```
protected void Form1_Paint(object sender, PaintEventArgs e)
{
bool bold = false;
bool italic = false;
e.Graphics.PageUnit = GraphicsUnit.Point;
using (SolidBrush b = new SolidBrush(Color.Black))
{
int y = 5;
foreach (FontFamily fontFamily in pfc.Families)
{
if (fontFamily.IsStyleAvailable(FontStyle.Regular))
{
using (Font font = new Font(fontFamily, 32, FontStyle.Regular))
{
e.Graphics.DrawString(font.Name, font, b, 5, y, StringFormat.GenericTypographic);
}
y += 40;
}
if (fontFamily.IsStyleAvailable(FontStyle.Bold))
{
bold = true;
using (Font font = new Font(fontFamily, 32, FontStyle.Bold))
{
e.Graphics.DrawString(font.Name, font, b, 5, y, StringFormat.GenericTypographic);
}
y += 40;
}
if (fontFamily.IsStyleAvailable(FontStyle.Italic))
{
italic = true;
using (Font font = new Font(fontFamily, 32, FontStyle.Italic))
{
e.Graphics.DrawString(font.Name, font, b, 5, y, StringFormat.GenericTypographic);
}
y += 40;
}
if(bold && italic)
{
using(Font font = new Font(fontFamily, 32, FontStyle.Bold | FontStyle.Italic))
{
e.Graphics.DrawString(font.Name, font, b, 5, y, StringFormat.GenericTypographic);
}
y += 40;
}
using (Font font = new Font(fontFamily, 32, FontStyle.Underline))
{
e.Graphics.DrawString(font.Name, font, b, 5, y, StringFormat.GenericTypographic);
y += 40;
}
using (Font font = new Font(fontFamily, 32, FontStyle.Strikeout))
{
e.Graphics.DrawString(font.Name, font, b, 5, y, StringFormat.GenericTypographic);
}
}
}
}
``` | How do I Embed a font with my C# application? (using Visual Studio 2005) | [
"",
"c#",
"fonts",
""
] |
If we are coding a JSP file, we just need to use the embedded "application" object. But how to use it in a Servlet? | The `application` object in JSP is called the [`ServletContext`](https://docs.oracle.com/javaee/7/api/javax/servlet/ServletContext.html) object in a servlet. This is available by the inherited [`GenericServlet#getServletContext()`](https://docs.oracle.com/javaee/7/api/javax/servlet/GenericServlet.html#getServletContext--) method. You can call this anywhere in your servlet except of the `init(ServletConfig)` method.
```
public class YourServlet extends HttpServlet {
@Override
public void init() throws ServletException {
ServletContext ctx = getServletContext();
// ...
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
ServletContext ctx = getServletContext();
// ...
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
ServletContext ctx = getServletContext();
// ...
}
}
```
See also [Different ways to get Servlet Context](https://stackoverflow.com/questions/35837285/differents-ways-to-get-servlet-context). | The [application](http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPIntro7.html) object references [javax.servlet.ServletContext](http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletContext.html) and you should be able to reference that in your servlets.
To reference the ServletContext you will need to do the following:
```
// Get the ServletContext
ServletConfig config = getServletConfig();
ServletContext sc = config.getServletContext();
```
From then on you would use the sc object in the same way you would use the application object in your JSPs. | How to use the "application" object in a Servlet? | [
"",
"java",
"jsp",
"servlets",
""
] |
I have a form which is a simple CRUD.
I am trying to display a cool looking success message when user enters or deletes a record. I've seen this a lot around the web.
I am very new to jquery. does anyone know any examples that would show how to do this?
Basically a div that would slowly dim out. | Your question is a little vague as a "cool looking success message" is not much to go with.
If you are interested, however, through answering questions here I have replicated the functionality of two of Stackoverflow's "notification" features that people seem to enjoy: the banner at the top of the page that comes up when you get a new badge, etc. and the red boxes around the site whenever something goes wrong with an action. I've used techniques similar to these to show success messages in my applications and my clients have loved them.
* [To show the top banners](https://stackoverflow.com/questions/659199/how-to-show-popup-message-like-in-stackoverflow/659243#659243) - [demo](http://jsbin.com/owuje)
* [To show the red boxes](https://stackoverflow.com/questions/758906/how-would-i-implement-stackoverflows-hovering-dialogs/759062#759062) - [demo](http://jsbin.com/oqale)
The examples are very simple, as all it is doing is showing a DIV somewhere in the document and fading it in and out depending on the situation. That's all you really need to get started.
In addition to this, if you are a Mac fan (and even if you're not) there is the [jQuery Growl](http://plugins.jquery.com/project/Growl) plugin which is based on the OS X notification system. I am also a big fan of using the [BeautyTips](http://www.lullabot.com/files/bt/bt-latest/DEMO/index.html) plugin to show messages near an element, as the bubbles are very nice and easy to style. | I really like [jGrowl](https://github.com/stanlemon/jGrowl). It's very unobtrusive as the messages appear in the left corner and the user can continue to do whatever he's doing, but he does get feedback from the system. And it also looks very fancy :). | Best ways to display notifications with jQuery | [
"",
"javascript",
"jquery",
"html",
""
] |
Does anyone have good examples of IoC containers (preferably in c#) and how and why to use them ? I have checked out the [wiki page](http://en.wikipedia.org/wiki/Inversion_of_control) and [Ayende's](http://ayende.com/Blog/archive/2007/10/20/Building-an-IoC-container-in-15-lines-of-code.aspx) example, but I don't quite get the concept yet.
And when and where should I use an IoC container ? | I've used [StructureMap](http://structuremap.github.io/) quite a bit. The rest of your question is pretty loaded. I'll try to explain the concept in an example.
Suppose you created a website that will accept payments through PayPal. PayPal is now a dependency. But you don't want to code against a specific PayPal provider.
Instead, you would create and code against an interface like this:
```
interface IPaymentProcessor
{
bool ProcessPayment(amount, ....);
}
```
All your PayPal code would reside in a class that implements the methods of your interface - `PayPalPaymentProcessor`, for example.
Now you have an object that you will actually use to process the payments. This could be a Controller (ASP.NET-MVC, ViewModel-WPF) or just a class as shown here:
```
class PaymentProcessor
{
private IPaymentProcessor _processor = null;
public PaymentProcessor(IPaymentProcessor processor)
{
_processor = processor;
}
public bool ProcessTransaction(Transaction trans)
{
_processor.ProcessPayment(trans.amount, ...);
}
}
```
This is where an IoC container comes in. Instead of you calling the constructor manually, you would let an IoC container *inject* the dependency:
```
PaymentProcessor processor = ObjectFactory.GetInstance<PaymentProcessor>();
```
This piece of code tells StructureMap "Anytime you see a constructor that needs an `IPaymentProcessor`, return a new `PayPalPaymentProcessor`".
```
ObjectFactory.Initialize(x =>
{
x.ForRequestedType<IPaymentProcessor>().TheDefaultIsConcreteType<PayPalPaymentProcessor>();
});
```
All this mapping is separate from your implementation code and you could swap out these at a later point with little refactoring needed. There is a lot more to IoC containers, but that the basic concept. You can automate the injection of constructors to avoid the calls directly to `ObjectFactory` as well.
Hope this helps! | Be aware of the following limitations of the IOC container. I have to warn people, because I am living with the hell of having to support a system using it:
* Exceptions thrown by constructors get swallowed. You only get the “couldn’t create dependency” exception. That means you can't catch expected exceptions if it's throw in a constructor.
* Can’t step through constructors.
* Forgetting to register an interface breaks at runtime instead of compile time.
* All your classes can only have one constructor and they all have to accept interfaces as parameters.
* All dependencies are instantiated so you can’t share instances, which means your memory usage can get large quickly.
* It promotes a lot of interdepencies which can hide the fact that you code has turned into spaghetti. Making it easier to instatiate all of these interdepencies just masks that there is a potential underlying problem.
* You can't manage your own "Unit of Work" very easily because you can't manage a transaction across multiple dependencies since you didn't have control of instantiating them and passing in the context of that transaction.
Don't get me wrong, I love dependency injection and the inversion of control principle, but I think the IOC container could be used responsibly, but just be aware of the battles that you will need to fight because of the above list. | Examples of IoC Containers | [
"",
"c#",
"inversion-of-control",
""
] |
I read the [C++ version of this question](https://stackoverflow.com/questions/321068/returning-multiple-values-from-a-c-function) but didn't really understand it.
Can someone please explain clearly if it can be done in C#, and how? | In C# 7 and above, see [this answer](https://stackoverflow.com/a/36436255/316760).
In previous versions, you can use [.NET 4.0+'s Tuple](http://msdn.microsoft.com/en-us/library/system.tuple.aspx):
For Example:
```
public Tuple<int, int> GetMultipleValue()
{
return Tuple.Create(1,2);
}
```
Tuples with two values have `Item1` and `Item2` as properties. | Now that C# 7 has been released, you can use the new included Tuples syntax
```
(string, string, string) LookupName(long id) // tuple return type
{
... // retrieve first, middle and last from data storage
return (first, middle, last); // tuple literal
}
```
which could then be used like this:
```
var names = LookupName(id);
WriteLine($"found {names.Item1} {names.Item3}.");
```
You can also provide names to your elements (so they are not "Item1", "Item2" etc). You can do it by adding a name to the signature or the return methods:
```
(string first, string middle, string last) LookupName(long id) // tuple elements have names
```
or
```
return (first: first, middle: middle, last: last); // named tuple elements in a literal
```
They can also be deconstructed, which is a pretty nice new feature:
```
(string first, string middle, string last) = LookupName(id1); // deconstructing declaration
```
Check out [this link](https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/) to see more examples on what can be done :) | Return multiple values to a method caller | [
"",
"c#",
"return",
""
] |
Learning boost, and compiled their daytime server client [example](http://www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/examples.html). Since I cant use port 13 that is in the example I only changed the port numbers in the server and client example. Server runs fine, but the client doesnt connect it seems, and no error is given.
Input data for the client is "127.0.0.1".
Server:
```
#include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
int main()
{
try
{
boost::asio::io_service io_service;
tcp::endpoint endpoint(tcp::v4(), 8087);
tcp::acceptor acceptor(io_service, endpoint);
for (;;)
{
tcp::iostream stream;
acceptor.accept(*stream.rdbuf());
stream << "test" << make_daytime_string();
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
```
And the client:
```
#include <iostream>
#include <string>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: daytime_client <host>" << std::endl;
return 1;
}
tcp::iostream s(argv[1], 8087);
std::string line;
std::getline(s, line);
std::cout << line << std::endl;
}
catch (std::exception& e)
{
std::cout << "Exception: " << e.what() << std::endl;
}
return 0;
}
``` | A few things would help to debug this for you:
1. What platform are you running
2. What compiler are your using, including version
3. What version of boost are you using
Also, one thing to check is whether the server is binding to 127.0.0.1 or the external interface. Try using the IP address of your external interface instead of 127.0.0.1. Check this in windows using ipconfig and in linux using ifconfig. | What worked for me was to change the way I create the endpoint from
```
tcp::endpoint( tcp::v4(), port );
```
to
```
tcp::endpoint( boost::asio::ip::address::from_string("127.0.0.1"), port );
```
The first method creates an endpoint of 0.0.0.0 which works fine on Mac OS X, but gives the "not valid" message on Windows (XP, building with MSVC 2008).
I wouldn't mind knowing WHY the difference, but at least it works. | Simple server/client boost example not working | [
"",
"c++",
"boost",
"tcp",
"boost-iostreams",
""
] |
Let's say I've got a PHP function foo:
```
function foo($firstName = 'john', $lastName = 'doe') {
echo $firstName . " " . $lastName;
}
// foo(); --> john doe
```
Is there any way to specify only the second optional parameter?
Example:
```
foo($lastName='smith'); // output: john smith
``` | PHP does not support named parameters for functions per se. However, there are some ways to get around this:
1. Use an array as the only argument for the function. Then you can pull values from the array. This allows for using named arguments in the array.
2. If you want to allow optional number of arguments depending on context, then you can use func\_num\_args and func\_get\_args rather than specifying the valid parameters in the function definition. Then based on number of arguments, string lengths, etc you can determine what to do.
3. Pass a null value to any argument you don't want to specify. Not really getting around it, but it works.
4. If you're working in an object context, then you can use the magic method \_\_call() to handle these types of requests so that you can route to private methods based on what arguments have been passed. | A variation on the array technique that allows for easier setting of default values:
```
function foo($arguments) {
$defaults = array(
'firstName' => 'john',
'lastName' => 'doe',
);
$arguments = array_merge($defaults, $arguments);
echo $arguments['firstName'] . ' ' . $arguments['lastName'];
}
```
Usage:
```
foo(array('lastName' => 'smith')); // output: john smith
``` | Any way to specify optional parameter values in PHP? | [
"",
"php",
"function",
"optional-parameters",
""
] |
I'm trying to write a PHP script using cURL that can authorize a user through a page that uses an SSL certificate, in addition to username and password, and I can't seem to get past the SSL cert stage.
In this case, `curl_setopt($handle, CURLOPT_VERIFYPEER, 0)` unfortunately isn't an option. The certificate is a required part of authentication, otherwise I get the error mentioned in [this other similar SO post](https://stackoverflow.com/questions/521418/reading-ssl-page-with-curl-php).
I've tried a few command-line runs with cURL:
`> curl --url https://website`
This returns the `(60) SLL certificate problem` error. If I adjust the command to include the `--cacert` option:
`> curl --url https://website --cacert /path/to/servercert.cer`
It works just fine; the auth website is returned.
However, I've tried the following PHP code:
```
$handle = curl_init();
$options = array(
CURLOPT_RETURNTRANSFER => false,
CURLOPT_HEADER => true,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_SSL_VERIFYHOST => '0',
CURLOPT_SSL_VERIFYPEER => '1',
CURLOPT_CAINFO => '/path/to/servercert.cer',
CURLOPT_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)',
CURLOPT_VERBOSE => true,
CURLOPT_URL => 'https://website'
);
curl_setopt_array($handle, $options);
curl_exec($handle);
if (curl_errno($handle)) {
echo 'Error: ' . curl_error($handle);
}
curl_close($handle);
```
I would have thought the code was essentially analogous to the shell commands, but instead I'm greeted with the following error message:
> Error: error setting certificate verify locations: CAfile: /path/to/servercert.cer CApath: none
I've read all the literature I can find (particularly on php.net and curl.haxx) and can't seem to find anything that fixes this problem. Any suggestions?
I have tried `chmod 777 servercert.cer` with no success. However, in executing the PHP script with the above code from the command line instead of the browser via `php test.php`, it works perfectly. Any explanation for why it doesn't work in the browser? | Because things work via the command line but not via php using curl then I would pursue curl being the problem.
According to this URL, <http://curl.haxx.se/docs/sslcerts.html>, which was reference in an SO post you cited above ( [reading SSL page with CURL (php)](https://stackoverflow.com/questions/521418/reading-ssl-page-with-curl-php) )...
"Until 7.18.0, curl bundled a severely outdated ca bundle file that was
installed by default. These days, the curl archives include no ca certs at
all. You need to get them elsewhere. See below for example.
If the remote server uses a self-signed certificate, if you don't install a CA
cert bundle, if the server uses a certificate signed by a CA that isn't
included in the bundle you use or if the remote host is an impostor
impersonating your favorite site, and you want to transfer files from this
server, do one of the following:"
It then goes on to list a number of steps that you can try.
Since your 7.16.3 version of curl is prior to 7.18.0, if you haven't already, I would recommend updating your curl and openssl components and then working through the list referenced above. | To elaborate and sum this up:
if you have a PHP file using PHP curl and place the ca certificate for your systems in the same directory, the below code will give you a jumpstart
```
$url = "https://myserver.mydomain.local/get_somedata.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//These next lines are for the magic "good cert confirmation"
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_VERBOSE, true);
//for local domains:
//you need to get the pem cert file for the root ca or intermediate CA that you signed all the domain certificates with so that PHP curl can use it...sorry batteries not included
//place the pem or crt ca certificate file in the same directory as the php file for this code to work
curl_setopt($ch, CURLOPT_CAINFO, __DIR__.'/cafile.pem');
curl_setopt($ch, CURLOPT_CAPATH, __DIR__.'/cafile.pem');
//DEBUG: remove slashes on the next line to prove "SSL verify" is the cause
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Error handling and return result
$data = curl_exec($ch);
if ($data === false) {
$result = curl_error($ch);
} else {
$result = $data;
}
// Close handle
curl_close($ch);
return $result;
``` | Error using PHP cURL with SSL certificates | [
"",
"php",
"ssl",
"curl",
"certificate",
""
] |
We host a service (servlet running on jboss), which receives something like 5-6 requests per second. Every request needs to connect to mysql through hibernate. Most of our requests do selects, with an insert/update every 5th/6th request. The hibernate mysql connection gets timed out after mysql connection time out period (8 hours). Even after having a request pinging our service, every hour, the mysql connection sometimes gets randomly disconnected after a day or so. We want hibernate to reconnect in case the connection is disconnected due to any reason, and maintain the number of connections we want it to.
We tried C3P0, with the following configuration:
```
<property name=c3p0.acquire_increment>1</property>
<property name=c3p0.idle_test_period>3600</property>
<property name=c3p0.max_statements>0</property>
<property name=c3p0.min_size>1</property>
<property name=c3p0.timeout>3605</property>
<property name=hibernate.c3p0.preferredTestQuery>select 1;</property>
```
Hibernate connection\_pool size was set to 1.
This made the timeout/disconnect problem go away. But we started facing another problem. Long waits. Normally the request serve time for us is 2-3ms for select and 40-50ms for insert/update. But, after using the above C3P0 configuration, we saw that every request completing after an update was taking more than a minute and sometimes even 4-5 minutes! From our logs, it seemed that randomly a select request would get stuck and will be able to complete only after an update request was received and served.
Above problem goes away if we remove the C3P0 config. Can somebody suggest what we might be doing wrong?
Here is the complete hibernate config for reference:
```
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://xxx.xxx.xxx</property>
<property name="connection.username">xxx</property>
<property name="connection.password">xxx</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.cache.use_query_cache">false</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
<property name="show_sql">true</property>
<!-- Transaction isolation 2 = READ_COMMITTED -->
<property name="connection.isolation">2</property>
<property name="connection.autocommit">true</property>
<!-- configuration pool via c3p0-->
<property name="c3p0.acquire_increment">1</property>
<property name="c3p0.idle_test_period">3600</property> <!-- seconds -->
<property name="c3p0.max_size">1</property>
<property name="c3p0.max_statements">0</property>
<property name="c3p0.min_size">1</property>
<property name="c3p0.timeout">3605</property> <!-- seconds -->
<property name="hibernate.c3p0.preferredTestQuery">select 1;</property>
</session-factory>
</hibernate-configuration>
``` | I'd recommend abandoning C3P0 and using the JNDI naming service and connection pooling that JBOSS provides.
Be sure that you are closing connections properly and returning them to the pool. Connect, query, close, all in the narrowest scope possible. No connection should be hanging around for eight hours.
Some more links might be pertinent: <http://www.hibernate.org/117.html> and <http://www.informit.com/articles/article.aspx?p=353736&seqNum=4> regarding Hibernate and closing connections, and this MySQL bug that cites problems with MySQL, Hibernate, and connections: <http://bugs.mysql.com/bug.php?id=10917> | Something seems amiss with your configuration. All configuration parameters should be in the hibernate.c3p0 namespace, not c3p0.\*.
But that's probably not the problem. I think most likely your pool is only one connection big and you are experiencing resource contention issues somewhere. Most likely not releasing a connection where you should, or a deadlock on some data. Try setting maxPoolsize to something higher, like 2 and see if the problem is mitigated any. This would probably mean you're not properly returning connections. | Hibernate/mysql connection pooling | [
"",
"java",
"mysql",
"hibernate",
""
] |
I'm been a PHP developer for quite some time now but until today I've not found a simple way to process (aka normalize, sanitize, validate, populate and display forms and it's respective field errors).
I know that most of the PHP frameworks nowadays make this job easier but somehow I don't feel like porting all my code to one of these frameworks, and I can't quite understand how the form validation is implemented in Django for instance (I know, it's Python but I really like their approach), so I though the best way would for me to post here the way I process a simple form and maybe you guys can point me in the best direction.
```
<?php
// sample controller
class _sample extends framework
{
// sample action
function contact()
{
if ($this->Is->Post() === true)
{
$errors = array();
if ($this->Is->Set($_POST['name']) === false)
{
$errors['name'] = 'Please fill in your name.';
}
if (($this->Is->Email($_POST['email']) === false) || ($this->Is->Set($_POST['email']) === false))
{
$errors['email'] = 'Please fill in your email address.';
}
if (($this->Is->Phone($_POST['contact']) === false) && ($this->Is->Mobile($_POST['contact']) === false))
{
$errors['contact'] = 'Please fill in your phone (or cell phone) number.';
}
if ($this->Is->Set($_POST['message']) === false)
{
$errors['message'] = 'Please type a message';
}
// no errors, it's valid!
if (empty($errors) === true)
{
// do stuff and redirect to "success" / "thank you" page
}
// load the form view, and let it display the errors
// automatically prefill fields with $_POST values
else
{
$this->View('contact_form', $errors);
}
}
// load the form view for the first time
else
{
$this->View('contact_form');
}
}
}
?>
```
As you can see, this is supposed to be a simple contact form however it takes the life out of me to validate it, I have been looking into some design patterns (Observer, Factory) but I do not feel confident if and in what way I should implement them. | You could make an abstract base class for all your forms, classes for fieldtypes, and a static class just for validating the values of various types (validateString, validateHtml, validateEmail, validateNumber, date, etc, just the methods..). Defining your form, you would define what field objects would it use, so the Form->validate() method would invoke the Field->validate() and return the filtered value or error message. Specify default error messages for the fields, but give an option to override it when defining fields in your form class.
Oh, and leave that $\_POST thing. Read the post once, pass it once to the form validation and then work on filtered field values.
Another thing is there are various ways to achieve form validation depending on your needs and the architecture of your applications, it can be hard to make an all-purpose form validator when you have various approaches to your application design. Choose a way of doing your work and stick to it (regardless if it's a ready to go framework or your own code), or whatever super-duper-form-validation you write, it will make no sense in latter projects.
One more: like Django? Good! So start programming Python in Django, you'll really change the way of thinking how to get your job done. | IMHO, the attempt to treat a form as a single concept is a failure. If you have any kind of layered architecture to your application, forms are likely to cut across these. Forms have application logic (controller layer), they have a visual representation (view layer), they have state (application layer model), and in the end they usually invoke some kind of transactional script (model layer).
I think you're much better off dropping the idea of a "form" as an entity and instead focus on the three parts (input processing, rendering and model layer) as completely separate matters, that just might (or might not) happen to be closely related to each other. This is some times referred to as the MVC pattern, although the term is so strongly loaded by now that it could mean a lot of things. | How do I simplify Form Processing in PHP? | [
"",
"php",
"validation",
"forms",
""
] |
I have made an application, which keeps getting updated frequently. So every time a change occurs, i've to include it's fresh builds to the setup and deployment program again and again. Is there any way to simplify the procedure? The files to be added are static in number and exist in a folder. I've heard we can write installer classes in c#, does my requirement has any thing to do with it?
I think ClickOnce doesn't suit my requirement because, for the first time i want it to run like a setup package, since it has some packages and some settings needed to be implemented on the user's machine at the time of install. Can click once help me with that? Also i want to run my application as an administrator and it references to many external dll files. So will it help my purpose?
**I finally did it using clickonce deployment. I used content files to mark all the files i wanted to copy to the target computer and used clickonce deployment. Then i modified the way my program starts, so that i can lauch the installer script i wanted to run only when the app runs for the first time. Further i hosted it on IIS and had to change lot of MIME types and add new ones for the download to work over internet** | Look into something called "ClickOnce" deployment. It automates a lot of what you're talking about.
EDIT: You can add custom installer actions to a ClickOnce project just like any other, to set up additional components and whatnot. As for permissions, ClickOnce will let you run as administrator if you so choose, but that sort of thing isn't recommended, and it might whine about it. | You can use ClickOnce (<http://msdn.microsoft.com/en-us/library/t71a733d(VS.80).aspx>) which simplify the deployment process.
Maybe you can also automate the build process using NANT (<http://nant.sourceforge.net/>).
HTH | Simplifying setup and deployment in c# | [
"",
"c#",
"installation",
""
] |
*Even though the solution is so obvious I should have never have posted this, I'm leaving it up as a reminder and a useful point of reference to others.*
I've got the following in my app.config file:
```
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
```
Followed by:
```
<spring>
<context>
<resource uri="config://spring/objects"/>
</context>
<objects xmlns="http://www.springframework.net">
<object name="mediaLibrary" type="AlbumLibraryWPF.AlbumLibrary, AlbumLibraryWPF"/>
</objects>
</spring>
```
Then in my app I've got:
```
using Spring.Context;
using Spring.Context.Support;
public partial class AlbumChecker : Window
{
private DataTable dataTable;
private Library library;
private Thread libraryThread;
public AlbumChecker()
{
InitializeComponent();
CreateToolTips();
IApplicationContext ctx = ContextRegistry.GetContext();
library = (Library)ctx.GetObject("mediaLibrary");
// Other initialisation
}
// Other code
}
```
It all compiles quite nicely, however, I'm getting an exception raised on the call to GetContext():
```
Error creating context 'spring.root': Could not load type from string value
'AlbumLibraryWPF.AlbumLibrary, AlbumLibraryWPF'.
```
I've checked the Spring.NET documentation and can't see what I'm doing wrong - but I clearly have got something wrong, otherwise it wouldn't raise the exception!
`AlbumLibraryWPF` is the namespace and `AlbumLibraryWPF.AlbumLibrary` is the fully qualified name of the class I want to instantiate. I'm guessing that it's this I've got wrong, but can't see how. | I feel such a fool.
It was because I'd failed to copy the AlbumLibrary.dll to the correct output directory. That meant that Spring couldn't find it - even after I'd fixed the assembly name problem Kent highlighted. | The name after the comma should be the assembly name, which is not necessarily the same as the namespace name. | Why am I getting an exception raised from Spring.NET on the call to ContextRegistry.GetContext()? | [
"",
"c#",
"wpf",
"spring.net",
""
] |
I am having problem with writing PDF files to browser. Other mime types work fine.
PDF files become corrupted.
```
FileInfo file = new FileInfo(Path.Combine(_module.FileDir, _file.FilePath));
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = _file.ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Regex.Replace(_file.FilePath, "\\s", "-"));
Response.AppendHeader("Content-Length", file.Length.ToString());
try
{
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}
catch
{
Response.ClearContent();
}
``` | My problem was with HTTP Module. I was applying White space filter
```
HttpApplication app = sender as HttpApplication;
if (app != null && app.Request.RawUrl.Contains(".aspx"))
{
app.Response.Filter = new WhitespaceFilter(app.Response.Filter);
}
``` | IIS HTTP Compression and Streaming PDF's: Don't work well.
<http://blog.1530technologies.com/2006/11/iis_http_compre.html> | Response.WriteFile PDF files - corrupted files | [
"",
"c#",
"pdf",
""
] |
How might I design a UI in C#/WinForms which happens to contain several different control types such that only the ListView control gets resized if the user resizes the window? | There are two primary ways to make a control automatically resize based on size changes of the parent container (a Form in your case):
1. Set the Dock property of the control to DockStyle.Fill.
2. Set the Anchor property to "Top, Bottom, Left, Right"
### Use the Dock property with Dock.Fill
The advantage of this method is that it takes the entire control and tells it to always fill the entire client area of the parent container (in your case, the Form client area). That's useful if you want to do something like fill a Form with a ListControl or TreeView or something like that. But it's not as useful if you want to scale a single control while using other controls (as you indicate is your need). In that case, you would need to set the Dock property on those other controls to DockStyle.Top or DockStyle.Bottom to have them float above or below your main resizing control.
That's a hassle and it also limits the layout options of the other controls. You can mitigate that problem by docking two Panel controls, one at the top and another at the bottom of the Form. Those panels will remain in fixed positions while the middle area (with your DockStyle.Fill control) scales with the parent Form. You can then put any controls in any layout configuration in those "header" and "footer" panels.
This kind of composite form-building using docked panels is incredibly powerful. Quite frankly, it was game changing in .NET when they introduced this with .NET 1.0 WinForms.
### Use the Anchor property with "Top, Bottom, Left, Right"
If all you want to do is have a single control on a form scale, while others stay "stuck" to the edges, use the Anchor property. For the controls that you want to stay at the top, set the Anchor property to "Top, Left" (the default). For controls that you want to stay at the bottom, set the Anchor property to "Bottom, Left". For controls that you want to grow in width with the form/dialog (such as a single-line textbox control), set the Anchor property to "Left, Right" (and set Top or Bottom depending whether you want it move as the top or the bottom of the dialog changes.
And if you want a control to resize in all directions with a Form, set the Anchor property to "Top, Left, Bottom, Right". Very useful for "main control" type of things, such as a dominant listbox, tree control, or multi-line textbox.
For what you need, don't mess with the AutoSize or AutoSizeMode... those properties control how a control changes size based on its own contents, not how it resizes based on its container's behavior. Think of AutoSize/AutoSize mode as inward looking, while Anchor/Dock are outward looking. You get some very bizarre behavior if you use both sizing methods at the same time. Generally not useful. | Dock the ListView to all four sides of the form, and the other controls to 2 or less. | Resizing a Single Control In WinForms | [
"",
"c#",
"windows",
"winforms",
"user-interface",
"resize",
""
] |
I'm looking at the generated code by ASP.NET MVC 1.0, and was wondering; what do the double question marks mean?
```
// This constructor is not used by the MVC framework but is instead provided for ease
// of unit testing this type. See the comments at the end of this file for more
// information.
public AccountController(IFormsAuthentication formsAuth, IMembershipService service)
{
FormsAuth = formsAuth ?? new FormsAuthenticationService();
MembershipService = service ?? new AccountMembershipService();
}
```
### Related:
> [?? Null Coalescing Operator —> What does coalescing mean?](https://stackoverflow.com/questions/770186/-null-coalescing-operator-what-does-coalescing-mean) | This is the [null-coalescing operator](http://msdn.microsoft.com/en-us/library/ms173224.aspx). It will return the value on its left if that value is not null, else the value on the right (even if it is null). They are often chained together ending in a default value.
[Check out this article for more](http://weblogs.asp.net/scottgu/archive/2007/09/20/the-new-c-null-coalescing-operator-and-using-it-with-linq.aspx) | It means the same as
```
If (formsAuth != null)
FormsAuth = formsAuth;
else
FormsAuth = FormsAuthenticationService();
``` | What does "??" mean? | [
"",
"c#",
""
] |
I have a form in a PHP sending variables to a PHP file which duly inserts them into a MySQL table.
I currently have a div displaying the response from the PHP (which is anything that is printed by the PHP).
All works fine. The problem is I want to use variables that are created/updated during the PHP MySQL insert process. I.e. not only show what is printed in that PHP file, but USE those variables.
I have seen complicated use of the JSON Encoding to possibly cross this divide, but I'd love to know if that's the simplest approach. And if anyone has any good links or examples on the subject. | I assume that you want to be able to have multiple pieces of data sent back via AJAX to your page and manipulate those.
JSON is indeed the simplest way to do this. If you use PHP5, you can use json\_encode() from the PHP side to send a complicated data type (such as an object or an array) back to the browser page. Then in the javascript, you use eval() on the data that is sent back (ex: var data = eval(response);) to parse it back into a usable complicated type in javascript.
There are tons of tutorials out there that will show you how to do this and explain it in further detail than a response here ever could. | Use [PrototypeJS](http://www.prototypejs.org) and do it like this:
Have some PHP like this
```
$jsonHeader = array();
if($_REQUEST['param1'])
{
echo '<p>You passed ' . $_REQUEST['param1'] . '</p>';
$jsonHeader['status'] = 'Success';
}else
{
$jsonHeader['status'] = 'Failed because the request was invalid';
}
if(is_array($jsonHeader) and sizeof($jsonHeader) > 0)
{
header('X-JSON: (' . json_encode($jsonHeader) . ')');
}
```
Then make your Ajax call like this
```
new Ajax.Request('dostuff.php', {
method: 'get',
parameters: {'param1': 'this is param 1'},
onSuccess: function(response, jsonHeader){
if(jsonHeader['status'] == 'Success'){
//Everything is OK, do stuff
}else{
alert(jsonHeader['status']);
}
},
onFailure: function(){
alert('Fail!');
}
});
```
Prototype grabs the X-JSON header returned by PHP and automatically sets the jsonHeader argument of the onSuccess function to a Javascript array of the values that were originally set in PHP.
---
The above scenario is good as long as the amount of data you're returning to Javascript fits in the HTTP header.
If you need to pass back lots of data, just have PHP output the JSON encoded result rather than making it part of the header. Then you can use the evalJSON() method of the response object in your Ajax call. | Retrieving PHP variables from an AJAX form input | [
"",
"php",
"ajax",
"json",
""
] |
I've got a requirement to pass parameters as Xml to my stored procedures.
I have a WCF service in the middle tier that makes calls to my data layer which in turn forwards the request to the appropriate stored procedure.
The design is that the WCF service is responsible for building the Xml to pass to the Repository.
I'm just wondering whether to keep control of what parameters are contained within the Xml in the middle tier or use a Dictionary built up by the client which I then convert to Xml in the middle tier?
At the moment I've gone for the latter - for example:
```
public TestQueryResponseMessage TestQuery(TestQueryRequestMessage message)
{
var result = Repository.ExecuteQuery("TestQuery", ParamsToXml(message.Body.Params));
return new TestQueryResponseMessage
{
Body = new TestQueryResponse
{
TopicItems = result;
}
}
}
private string ParamsToXml(Dictionary<string, string> nvc)
{
//TODO: Refactor
StringBuilder sb = new StringBuilder();
sb.Append("<params>");
foreach (KeyValuePair<string, string> param in nvc)
{
sb.Append("<param>");
sb.Append("<" + param.Key + ">");
sb.Append(param.Value);
sb.Append("</" + param.Key + ">");
sb.Append("</param>");
}
sb.Append("</params>");
return sb.ToString();
}
```
However I might need to do it the first way. E.g.
```
public TestQueryResponseMessage TestQuery(TestQueryRequestMessage message)
{
string xml = string.Format("<params><TestParameter>{0}</TestParameter></params>",message.Body.TestParameter)
var result = Repository.ExecuteQuery("TestQuery", xml);
return new TestQueryResponseMessage
{
Body = new TestQueryResponse
{
TopicItems = result;
}
}
}
```
What does the hivemind recommend? | If you must use xml; then rather than passing around a dictionary, I'd use a class that represents that data, and use `XmlSerializer` to fetch it as xml:
```
[Serializable, XmlRoot("args")]
public class SomeArgs {
[XmlElement("foo")] public string Foo { get; set; }
[XmlAttribute("bar")] public int Bar { get; set; }
}
...
SomeArgs args = new SomeArgs { Foo = "abc", Bar = 123 };
XmlSerializer ser = new XmlSerializer(typeof(SomeArgs));
StringWriter sw = new StringWriter();
ser.Serialize(sw, args);
string xml = sw.ToString();
```
This makes it much easier to manage which arguments apply to which queries, in an object-oriented way. It also means you don't have to do your own xml escaping... | Once you use Bob The Janitor's solution and you have your XML.
Create your stored procedure with a XML parameter. Then depending on how much XML you have and what your doing with it you can use Xquery or OpenXML to shred the XML document. Extract the data and perform the right action. This example is basic and pseudocode like but you should get the idea.
```
CREATE PROCEDURE [usp_Customer_INS_By_XML]
@Customer_XML XML
AS
BEGIN
EXEC sp_xml_preparedocument @xmldoc OUTPUT, @Customer_XML
--OPEN XML example of inserting multiple customers into a Table.
INSERT INTO CUSTOMER
(
First_Name
Middle_Name
Last_Name
)
SELECT
First_Name
,Middle_Name
,Last_Name
FROM OPENXML (@xmldoc, '/ArrayOfCustomers[1]/Customer',2)
WITH(
First_Name VARCHAR(50)
,Middle_Name VARCHR(50)
,Last_Name VARCHAR(50)
)
EXEC sp_xml_removedocument @xmldoc
END
``` | Passing Parameters as Xml to a Stored Procedure | [
"",
"c#",
"xml",
"t-sql",
"soa",
""
] |
I'm trying to load a properties file without using the actual path of the file. I've already done that on some other simple apps using:
```
InputStream inputStream = ClassLoader.getSystemResourceAsStream(PROPERTIES_FILE);
props.load(inputStream);
```
But this time it doesn't work. The inputStream is null for some reason. PROPERTIES\_FILE is a constant defined as "app.properties". I tried to remove the .properties extension and got the same results.
Any ideas?
Thanks. | The PROPERTIES\_FILE constant should include the package as well as the properties file (e.g. "com/some/library/file.properties".
```
final static String PROPS_FILE = "/com/some/library/file.props";
//The preceding "/" is dependendant on wheterh
//you are going to be giving a relative or absolute location
InputStream is = YourCurrentClass.class.getResourceAsStream(PROPS_FILE);
``` | Got the same problem.
Reason: I renamed `DAO` package to `dao`. While exploding the `artifact`, directory `DAO` not get overwritten.
So I got `dao` in project internals and `DAO` in filesystem :facepalm: | classloader.getSystemResourceAsStream returns null | [
"",
"java",
"properties",
"classloader",
""
] |
I am randomly generating a grid of characters and storing it in a char[,] array ...
I need a way to ensure that i haven't already generated a grid before serializing it to a database in binary format...what is the best way to compare two grids based on bytes? The last thing i want to do is loop through their contents as I am already pulling one of them from the db in byte form.
I was thinking checksum but not so sure if this would work.
```
char[,] grid = new char[8,8];
char[,] secondgrid = new char[8,8];//gets its data from db
``` | From what I can see, you are going to *have* to loop over the contents (or at least, a portion of it); there is no other way of talking about an arrays contents.
Well, as a fast "definitely not the same" you could compute a hash over the array - i.e. something like:
```
int hash = 7;
foreach (char c in data) {
hash = (hash * 17) + c.GetHashCode();
}
```
This has the risk of some false positives (reporting a dup when it is unique), but is otherwise quite cheap. Any use? You could store the hash alongside the data in the database to allow fast checks - but if you do that you should pick your own hash algorithm for `char` (since it isn't guaranteed to stay the same) - perhaps just convert to an int, for example - or to re-use the existing implementation:
```
int hash = 7;
foreach (char c in data) {
hash = (hash * 17) + (c | (c << 0x10));
}
```
---
As an aside - for 8x8, you could always just think in terms of a 64 character string, and just check `==`. This would work equally well at the database and application. | Can't you get the database to do it? Make the grid column UNIQUE. Then, if you need to detect that you've generated a duplicate grid, the method for doing this might involve checking the number of rows affected by your operation, or perhaps testing for errors.
Also, if each byte is simply picked at random from [0, 255], then performing a hash to get a 4-byte number is no better than taking the first four bytes out of the grid. The chance of collisions is the same. | ensure two char arrays are not the same | [
"",
"c#",
".net",
""
] |
I'm trying to work out what's not working in this code:
```
#!/usr/bin/python
import cmd
class My_class (cmd.Cmd):
"""docstring for Twitter_handler"""
def __init__(self):
super(My_class, self).__init__()
if __name__ == '__main__':
my_handler = My_class()
```
Here's the error I get
```
Traceback (most recent call last):
File "main.py", line 12, in <module>
my_handler = My_class()
File "main.py", line 9, in __init__
super(My_class, self).__init__()
TypeError: super() argument 1 must be type, not classobj
```
If I change the superclass of "My\_class" to an object it works fine. Where am I going wrong? | [super()](http://docs.python.org/library/functions.html#super) only works for [new-style classes](http://docs.python.org/reference/datamodel.html#newstyle) | cmd.Cmd is not a new style class in Python 2.5, 2.6, 2.7.
Note that your code does *not* raise an exception in Python 3.0. | Python Cmd module, subclassing issue | [
"",
"python",
""
] |
I have some Java code similar to:
```
public class Thing {
private IPolicy policy;
public Thing(IPolicy policy) {
this.policy = policy;
}
public void doSomething() {
this.policy.execute();
}
}
```
My question is: is it possible to do this with generics rather than passing the policy to the constructor? I think this means I want it to end up as
```
public class Thing<T extends IPolicy>
```
but I'm not that up on generics.
My motivations are: 1) it would make more sense to me for my program for this to be part of the type and not be involved with the constructor (which has other more relevant things to do) and 2) I'm trying to learn generics. | I don't think that makes a lot of sense. Isn't it the policy itself that you depend on, rather than just the *type* of policy? Aren't you going to want to ask the policy questions (e.g. whether or not an action is allowed)? That means you'll need an instance of the policy - which means it makes sense for it to be passed into the constructor.
Generics are suitable when you want a strongly typed API where part of the API depends on another type, but the implementation itself doesn't care what the type is (potentially with some constraints). The collections API is probably the canonical example - a `List<T>` doesn't care what `T` is, but wants to expose a strongly-typed API *in terms of T*. I can't see that fitting in with your policy example. | What you are trying to do is make sure that a Thing always has a policy ie. a Thing cannot exist with a policy. This requires only constructor mechanism or abstraction like,
```
public abstract class Thing {
public abstract Policy getPolicy();
public void doSomething() {
getPolicy().execute();
}
}
``` | Java generics for policy as alternative to passing policy in constructor | [
"",
"java",
"generics",
""
] |
I have an app written in C# that does a lot of string comparison. The strings are pulled in from a variety of sources (including user input) and are then compared. However I'm running into problems when comparing space '32' to non-breaking space '160'. To the user they look the same and so they expect a match. But when the app does the compare, there is no match.
What is the best way to go about this? Am I going to have to go to all parts of the code that do a string compare and manually normalize non-breaking spaces to spaces? Does .NET offer anything to help with that? (I've tried all the compare options but none seem to help.)
It has been suggested that I normalize the strings upon receipt and then let the string compare method simply compare the normalized strings. I'm not sure it would be straight-forward to do that because what is a normalized string in the first place. What do I normalize it too? Sure, for now I can convert non-breaking spaces to breaking spaces. But what else can show up? Can there potentially be very many of these rules? Might they even be conflicting. (In one case I want to use a rule and in another I don't.) | If it were me, I would 'normalize' the strings as I 'pulled them in'; probably with a string.Replace(). Then you won't need to change your comparisons anywhere else.
**Edit**: Mark, that's a tough one. Its really up to you, or you clients, as to what is a 'normalized' string. I've been in a similar situation where the customer demanded that strings like:
```
I have 4 apples.
I have four apples.
```
were actually equal. You may need separate normalizers for different situations. Either way, I would still do the normalization upon retrieval of the original strings. | I went through lots of pain to find this simple answer. The code below uses a regular expression to replace non breaking spaces with normal spaces.
```
string cellText = "String with non breaking spaces.";
cellText = Regex.Replace(cellText, @"\u00A0", " ");
```
Hope this helps, Dan | String Comparison, .NET and non breaking space | [
"",
"c#",
"string",
"character-encoding",
""
] |
I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.
```
>>> a = [2,3,4]
>>> print (1 or 2) in a
False
>>> print (2 or 1) in a
True
``` | ```
>>> L1 = [2,3,4]
>>> L2 = [1,2]
>>> [i for i in L1 if i in L2]
[2]
>>> S1 = set(L1)
>>> S2 = set(L2)
>>> S1.intersection(S2)
set([2])
```
Both empty lists and empty sets are False, so you can use the value directly as a truth value. | I was thinking of this slight variation on [Tobias' solution](https://stackoverflow.com/a/740359/4518341):
```
>>> a = [1,2,3,4]
>>> b = [2,7]
>>> any(x in a for x in b)
True
``` | How to check if one of the following items is in a list? | [
"",
"python",
""
] |
I have a collection of extjs objects on a webpage, developing using Firefox so I can debug using Firebug. After a while I start IE to check compatibility and get a blank page in IE, but all works in FF.
In IE I get no Javascript errors. | In the Firebug options turn on "Strict Warnings" then look for a warning in the .js source file for your page. It seems that Firefox is much more forgiving of a comma after the last member of a collection. Look for warning labeled "trailing comma is not legal in ECMA-262 object initializers". This pinpointed the problem. | 'It seems that Firefox is much more forgiving of a comma after the last member of a collection.'
Yeah!! thats it. In addition to jslint theres is also <http://www.jsonlint.com/> available. | extjs grid works in Firefox, not in IE | [
"",
"javascript",
"debugging",
"extjs",
"firebug",
""
] |
In the past, I've always edited all my sites live; wasn't too concerned about my 2 visitors seeing an error message.
However, there may come a day when I get more than 2 visitors. What would be the best approach to testing my changes and then making all the changes go live simultaneously?
Should I copy and paste ever single file into a sub-folder and edit these, then copy them back when I'm done? What if I have full URLs in my code (they'll break if I move them)? Maybe I can use some .htaccess hackery to get around this? What about database dummy test data? Should I dupe all my MySQL tables and reference those instead?
I'm using CakePHP for the particular project I'm concerned about, but I'm curious to know what approaches people are taking both with Cake (which *may* have tools to assist with this?), and without a framework.
---
I've been getting a lot of recommendations for SVN, which sounds great, but unfortunately my host doesn't support it :\ | The best thing you can do is to create a staging environment in which you test your changes. The staging environment (ideally) is a complete, working duplicate of your production system. This will prevent you from experiencing many headaches and inadvertent production crashes.
If you are working on a small project the best thing to do is to recreate your remote site locally (including the database). Code all your changes there and then, once you are satisfied that you are finished, deploy the changes to your remote site in one go. | I would recommend putting your website code under full version control (git or subversion). Test and maintain your source in a separate, private sandbox server, and just check out the latest stable version at the production site whenever it's ready for release.
For database support, even for small projects I maintain separate development and production databases. You can version the SQL used to generate and maintain your schema and testing or bootstrapping data along with the rest of your site. Manage the database environment used by your site from an easily separated configuration file, and tell your version control solution to ignore it.
Absolute URLs are going to be a problem. If you can't avoid them, you could always store the hostname in the same configuration file and read it as needed... except within stylesheets and Javascript resources, of course. My second choice for that problem would be URL-rewriting magic or its equivalent in the development server, and my last choice would be just messing with the `/etc/hosts` file when I wanted to test features that depend on them. | How should I set up my development environment for rolling code into a live website? | [
"",
"php",
"cakephp",
""
] |
In Java, I have a `Set`, and I want to turn it into a sorted `List`. Is there a method in the `java.util.Collections` package that will do this for me? | The answer [provided by the OP](https://stackoverflow.com/questions/740299/how-do-i-sort-a-set-in-java/740301#740301) is not the best. It is inefficient, as it creates a new `List` *and* an unnecessary new array. Also, it raises "unchecked" warnings because of the type safety issues around generic arrays.
Instead, use something like this:
```
public static
<T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c) {
List<T> list = new ArrayList<T>(c);
java.util.Collections.sort(list);
return list;
}
```
Here's a usage example:
```
Map<Integer, String> map = new HashMap<Integer, String>();
/* Add entries to the map. */
...
/* Now get a sorted list of the *values* in the map. */
Collection<String> unsorted = map.values();
List<String> sorted = Util.asSortedList(unsorted);
``` | Sorted set:
```
return new TreeSet(setIWantSorted);
```
or:
```
return new ArrayList(new TreeSet(setIWantSorted));
``` | How do I sort a Set to a List in Java? | [
"",
"java",
"sorting",
"collections",
""
] |
I'm using this code:
```
for (final String code : Locale.getISOCountries())
{
//stuff here
}
```
But on compile I get this error:
```
[ERROR] Line 21: No source code is available for type java.util.Locale; did you forget to inherit a required module?
```
And then a stack trace of compiler errors.
I'm doing both of these imports at the beginning of the class:
```
package com.me.example;
import java.util.Locale;
import java.util.*;
```
What can be wrong?
In Netbeans i see the autocomplete options and no syntax error for the Locale object... | Something screwy with your setup, the folllowing program works fine for me.
```
import java.util.*;
import java.util.Locale;
public class Donors {
public static void main (String [] args) {
for (final String code : Locale.getISOCountries()) {
System.out.println (code);
}
}
}
```
The fact that it's asking for *source* code leads me to believe that it's trying to compile or run it in some sort of debugging mode. You shouldn't need the source code for java.util.\* to compile, that's just bizarre.
See if my simple test program works in your environment, then try looking for something along those lines (debugging options). Final step: compile **your** code with the baseline javac (not NetBeans).
**UPDATE:**
Actually, I have found something. If you are creating GWT applications, I don't think `java.util.Locale` is available on the client side (only the server side). All of the references on the web to this error message point to GWT and its limitations on the client side which are, after all, converted to Javascript goodies, so cannot be expected to support the entire set of Java libraries.
This page [here](http://www.ociweb.com/mark/programming/GWT.html) shows how to do i18n on GWT apps and there's no mention of `java.util.Locale` except on the server side. | Looks like there might be something fishy in your build environment, as `Locale.getISOCountries()` should work just fine. Try compiling a small test program manually and see if you get the same error. | Weird error with Locale.getISOCountries() | [
"",
"java",
"gwt",
"locale",
""
] |
Other than `Locale.getISOCountries()` that is, because I'm already [getting some strange errors with that](https://stackoverflow.com/questions/712230/weird-error-with-locale-getisocountries). What else is the best way to get the 2-letter country codes as well as the full country name? | For a separate project, I took the country code data from the [ISO site](http://www.iso.org/iso/country_codes/iso_3166_code_lists.htm).
Beware of the following:
* The names are in all caps. You will probably want to tweak it so it's not.
* The names are not all in simple ASCII.
* The names are not entirely political neutral (it is probably impossible for any purported list of countries to be). E.g., "Taiwan, Province of China" is a name. A good starting point to learn about the issues is [this blog post](http://www.koziarski.net/archives/2008/9/24/countries-and-controversies). | See code snippets :
```
String[] countryCodes = Locale.getISOCountries();
for (String countryCode : countryCodes) {
Locale obj = new Locale("", countryCode);
System.out.println("Country Code = " + obj.getCountry()
+ ", Country Name = " + obj.getDisplayCountry());
}
```
Refer to this [country list in Java](http://www.mkyong.com/java/display-a-list-of-countries-in-java/) for more examples. | Best way to get a list of countries in Java | [
"",
"java",
""
] |
My percentages get truncated by the default java.text.MessageFormat function, how do you format a percentage without losing precision?
Example:
```
String expectedResult = "12.5%";
double fraction = 0.125;
String actualResult = MessageFormat.format("{0,number,percent}", fraction);
assert expectedResult.equals(actualResult) : actualResult +" should be formatted as "+expectedResult;
``` | Looks like this:
```
String actualResult = MessageFormat.format("{0,number,#.##%}", fraction);
```
... is working.
EDIT: To see how are the #'s and %'s interpreted, see the javadoc of java.text.DecimalFormat.
EDIT 2: And, yes, it is safe for internationalization. The dot in format string is interpreted as a decimal separator, not as a hardcoded dot. :-) | I think the proper way to do it is the following:
```
NumberFormat percentFormat = NumberFormat.getPercentInstance();
percentFormat.setMaximumFractionDigits(1);
String result = percentFormat.format(0.125);
```
It also takes internalization into account. For example on my machine with hungarian locale I got "12,5%" as expected. Initializing percentFormat as `NumberFormat.getPercentInstance(Locale.US)` gives "12.5%" of course. | How do you format a fractional percentage with java.text.MessageFormat | [
"",
"java",
"text",
"localization",
""
] |
Is there any way to enumerate tables used in mysql query?
Lets say I have query :
```
SELECT * FROM db_people.people_facts pf
INNER JOIN db_system.connections sm ON sm.source_id = pf.object_id
INNER JOIN db_people.people p ON sm.target_id = p.object_id
ORDER BY pf.object_id DESC
```
And I want in return array:
```
$tables = array(
[0] => 'db_people.people_facts',
[1] => 'db_system.connections',
[2] => 'db_people.people',
);
``` | The solution marked as good will return only the result tables. But if you do the next query it will fail:
```
SELECT users.* FROM users, cats, dogs WHERE users.id = cats.user_id
```
Will **return only users** and not cats and dogs tables.
The best solution is find a good parser, another solution is using REGEX and EXPLAIN query (more info in the next link):
[Get mysql tables in a query](https://stackoverflow.com/questions/3397568/get-mysql-tables-in-a-query)
But I think that another good solution is ***list all tables and search them inside the query***, you can cache the list of tables.
**EDIT**: When searching for tables, better use a preg like:
```
// (`|'|"| )table_name(\1|$)
if(preg_match('/(`|\'|"| )table_name(\1|$)/i', $query))
// found
```
If not, it can return false positives with for example "table\_name2", "table\_name3"... table\_name will return FOUND two times. | Yes, you can get information about tables and columns that are part of a query result. This is called **result set metadata**.
The only PHP solution for MySQL result set metadata is to use the MySQLi extension and the [`mysqli_stmt::result_metadata()`](http://php.net/manual/en/mysqli-stmt.result-metadata.php) function.
```
$stmt = $mysqli->prepare("SELECT * FROM db_people.people_facts pf
INNER JOIN db_system.connections sm ON sm.source_id = pf.object_id
INNER JOIN db_people.people p ON sm.target_id = p.object_id
ORDER BY pf.object_id DESC");
$meta = $stmt->result_metadata();
$field1 = $meta->fetch_field();
echo "Table for field " . $field1->name . " is " . $field1->table . "\n";
```
You'll have to build the array of distinct tables used in the query yourself, by looping over the fields. | Enumerating tables used in mysql query? | [
"",
"php",
"mysql",
"tags",
"enumerate",
""
] |
is the FROM clause necessary in every SELECT statement?Thanks.. | Not really - you can use SELECT to initialize a variable.
Examples [from here](http://dev.mysql.com/doc/refman/5.1/en/select.html):
mysql> SELECT 1 + 1;
-> 2 | Not in MySQL, no. You could do this:
```
SELECT 1 + 1;
```
It will be in some DBMSs though - Oracle for example would require you to do:
```
SELECT 1 + 1 FROM DUAL;
``` | FROM clause necessary in every SELECT statement | [
"",
"sql",
"mysql",
""
] |
I want to print a table of report on an a4 size paper , but only a part of the table is getting printed , few columns are being left out.
Can anybody please tell me what might be the problem?
I tried to shrink to fit but , it becomes too small to read. | try using the landscape paper mode rather than portrait mode. Next shrink your contents to fit the page. If they don't you can't get entire thing on a single sheet unless you want unreadable font size (read smaller than your eye can read). | It used to be that monitors had a display area smaller than a piece of paper, but now the opposite is true.
You should have stylesheets for both screen and print. On the print CSS, set the table in percentages, and not ever span more than 100% of the page's width. For print, especially for reports, the simpler the better. A clean header is about all you need for aesthetics.
to do that, you just declare 2 stylesheets:
```
<style type="text/css" media="screen">
</style>
```
as well as...
```
<style type="text/css" media="print">
</style>
```
There are other media types too:
```
all
aural
braille
embossed
handheld
print
projection
screen
tty
tv
``` | how to fit wide table on an a4 size paper? | [
"",
"php",
"html",
"css",
"printing",
""
] |
Is there a way to determine if the current file is the one being executed in Perl source? In Python we do this with the following construct:
```
if __name__ == '__main__':
# This file is being executed.
raise NotImplementedError
```
I can hack something together using `FindBin` and `__FILE__`, but I'm hoping there's a canonical way of doing this. Thanks! | ```
unless (caller) {
print "This is the script being executed\n";
}
```
See [caller](http://perldoc.perl.org/functions/caller.html). It returns `undef` in the main script. Note that that doesn't work inside a subroutine, only in top-level code. | See the "Subclasses for Applications (Chapter 18)" portion of [brian d foy](https://stackoverflow.com/users/8817/brian-d-foy)'s article [Five Ways to Improve Your Perl Programming](http://www.onlamp.com/pub/a/onlamp/2007/04/12/five-ways-to-improve-your-perl-programming.html). | Is there a Perl equivalent to Python's `if __name__ == '__main__'`? | [
"",
"python",
"perl",
"executable",
""
] |
I know it is possible to get data from a SQL database into an excel sheet, but i'm looking for a way to make it possible to edit the data in excel, and after editing, writing it back to the SQL database.
It appears this is not a function in excel, and google didn't come up with much usefull. | If you want to have the Excel file do all of the work (retrieve from DB; manipulate; update DB) then you could look at ActiveX Data Objects (ADO). You can get an overview at:
<http://msdn.microsoft.com/en-us/library/ms680928(VS.85).aspx> | You want the Import/Export wizard in SQL Management Studio. Depending on which version of SQL Server you are using, open SSMS (connect to the SQL instance you desire), right click on the database you want to import into and select Tasks.. "Import Data".
In the wizard, click Next (past the intro screen) and from the Data Source drop list select "Microsoft Excel". You specify the path and file name of the Excel spreadsheet, whether you have column headings or not.. then press Next. Just follow the wizard through, it'll set up the destination (can be SQL Server or another destination) etc.
There is help available for this process in [SQL Server Books Online](http://msdn.microsoft.com/en-us/library/ms188032.aspx) and more (a walkthrough) from [MSDN](http://msdn.microsoft.com/en-us/library/ms141209.aspx).
If you need something deployable/more robust (or less wizard driven) then you'd need to take a look at SQL Server Integration Services (for a more "Enterprise" and security conscious approach). It's probably overkill for what you want to accomplish though. | Writing data back to SQL from Excel sheet | [
"",
"sql",
"excel",
""
] |
Are there any C# attributes that I can apply to class members, to change the way they appear in the IntelliSense listings? This popped into my head when I was building a class with many static constants, and I (briefly!) wanted it to look like an enumeration in IntelliSense.
Yes, that's silly.
But it got me thinking - *is* there any way some crazy programmer can make a class members appear differently in IntelliSense? Make fields look like properties, etc?
For instance, there's the `Obsolete` attribute:
```
[Obsolete("Stop using this. Really. It's old.")]
public int VariableThatIsReallyOld;
```
Which prefixes the word `[obsolete]` to the description of `VariableThatIsReallyOld`. | There's the DebuggerDisplay attribute described [here](https://stackoverflow.com/questions/471241/can-i-customize-the-intellisense-value-shown-when-hovering-while-debugging-in-vis). | Turns out there also some other attributes at [Custom intellisense for server controls?](https://stackoverflow.com/questions/307514/custom-intellisense-for-server-controls) (But the search continues!)
```
[EditorBrowsable(EditorBrowsableState.Never)]
``` | Are there attributes in C# for affecting how IntelliSense displays class members? | [
"",
"c#",
"attributes",
"intellisense",
""
] |
I'm trying to build a application for the iPhone, although I am completely new to Obj-C. For one problem I'd use a ByteBuffer in Java, but I don't see any appropriate class in Apple's documentation. So I probably have to implement it on my own.
My question is, how to do it best:
* Is there a similar class in Obj-C? (That would be the best solution ;))
* Should I do it by using Obj-C classes like NSData?
* Or should I stay with plain C code? | You probably want NSMutableData. | My recollection of `java.nio.ByteBuffer` (from working with Java many moons ago) is that `ByteBuffer` implements sequential reads/writes to an array of bytes. This is analogous to an `NSInputStream` backed by an `NSData` (for input):
```
NSInputStream *inputStream = [NSInputStream inputStreamwithData:myData]; //assuming myData is NSData*
float myFloat;
if([inputStream hasBytesAvailable]) { // NO if you've already read to the end of myData
NSInteger bytesRead = [inputStream read:&myFloat maxLength:sizeof(myFloat)];
NSAssert(bytesRead == sizeof(myFloat);
}
```
You can do something similar with an `NSOutputStream` writing to an `NSData`. | What's the best way to implement a Java-like ByteBuffer in Obj-C? | [
"",
"java",
"objective-c",
"porting",
""
] |
I have quite a long data mining script, and in parts of it I echo some information to the page (during a foreach loop, actually.)
However I am noticing that the information is being sent to the browse not immediately as I had hoped, but in 'segments'.
Is there some function I can use after my echo to send all the data to the browser immediately?
Thanks. | You probably want `flush()`. However, PHP may be using output buffering. There are a few ways that this can change things, but in a nutshell, you can `flush()`, then `ob_flush()`. | You can try using flush() after each echo, but even that won't guarantee a write to the client depending on the web server you're running. | PHP immediate echo | [
"",
"php",
"io",
"echo",
""
] |
I have seen the mentioned piece of code on several occasions now, what's the point of doing a `Max(a+1, a-1)`? At first I thought it might be to prevent underflow, but it doesn't really make sense not to prevent the underflow in that case. | As you mentioned, it's possible they are trying to detect when `Offset` wraps to zero (or goes negative) and keep it pegged at the max value for whatever type `Offset` is. Or they may be trying to deal with a situation where `Offset` is 'simultaneously' incremented in multiple threads (or something).
In either case, this is buggy code.
If they are trying to detect/prevent wrap to zero or negative, one too many increments will cause the problem anyway. If they are trying to deal with `Offset` being incremented 'simultaneously', I'm not sure what problem they're really trying to solve or how they are trying to solve it.
Here are the problems:
[As Jon Skeet says](https://stackoverflow.com/questions/765686/whats-the-point-in-maxthreading-interlocked-incrementoffset-offset-1/765697#765697):
> However, it still sounds odd to me - because unless Offset is volatile, the latter expression may not get the latest value anyway.
But it's even worse than that - even if `Offset` is volatile there's nothing to serialize reading the new value of `Offset` with another thread that may be incrementing it, so the very instant after the `Max()` expression re-reads the value of `Offset` any number of other threads may come along and increment it (any number of times). So at best, the expression is useless, but using that technique can be harmful because you may end up using a value of `Offset` that doesn't 'belong' to you.
Consider the situation where you're using `Offset` to track an array index or something (which given the name sounds like exactly what might be going on). When you atomically increment `Offset` the array element at that index becomes yours to use. If you use the `Max()` expression as in the question, you may suddenly be trampling on an array element that really belongs to another thread.
I can't think of a legitimate reason to use
```
Max(Threading.Interlocked.Increment(Offset), Offset - 1)
```
Like I said, at best it's harmless (and useless), but it could introduce ***very*** hard to diagnose problems - **don't use it**.
---
Thanks to the comment by Simon Svensson that pointed to a Google search for the usage in the question, it looks like this code usually (always?) comes from the output of a C# to VB.NET converter. It even uses this expression to increment local variables (so threading isn't an issue). In the cases where `Offset` is a local variable, this expression falls into the useless but mostly harmless variety (there will be a 'bug' if the increment wraps). It's really more or less a very inefficient `Offset++` expression (in fact it appears to be the way the converter converts the C# expression `Offset++` to VB.NET - see <http://www.telerik.com/community/forums/open-source-projects/code-converter/added-value.aspx#307755>). Actually this conversion is buggy for `Offset++` anyway because it returns the incremented value when it should return what the value was before incrementing.
The really bad thing is that other people may look at that code and think, "so that's the way I need to use `Interlocked.Increment()`". | A bit of googling gives me a suspicion that this might arise from some (possibly buggy) C# to VB.NET convertor software. That would explain the frequent appearance of it.
**Added:** Yessss, I [found it](http://converter.telerik.com/Default.aspx)! Try entering the following C# code in it and convert to VB.NET:
```
int i;
i++;
``` | What's the point in Max(Threading.Interlocked.Increment(Offset), Offset - 1)? | [
"",
"c#",
".net",
"multithreading",
""
] |
I am looking for square root functions (to use in java) that can give square roots upto atleast to 5-6 decimal places accurately. If there is a way to control accuracy of java.lang.Math.sqrt(double) or any external math library, please mention it. | What problem are you trying to solve? I believe [java.lang.Math's sqrt is supposed to be accurate to the full double width](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html). Do you need more than this? | Try out the code at this link, which uses Newton's method to compute square roots for large numbers (and gets BigDecimal output) to see if it fits your needs. If not, you can modify it :) .
<http://www.merriampark.com/bigsqrt.htm> | Is there any square root function more accurate than java.lang.Math.sqrt(double) | [
"",
"java",
"math",
""
] |
I've got a classification of certain values in different intervals. Most have the form [20-30], but some are of the form [30-infinite).
Is there an interval class you know of which can represent:
* an interval which is not closed on both sides (e.g. (0-5) or [0-5) )
* an interval which closes (or starts) on infinite | [Time&Money](http://timeandmoney.sourceforge.net/) project seems to have Interval class that you need.
See these files in their svn: [interval package](http://timeandmoney.svn.sourceforge.net/viewvc/timeandmoney/timeandmoney/trunk/src/main/java/com/domainlanguage/intervals/). | The Apache-commons-lang project (<http://commons.apache.org/lang/>) contains classes dealing with ranges (like IntRange - <https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/IntRange.html>). I'm not sure it covers all your needs, but it might be worth checking. | Does an open-ended interval implementation exist for Java? | [
"",
"java",
"math",
"intervals",
""
] |
I often find myself writing if / elif / else constructs in python, and I want to include options which can occur, but for which the corresponding action is to do nothing. I realise I could just exclude those if statements, but for readability I find it helps to include them all, so that if you are looking through the code you can see what happens as a result of each option. How do I code the no-op? Currently, I'm doing it like this:
```
no_op = 0
if x == 0:
y = 2 * a
elif x == 1:
z = 3 * b
elif x == 3:
no_op
```
(The code is actually quite a bit longer than that, and more complicated. This is just to illustrate the structure).
I don't like using a variable as a no-op, but it's the neatest way I could think of. Is there a better way? | Use [pass](http://docs.python.org/reference/simple_stmts.html#the-pass-statement) for no-op:
```
if x == 0:
pass
else:
print "x not equal 0"
```
And here's another example:
```
def f():
pass
```
Or:
```
class c:
pass
``` | How about `pass`? | What's a standard way to do a no-op in python? | [
"",
"python",
""
] |
I want to create something similiar to a facebook wall on my social site. I want to store the posts in an sql database and that should be rather simple. What I am looking for is a good way to display the posts? I guess I don't even really know where to start, as I can only think of using a loop to display `asp:textboxes`. Which obviously is not correct.
I want there to be multiple posts displayed on the page, which should include:
* the user who posted,
* the text posted,
* the date posted,
* and if I want to get crazy...a means of deleting/editing the post.
I really have no idea of how to implement this concept, so any ideas would help greatly. | To get started, view this article from [asp.net](http://www.asp.net/) on the [Repeater control](http://www.asp.net/learn/data-access/tutorial-01-cs.aspx), or [this great article.](http://www.beansoftware.com/ASP.NET-Tutorials/Repeater-Control.aspx)
The Repeater control lets you databind to a list of objects, and then define one template for how that object should be displayed. Then, ASP.NET will handle showing it as many times as necessary. You can write the code-behind for dealing with delete and edit as if there were only one instance on the page. | go ahead with jquery, use a lot of ajax. for the mark up, use a repeater control with all clean html mark up (instead of server side controls which would generate a lot of unnecessary mark up quickly creating performance issues)
only populate x number of items on initial load, and then using jquery pull data as required based on user action. you can serve this data via json, decode json on client side using jquery and perform a loop which converts this json into appropriate html and injects it into the correct html element
should be simple ;-) | Facebook Wall functionality using ASP.Net | [
"",
"asp.net",
"sql",
"blogs",
"facebook-wall",
""
] |
I have a list of data like so:
```
ID AddressPurpose Address ...
1 L
1 P
2 L
2 P
3 P
3 L
4 P
4 L
5 P
6 L
```
I want to be able to filter the data so that for each unique number if there is a P row then it is returned else the L row is returned. So the data will look like this:
```
ID AddressPurpose Address ...
1 P
2 P
3 P
4 P
5 P
6 L
```
At the moment I have this query which works fine:
```
var query = from c in list
orderby c.AddressPurpose descending
group c by c.ID
into g
select g;
var finalList = new List<Company>();
foreach (var list in query)
{
finalList.Add(list.First());
}
return finalList;
```
**Is there a better way to do this without using the extra foreach?** | Why don't you `select` `g.First()` instead? | You could always nest your queries:
```
var query =
from i in (
from c in list
orderby c.AddressPurpose descending
group c by c.ID into g
select g)
select i.First();
return query;
```
I'm sure this isn't the only way to do it (or possibly even the best), but it does wrap your "foreach" up into the one query.
**Edit**
In fact, you can simplify this down to:
```
var query = from c in list
orderby c.AddressPurpose descending
group c by c.ID into g
select g.First();
```
That seems to give the right result. | Flattening Linq Group query | [
"",
"c#",
"linq",
"group-by",
"linq-to-objects",
""
] |
I want to apply the ["ordering"](http://docs.djangoproject.com/en/dev/ref/models/options/#ordering) Meta option to the Django model User from django.contrib.auth.models. Normally I would just put the Meta class in the model's definition, but in this case I did not define the model. So where do I put the Meta class to modify the User model? | Paolo's answer is great; I wasn't previously aware of the new proxy support. The only issue with it is that you need to target your code to the OrderedUser model - which is in a sense similar to simply doing a `User.objects.filter(....).order_by('username')`. In other words, it's less verbose but you need to explicitly write your code to target it. (Of course, as mentioned, you'd also have to be on trunk.)
My sense is that you want *all* `User` queries to be ordered, including in third party apps that you don't control. In such a circumstance, monkeypatching the base class is relatively easy and very unlikely to cause any problems. In a central location (such as your settings.py), you could do:
```
from django.contrib.auth.models import User
User.Meta.ordering = ['username']
```
UPDATE: Django 1.5 now supports [configurable User models](https://docs.djangoproject.com/en/dev/releases/1.5-alpha-1/#configurable-user-model). | [This is how the Django manual recommends you do it](http://docs.djangoproject.com/en/dev/topics/db/models/#specifying-the-parent-link-field):
> You could also use a proxy model to define a different default ordering on a model. The standard User model has no ordering defined on it (intentionally; sorting is expensive and we don't want to do it all the time when we fetch users). You might want to regularly order by the username attribute when you use the proxy. This is easy:
```
class OrderedUser(User):
class Meta:
ordering = ["username"]
proxy = True
```
> Now normal User queries will be unorderd and OrderedUser queries will be ordered by username.
**Note that for this to work you will need to have a trunk checkout of Django as it is fairly new.**
If you don't have access to it, you will need to get rid of the proxy part and implement it that way, which can get cumbersome. [Check out this article on how to accomplish this.](http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/) | How do I apply Django model Meta options to models that I did not write? | [
"",
"python",
"django",
""
] |
I'm watching a tv show on Hulu.com (which is btw, the absolute best streaming-video site around) and whether I close my browser, disconnect from the internet, and even if I restart my computer in the middle of watching a show, the next time I go to their site, I can resume the tv from exactly the time where I left off in the show.
My question is from a detailed web programming perspective, how can they achieve this? I assume it's not using sessions because I don't think that would work if I restarted my computer. If it's using cookies, then how can they constantly update the cookie with your location in a show?
In order to receive the attached bounty, please include code examples in preferably Java/JSP (PHP is ok too) of how to create the cookie and a snippet of server-side code that would allow for the updated viewer's position.
thanks! | One simple way is that the player can update your cookie(s) via JavaScript, and that JavaScript function can be called every *n* seconds by the Flash player:
```
<script type="text/javascript">
function UpdateViewData(videoId, time)
{
//for a video with id 12345, sets a cookie called:
//hulu12345 with a value of the position
var cookieData = 'hulu' + videoId + '=' + time + '; expires=' + getDate() + ';path=/';
document.cookie = cookieData;
}
</script>
```
In the Flash player, ActionScript can invoke the JavaScript frequently to get a fairly accurate update of where the player was the last time the cookie was set. Each time it's called, it overwrites the cookie with updated data:
```
import flash.external.ExternalInterface;
//in flash video player code,
//have variables for video ID and current player position
//every 5 seconds, call:
ExternalInterface.call("UpdateViewData", videoId, currentPlayerPosition);
//this will invoke a JS function on the host page named "UpdateViewData"
//and pass in the provided arguments
```
When you revisit the page, the first thing the server does is check to see if you have a cookie called "hulu{ID of video}" and if so, the value of that cookie is the position set last time you were viewing it.
Again (as stated in the beginning) this is a very simple way to accomplish what you're asking. I find the best way to learn is to go with a simple implementation and then add complexity once the simpler case is well-understood. Hulu likely makes periodic updates behind the scenes using AJAX. (In fact, if you watch the net traffic while watching a video using something like [Firebug](http://getfirebug.com/), you'll see occasional calls to `http://t2.hulu.com/v3/playback/position?...`). | Flash has it's own cookie-like mechanism: [Local Shared Object](http://en.wikipedia.org/wiki/Local_Shared_Object).
There are some [code examples here](http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_16194). I imagine Hulu just creates an LSO and periodically updates it with the position in the movie. When the movie is next loaded, it can get the LSO and restore the position. Alternatively, they could store a unique ID and save the positions server-side. | How can Hulu.com keep track of your position in a tv show? | [
"",
"java",
"jsp",
"web-applications",
"cookies",
"video-streaming",
""
] |
How can I parse text and find all instances of hyperlinks with a string? The hyperlink will not be in the html format of `<a href="http://test.com">test</a>` but just `http://test.com`
Secondly, I would like to then convert the original string and replace all instances of hyperlinks into clickable html hyperlinks.
I found an example in this thread:
[Easiest way to convert a URL to a hyperlink in a C# string?](https://stackoverflow.com/questions/32637/easiest-way-to-convert-a-url-to-a-hyperlink-in-a-c-string)
but was unable to reproduce it in python :( | Here's a Python port of [Easiest way to convert a URL to a hyperlink in a C# string?](https://stackoverflow.com/questions/32637/easiest-way-to-convert-a-url-to-a-hyperlink-in-a-c-string/32648#32648):
```
import re
myString = "This is my tweet check it out http://tinyurl.com/blah"
r = re.compile(r"(http://[^ ]+)")
print r.sub(r'<a href="\1">\1</a>', myString)
```
Output:
```
This is my tweet check it out <a href="http://tinyurl.com/blah">http://tinyurl.com/blah</a>
``` | [Here](http://mail.python.org/pipermail/tutor/2002-September/017228.html) is a much more sophisticated regexp from 2002.
@yoniLavi minified this to:
```
re.compile(r'\b(?:https?|telnet|gopher|file|wais|ftp):[\w/#~:.?+=&%@!\-.:?\\-]+?(?=[.:?\-]*(?:[^\w/#~:.?+=&%@!\-.:?\-]|$))')
``` | Find Hyperlinks in Text using Python (twitter related) | [
"",
"python",
"regex",
""
] |
Should you always create an interface if there's a possibility that there might be something else that could use it, or wait until there's an actual need for it then refactor to use an interface?
Programming to an interface generally seems like sound advice, but then there's YAGNI...
I guess maybe it depends on the situation. Right now I have an object representing a folder that can contain recipes or other folders. Instead of using Folder directly, should I worry about implementing something like IContainer? In case in the future I want to have a recipe that refers to other sub recipes (say an apple pie recipe that is also a container for a pie crust recipe) | It always depends on the situation. If you KNOW there is going to be another class using the interface, then yes, create the interface class to save time later. However, if you are not sure (and most of the time you aren't) then wait till you need it.
Now that doesn't mean to ignore the possibility of the interface - think about the object's public methods and such with an eye toward making an interface later, but don't clutter your codebase with anything that you don't actually NEED. | Think of an interface as a contract to define semantics, or a concept. That's a general approach and not really language specific. In context of OO, if you are working in a single inheritance model, there is an excellent case to be made for preferring interfaces over classes for defining your object model, since that single super class pathway is fairly precious and you want to save it for something more 'substantial' than defining properties that are exposed on an object, or methods.
To have IContainer semantics (contract) is a fairly poor reason to make an interface out of your folder; better to have your folder (if it is doing any non-trivial logic) 'implement' the (likely already existing) IContainer or ICollection interface in your language's core frameworks.
As always, the better choice is fairly dependent on the specific problem. In case of your recipes that are also folders (?!) you are probably thinking of a parent-child, or composition, relationship -- a semantic that can (and should) be expressed using interfaces if you will have other elements in your system 'operate' on things that are composed using that sort of semantics.
There is a bit of overhead (programming wise) with interfaces, and, if you find yourself when you are done with nothing more than a set of Woof and IWoof classes and interfaces, then you'll know you probably didn't need to express your problem in terms of interfaces -- simple classes would have been sufficient.
As a rule, for any I, you should have at least a couple of concrete classes (with more meaningful names other than IImpl, or ).
Hope that helps. | Should you create an interface when there (currently) is only going to be one class that implements it? | [
"",
"c#",
"interface",
"yagni",
""
] |
The application handles users and objects, users rate objects with 3 features (one rate per feature).
**EDIT**: the last sentence is unclear : by features I mean criterias shared by all the objects
How efficiently design a database for such a system ?
What are the best-practices for designing a database dealing with a rating system ?
what I was thinking of:
Tables:
* users
* objects
* feat1rates
* feat2rates
* feat3rates
and relationships :
An object has many
* feat1rates
* feat2rates
* feat3rates
A user has many
* feat1rates
* feat2rates
* feat3rates | Assuming you are not going to increase or decrease the number of rating features to rate, I would make a single table of ratings that would track the user, the product, and three columns (one for each feature)
So you have your Users table, an Objects table, and your Ratings table which has the UserID and ObjectID as a combined primary key, that way you enforce the one rating per object per user standard. | You want to encapsulate data in such a way that each table only contains information directly related to what it needs to deal with. Create linking tables to provide relationships between different sets of data (in this case, users and objects).
I would create the following tables:
**User** - the user's base information: login, password, user ID, whatever you need.
**Object** - the object to rate: its name/ID and attributes.
**Feature** - a table describing a type of feature, with some sort of feature name/ID. This may start with your three main types, but you could always expand/modify this. You can also customize which features each object will have available for rating.
**ObjectFeature** - a linking table for object and feature. Contains the primary key of each table, creating a many-to-many relationship between the two.
**UserRating** - another linking table of sorts, between the ObjectFeature and the User. Contains the primary keys of these two tables, as well as the rating assigned.
From a relational standpoint, this is a better way of organizing the data than what you presented. Through its design it makes clear how each set of data is connected and makes expandability (e.g. adding additional features to rate, having different objects have different features to rate) much cleaner. | Database design for a rating system | [
"",
"sql",
"database-design",
"rating-system",
""
] |
Let's say you have a set of ranges:
* 0 - 100: 'a'
* 0 - 75: 'b'
* 95 - 150: 'c'
* 120 - 130: 'd'
Obviously, these ranges overlap at certain points. How would you dissect these ranges to produce a list of non-overlapping ranges, while retaining information associated with their original range (in this case, the letter after the range)?
For example, the results of the above after running the algorithm would be:
* 0 - 75: 'a', 'b'
* 76 - 94: 'a'
* 95 - 100: 'a', 'c'
* 101 - 119: 'c'
* 120 - 130: 'c', 'd'
* 131 - 150: 'c' | I had the same question when writing a program to mix (partly overlapping) audio samples.
What I did was add an "start event" and "stop event" (for each item) to a list, sort the list by time point, and then process it in order. You could do the same, except using an integer point instead of a time, and instead of mixing sounds you'd be adding symbols to the set corresponding to a range. Whether you'd generate empty ranges or just omit them would be optional.
`Edit` Perhaps some code...
```
# input = list of (start, stop, symbol) tuples
points = [] # list of (offset, plus/minus, symbol) tuples
for start,stop,symbol in input:
points.append((start,'+',symbol))
points.append((stop,'-',symbol))
points.sort()
ranges = [] # output list of (start, stop, symbol_set) tuples
current_set = set()
last_start = None
for offset,pm,symbol in points:
if pm == '+':
if last_start is not None:
#TODO avoid outputting empty or trivial ranges
ranges.append((last_start,offset-1,current_set))
current_set.add(symbol)
last_start = offset
elif pm == '-':
# Getting a minus without a last_start is unpossible here, so not handled
ranges.append((last_start,offset-1,current_set))
current_set.remove(symbol)
last_start = offset
# Finish off
if last_start is not None:
ranges.append((last_start,offset-1,current_set))
```
Totally untested, obviously. | A similar answer to Edmunds, tested, including support for intervals like (1,1):
```
class MultiSet(object):
def __init__(self, intervals):
self.intervals = intervals
self.events = None
def split_ranges(self):
self.events = []
for start, stop, symbol in self.intervals:
self.events.append((start, True, stop, symbol))
self.events.append((stop, False, start, symbol))
def event_key(event):
key_endpoint, key_is_start, key_other, _ = event
key_order = 0 if key_is_start else 1
return key_endpoint, key_order, key_other
self.events.sort(key=event_key)
current_set = set()
ranges = []
current_start = -1
for endpoint, is_start, other, symbol in self.events:
if is_start:
if current_start != -1 and endpoint != current_start and \
endpoint - 1 >= current_start and current_set:
ranges.append((current_start, endpoint - 1, current_set.copy()))
current_start = endpoint
current_set.add(symbol)
else:
if current_start != -1 and endpoint >= current_start and current_set:
ranges.append((current_start, endpoint, current_set.copy()))
current_set.remove(symbol)
current_start = endpoint + 1
return ranges
if __name__ == '__main__':
intervals = [
(0, 100, 'a'), (0, 75, 'b'), (75, 80, 'd'), (95, 150, 'c'),
(120, 130, 'd'), (160, 175, 'e'), (165, 180, 'a')
]
multiset = MultiSet(intervals)
pprint.pprint(multiset.split_ranges())
[(0, 74, {'b', 'a'}),
(75, 75, {'d', 'b', 'a'}),
(76, 80, {'d', 'a'}),
(81, 94, {'a'}),
(95, 100, {'c', 'a'}),
(101, 119, {'c'}),
(120, 130, {'d', 'c'}),
(131, 150, {'c'}),
(160, 164, {'e'}),
(165, 175, {'e', 'a'}),
(176, 180, {'a'})]
``` | How to divide a set of overlapping ranges into non-overlapping ranges? | [
"",
"python",
"algorithm",
"math",
"range",
"rectangles",
""
] |
I'm ultimately trying to install PEAR so I can easily install PHPUnit. I want to set up a Mac, Apache, MySQL, PHP, PHPUnit development environment so I can test locally. I already have Apach, MySQL and PHP working. Now all I need is PHPUnit, which means I need PEAR to install it.
I have searched all over, and there are a few variations of "the tutorial" on how to install PEAR on Mac OS X 10.5. However, I can't seem to get any of them to work! Has anyone had success with this? I'm not totally confident that I have everything set up as it should be, so if you could include the "default" Mac OS X 10.5 include paths, or a simple explanation of where everything should go, I would appreciate it.
Following [this](http://clickontyler.com/blog/2008/01/how-to-install-pear-in-mac-os-x-leopard/) tutorial I do the following:
```
curl http://pear.php.net/go-pear > go-pear.php
sudo php -q go-pear.php
```
I press enter until I get to a list with 7 include paths:
```
1. Installation prefix ($prefix) : /Users/andrew
2. Temporary files directory : $prefix/temp
3. Binaries directory : $prefix/bin
4. PHP code directory ($php_dir) : $prefix/PEAR
5. Documentation base directory : $php_dir/docs
6. Data base directory : $php_dir/data
7. Tests base directory : $php_dir/tests
```
I change the `Installation prefix` to be `/usr/local`, press enter to continue, type `Y` to also install `PEAR_Frontend_Web-beta, PEAR_Frontend_Gtk2, MDB2`. Eventually, everything is installed.
Next...
On the first try, I think `include_path` was commented out of the php.ini file, but since I've already changed this line, and this is not the first time I've tried installing, I get the following message:
```
WARNING! The include_path defined in the currently used php.ini does not
contain the PEAR PHP directory you just specified:
</usr/local/PEAR>
If the specified directory is also not in the include_path used by
your scripts, you will have problems getting any PEAR packages working.
Would you like to alter php.ini </private/etc/php.ini>? [Y/n] :
```
I type `Y` and let pear automatically update my include path:
```
php.ini </private/etc/php.ini> include_path updated.
Current include path : .:/usr/share/pear
Configured directory : /usr/local/PEAR
Currently used php.ini (guess) : /private/etc/php.ini
```
I press enter to continue, and get the following message:
```
The 'pear' command is now at your service at /usr/local/bin/pear
** The 'pear' command is not currently in your PATH, so you need to
** use '/usr/local/bin/pear' until you have added
** '/usr/local/bin' to your PATH environment variable.
Run it without parameters to see the available actions, try 'pear list'
to see what packages are installed, or 'pear help' for help.
For more information about PEAR, see:
http://pear.php.net/faq.php
http://pear.php.net/manual/
Thanks for using go-pear!
PHP Warning: rmdir(/usr/local/temp): Not a directory in /Users/andrew/go-pear.php on line 1237
Warning: rmdir(/usr/local/temp): Not a directory in /Users/andrew/go-pear.php on line 1237
```
**Update:** I think I know why these last two warnings came up. Previously, I tried to fix the temp directory problem by creating a symbolic link to /tmp but if I understand correctly, PEAR is trying to create its own temp directory for installation, then it's going to delete it when it's finished. So I should not have created this symbolic link since it's going to try to delete the temp directory when the installation has finished. | There's a few things that could be going wrong here, these are only guesses.
First, there's **two** include paths you'll need to worry about. The first is your PHP include path. PEAR libraries are (mostly) just PHP code, specially packaged up. When you install a PEAR module you're downloading all the PHP code needed for that library, and any other PEAR libraries the library you're installing rely on (sorry about that sentence, but I'm not sure there's a better way to say that). This include path is set in your php.ini files (one file for your command line php, another for yoru web server php; often the same file).
The second include path you'll need to worry about is your UNIX/shell include path. This is the path that your computer will search for commands in when you enter a command from a terminal. The 'pear' command is a command line command.
So, we need to make sure that
1. The php.ini file for your website has the PEAR directory in its include path
2. The php.ini file for your command line php application has the PEAR directory in its include path
3. Your shell application (terminal, likely BASH in you're on OS X) has the PEAR directory in its include path
So, for number 1, put a PHP page on your server that include the function call
```
phpinfo();
```
This will list a bunch of information about your server. Look for the location of php.ini. Open this file in a text editor, look for the include\_path variable, and add the path to your PEAR directory (don't remove the other paths, just add yours).
For number 2, run the following from your command line
```
php -r "phpinfo();" | grep '.ini'
```
A bunch of lines will print out, look for the one that reads something like "Loaded Configuration File". Open this file in a text editor, look for the include\_path variable, and add the path to your PEAR directory (don't remove the other paths, just add yours).
Finally, and this is what I think your problem is, we need to ensure that the pear command line command is in your shell/bash path. That's what this error is refering to
```
** The 'pear' command is not currently in your PATH, so you need to
```
There should be a file in your home directory named '.bash\_profile'. It's a hidden file, so it won't showup in the Finder. Open it with a text editor. If you're having trouble because this is a hidden file, use the command line pico editor. Ctrl-X will save from pico
```
cd ~
pico .bash_profile
```
This file gets executed by your shell everytime you open a terminal window. We're going to add /usr/local/bin to your PATH, which means when you attempt to run a command, yoru computer will search for the command in this folder. Add the following line to the bottom of .bash\_profile
```
export PATH=/usr/local/bin:$PATH
```
This is, more or less, equivilant to the following PHP code
```
$PATH = '/usr/local/bin:'.$PATH
```
You're adding /usr/local/bin as the first colon-delimited place to look for command, and then adding the rest of the existing path to it. Once you've added that line, close your terminal, re-open it, and then type
```
pear
```
This should give you a list of valid pear commands, but more importantly will let you know pear is in your path.
Good luck! | I figured it out. You "HAVE TO" run the go-pear.php at where you want pear installed, so you need to run it under /usr/local if you want pear binary to be installed under /usr/local/bin
:-) | How to set up PEAR on Mac OS X 10.5 Leopard | [
"",
"php",
"macos",
"pear",
"osx-leopard",
""
] |
I couldn't describe the title of my question the best,I'm sorry.
Currently,I use Invoke to access the properties on my form,It works perfect,but I have a function for each property,which is quite not comfortable.
```
public static void EnableLogin(int enabled)
{
var form = Form.ActiveForm as FormMain;
if (form != null)
form.EnableLogin = enabled;
}
public static void EnableConfirm(int enabled)
{
var form = Form.ActiveForm as FormMain;
if (form != null)
form.EnableConfirm = enabled;
}
public static void EnableRetry(int enabled)
{
var form = Form.ActiveForm as FormMain;
if (form != null)
form.EnableRetry = enabled;
}
public static void EnableTABLogin(int enabled)
{
var form = Form.ActiveForm as FormMain;
if (form != null)
form.EnableTABLogin = enabled;
}
```
Each of these functions looks like that
```
public int EnableLogin
{
set
{
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
if (value == 0)
this.btnLogin.Enabled = false;
else
this.btnLogin.Enabled = true;
});
}
else
{
if (value == 0)
this.btnLogin.Enabled = false;
else
this.btnLogin.Enabled = true;
}
}
}
```
My question is,can't I do it like that
```
public static void EnableObject(object name)
{
var form = Form.ActiveForm as FormMain;
if (form != null)
form.Enable + name = enabled;
}
```
It's definitely not that way,I couldn't think of something more OO,but instead of writing tons of functions with same code,can't I use one by passing the object I'd like to change? | You could create a method that takes an delegate parameter describing the action to perform. Then you could get rid of the repeated code.
Here is an example: I create a public method called PerformAction on my form. It takes an Action<MainForm> delegate as argument; this delegate describes the action that should be taken.
The instance method should be used when possible, but for completeness I created a static version that gets the Form instance from Form.ActiveForm.
The code looks like this:
```
using System;
using System.Windows.Forms;
namespace WinFormTest
{
public partial class MainForm : Form
{
public void PerformAction(Action<MainForm> action)
{
if (InvokeRequired)
Invoke(action,this);
else
action(this);
}
public static void PerformActionOnMainForm(Action<MainForm> action)
{
var form = ActiveForm as MainForm;
if ( form!= null)
form.PerformAction(action);
}
}
}
```
And can then be used like this from another thread:
```
MainForm.PerformActionOnMainForm(form => form.Text = "My form");
// The action can also be a code block or a method:
MainForm.PerformActionOnMainForm(form =>
{
form.Width = 200;
form.Height = 300;
form.Left = 100;
form.Top = 200;
});
```
PerformAction could also be made generic so you can use it on any of your forms. Then the signature would be:
```
public void PerformAction<T>(Action<T> action)
where T : Form
{
...
}
```
It would make sense to declare it like this if you have a common base class that is shared amongst your forms. Alternatively, you could create a helper class containing the method. | I asked a [similar question](https://stackoverflow.com/questions/657037/why-the-overhead-for-multi-threaded-access-to-wpf-ui-controls) but for WPF, the principle is the same though. Modifying the answer that was provided to me by Jon skeet for your question you could use something like this:
```
public static void InvokeIfNecessary(Form form, MethodInvoker action)
{
if (form.InvokeRequired)
{
form.Invoke(DispatcherPriority.Normal, action);
}
else
{
action();
}
}
public static void EnableLogin(int enabled)
{
var form = Form.ActiveForm as FormMain;
if (form != null)
InvokeIfNecessary(form, delegate { form.btnLogin.Enabled = (enabled != 0) });
}
```
Edit: Changed from using form.Dispatcher. | How do I access form properties with Invoke, but with object parameter in C#? | [
"",
"c#",
"oop",
"parameters",
"invoke",
""
] |
I am trying to trigger a show/hide of one div at a time.
What is happening is that all the divs (.shareLink) are opening at the same time.
Below is my jQuery:
```
$(document).ready(function(){
$(".shareLink").hide();
$("a.trigger").click(function(){
$(".shareLink").toggle("400");
return false;
});
});
```
Below is my HTML:
```
<dl class="links">
<dd>content</dd>
<dt class="description">content</dt>
<ul class="tools">
<li><a class="trigger" href="#">Share Link</a></li>
</ul>
</dl>
<div class="shareLink">
<?php print check_plain($node->title) ?>
</div>
```
Any help with the above problem would be much appreciated.
Cheers. | Based on your HTML, you need to do this:
```
$(function() {
$("div.shareLink").hide();
$("a.trigger").click(function(){
$(this).parents('dl.links').next('div.shareLink').toggle(400);
return false;
});
});
```
This walks up to the parent DL and then moves over to the next shareLink div and toggles it. | ```
$(".shareLink").toggle("400");
```
Refers to any div on the page with a class of ".shareLink".
You will need to find a way to distinguish the specific div you want to show. | Show/Hide Multiple Divs | [
"",
"javascript",
"jquery",
""
] |
I am currently in need of a high performance java storage mechanism.
This means:
**1)** I have 10,000+ objects with 1 - Many Relationship.
**2)** The objects are updated every 5 seconds, with the most recent updates persistent in the case of system failure.
**3)** The objects need to be queryable in a reasonable time (1-5 seconds). (IE: Give me all of the objects with this timestamp or give me all of the objects within these location boundaries).
**4)** The objects need to be available across various Glassfish installs.
Currently:
I have been using JMS to distribute the objects, Hibernate as an ORM, and HSQLDB to provide the needed recoverablity.
I am not exactly happy with the performance. Especially the JMS part of this.
After doing some Stack Overflow research, I am wondering if this would be a better solution. Keep in mind that I have no experience with what Terracotta gives me.
I would use Terracotta to distribute objects around the system, and something else need to give the ability to "query" for attributes of those objects.
Does this sound reasonable? Would it meet these performance constraints? What other solutions should I consider? | At first, Lucene isn't your friend here. (read only)
Terracotta is to scale around at the Logical layer! Your problem seems not to be related to the processing logic. It's more around the Storage/Communication point.
1. Identify your bottleneck! Benchmark the Storage/Logic/JMS processing time and overhead!
2. Kill JMS issues with a good JMS framework (eg. ActiveMQ) and a good/tuned configuration.
3. Maybe a distributed key=>value store is your friend. Try [Project Voldemort](http://project-voldemort.com/)!
4. If you like to stay at Hibernate and HSQL, check out the Hibernate 2nd level cache and connection pooling (c3po, container driven...)! | I know it's not what you asked, but, you may want to start by switching from HSQLDB to [H2](http://www.h2database.com/html/main.html). H2 is a relatively new, pure Java DB. It is written by the same guy who wrote HSQLDB and he claims the performance is much better. I'm using it for some time now and I'm very happy with it. It should be a very quick transition (add a Jar, change the connection string, create the database) so it's worth a shot.
In general, I believe in trying to get the most of what I have before rewriting the application in a different architecture. Try profiling it to identify the bottleneck first. | Terracotta + Compass = Hibernate + HSQLDB + JMS? | [
"",
"java",
"hibernate",
"jakarta-ee",
"cluster-computing",
"terracotta",
""
] |
Any code examples on how i must go about creating a folder say "pics" in my root and then upload a images from the file upload control in into that "pics" folder?
If you don't want to give me all the code, i will be happy with a nice link also to show me how this will be done in VB.NET (C# is also ok). | Try/Catch is on you :)
```
public void EnsureDirectoriesExist()
{
// if the \pix directory doesn't exist - create it.
if (!System.IO.Directory.Exists(Server.MapPath(@"~/pix/")))
{
System.IO.Directory.CreateDirectory(Server.MapPath(@"~/pix/"));
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile && Path.GetExtension(FileUpload1.FileName) == ".jpg")
{
// create posted file
// make sure we have a place for the file in the directory structure
EnsureDirectoriesExist();
String filePath = Server.MapPath(@"~/pix/" + FileUpload1.FileName);
FileUpload1.SaveAs(filePath);
}
else
{
lblMessage.Text = "Not a jpg file";
}
}
``` | here is how I would do this.
```
protected void OnUpload_Click(object sender, EventArgs e)
{
var path = Server.MapPath("~/pics");
var directory = new DirectoryInfo(path);
if (directory.Exists == false)
{
directory.Create();
}
var file = Path.Combine(path, upload.FileName);
upload.SaveAs(file);
}
``` | Best way to create a folder and upload a image to that folder in ASP.NET? | [
"",
"c#",
"asp.net",
"vb.net",
"image",
""
] |
I am trying to understand why you would use [`jQuery.get()` and `jQuery.get(index)`](http://docs.jquery.com/Core/get). The docs say it is to convert the jQuery selection to the raw DOM object instead of working with the selection as a jQuery object and the methods available to it.
So a quick example:
```
$("div").get(0).innerHTML;
```
is the same as:
```
$("div").html();
```
Obviously this is a bad example but I am struggling to figure when you would use `.get()`. Can you help me understand when I would use this method in my code? | Cody Lindley (jQuery Team Member) has a [great example](http://codylindley.com/Webdev/355/jquery-get-caching-dom-nodes-in-an-array) of why you would use get()
> If you ever need to cache a set of elements, because you are about to remove them, the jQuery get() method is really handy. For example, in the code below I am saving all my `<li>` elements on the page in an array, removing them, and then adding them back into the page using this array. Make sense?
```
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
</head>
<body>
<ul>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
</ul>
<script>
var test = $('ul li').get();
$('ul').empty();
$.each(test, function(){ $('ul').append('<li>'+$(this).html() + ' new</li>'); });
</script>
</body>
</html>
``` | It happens often when you want to call a native JS method on an element.
```
//submitting a form...
$('#mySearchForm').get().submit();
``` | jQuery.get() - Practical uses? | [
"",
"javascript",
"jquery",
""
] |
I need to implement a large collection of Widget objects, each of which contain a unique file path string ("FilePath"). I need to be able to do the following:
1. Retrieve a Widget object quickly given the file path
2. Change the file path of a Widget without creating a new object (multiple other objects may contain references to a single Widget, and tracking them down would impact performance)
3. Given a Widget reference, determine it's file path
I first thought of using a generic SortedList using the file path as a key, but duplicating the path for many thousands of objects could quickly eat up memory. I considered removing the path from the object and only storing it in the list of keys, but that would make requirement 3 above hard to accomplish.
What I'm leaning towards now is rolling my own class derived from List<> that adds the Widget objects in a sorted order, and retrieves them with a binary search. Requirement 2 can be accomplished simply by removing an object from the list, changing it's file path, and adding it back to the list.
But I'm relatively new to C# and I wanted to check with the great minds here and see if I'm missing another obvious solution.
Thanks! | "Duplicating" the strings will not use twice the memory: Since strings are immutable objects in c#, you will just store another reference (i.e. pointer, 4 or 8 byts) per entry in the dictionary:
```
Dictionary<string, Widget> dict = new Dictionary<string, Widget>();
Widget myWidget = GetSomeWidget();
dict.Add(myWidget.Name, myWidget);
```
You will always be reusing the string object from the widget's property, so just go on with the dict and store the path as property inside the widget.
If you don't need to enumerate the widgets in sorted order, don't use the SortedList, it will be slower than the Dictionary (O(n log n) insertion/deletion/retrieval vs. O(n) average time)
Changing the widget's path will need you to remove it from the dictionary and add it with the changed path, but this is an average constant time operation, so it should be pretty fast.
And just to mention it: Even if you would have to spend one MB of additional memory for getting more performance or using a better-suited (and well-tested) data structure, I don't think that would be a great problem considering the amount of memory other applicatins are using (wasting?) these days ... | Can't you use 2 dictionarys?
```
Dictionary<string, Widget> WidgetsByPath;
Dictionary<Widget, string> PathsByWidget;
```
The handling will have a little more overhead (as you need to update both dictionaries when inserting, modifying or deleting elements) but you'll probably will just insert once lookup many times so it should be enought.
You can even construct a simple class around it:
```
public class Widgets
{
public Widget Add(string Path, Widget wdg)
{
// Chek it doesn't already exits and all...
WidgetsByPath.Add(Path, wdg);
PathsByWidget.Add(wdg, Path);
}
public void Delete(string Path)
{
Widget w = WidgetsByPath[Path];
PathsByWidget.Delete(w);
WidgetsByPath.Delete(Path);
}
}
``` | C# Data Structures Question (Which collection to use?) | [
"",
"c#",
"list",
"data-structures",
"sortedlist",
""
] |
I was reading Eloquent JavaScript and I came across this example for the puzzle:
> Consider this puzzle: By starting from
> the number 1 and repeatedly either
> adding 5 or multiplying by 3, an
> infinite amount of new numbers can be
> produced. How would you write a
> function that, given a number, tries
> to find a sequence of additions and
> multiplications that produce that
> number?
Here's the code for the solution:
```
function findSequence(goal) {
function find(start, history) {
if (start == goal)
return history;
else if (start > goal)
return null;
else
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
}
return find(1, "1");
}
print(findSequence(24));
```
Could someone clear up how dod find get executed if it didn't have a value for the arguments start and goal? Also how did the recursion happen? | But `find` *didn't* get executed without a value for `start` and `goal`. It was first executed with the value `1` for `start`, and the only value for `goal` was `24`.
Perhaps you're confused about the order of operations. There we see the *declaration* of a function, `findSequence`. During the declaration, no code is executed. The `findSequence` function only gets executed later, on the last line, where the result of executing the function gets printed out.
Within the declaration of `findSequence`, there's a declaration of another function, `find`. Once again, it doesn't get executed until later. The `findSequence` function has just *one* executable line of code, the one that calls `find(1, "1")`. Execution of that one line triggers the execution of `find` some number of times, recursively. The `find` function makes reference to `goal`; when the Javascript interpreter executes the code, `goal` always refers to the parameter of `findSequence`, and since in this example `findSequence` is only called once, `goal` always has the same value, `24`.
You should be able to see where the recursion happened. If `start` was equal to `goal`, then the function stops; it returns the history of how it arrived at that number. If `start` is greater than `goal`, then it returns `null`, indicating that that path was not a path to the target number. If `start` is still less than `goal`, then the function tries *calling itself* with its start value plus 5. If that returns a non-null value, then that's what gets returned. Otherwise, it tries multiplying by 3 and returning that history value instead.
Note that although this code can return many numbers, it cannot return *all* numbers. If the goal is `2`, for example, `findSequence` will return `null` because there is no way to start at `1` and get to `2` by adding `5` or multiplying by `3`. | When find is called inside of findSequence, it has access to the goal variable that is set in findSequence's definition. A simple example of this is:
```
function outerFunction() {
var a = 2;
function innerFunction() {
alert(a);
}
innerFunction();
}
outerFunction();
```
The start variable is defined when it does:
```
return find(1, "1");
```
Effectively having an initial start variable of 1, goal variable of 24, and a history of "1" on the first pass.
EDIT: Per Rob's comment, closures aren't actually what's causing this here, as find() is not being executed outside of findSequence(), scoping is causing goal to be found. | A clearer explanation for recursion and flow of execution in JavaScript? | [
"",
"javascript",
"recursion",
""
] |
I'm doing a print\_r on a array stored on a session variable and for some unknown reason it's adding a number after the array prints.
Example:
```
Array
(
[0] => 868
[userid] => 868
)
1
```
If I do a print\_r directly in the function itself and before the variable gets stored on session variable, it doesn't add that number 1.
Solution:
Almost at the same time as Paolo answered my question correctly I found the causing code.
A simple echo on print\_r | Can you post the code you are using to do this around `print_r`? The most common reason for getting a 1 is when you try to print a boolean:
```
$my_bool = true;
print $my_bool; // will be printed as 1
print_r($my_bool); // will also be printed as 1
``` | I had the same issue. You're probably echoing out the return value of print\_r() which is 'true'. You'll have to set print\_r() to return the formatted text rather that its success or failure.
```
echo "Session: ".print_r($_SESSION,true)."<br />\n";
``` | Number Appears after Array Stored in SESSION | [
"",
"php",
"arrays",
"session",
""
] |
When should we use an `out` parameter in C#?
For example
```
bool TryGetValue(out object value);
```
vs.
```
class ReturnType
{
public bool Found {get;set;}
public object Value {get;set;}
}
ReturnType TryGetValue();
```
Apart from reducing the number of lines of code, when should an `out` parameter to be used and when it should be returned as return type? | Out can also be used for operations that might fail (typically found in methods starting Try\*).
E.g. TryParse will return a bool indicating success/failure while using the out value as the result. This avoids having to throw exceptions. | You've nailed exactly the reason why it should be used. To reduce code complexity.
```
if (TryGetValue(myObj))
{
[...]
}
```
is more tidy than
```
Result tryGetValueResult = TryGetValue();
if (tryGetValueResult.Found)
{
[...]
}
```
It can also save on garbage when result needs to be a reference type. | When should an `out` parameter be used instead of returning a complex type? | [
"",
"c#",
".net",
""
] |
Bit of a weird one: I was told a while ago by a friend that rearranging this example `for` loop from :
```
for(int i = 0; i < constant; ++i) {
// code...
}
```
to:
```
for(int i = 0; constant > i; ++i) {
// code...
}
```
would slightly increase performance in C++. I don't see how comparing a constant value to a variable is faster than vice-versa, and some rudimentary tests I ran didn't show any difference in speed between the two implementations. The same was also true of testing this Python `while` loop:
```
while i < constant:
# code...
i += 1
```
vs:
```
while constant > i:
# code...
i += 1
```
Am I wrong? Are my simple tests not enough to determine the speed variation? Is this true of other languages? Or is this just a new best practice? | It's more in the line of C++ folklore, hand micro-optimizations that worked once on a particular version of a particular compiler and get passed down ever after as some kind of lore distinguishing the possessor from the common herd. It's rubbish. Profiling is truth. | Probably not, but if it did, the compiler would probably make the optimization for you automatically anyways. So do it whatever way makes your code most readable. | Does rearranging a conditional evaluation speed up a loop? | [
"",
"c++",
"optimization",
"micro-optimization",
"premature-optimization",
""
] |
I have a table called 'movie2person' with 3 columns: movieID, personID and role. I use this table to connect betwen the 'movies' table and the 'persons' table... many-to-many relationship..
I have selected movieID and personID both as primary keys...
The problem is that sometimes I need to enter the same personID for the same movieID several times and I can't do it because only one combination of the same movieID and personID is permited...
How can I do it??
Thanks.. | Either include role in the primary key, or add a new artificial key to the table and use this new column as the primary key, which you wouldn't use outside of this table. | Based on some comments you've made, I think you need more normalization. Create a role table and adjust your lookup table accordingly
```
movie
+----+------------+
| id | title |
+----+------------+
| 1 | Braveheart |
+----+------------+
person
+----+------------+
| id | name |
+----+------------+
| 4 | Mel Gibson |
+----+------------+
role
+----+------------+
| id | title |
+----+------------+
| 1 | Director |
| 2 | Actor |
+----+------------+
movie2person
+---------+----------+--------+
| movieID | personID | roleID |
+---------+----------+--------+
| 1 | 4 | 1 |
| 1 | 4 | 2 |
+---------+----------+--------+
```
With this setup you'd have a three-column composite primary key on movie2person. | How to design MySQL Database | [
"",
"php",
"mysql",
"database",
"database-design",
""
] |
Lets say I have a file t.txt, a directory t and another file t/t2.txt. If I use the linux zip utility "zip -r t.zip t.txt t", I get a zip file with the following entries in them (unzip -l t.zip):
```
Archive: t.zip
Length Date Time Name
-------- ---- ---- ----
9 04-11-09 09:11 t.txt
0 04-11-09 09:12 t/
15 04-11-09 09:12 t/t2.txt
-------- -------
24 3 files
```
If I try to replicate that behavior with java.util.zip.ZipOutputStream and create a zip entry for the directory, java throws an exception. It can handle only files. I can create a t/t2.txt entry in the zip file and add use the t2.txt file contents to it but I can't create the directory. Why is that? | `ZipOutputStream` *can* handle empty directories by adding a forward-slash `/` after the folder name. Try ([from](http://www.jguru.com/faq/viewquestion.jsp?EID=528882))
```
public class Test {
public static void main(String[] args) {
try {
FileOutputStream f = new FileOutputStream("test.zip");
ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(f));
zip.putNextEntry(new ZipEntry("xml/"));
zip.putNextEntry(new ZipEntry("xml/xml"));
zip.close();
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
``` | Just go through the source of java.util.zip.ZipEntry. It treats a ZipEntry as directory if its name ends with "/" characters. Just suffix the directory name with "/".
Check this example for zipping just the empty directories,
<http://bethecoder.com/applications/tutorials/showTutorials.action?tutorialId=Java_ZipUtilities_ZipEmptyDirectory>
Good luck. | directories in a zip file when using java.util.zip.ZipOutputStream | [
"",
"java",
"directory",
"zip",
""
] |
In this code, why isn't my array initialised as I want it to? Is the for-each loop not designed to do that, or am I just not using it correctly?
```
int[] array = new int[5];
//initialise array -> Doesn't work! Array still full of 0's
for(int i : array)
i = 24;
``` | The for-each loop will not work for this case. You cannot use a for-each loop to initialize an array. Your code:
```
int[] array = new int[5];
for (int i : array) {
i = 24;
}
```
will translate to something like the following:
```
int[] array = new int[5];
for (int j = 0; j < array.length; j++) {
int i = array[j];
i = 24;
}
```
If this were an array of objects, it would still fail. Basically, for-each assigns each entry in the collection or array, in turn, to the variable you provide, which you can then work with. The variable is *not* equivalent to an array reference. It is just a variable.
For-each cannot be used to initialize *any* array or Collection, because it loops over the current contents of the array or Collection, giving you each **value** one at a time. The variable in a for-each is *not* a proxy for an array or Collection reference. The compiler does not replace your "`i`" (from "`int i`") with "`array[index]`".
If you have an array of Date, for example, and try this, the code:
```
Date[] array = new Date[5];
for (Date d : array) {
d = new Date();
}
```
would be translated to something like this:
```
Date[] array = new Date[5];
for (int i = 0; i < array.length; i++) {
Date d = array[i];
d = new Date();
}
```
which as you can see will not initialize the array. You will end up with an array containing all nulls.
NOTE: I took the code above, compiled it into a `.class` file, and then used [jad](http://www.varaneckas.com/jad) to decompile it. This process gives me the following code, generated by the Sun Java compiler (1.6) from the code above:
```
int array[] = new int[5];
int ai[];
int k = (ai = array).length;
for(int j = 0; j < k; j++)
{
int i = ai[j];
i = 5;
}
``` | `i` is just a copy of the int at that point in the array, not a reference to it. The for-each loop doesn't work in this case. | Why doesn't this for-each loop work? | [
"",
"java",
"foreach",
""
] |
I have been playing around with a search control and i have noticed that when you try and press enter from within the textbox it submits the form but doesnt click the search button (like i want it to).
My markup is:
```
<div>
<span>Search</span>
<asp:TextBox ID="txtSearch" runat="server" Width="170"
onkeydown="if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {$('#<%=lkbSearch.ClientID %>').click();return false;} else return true; ">
</asp:TextBox>
</div>
<asp:LinkButton ID="lkbSearch" runat="server" CssClass="searchButton">
<asp:Image ID="imgSearch" runat="server" ImageUrl="~/Images/Master/button_go.gif" />
</asp:LinkButton>
```
i added the onkeydown event to the textboxes, and it runs, but when i try to use JQuery to call the Click() function from the button it does nothing.
How can i make it so when enter is pressed in the textbox it "clicks" the button? | After playing around with a few different things i finally came up with the solution.
I wrapped the textbox and button in an asp:panel control and set the default button to the ID of my LinkButton only to find that panels cant have LinkButtons as the DefaultButton.
But changing the link button to an ImageButton and using its ID in the DefaultButton filed of the panel works perfectly.
```
<asp:Panel ID="pnlSearch" runat="server" DefaultButton="imbSearch">
...
</asp:Panel>
``` | Since a `LinkButton` is added to the page as an `<a>`. When you select the button using jQuery you get the element wrapped in jQuery. Because of that calling the click event only triggers the click event, without following the `href`.
The following code would simulate clicking the button:
```
$('#<%= linkbuttonid.ClientID%>')[0].click();
```
You may replace `'#<%= linkbuttonid.ClientID%>'` with any selector that will get the correct element. But it is necessary to include `[0]` so that click is invoked on the `<a>` itself.
Alternately, you could reroute the page to the href:
```
window.location = $('yourselector').attr('href');
```
See [this question](https://stackoverflow.com/q/980709/1316573) for more information about invoking a click-event for an anchor tag in javascript. | Use JQuery to call an asp:linkbutton click function | [
"",
"asp.net",
"javascript",
"jquery",
""
] |
I have a few `TextField`s in my `Frame`. I want to know which `TextField` currently has focus. How can I find this information? | `JFrame.getFocusOwner()` (inherited from [`Window.getFocusOwner()`](http://java.sun.com/javase/6/docs/api/java/awt/Window.html#getFocusOwner())) ought to return a reference to the component with focus. `getMostRecentFocusOwner()` might also be of interest. | ```
KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()
``` | How to find out which object currently has focus | [
"",
"java",
"swing",
"focus",
""
] |
I have the following string which won't compile:
```
String formLookupPull = @"SELECT value1, '"+tableName+"', '"+columnName+"' FROM lkpLookups WHERE ""table"" = '" + tableName + "' and ""field"" = '" + columnName + "';";
```
The offending sections are :
```
""table"" =
```
and
```
""field"" =
```
The compiler is getting all mixed up on the escape sequence. Can anyone see what's wrong? | The problem is that not all the strings you are concatenating are *verbatim* string literals, only the first portion of the concatenation is.
In other words,
```
@"SELECT value1, '"
```
is the only *verbatim* literal in the entire statement to build the final string.
You would need to add @ in front of the rest of your strings to make them all verbatim.
Which would make it look like:
```
String formLookupPull = @"SELECT value1, '"+tableName+ @"', '"+columnName+ @"' FROM lkpLookups WHERE ""table"" = '" + tableName + @"' and ""field"" = '" + columnName + @"';";
``` | To address your title question...
To escape the quote in a verbatim string literal, use the quote-escape-sequence `""` (that's two quote characters)
```
string a = @"He said ""Hi!""..."; // He said "Hi!"...
```
See [MSDN](http://msdn.microsoft.com/en-us/library/aa691090.aspx) for more details on escaping, etc.
Note that in your posted code, the only verbatim string is the very first one (with the `@` before it). The subsequent strings are not verbatim, so the proper escape sequence would be `\"`.
You can make it look prettier with `string.Format`:
```
String formLookupPull =
string.Format(@"SELECT value1, '{0}', '{1}' FROM lkpLookups" +
@"WHERE ""table"" = '{0}' and ""field"" = '{1}';",
tableName, columnName)
``` | Escaping verbatim string literals | [
"",
"c#",
"string",
"escaping",
"verbatim-string",
""
] |
I need to iterate through SortedMap's entry set (which is a SortedSet) backwards. The code I'm writing is extremely performance-sensitive, as it's going to be called from many places thousands times per second, maybe more. Any advice on doing it the fastest way? | In Java 1.6 you can use [NavigableSet](http://java.sun.com/javase/6/docs/api/java/util/NavigableSet.html). | use this before you fill your map :
```
SortedMap sortedMap = new TreeMap(java.util.Collections.reverseOrder());
``` | The best way to iterate SortedSet / SortedMap in Java backwards | [
"",
"java",
"collections",
""
] |
I know *unsigned int* can't hold negative values. But the following code compiles without any errors/warnings.
```
unsigned int a = -10;
```
When I print the variable *a*, I get a wrong value printed. If unsigned variables can't hold signed values, why do compilers allow them to compile without giving any error/warning?
Any thoughts?
**Edit**
Compiler : VC++ compiler
**Solution**
Need to use the warning level 4. | ### Microsoft Visual C++:
> warning C4245: 'initializing' :
> conversion from 'int' to 'unsigned
> int', signed/unsigned mismatch
On warning level 4.
### G++
Gives me the warning:
> warning: converting of negative value
> `-0x00000000a' to` unsigned int'
Without any -W directives.
### GCC
You must use:
> gcc main.c -Wconversion
Which will give the warning:
> warning: negative integer implicitly converted to unsigned type
Note that -Wall will not enable this warning.
---
Maybe you just need to turn your warning levels up. | Converting a `signed int` to an `unsigned int` is something known in the C standard as a "Usual arithmetic conversion", so it's not an error.
The reason compilers often don't issue a warning on this by default is because it's so commonly done in code there would be far too many 'false positive' warnings issued in general. There is an awful lot of code out there that works with `signed int` values to deal with things that are inherently unsigned (calculating buffer sizes for example). It's also very common to mix signed and unsigned values in expressions.
That's not to say that these silent conversions aren't responsible for bugs. So, it might not be a bad idea to enable the warning for new code so it's 'clean' from the start. However, I think you'd probably find it rather overwhelming to deal with the warnings issued by existing code. | Why compiler is not giving error when signed value is assigned to unsigned integer? - C++ | [
"",
"c++",
"variables",
"compiler-errors",
"compiler-warnings",
"unsigned",
""
] |
I'm working with C#, I need to obtain a specific instance of excel by it's process ID; I get the Process ID of the instance that I need from another application but I don't know what else to do, I don't know how can I get a running instance of excel given his process ID.
I have researched a lot on the web, but I have only see examples of using Marshal.GetActiveObject(...) or Marshal.BindToMoniker(...), which I can't use since the first one returns the first Excel instance registered in the ROT and not precisely the one that I need, and the second one requires that you save the excel file before trying to get the instance.
Also, if I where able to get the CLSID of the excel instance that I need, using the process ID, then I may be able to call
```
GetActiveObject(ref _guid, _ptr, out objApp);
```
that ultimately will return the excel instance that I need. | Once you identify the process via the process id, you can get the [Process.MainWindowHandle](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.mainwindowhandle.aspx) and then use that along with the [AccessibleObjectFromWindow API](http://msdn.microsoft.com/en-us/library/dd317978(VS.85).aspx) to get access to the Excel object model for that process.
The article [Getting the Application Object in a Shimmed Automation Add-in](https://web.archive.org/web/20130518152056/http://blogs.officezealot.com/whitechapel/archive/2005/04/10/4514.aspx) by Andrew Whitechapel describes this technique in detail, along with sample code.
The key code in that article for you begins at the line:
```
int hwnd = (int)Process.GetCurrentProcess().MainWindowHandle
```
Which in your case might look more like:
```
int excelId = 1234; // Change as appropriate!
int hwnd = (int)Process.GetProcessById(excelId).MainWindowHandle
```
where the 'excelId' is the process id number that you are looking for. Otherwise, the code should be essentially the same as given in the article. (Ignore the fact that his code is written for an add-in; that aspect won't affect your needs here, so just ignore it.)
If you do not have the process id, then you you would want to use [Process.GetProcessesByName](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getprocessesbyname.aspx), whereby you could enumerate each one and grab control of each Excel instance with access to the object model, as needed.
Hope this helps,
Mike | The ROT entries are not tagged with a CLSID. The ROT returns a DWORD from Register, which is used as a identifier for Unregister.
I've run into this problem before and the only way I've solved it is to have some kind of add-in loaded into each Excel that you can communicate directly with. | How to get Excel instance or Excel instance CLSID using the Process ID? | [
"",
"c#",
"excel",
""
] |
With this code I tried to print the string "foo" 10 times
in binary format. But why doesn't the function to do it work?
```
#include <iostream>
#include <fstream>
using namespace std;
template <typename T> void WriteStr2BinFh (string St, ostream &fn) {
for (unsigned i = 0; i < St.size(); i++) {
char CStr = St[i];
fn.write(&CStr.front(), CStr.size());
}
return;
}
int main() {
string MyStr = "Foo";
ofstream myfile;
myfile.open("OuputFile.txt", ios::binary|ios::out);
// We want to print it 10 times horizontally
// separated with tab
for (int i = 0; i < 9; i++) {
WriteStr2BinFh(Mystr+"\t", myfile);
}
myfile.close();
}
``` | There is so much wrong here, I'm just going to list everything I see:
Your for loop condition should be i < 10.
Why are you using a template but not the templatized parameter T?
You're calling the method front() on CStr, but CStr is a char, not a string, so I don't even know how that compiles.
Assuming CStr was a string, you don't want to take the address of the front() iterator using &, instead you want to say something like:
```
fn.write(St.c_str(), St.size());
```
And you don't want to loop for St.size() iterations. Just do the above. | omg, it have a lot of errors:
* int main - should return value;
* you don't use template< typename T > in your function;
* Mystr - not correct name in function call, names in c++ are case sencetive;
* char CStr - doesn't have method front, and std::string too;
* you couldn't get address of first element such as in case with vector;
* it will be better if you will accept std::string as const reference;
* you forgot to include string header;
* ...
fixed your example, with your code organize and your naming:
```
#include <iostream>
#include <fstream>
#include <string>
void WriteStr2BinFh( const std::string& St, std::ostream &out )
{
out.write( St.c_str(), St.size() );
}
int main()
{
std::string MyStr = "Foo";
std::ofstream myfile( "OuputFile.txt", std::ios::binary | std::ios::out );
for (size_t i = 0; i < 9; ++i)
{
WriteStr2BinFh( MyStr+"\t", myfile );
}
myfile.close();
return 0;
}
```
but I've reccomended to use `std::fill_n` algorithm
```
std::fill_n( std::ostream_iterator< std::string >( myfile, "\t" ), 10, MyStr );
``` | How to Write Strings Into Binary File | [
"",
"c++",
"binaryfiles",
""
] |
I have a large project in my workspace. Each time I save a jsp or any file (java, txt, properties etc.) the build runs. It takes about 30 to 45 secs to build. I hate it! I can't be productive like this. This just started happening recently, I've always had auto build enabled which didn't cause this issue. Other people here in the office do not get this problem. So it must be my settings.
I guess the questions is, how do I get eclipse to build only the class file that I modified and not a complete build each time I edit any file in the project?
Please help! | It turns out that I did not have all my jars in the classpath. These jars were not being directly used by my codes hence there were no errors in my codes per se. They were needed by the other libraries that I was using.
FIX:
Made sure all dependencies are added to classpath. | > I guess the questions is, how do I get
> eclipse to build only the class file
> that I modified and not a complete
> build each time I edit any file in the
> project?
That is what Eclipse usually does out-of-the-box. You must have broken something...
Are you using external build tools (such as Ant)? Check the Builders settings for the project.
If nothing else helps, try to create a new workspace and import your project into it. | Eclipse builds ALL classes on each save | [
"",
"java",
"eclipse",
"build",
""
] |
I have simple code that does a head request for a URL and then prints the response headers. I've noticed that on some sites, this can take a long time to complete.
For example, requesting `http://www.arstechnica.com` takes about two minutes. I've tried the same request using another web site that does the same basic task, and it comes back immediately. So there must be something I have set incorrectly that's causing this delay.
Here's the code I have:
```
$ch = curl_init();
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
// Only calling the head
curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD'
$content = curl_exec ($ch);
curl_close ($ch);
```
Here's a link to the web site that does the same function: <http://www.seoconsultants.com/tools/headers.asp>
The code above, at least on my server, takes two minutes to retrieve www.arstechnica.com, but the service at the link above returns it right away.
What am I missing? | Try simplifying it a little bit:
```
print htmlentities(file_get_contents("http://www.arstechnica.com"));
```
The above outputs instantly on my webserver. If it doesn't on yours, there's a good chance your web host has some kind of setting in place to throttle these kind of requests.
**EDIT**:
Since the above happens instantly for you, try setting [this curl setting](http://www.php.net/manual/en/function.curl-setopt.php) on your original code:
```
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
```
Using the tool you posted, I noticed that `http://www.arstechnica.com` has a 301 header sent for any request sent to it. It is possible that cURL is getting this and not following the new Location specified to it, thus causing your script to hang.
**SECOND EDIT**:
Curiously enough, trying the same code you have above was making my webserver hang too. I replaced this code:
```
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD'
```
With this:
```
curl_setopt($ch, CURLOPT_NOBODY, true);
```
Which is the way [the manual](http://www.php.net/manual/en/function.curl-setopt.php) recommends you do a HEAD request. It made it work instantly. | You have to remember that HEAD is only a suggestion to the web server. For HEAD to do the right thing it often takes some explicit effort on the part of the admins. If you HEAD a static file Apache (or whatever your webserver is) will often step in an do the right thing. If you HEAD a dynamic page, the default for most setups is to execute the GET path, collect all the results, and just send back the headers without the content. If that application is in a 3 (or more) tier setup, that call could potentially be very expensive and needless for a HEAD context. For instance, on a Java servlet, by default doHead() just calls doGet(). To do something a little smarter for the application the developer would have to explicitly implement doHead() (and more often than not, they will not).
I encountered an app from a fortune 100 company that is used for downloading several hundred megabytes of pricing information. We'd check for updates to that data by executing HEAD requests fairly regularly until the modified date changed. It turns out that this request would actually make back end calls to generate this list every time we made the request which involved gigabytes of data on their back end and xfer it between several internal servers. They weren't terribly happy with us but once we explained the use case they quickly came up with an alternate solution. If they had implemented HEAD, rather than relying on their web server to fake it, it would not have been an issue. | PHP / Curl: HEAD Request takes a long time on some sites | [
"",
"php",
"curl",
"http-headers",
"header",
"performance",
""
] |
I'm trying to make all white pixels transparent using the Python Image Library. (I'm a C hacker trying to learn python so be gentle)
I've got the conversion working (at least the pixel values look correct) but I can't figure out how to convert the list into a buffer to re-create the image. Here's the code
```
img = Image.open('img.png')
imga = img.convert("RGBA")
datas = imga.getdata()
newData = list()
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append([255, 255, 255, 0])
else:
newData.append(item)
imgb = Image.frombuffer("RGBA", imga.size, newData, "raw", "RGBA", 0, 1)
imgb.save("img2.png", "PNG")
``` | You need to make the following changes:
* append a tuple `(255, 255, 255, 0)` and not a list `[255, 255, 255, 0]`
* use `img.putdata(newData)`
This is the working code:
```
from PIL import Image
img = Image.open('img.png')
img = img.convert("RGBA")
datas = img.getdata()
newData = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255, 255, 255, 0))
else:
newData.append(item)
img.putdata(newData)
img.save("img2.png", "PNG")
``` | You can also use pixel access mode to modify the image in-place:
```
from PIL import Image
img = Image.open('img.png')
img = img.convert("RGBA")
pixdata = img.load()
width, height = img.size
for y in range(height):
for x in range(width):
if pixdata[x, y] == (255, 255, 255, 255):
pixdata[x, y] = (255, 255, 255, 0)
img.save("img2.png", "PNG")
```
You can probably also wrap the above into a script if you use it often. | How to use PIL to make all white pixels transparent? | [
"",
"python",
"image",
"python-imaging-library",
""
] |
I'm tempted to lie and say that English is my second language, but the truth is that I just have no idea what 'Coalescing' means. I know what `??` 'does' in C#, but the name doesn't make sense to me.
I looked up the word and I understand it to be a synonym for 'join'. 'Null Join Operator' still doesn't make sense.
Can someone enlighten me? | > I'm tempted to lie and say that English is my second language...but the truth is that I just have no idea what 'Coalescing' means. I know what ?? 'does' in C#, but the name doesn't make sense to me.
>
> I looked up the word and I understand it to be a synonym for 'join'.
I'd say a more accurate description of "coalesce" would be "to form one thing from different elements". The "coalescing" of the `??` operator happens because a single value is always resolved from one of the two values. The first non-null value is the result. | *Coalescing* is when you have more than one item and then you end up with exactly one—either by joining the items together or by choosing a single item from the group. In the case of the *??* operator, you're choosing the first non-null value of the pair of values. | ?? Null Coalescing Operator --> What does coalescing mean? | [
"",
"c#",
"terminology",
"coalesce",
"null-coalescing-operator",
""
] |
I need to create an application "dll, script or exe" which when the user upload on a folder on his server using his ftp, it will automatically run on the current folder and do some image manipulations in the folder images,
My Question is how to make something like this, which the user will not need to configure anything on his server, all what he want is upload in the right folder, and it will run automatically and keep running
Is it possible? How do it? Which Language to use?
**UPDATE:** I am targeting shared hosting server, which the user have no way to configure his server OS, about the OS, lets start saying its just windows.
I know that "Not possible" may be the right answer, and also "its a virus" may be another answer, i just want to know if its possible or should i think in another new way. | Everything I have read in this question screams "security vulnerability exploit". Since it's one of the main things hosting companies are making sure doesn't happen, I would say your chances are very slim to have that work.
However, if it's a web server, with something like CGI or PHP enabled, you could leverage that by uploading a CGI or PHP script in a place it can be run, and then calling it through a browser, thus doing whatever file manipulations you need... Things like safe mode, reserved or virtual directories could get in the way, but I think there is a better chance of that working. | Hmmm... is this a Window's or Linux machine? If this were on Windows, I would say create a C# service that uses FileSystemWatcher to listen for changes to the FTP folder and do your processing. As a service, it has no user interface and can run automatically on bootup. | Is there something called Self running applications? | [
"",
"java",
".net",
"c",
"security",
""
] |
```
public string GetArtistThumbnail(string artistName)
{
var request =
WebRequest.Create("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=" + artistName +
"&api_key=" +
APIKey) as HttpWebRequest;
using (var response = request.GetResponse() as HttpWebResponse)
{
var ds = new DataSet();
ds.ReadXml(response.GetResponseStream()); // <-- Exception is thrown here
}
return "";
}
```
The above method basically retrieves an xml file from one of [LastFM's API Services](http://www.last.fm/api/intro).
Now, I am facing the following **exception** when filling the dataset from the xml with the `ReadXml` method:
`The table (artist) cannot be the child table to itself in nested relations.`
---
[Here is an example](http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=iron%20maiden&api_key=b25b959554ed76058ac220b7b2e0a026) of an XML file that is being retrieved
Notice that there is a nested `Artist` in the XML file, and I obviously presume that that is the reason for the exception.
---
My question, **how can I prevent this from happening? as regards the nested tables** | As far as I know, DataSets aren't meant to hold just about any type of XML. Do you really need a dataset in this case?
I suggest switching to linq 2 xml or XmlDocument to manipulate the results of the web service. | I think Freddy's answer has merit, but you might be able to define the DataSet schema manually before ReadXml is invoked, instead of relying on the xml to define the schema.
You could also try separating ReadXml from GetResponse and perform an xslt before ReadXml is invoked, i.e. make the schema compatible with a DataSet.
Long shot...turn off DataSet.EnforceConstraints | C#: "The table 'sometable' cannot be the child table to itself in nested relations." | [
"",
"c#",
"web-services",
"api",
"httpwebrequest",
""
] |
I have run into two situations lately where I have chosen to use the command line for doing something rather than the PHP library. For example, in PHP doing this:
```
`curl http://someplace.com`
```
instead of this:
```
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
```
The other situation is using ImageMagick's command line interface, instead of the PHP interface.
Some people I have talked to think that using the libraries is better. Some say better is faster, other say safer, etc.
What is your opinion? What are the benefits to using one over the other?
I know one benefit, is that I only have one line of code instead of 5. | I'd always use the libraries:
1. No need to fork twice (once for the sub-shell, and another for the program you're running) - hence faster
2. No need to worry about escaping command line arguments, which helps security
If the number of lines of code is a worry, write those 5 lines once in a function, and then call that function when you need it. | Executing applications is both a potentially dangerous and nearly always a costly operation. You need to properly escape every parameter you pass to the program, amongst other things.
The cost of creating a new process is also far above calling a simple function in an existing one.
While what you are doing may work fine now, it won't once your application has several thousands of concurrent users. (You are planning for that, aren't you? :) ) | PHP library or command line? | [
"",
"php",
"command-line",
"curl",
"imagemagick",
""
] |
I want a method in a `DrawableGameComponent` class to **not return until a particular condition is met**
Say I have this class (snippet from a `DrawableGameComponent` class):
```
public override void Update(GameTime gameTime)
{
if (moving && pixFromLastMove <= distanceToMove)
{
position += velocity;
pixFromLastMove += velocity.Length();
}
else
{
moving = false;
}
if (rotating)
{
rotation += 0.1f;
var cRotation = MathHelper.Clamp(rotation, -MathHelper.PiOver2, angleBeforeRotation + degToRotate);
if (cRotation != rotation)
{
rotation = cRotation;
angleBeforeRotation = rotation;
rotating = false;
}
}
base.Update(gameTime);
}
public void Ahead(int pix)
{
moving = true;
distanceToMove = pix;
pixFromLastMove = 0;
velocity = new Vector2((float) Math.Cos(rotation), (float) Math.Sin(rotation))*5.0f;
//DO NOT RETURN UNTIL THIS ROBOT HAS MOVED TO ITS DESTINATION
}
public void TurnLeft(int deg)
{
rotating = true;
degToRotate = MathHelper.ToRadians(deg);
angleBeforeRotation = rotation;
//DO NOT RETURN UNTIL THIS ROBOT HAS BEEN FULLY ROTATED
}
```
This class is being drawn (`Draw()`)in the main thread (because this drawablegamecomponent is executing in seperate thread), and also in the main thread I have a list of commands that I want to be executed in order...but currently, since the `Ahead` method returns just after assigning a value to `velocity`, the methods will run almost concurrently, which in turn just executes all the animations at the same time.
So what do you think should I do to prevent methods that are commands (`Ahead`,`TurnLeft` etc..) from returning before a certain condition is met? | You need to create some kind of state machine for your Update() method. e.g.
```
public override void Update() {
if (movingRobot) {
OnlyUpdateRobotPosition();
}
else {
DoStuffPerhapsIncludingStartingRobotMove();
}
}
```
Or am I missing the question? | Ahh, two words: Cooperative multitasking. With the joy of [Fibers](http://msdn.microsoft.com/en-us/library/ms682661(VS.85).aspx) (or your cooperative multitasking building block of choice) you could (after laying some ground work, such as [this to enable fibers in C#](http://www.java2s.com/Tutorial/CSharp/0520__Windows/Fiber.htm)) do something like this:
```
public void Ahead(int pix)
{
moving = true;
distanceToMove = pix;
pixFromLastMove = 0;
velocity = new Vector2((float) Math.Cos(rotation), (float) Math.Sin(rotation))*5.0f;
//DO NOT RETURN UNTIL THIS ROBOT HAS MOVED TO ITS DESTINATION
while(!HasReachedDestination())
{
Yield(); // let another fiber run
}
}
```
In order to make this work however you need to implement a simple round-robin scheduler. C# isn't really my boat, but what I'd do is to keep it simple and create some sort of base-class that I'd call Cooperative (or something). This class would have a static list of all created fibers as well as the static methods Create() and Yield(). Create() will create a new fiber (or whatever) and Yield() will simply schedule next fiber to execute (round-robin style), in fiber-world that would include a call to SwitchToFiber(). It will also have a virtual method called Start() (or whatever) that is where the fiber will start to run.
To make it more fancy-smancy you could later keep separate lists of fibers that are either runnable or not runnable (i.e. waiting for something to happen). In that case you might be able to simplify the loop in Ahead to:
```
WaitFor(HasReachedDestination);
```
But I suggest getting your feet wet with the concept of cooperative multitasking first.
Finally some thoughts on what should be made fibers, typically your main update loop is one fiber, updating and drawing all objects and then calls Yield(). The all game objects would also be fibers (this may not be feasible if you have a lot of game objects). For your game objects you'd do something like:
```
public override Start()
{
do
{
if(EnemyToTheLeft())
{
TurnLeft(90); // this will call Yield and return when we have finished turning
Shoot();
}
Yield(); // always yield
}while(!dead);
}
``` | XNA: Preventing a method from returning | [
"",
"c#",
"xna",
"drawablegamecomponent",
""
] |
I run in to something that illustrates how I clearly don't get it yet.
Can anyone please explain why the value of "this" changes in the following?
```
var MyFunc = function(){
alert(this);
var innerFunc = function(){
alert(this);
}
innerFunc();
};
new MyFunc();
``` | In JavaScript, `this` represents the context object on which the function was *called*, not the scope in which it was defined (or the scope in which it was called). For `MyFunc`, this references the new object being created; but for `innerFunc`, it references the global object, since no context is specified when `innerFunc` is called.
This tends to trip up those used to Java or similar OO languages, where `this` almost always references an instance of the class on which the method being called is defined. Just remember: JavaScript doesn't have methods. Or classes. Just objects and functions.
### See also: [What is the rationale for the behavior of the ‘this’ keyword in JavaScript?](https://stackoverflow.com/questions/541167/what-is-the-rationale-for-the-behavior-of-the-this-keyword-in-javascript) | Just do the following:
```
var MyFunc = function(){
var self = this;
alert(self);
var innerFunc = function(){
alert(self);
}
innerFunc();
};
new MyFunc();
```
This way self will always mean this, irrespective of where you're calling it from, which is usually what you want. | Just when I think I finally understand Javascript scope | [
"",
"javascript",
"scope",
""
] |
The spreadsheet still displays, but with the warning message. The problem seems to occur because Excel 2007 is more picky about formats matching their extensions than earlier versions of Excel.
The problem was initially discovered by an ASP.Net program and produces in the Excel error "The file you are trying to open, "Spreadsheet.aspx-18.xls', is in a different format than specified by the file extension. Verify ...". However, when I open the file it displays just fine. I am using Excel 2007. Firefox identifies the file as an Excel 97-2003 worksheet.
Here is an ASP.NET page which generates the problem:
```
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Spreadsheet.aspx.cs" Inherits="Spreadsheet" %>
```
The code behind file looks like:
```
public partial class Spreadsheet : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/vnd.ms-excel";
Response.Clear();
Response.Write("Field\tValue\tCount\n");
Response.Write("Coin\tPenny\t443\n");
Response.Write("Coin\tNickel\t99\n");
}
```
}
T | <http://blogs.msdn.com/vsofficedeveloper/pages/Excel-2007-Extension-Warning.aspx>
That is a link basically describing that MS knows about the problem your describe and that it cannot be suppressed from within ASP.NET code. It must be suppressed/fixed on the client's registry. | If you're like me and generating the Excel Sheet as 2003 XML document, you can remove the warnings by doing the following:
**Added to the XML output:**
```
<?xml version="1.0" encoding="utf-16"?>
<?mso-application progid="Excel.Sheet"?>
...
```
**Added to the download page:**
```
// Properly outputs the xml file
response.ContentType = "text/xml";
// This header forces the file to download to disk
response.AddHeader("content-disposition", "attachment; filename=foobar.xml");
```
Now Excel 2007 will not display a warning that the file content and file extension don't match. | Excel spreadsheet generation results in "different file format than extension error" when opening in excel 2007 | [
"",
"c#",
"excel",
"webforms",
"xls",
""
] |
How do I match the following string?
```
http://localhost:8080/MenuTest/index.action
```
The regex should return true if it contains "MenuTest" in the above pattern.
Cheers | Maybe you don't need a regex?
```
String url = "http://localhost:8080/MenuTest/index.action";
boolean hasWhatImLookingFor = url.contains("MenuTest");
``` | If you need to check if "MenuTest" appears *at that specific position* (i.e. after the host/port), then you can use:
```
^https?://[^/]++/MenuTest
``` | Regular Expression (Java) | [
"",
"java",
"regex",
"string",
""
] |
After posting [my solution](https://stackoverflow.com/questions/724536/does-memory-stay-allocated-when-a-c-thread-exits/730868#730868) to my own problem regarding memory issues, [nusi suggested that my solution lacks locking](https://stackoverflow.com/questions/724536/does-memory-stay-allocated-when-a-c-thread-exits/731025#731025).
The following pseudo code vaguely represents my solution in a very simple way.
```
std::map<int, MyType1> myMap;
void firstFunctionRunFromThread1()
{
MyType1 mt1;
mt1.Test = "Test 1";
myMap[0] = mt1;
}
void onlyFunctionRunFromThread2()
{
MyType1 &mt1 = myMap[0];
std::cout << mt1.Test << endl; // Prints "Test 1"
mt1.Test = "Test 2";
}
void secondFunctionFromThread1()
{
MyType1 mt1 = myMap[0];
std::cout << mt1.Test << endl; // Prints "Test 2"
}
```
I'm not sure at all how to go about implementing locking, and I'm not even sure why I should do it (note the actual solution is much more complex). Could someone please explain how and why I should implement locking in this scenario? | In general, threads might be running on different CPUs/cores, with different memory caches. They might be running on the same core, with one interrupting ("pre-empting" the other). This has two consequences:
1) You have no way of knowing whether one thread will be interrupted by another in the middle of doing something. So in your example, there's no way to be sure that thread1 won't try to read the string value before thread2 has written it, or even that when thread1 reads it, it is in a "consistent state". If it is not in a consistent state, then using it might do anything.
2) When you write to memory in one thread, there is no telling if or when code running in another thread will see that change. The change might sit in the cache of the writer thread and not get flushed to main memory. It might get flushed to main memory but not make it into the cache of the reader thread. Part of the change might make it through, and part of it not.
In general, without locks (or other synchronization mechanisms such as semaphores) you have no way of saying whether something that happens in thread A will occur "before" or "after" something that happens in thread B. You also have no way of saying whether or when changes made in thread A will be "visible" in thread B.
Correct use of locking ensures that all changes are flushed through the caches, so that code sees memory in the state you think it should see. It also allows you to control whether particular bits of code can run simultaneously and/or interrupt each other.
In this case, looking at your code above, the minimum locking you need is to have a synchronisation primitive which is released/posted by the second thread (the writer) after it has written the string, and acquired/waited on by the first thread (the reader) before using that string. This would then guarantee that the first thread sees any changes made by the second thread.
That's assuming the second thread isn't started until after firstFunctionRunFromThread1 has been called. If that might not be the case, then you need the same deal with thread1 writing and thread2 reading.
The simplest way to actually do this is to have a mutex which "protects" your data. You decide what data you're protecting, and any code which reads or writes the data must be holding the mutex while it does so. So first you lock, then read and/or write the data, then unlock. This ensures consistent state, but on its own it does not ensure that thread2 will get a chance to do anything at all in between thread1's two different functions.
Any kind of message-passing mechanism will also include the necessary memory barriers, so if you send a message from the writer thread to the reader thread, meaning "I've finished writing, you can read now", then that will be true.
There can be more efficient ways of doing certain things, if those prove too slow. | One function (i.e. thread) modifies the map, two read it. Therefore a read could be interrupted by a write or vice versa, in both cases the map will probably be corrupted. You need locks. | When is it necessary to implement locking when using pthreads in C++? | [
"",
"c++",
"locking",
"pthreads",
""
] |
I was reading item #6.10 on <http://www.cafeaulait.org/javafaq.html> and I began wondering how the big players go about creating their own implementation of a JVM. Would an experimental something or another be possible (and feasible) for one guy? | technically, all the information people need to create a new JVM is in the public specifications for the language and the targetted platform. A JVM would need to behave differently depending on whether it is meant to run on a desktop computer or a mobile phone, even if the bytecode interpretation would be largely identical.
A few places to start looking for information:
<http://en.wikipedia.org/wiki/List_of_Java_virtual_machines>
Reading The "Java Virtual Machine Specification" by Tim Lindholm
<http://www.jcp.org/en/jsr/detail?id=30>
From what I have seen of JVM implementations by Sun, IBM or smaller companies like Esmertec, writing a simple JVM is a several man-months project but adding JSR after JSR to support more functionality can take years afterwards.
Now, if all you need is a simple bytecode interpreter, it's not that bad, but it's still quite a bit of code to write. | A handmade JVM would be a great way to learn about virtual machines in general, the issues of program language design (through the JVM spec), and the nitty gritty of parsing and so forth.
If you choose to take it in that direction, you could also explore optimizations, which is where it can get interesting, and you can take research papers and implement their algorithms.
That being said, if you're less interested in the long and arduous task of creating a VM from scratch, you might want to modify an existing open source VM like [Kaffe](http://www.kaffe.org/). It will show you what a virtual machine does, but not necessarily how Java code works in Sun's JVM:
> Kaffe is a clean room implementation of the Java virtual machine, plus the associated class libraries needed to provide a Java runtime environment.
This way, you could study the details, but dive in to implementing more interesting features. | How to create custom JVM? | [
"",
"java",
"jvm",
""
] |
Using this method after the SignOut() call redirects to '...login.aspx?ReturnUrl=%2fmydomainname%2flogout.aspx' so that the user can't log back in again, since a successful login returns to the logout page. The login page is set in webconfig and the app successfully gets that page. Why would a ReturnURL be stuck on the tail of the URL? | This is how `RedirectFromLoginPage` works. It appends the current URL to the query string of the login page. This way, the login page can redirect the user back to the place he where.
If you don't want this to happen, you can manually redirect to the login page using `Response.Redirect`. | use this code on logout
```
<asp:LoginStatus ID="LoginStatus1" runat="server" LogoutPageUrl="/xyz.aspx" LogoutAction="Redirect" />
``` | FormsAuthentication RedirectToLoginPage Quirk | [
"",
"c#",
"forms-authentication",
""
] |
I was reading through a Java textbook, and it mentions something called a "driver class". What is it, and how is it different from a normal class? | A "Driver class" is often just the class that contains a main. In a real project, you may often have numerous "Driver classes" for testing and whatnot, or you can build a main into any of your objects and select the runnable class through your IDE, or by simply specifying "java classname." | Without context, it's hard to tell. Is it talking about a JDBC driver, perhaps? If so, the driver class is responsible for implementing the [java.sql.Driver](http://java.sun.com/javase/6/docs/api/java/sql/Driver.html) interface for a particular database, so that clients can write code in a db-agnostic way. The JDBC infrastructure works out which driver to use based on the connection string.
If the book wasn't talking about JDBC though, we'll need more context. | What is a "driver class"? | [
"",
"java",
"oop",
""
] |
Basically I want a function to be called every say, 10 milliseconds.
How can I achieve that in Java? | You might want to take a look at [Timer](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Timer.html#scheduleAtFixedRate(java.util.TimerTask,%20long,%20long)). | Check out java.util.Timer
<http://java.sun.com/javase/6/docs/api/java/util/Timer.html> | Java equivalent of setInterval in javascript | [
"",
"java",
"timing",
""
] |
In Java, nested classes can be either `static` or not. If they are `static`, they do not contain a reference to the pointer of the containing instance (they are also not called inner classes anymore, they are called nested classes).
Forgetting to make an nested class `static` when it does not need that reference can lead to problems with garbage collection or escape analysis.
Is it possible to make an anonymous inner class `static` as well? Or does the compiler figure this out automatically (which it could, because there cannot be any subclasses)?
For example, if I make an anonymous comparator, I almost never need the reference to the outside:
```
Collections.sort(list, new Comparator<String>(){
int compare(String a, String b){
return a.toUpperCase().compareTo(b.toUpperCase());
}
}
``` | No, you can't, and no, the compiler can't figure it out. This is why FindBugs always suggests changing anonymous inner classes to named `static` nested classes if they don't use their implicit `this` reference.
**Edit:** Tom Hawtin - tackline says that if the anonymous class is created in a static context (e.g. in the `main` method), the anonymous class is in fact `static`. But the JLS [disagrees](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.5):
> An anonymous class is never `abstract` (§8.1.1.1). An anonymous class is always an inner class (§8.1.3); it is never `static` (§8.1.1, §8.5.1). An anonymous class is always implicitly `final` (§8.1.1.2).
Roedy Green's Java Glossary [says that](http://mindprod.com/jgloss/anonymousclasses.html) the fact that anonymous classes are allowed in a static context is implementation-dependent:
> If you want to baffle those maintaining your code, wags have discovered `javac.exe` will permit anonymous classes inside `static` init code and `static` methods, even though the language spec says than anonymous classes are never `static`. These anonymous classes, of course, have no access to the instance fields of the object. I don’t recommend doing this. The *feature* could be pulled at any time.
**Edit 2:** The JLS actually covers static contexts more explicitly in [§15.9.2](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.2):
> Let *C* be the class being instantiated, and let *i* be the instance being created. If *C* is an inner class then *i* may have an immediately enclosing instance. The immediately enclosing instance of *i* (§8.1.3) is determined as follows.
>
> * If *C* is an anonymous class, then:
> + If the class instance creation expression occurs in a static context (§8.1.3), then *i* has no immediately enclosing instance.
> + Otherwise, the immediately enclosing instance of *i* is `this`.
So an anonymous class in a static context is roughly equivalent to a `static` nested class in that it does not keep a reference to the enclosing class, even though it's technically not a `static` class. | I think there's a bit of confusion in the nomenclature here, which admittedly is too silly and confusing.
Whatever you call them, these patterns (and a few variations with different visibility) are **all possible, normal, legal Java:**
```
public class MyClass {
class MyClassInside {
}
}
public class MyClass {
public static class MyClassInside {
}
}
public class MyClass {
public void method() {
JComponent jc = new JComponent() {
...
}
}
}
public class MyClass {
public static void myStaticMethod() {
JComponent jc = new JComponent() {
...
}
}
}
```
They are catered for in the language spec (if you're really bothered, see section 15.9.5.1 for the one inside the static method).
But this quote is **just plain wrong**:
> javac.exe will permit anonymous
> classes inside static init code and
> static methods, even though the
> language spec says than anonymous
> classes are never static
I think the quoted author is confusing the static *keyword* with static *context*. (Admittedly, the JLS is also a bit confusing in this respect.)
Honestly, all of the patterns above are fine (whatever you call them "nested", "inner", "anonymous" whatever...). Really, nobody is going to suddenly remove this functionality in the next release of Java. Honestly! | Is it possible to make anonymous inner classes in Java static? | [
"",
"java",
"syntax",
"inner-classes",
""
] |
I have the following table of counters:
```
CREATE TABLE cache (
key text PRIMARY KEY,
generation int
);
```
I would like to increment one of the counters, or set it to zero if the corresponding row doesn't exist yet. Is there a way to do this without concurrency issues in standard SQL? The operation is sometimes part of a transaction, sometimes separate.
The SQL must run unmodified on SQLite, PostgreSQL and MySQL, if possible.
A search yielded several ideas which either suffer from concurrency issues, or are specific to a database:
* Try to `INSERT` a new row, and `UPDATE` if there was an error. Unfortunately, the error on `INSERT` aborts the current transaction.
* `UPDATE` the row, and if no rows were modified, `INSERT` a new row.
* MySQL has an `ON DUPLICATE KEY UPDATE` clause.
EDIT: Thanks for all the great replies. It looks like Paul is right, and there's not a single, portable way of doing this. That's quite surprising to me, as it sounds like a very basic operation. | MySQL (and subsequently SQLite) also support the REPLACE INTO syntax:
```
REPLACE INTO my_table (pk_id, col1) VALUES (5, '123');
```
This automatically identifies the primary key and finds a matching row to update, inserting a new one if none is found.
Documentation: <https://dev.mysql.com/doc/refman/8.0/en/replace.html> | SQLite supports [replacing a row](http://www.sqlite.org/lang_insert.html) if it already exists:
```
INSERT OR REPLACE INTO [...blah...]
```
You can shorten this to
```
REPLACE INTO [...blah...]
```
This shortcut was added to be compatible with the MySQL `REPLACE INTO` expression. | How do I UPDATE a row in a table or INSERT it if it doesn't exist? | [
"",
"mysql",
"sql",
"sqlite",
"postgresql",
"upsert",
""
] |
After someone creates a DLL in C# using the Microsoft Visual development environment, how would another programmer take that code, make a new project that includes the DLL's source and make a GUI that uses the DLL'S API?
I have already done the following four steps:
1) In the Solution Explorer right-click "References" and select "Add Reference ...".
2) Select the "Browse" tab.
3) Navigate to the DLL and select it.
4) Add the appropriate "using" directive to the top of the code.
What is next? After I declare a new object, how do I see what methods to use? | View Menu -> Object Browser
You should be able to look at the objects/methods and so on contained in the DLL and publicly exposed. | You should be able to use intellisense and the object explorer as always. Without the source that will be your best bet. | Exposing the methods of a DLL in C# | [
"",
"c#",
"dll",
"using-directives",
""
] |
I'm using libgc, a garbage collector for C and C++.
To make STL containers garbage collectible one must use the gc\_allocator.
Instead of writing
```
std::vector<MyType>
```
one has to write
```
std::vector<MyType,gc_allocator<MyType> >
```
Could there be a way to define something like
```
template<class T> typedef std::vector<T,gc_allocator<T> > gc_vector<T>;
```
I checked some time ago and found out it was not possible. But I may have been wrong or there might be another way around.
Defining maps in this way is particularly unpleasing.
```
std::map<Key,Val>
```
becomes
```
std::map<Key,Val, std::less<Key>, gc_allocator< std::pair<const Key, Val> > >
```
EDIT: After trying the use of macro I found out the following code breaks it:
```
#define gc_vector(T) std::vector<T, gc_allocator<T> >
typedef gc_vector( std::pair< int, float > ) MyVector;
```
The comma inside the templated type definition is interpreted as a macro argument separator.
So it seems the inner class/struct is the best solution.
Here is an example on how it will be done in C++0X
```
// standard vector using my allocator
template<class T>
using gc_vector = std::vector<T, gc_allocator<T> >;
// allocates elements using My_alloc
gc_vector <double> fib = { 1, 2, 3, 5, 8, 13 };
// verbose and fib are of the same type
vector<int, gc_vector <int>> verbose = fib;
``` | You can use C++11 templated type aliasing using `using` e.g. like this
```
template <typename T>
using gc_vector = std::vector<T, gc_allocator<T>>;
```
Note: I know this is an old question but since it has quite many upvotes and as it turns up in search results I thought it deserved an updated answer. | You cannot use a "templated typedef", but you can use a convenience class/struct with an inner type:
```
template<typename T>
struct TypeHelper{
typedef std::vector<T,gc_allocator<T> > Vector;
};
```
and then use in your code
```
TypeHelper<MyType>::Vector v;
TypeHelper<MyType>::Vector::iterator it;
```
And something similar for the map:
```
template<typename K,typename V>
struct MapHelper{
typedef std::map<K, V, gc_allocator<K,V> > Map;
};
```
EDIT - @Vijay: I don't know if there's another possible workaround, that's how I would do it; a macro might give you a more compact notation, but personally I wouldn't like it:
```
#define GCVECTOR(T) std::vector<T,gc_allocator<T> >
```
EDIT - @chmike: Please note that the `TypeHelper` solution **does not** require you to redefine constructors! | templated typedef? | [
"",
"c++",
"templates",
"c++11",
"typedef",
""
] |
Recently I've faced such problem.
I'm working on the application, in which logging is very important.
By logs in that application I mean the messages, like
* User A(id=x) has created invoice(invoice # is XXX) (1)
* User B(id=y) has purchased the book (2)
* User A(id=x) has approved invoice XXX (3)
(1) and (3) are messages of one particular request/command - so when I want to see the logs, I need to get all the information about this request log thread.
Because of the application is highly loaded and uses AJAX a lot, log message of different users/operations/requests can be mixed.
Temporary, I've fixed this problem like this:
I've created at the beginning of the request some unique [UUID](http://en.wikipedia.org/wiki/UUID) code, and prepend any log messages with this unique code. So, I can find all the messages of particular thread by simple grep UNIX command.
That solves the problem, but I'm not sure it is the best solution for the task. Looks more like reinventing the wheel.
What solutions would you reccomend for this problem? | Off the top of my head, a couple of suggestions (if you haven't already implemented them)
1. Log each different type of event into a separate log file, e.g. BookPurchases.log, InvoiceApprovals.log. That said keep a raw output log of everything in case it's the sequence of events that matters as opposed to the classification.
2. Use a logging package if you don't already have one, examples are [The Log Package](http://www.indelible.org/php/Log/guide.html), or [Zend\_Log](http://framework.zend.com/manual/en/zend.log.html) where you can have different logging priorities.
I don't know if that's of any use to you, as what you have said seems pretty solid. | If you need to view all logs for a particular user session, use
```
session_start()
```
at the top of your script(s) and then prepend
```
session_id()
```
to the front of each log message. | Log threads in PHP | [
"",
"php",
"logging",
""
] |
Is there anything smart and helpful, that makes you able to search through the Microsoft .Net documentations (in Visual Studio 2008))? Before you mention Google: before you can search through that stuff with Google you have to know what you're searching for.
Let's say you don't know exactly what to look for and you insert ".Net C# String operations"... well... ;).
What I'm looking for is some small beginner-friendly stuff, just essentials. Not the huge thing for the professionals, because I think MS targets these people. And just those.
Thanks,
fnush | I find it helpful to launch the offline MSDN library separately rather than have it appear within Visual Studio. This makes it easier to browse at a decent size without interfering with your actual coding window - and often I'll look up documentation without having Visual Studio open at all.
I usually use the Index pane on the left - then if I need to know about what's in a particular namespace or type, I can just start typing the name. Of course, that only works if you know which namespace to look for: so I would thoroughly recommend taking half an hour to just browse the most important namespaces to get a feeling for them. In particular, have an idea of what's in:
* System
* System.IO
* System.Collections
* System.Collections.Generic
* System.Linq
* System.Diagnostics
* System.Net
* System.Xml
* System.ComponentModel
* System.Data
* For web UI:
+ System.Web.UI
+ System.Web.UI.WebControls
* For Windows Forms:
+ System.Windows.Forms
+ System.Drawing
* For WPF:
+ System.Windows
+ System.Media
You don't need to really learn anything there by rote - just try to get the gist of what's where, so you know where to look later.
I also find that when searching the web, including `site:msdn.microsoft.com` helps a lot. Of course there's plenty of great *non*-MSDN content too, but it's nice to be able to filter it sometimes. | It's far simpler to search for API calls once you have some idea of the operation you'd like to perform. The more general your query, the more general and varied the answers that you'll get back.
In your case you're looking for an introduction to C#, so try searching that in Google:
<http://www.google.com/search?q=Intro+to+C%23>
That should bring you some documentation from the Interwebs which will provide you a decent intro to C#. | Lost in .Net SDK with C# due finding the documentation | [
"",
"c#",
".net",
""
] |
in my list:
```
animals = [ ['dog', ['bite'] ],
['cat', ['bite', 'scratch'] ],
['bird', ['peck', 'bite'] ], ]
add('bird', 'peck')
add('bird', 'screech')
add('turtle', 'hide')
```
The add function should check that the animal and action haven't been added before adding them to the list. Is there a way to accomplish this without nesting a loop for each step into the list? | While it is possible to construct a generic function that finds the animal in the list using a.index or testing with "dog" in animals, you really want a dictionary here, otherwise the add function will scale abysmally as more animals are added:
```
animals = {'dog':set(['bite']),
'cat':set(['bite', 'scratch'])}
```
You can then "one-shot" the add function using setdefault:
```
animals.setdefault('dog', set()).add('bite')
```
It will create the 'dog' key if it doesn't exist, and since setdefault returns the set that either exists or was just created, you can then add the bite action. Sets ensure that there are no duplicates automatically. | You're using the wrong data type. Use a `dict` of `set`s instead:
```
def add(key, value, userdict):
userdict.setdefault(key, set())
userdict[key].add(value)
```
Usage:
```
animaldict = {}
add('bird', 'peck', animaldict)
add('bird', 'screech', animaldict)
add('turtle', 'hide', animaldict)
``` | Check if value exists in nested lists | [
"",
"python",
""
] |
Are there any good programs out there to compare to compile .NET assemblies?
For example I have HelloWorld.dll (1.0.0.0) and HelloWorld.dll (2.0.0.0), and I want to compare differences how can I do this?
I know I can use .NET Reflector and use the Assembly Diff plugin. Are there any other good tools out there to do this? | [Ways to Compare .NET Assemblies](http://immitev.blogspot.com/2008/10/ways-to-compare-net-assemblies.html) suggests
Commercial:
* [NDepend](http://www.ndepend.com/)
Free:
* [JustAssembly](http://www.telerik.com/justassembly) (only shows differences in API)
* [BitDiffer](https://github.com/grennis/bitdiffer) (same)
* [Reflector Diff Add-in](http://www.codingsanity.com/diff.htm) (which you've already discovered, but not available anymore)
---
Existing compare tools like Beyond Compare (commercial) can do this by special configuration. Here's how to do this for Beyond Compare:
* Go to `Tools` → `Options`
* Click `New..`, select "Text format", click `OK`
* Give it a name (say, EXE, or DLL), and specify the mask as `*.exe` or `*.dll`
* Click on tab `Conversion` and select "External program (Unicode filenames)"
* Under "Loading", specify the path to `ildasm` and add `%s /OUT:%t /NOBAR` (i.e.: `C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools\ildasm.exe %s /OUT:%t /NOBAR`)
* Make sure to check `disable editing`.
* Click `Save`, then `Close`
* Restart BC and open two `exe` files to compare, it should decompile into `ilasm` automatically now.
You can also add syntax highlighting to this new format. I plan to send the syntax file to them so that it'll [become available to share](https://www.scootersoftware.com/download.php?zz=kb_moreformatsv3). | Two ways.
You could ILDASM and diff with classic tools.
Or you could use NDepends, which will cost for that feature.
[Piece to C# bloaters..] | Compare compiled .NET assemblies? | [
"",
"c#",
".net",
"vb.net",
"debugging",
"reverse-engineering",
""
] |
Hypothetical situation. I want to populate/load a `sales/order` collection with every order where the grand\_total is equal to the `total_paid`. I know I can use `addFieldToFilter` to filter by a specific value, but is it possible to use this method to filter by other database values. If not, is there any data access object in the Magento system that allows this.
```
$orders = Mage::getModel('sales/order');
$orders = $orders->getCollection();
$orders->addFieldToFilter('total_paid',Array('eq'=>30)); //would find all the orders that were 30
//syntax to find all the orders whose total_paid value is equal to it's grand_total attribute
//????????
```
The `non-eav` SQL concept I’m grasping for is:
```
SELECT * FROM Orders o WHERE o.total_paid = o.grand_total
```
Is this possible to do purely with object method calls, or do I need to do post-load filtering?
How do other `ORM` systems handle this? | I was waiting for a definite answer to this, but seeing as nothing's come up I might as well share what I've found out.
I traced addFieldToFilter and apparently every value you use ends up quoted so you can't really "hack" this by using the name of a column.
In fact I don't see any way to do this, at least not within this class.
Realistically I think you'll need to go with post-load filtering, at least for now. This of course is the very definition of inefficient code, but then again if computational efficiency was a priority, you wouldn't be using Magento in the first place... | Just had to address this in one of my projects and came across this question while searching for a better resolution. My hack looks like this:
```
$orders = Mage::getModel('sales/order')->getCollection();
$orders->getSelect()
->where('total_paid=grand_total');
```
It annoys me that such a basic functionality of databases is overlooked by Magento's ORM. | Using Magento's addFieldToFilter to filter by existing columns | [
"",
"php",
"orm",
"magento",
"entity-attribute-value",
""
] |
I have a page which needs to download an image file on onload event but, for all page calls! Now, it downloads the image in first call but in second call it gets from temporary and that is not the thing I want. I need to make some calculations for each load. So I want to delete the file that I download on each load from temporary or something else that forces client to download it from server again.
A javascript solution will be great. Thanks. | No, you can't do anything at all to the cache using Javascript, but you can change the url of the image so that it's not in the cache.
Just add a query string to the url of the image, and use the current time to make it unique each time:
```
<script type="text/javascript">
document.write('<img src="images/theImage.gif?t=' + new Date().getTime() + '" alt="" />');
</script>
``` | I understand you are looking for a javascript solution, but the good way to solve this is to use HTTP response headers which specify no-cache and expiry values. If you have no control over the web server configuration with .htaccess, you can create a simple PHP script that sets these headers before serving the content. In PHP:
```
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
``` | Can I delete file from temporary internet files in javascript? | [
"",
"javascript",
"file-io",
""
] |
Is it possible to import modules based on location?
(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)
I'd like to import a module that's local to the current script. | You can extend the path at runtime like this:
```
sys.path.extend(map(os.path.abspath, ['other1/', 'other2/', 'yourlib/']))
``` | You can edit your [PYTHONPATH](http://docs.python.org/tutorial/modules.html#the-module-search-path) to add or remove locations that python will search whenever you attempt an import. | Importing In Python | [
"",
"python",
"import",
""
] |
In `pom.xml` you can:
```
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
```
How does Maven know where I have 1.5 version? | As far as I know, this will *not* make Maven compile against the Java 1.5 libraries. This will only tell the compiler to accept 1.5-level source code and produce 1.5-level class files.
Your code could still possibly refer to Java 6 classes, as long as your Maven task is run with a Java 6 JVM.
IF you execute:
```
mvn -v
```
The output will show you what version of Java is being used. For example:
```
Apache Maven 2.1.0 (r755702; 2009-03-18 19:10:27+0000)
Java version: 1.6.0_13
Java home: C:\Program Files\Java\jdk1.6.0_13\jre
Default locale: en_IE, platform encoding: Cp1252
OS name: "windows vista" version: "6.0" arch: "x86" Family: "windows"
``` | I take it that we are talking about Maven here. I would guess via the JAVA\_HOME environmental variable. If Windows do a echo %JAVA\_HOME% or Linux do a echo $JAVA\_HOME and see.
Oops: Sorry I see it is Maven. | How does Maven know where to find Java 1.5 | [
"",
"java",
"maven-2",
""
] |
I have a dataset being returned by a stored proc and one of the items in it can potentially be null. I'm trying to convert each row in the dataset to a strongly typed object but I can't seem to cast the null value properly.
I've created a mock up of my scenario as follows:
```
DataSet ds = new DataSet();
ds.Tables.Add(new DataTable());
ds.Tables[0].Columns.Add("Name", typeof(string));
ds.Tables[0].Columns.Add("Amount", typeof(decimal));
ds.Tables[0].Rows.Add("My Name Here", null); //create row with a null item
DataRow dataRow = ds.Tables[0].Rows[0];
Person p = new Person
{
Name = (string)dataRow["Name"],
Amount = (decimal)dataRow["Amount"]
}
```
Unfortunately I'm getting the following exception: `System.InvalidCastException: Specified cast is not valid.`
If I try to use a nullable type (decimal?) I get this error: `System.NotSupportedException: DataSet does not support System.Nullable<>.`
In the debugger I've done the following tests on the value in dataRow["Amount"]:
```
dataRow["Amount"] is decimal (false)
dataRow["Amount"] is decimal? (false)
dataRow["Amount"] == null (false)
dataRow["Amount"] is object (true)
```
All I can establish is that it's some sort of object...which isn't particularly helpful.
Can any of you spot what I'm doing wrong? | You can use `dataRow.IsNull("Amount")` or `Convert.IsDBNull(dataRow["Amount"])` or `(dataRow["Amount"] as Decimal) != null`. | You can also do a check for Null being returned by the database as:
```
if (dataRow["Amount"] is System.DBNull.Value)
```
That should enable you to check the value before you attempt to cast it to avoid that error message. | How do I correctly cast an item in a DataSet when it can potentially be null? | [
"",
"c#",
"casting",
"null",
"dataset",
""
] |
There are some posts about this matter, but I didn't clearly get when to use object-oriented coding and when to use programmatic functions in an include. Somebody also mentioned to me that OOP is very heavy to run, and makes more workload. Is this right?
Let's say I have a big file with 50 functions. Why will I want to call these in a class? And not by function\_name()? Should I switch and create an object which holds all of my functions? What will be the advantage or specific difference? What benefits does it bring to code OOP in PHP? Modularity? | In a lot of scenarios, procedural programming is just fine. Using OO for the sake of using it is useless, especially if you're just going to end up with [POD](http://en.wikipedia.org/wiki/Plain_old_data_structure) objects (plain-old-data).
The power of OO comes mainly from inheritance and polymorphism. If you use classes, but never use either of those two concepts, you probably don't need to be using a class in the first place.
One of the nicest places IMO that OO shines in, is allowing you to get rid of switch-on-type code. Consider:
```
function drive($the_car){
switch($the_car){
case 'ferrari':
$all_cars->run_ferrari_code();
break;
case 'mazerati':
$all_cars->run_mazerati_code();
break;
case 'bentley':
$all_cars->run_bentley_code();
break;
}
}
```
with its OO alternative:
```
function drive($the_car){
$the_car->drive();
}
```
Polymorphism will allow the proper type of "driving" to happen, based on runtime information.
---
Notes on polymorphism:
The second example here has some premisses: That is that all car classes will either extend an [abstract](http://php.net/manual/en/language.oop5.abstract.php) class or implement an [interface](http://php.net/manual/en/language.oop5.interfaces.php).
Both allow you to force extending or implementing classes to define a specific function, such as `drive()`. This is very powerful as it allows you to `drive()` all cars without having to know which one you're driving; that is because they're extending an abstract class containing the `drive()` method or implementing an interface forcing the `drive()` method to be defined.
So as long as you make sure that all your specific cars either extend the abstract class `car` or implement an interface such as `canBeDriven` (both of which must *declare* the `drive()` method) you can just call the `drive()` method on an object which you know is a car (but not what type of car) without fear of it not being defined, as PHP will throw fatal errors at you until you define those methods in your specific car classes. | I'll try to keep my answer as an addition because the answers by Majd Taby and Coobird are really good.
I was mostly a procedural programmer for several years and didn't fight against OOP programming, but never really saw much relevance...that is until I started working on a team and building more important and complex projects.
OOP really shines, in my opinion, when you need to write lean, easily maintainable code for more complex applications. And mind you, not in every situation, but there are some where procedural just won't work that well.
Most of my examples of great OOP implementations are for projects where I had several things that were all related but all slightly different. Sites with lots of forms, lots of users, lots of products etc.
They all have similar behaviour names like print(), update(), etc...but by encapsulating them as objects and varying the methods' implementations in the classes I can make my code at runtime very simple and clean throughout the site. Also, and this one was key, despite having different behaviours, I could work with different objects **using the same method calls throughout the entire application**. It allows a second developer to work on actual implementation while I work on deeper code.
I don't know if that helps any but speaking as someone who was in your situation not too long ago, I love OOP. | Why use PHP OOP over basic functions and when? | [
"",
"php",
"oop",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.