Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
```
$query = "UPDATE members SET userrole ='$userrole' WHERE member_id = '$member_id'";
```
Sometimes it updates and sometimes it does not... i don't know whether the syntax is correct.
userrole and member\_id has array of values. The update query is performed for multiple items being checked.
**There is no error in mysql connection or error.... for the first time the update does not happen and after that it happens** | It's all about debugging. First, I would check if there is a mysql error to start you off.
```
$query = "UPDATE members SET userrole ='$userrole' WHERE member_id = '$member_id'";
echo mysql_errno($yourmysqlconnection) . ": " . mysql_error($yourmysqlconnection) . "\n"
```
Then doublecheck your $userrole and $memberid Variable. Post your findings here, and we might to help you further
Good Luck,
rAyt | This cannot work, if both variables contain arrays. You need to update the items one by one (or use a clumsy MySql CASE statement, which I won't explain here):
```
foreach ($userrole as $key => $role) {
$query = "UPDATE members SET userrole ='$role'
WHERE member_id = '$member_id[$key]'";
// perform query ...
}
```
Or if only $member\_id is an array:
```
$query = "UPDATE members SET userrole ='$userrole'
WHERE member_id IN ('" . implode(',', $member_id) . "')";
// perform query ...
```
You should further rename your variables to reflect that they are arrays. Just use the plural:
```
$userrole => $userroles
$member_id => $member_ids
```
On more thing: Are these values coming from a HTML form? If yes, [you should really](http://xkcd.com/327/) sanitize them using [`mysql_escape_string()`](http://php.net/manual/en/function.mysql-escape-string.php). This can be done for multiple values at once using [`array_map()`](http://php.net/manual/en/function.array-map.php):
```
$userroles = array_map('mysql_escape_string', $userroles);
$member_ids = array_map('mysql_escape_string', $member_ids);
``` | Update command not working properly in PHP | [
"",
"php",
"mysql",
""
] |
I'm using pyodbc to query an AS400 (unfortunately), and some column names have hashes in them! Here is a small example:
```
self.cursor.execute('select LPPLNM, LPPDR# from BSYDTAD.LADWJLFU')
for row in self.cursor:
p = Patient()
p.last = row.LPPLNM
p.pcp = row.LPPDR#
```
I get errors like this obviously:
```
AttributeError: 'pyodbc.Row' object has no attribute 'LPPDR'
```
Is there some way to escape this? Seems doubtful that a hash is even allowed in a var name. I just picked up python today, so forgive me if the answer is common knowledge.
Thanks, Pete | Use the `getattr` function
```
p.pcp = getattr(row, "LPPDR#")
```
This is, in general, the way that you deal with attributes which aren't legal Python identifiers. For example, you can say
```
setattr(p, "&)(@#$@!!~%&", "Hello World!")
print getattr(p, "&)(@#$@!!~%&") # prints "Hello World!"
```
Also, as JG suggests, you can give your columns an alias, such as by saying
```
SELECT LPPDR# AS LPPDR ...
``` | You can try to give the column an alias, i.e.:
```
self.cursor.execute('select LPPLNM, LPPDR# as LPPDR from BSYDTAD.LADWJLFU')
``` | How to escape a hash (#) char in python? | [
"",
"python",
"odbc",
"escaping",
"pyodbc",
""
] |
Okay I have three tables that all communicate with each other.
```
ForumTopic t
ForumMessage m
ForumUser u
```
What I am trying to do is get the first message of each Topic.
I have tried this
```
SELECT
m.[Message], m.[TopicID], m.[Posted], u.Name, t.[Views], t.NumPosts,
t.Topic
FROM [ForumMessage] m
INNER JOIN ( SELECT TopicID, Topic, [Views], NumPosts, ForumID
FROM [ForumTopic]
GROUP BY TopicID, Topic, [Views], NumPosts, ForumID ) t ON t.TopicID = m.TopicID
INNER JOIN [ForumUser] u
ON u.UserID = m.UserID
WHERE t.ForumID IN(1,2)
ORDER BY m.Posted DESC;
```
And the Result is listed below
```
Message TopicID Posted Name Views NumPosts Topic
6 2009-07-20 18:14:06.270 Ravenal 26 3 GENESIS 2.5.1a RELEASE
6 2009-07-20 18:08:51.027 Ryan 26 3 GENESIS 2.5.1a RELEASE
6 2009-07-20 17:06:33.550 Ravenal 26 3 GENESIS 2.5.1a RELEASE
4 2009-07-17 14:22:47.560 Ravenal 14 1 MyGameTools IRC
3 2009-07-17 01:09:22.403 Ravenal 43 1 GENESIS 2.5.0b RELEASE
2 2009-07-17 00:48:30.873 Ravenal 44 2 GENESIS 2.5.0a RELEASE
2 2009-07-16 23:08:44.830 Ravenal 44 2 GENESIS 2.5.0a RELEASE
1 2009-07-16 23:03:11.790 Ravenal 20 1 Welcome to MyGameTools
```
So I am trying to figure out how to make it so that it ends up looking like this
```
Message TopicID Posted Name Views NumPosts Topic
6 2009-07-20 18:14:06.270 Ravenal 26 3 GENESIS 2.5.1a RELEASE
4 2009-07-17 14:22:47.560 Ravenal 14 1 MyGameTools IRC
3 2009-07-17 01:09:22.403 Ravenal 43 1 GENESIS 2.5.0b RELEASE
1 2009-07-16 23:03:11.790 Ravenal 20 1 Welcome to MyGameTools
```
Any help will be much appreciated. | Have you tried using a derived table to get the max posted datetime for each topic from the ForumMessages table?
eg
```
SELECT m.[Message], m.[TopicID], m.[Posted], u.Name, t.[Views], t.NumPosts, t.Topic FROM
( SELECT TopicID, Max(Posted) MaxPosted
FROM ForumMessage
GROUP BY TopicID ) MaxMessage
INNER JOIN [ForumMessage] m
ON m.TopicID = maxMessage.TopicID
AND m.Posted = maxMessage.MaxPosted
INNER JOIN ( SELECT TopicID, Topic, [Views], NumPosts, ForumID
FROM [ForumTopic]
GROUP BY TopicID, Topic, [Views], NumPosts, ForumID ) t
ON t.TopicID = m.TopicID
INNER JOIN [ForumUser] u
ON u.UserID = m.UserID
WHERE t.ForumID IN(1,2)
ORDER BY m.Posted DESC;
``` | It is giving multiple records for a message because you are JOINing it with user table & message has multiple users (other than Topic 4,3,1).
EDIT: You will have to reduce the output of outer query by limiting to give 1 record (as per max(PostedDateTime). | Hello need help with on how to do this in SQL Server News from Forum Topics/Messages | [
"",
"c#",
"asp.net",
"sql-server",
""
] |
I am building a personal site, for a blog I wish to use [WordPress](http://wordpress.org) and for a wiki i will use
[wikia](http://wikkawiki.org/). Is it possible that i use the same database for storing articles from both frontends (WordPress and wiki). If yes can i some how populate articles from my wiki to the blog, under a specific category.
EDIT-- By two different sites I mean two different frontends, hosted at different subdomains. | The short answer is YES.
However, you will need to watch out for database object naming conflicts.
Also, when you say 'two different sites' do you mean 2 different sites? Or just different 'frontends' within the same site? If it just different front apps running in the same website, then you will also have to make sure you won't have any configuration conflicts. | At installation time, both WordPress and Wikka allow you to prefix their tables with different names to prevent naming collisions. So yes it is possible to allow both applications to share the same database.
We have plenty of customers on our shared hosting environment who do this without any issues.
In answer to your second question, you may be in for a bit of custom code to do that. | Can two different sites running on same host, share same database for storage and retrieval? | [
"",
"sql",
"database",
"wordpress",
"wiki",
""
] |
I am working on a project in which, to resolve a versioning issue, I am creating many classes which will never be tested and must not ever be used - they just need to be there to keep the compiler happy. I'd like to make sure they are never used. This morning I had the idea of throwing an exception in a static initialization block:
```
public class Dummy {
static {
throw new IllegalStateException("Do not use this class!");
}
}
```
But the compiler doesn't like it. Can you think of any way to do this?
**EDIT:** to be clear (my fault I wasn't clear before), these won't just be empty classes. There will be all sorts of code in here, and by "keep the compiler happy" I did indeed mean that elsewhere I will be instantiating them, calling methods etc etc. I want this code elsewhere to compile but fail at runtime. I have accepted Jon's answer but will also be using `@Deprecated` and documenting extensively as appropriate. | Just add a dummy condition:
```
public class Dummy {
static {
if (true) {
throw new IllegalStateException("Do not use this class!");
}
}
}
```
I'm not really sure I *like* this, but it may do what you want it to. Are you sure there's no alternatively which would let you get away without having a completely useless class like this? | [@Deprecated](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Deprecated.html)
> A program element annotated @Deprecated is one that programmers are discouraged from using, typically because it is dangerous, or because a better alternative exists. Compilers warn when a deprecated program element is used or overridden in non-deprecated code. | In Java, how do I ensure a dummy class is never used? | [
"",
"java",
""
] |
How do I restrict the image's dimension that is being uploaded via a php script?
I am using cakephp v 1.2 | Unfortunately you only can check the dimensions after upload with
```
list($imagewidth, $width) = getimagesize("$myupload");
``` | You'll have to wait until the file is uploaded then call [`getimagesize()`](http://php.net/getimagesize) to check the dimensions and print an error if it's too big.
You can't check the size before the upload is complete. | restrict the dimensions of image file to be uploaded | [
"",
"php",
"file-upload",
""
] |
I am using the php mysqli extension with prepared statements, but on one query it is not creating the query object.
Here is the code:
```
$sqlq = "SELECT id,name FROM productcategories JOIN products ON productcategories.productid = products.id WHERE categoryid=?";
if($allsubcats)
{
foreach($allsubcats as $key => $data)
{
$sqlq .= " OR categoryid=?";
}
}
echo $sqlq;
if($query = $this->mysqli->connection->prepare($sqlq))
{
$query->bind_param("i", $cat);
if($allsubcats)
{
foreach($allsubcats as $key => $data)
{
$query->bind_param("i", $data[0]);
}
}
$query->execute();
$query->bind_result($id,$name);
$query->store_result();
if($query->num_rows > 0)
{
while($row = $query->fetch())
{
$allprods["id"] = $id;
$allprods["name"] = $name;
}
}
$query->close();
}
```
The problem:
The line `if($query = $this->mysqli->connection->prepare($sqlq))`
The `if()` is returning false, and therefore not creating the `$query` object, and not executing any of the code inside the if.
The `echo $sqlq;` returns:
> "SELECT id,name FROM productcategories JOIN products ON productcategories.productid = products.id WHERE categoryid=? OR categoryid=? OR categoryid=? OR categoryid=? OR categoryid=? OR categoryid=?"
Which I don't see anything wrong with.
Any help would be greatly appreciated,
Thanks, Nico | Typical, I worked it out myself as soon as I posted this, does anyone else see things better as soon as they ask for help??
Anyway,
SELECT id,name FROM productcategories JOIN products ON productcategories.productid = products.id WHERE categoryid=? OR categoryid=? OR categoryid=? OR categoryid=? OR categoryid=? OR categoryid=?
Should have been
SELECT productcategories.id,products.name,products.id FROM productcategories JOIN products ON productcategories.productid = products.id WHERE categoryid=? OR categoryid=? OR categoryid=? OR categoryid=? OR categoryid=? OR categoryid=? | Hey Nico. This isn't an answer to your question, as you already answered it. Just an unsolicited suggestion. I'm not sure how often that query will be run, or how many categories could be appended to it, but you may want to consider using the WHERE IN syntax.
Instead of:
```
WHERE foo = ? OR foo = ? OR foo = ? OR foo = ?
```
Use:
```
WHERE foo IN (?,?,?,?)
```
You'll make the queries more readable, and save a miniscule amount of time in your application. (sending less data to MySQL, smaller strings in PHP) | PHP Mysqli prepared not creating statement object | [
"",
"php",
"mysqli",
"prepared-statement",
""
] |
When I try to generate a CRUD test for a new project I am getting a PHP Warning and a Fatal Error.
The errors relate to files that it cannot find, however, I have checked and the files are definitely there.
The error text is 'require\_once(lib/model/map/QuestionMapBuilder.php): failed to open stream: No such file or directory in c:\webroot\askeet\lib\model\om\BaseQuestionPeer.php on line 547'
What details of my project should I check?
 | I finally tracked down the issue. In my PHP.ini files, they were setup wit the default UNIX file path settings.
Weirdly nothing had ever been broken by this incorrect configuration. Plus, everything in Symfony had worked up until now.
I have switched to Windows style file\_path and all is well again.
Thanks for all the answers! | I think it's a problem with your include path.
Check it, the require\_once() call is looking for `lib/model/map/QuestionMapBuilder.php`
But your include\_path is `C:\webroot\askeet\lib`
Which, when resolved together into a full path, would look like this
```
C:\webroot\askeet\lib\lib\model\map\QuestionMapBuilder.php
```
So, I *think* your solution is to add `C:\webroot\askeet` to your include path. | Error with propel-generate-crud in Symfony 1.0 | [
"",
"php",
"command-line",
"symfony1",
"crud",
""
] |
I am debugging a php application.
In the Local Debugging window, it shows the following information
* Name value Type
* LinkID 15 **mysql link**
The value of LinkID change within the program
**What is mysql link type , being shown in the debugging window?**
Also, can anyone explain what the function performs ?
Here is the php code using LinkID:
```
function connect($new_link = false)
{
if (!$this->LinkID) {
$server = ($this->DBPort != "") ? $this->DBHost . ":" . $this->DBPort : $this->DBHost;
if ($this->DBPersistent) {
$this->LinkID = @mysql_pconnect($server, $this->DBUser, $this->DBPassword);
} else {
$this->LinkID = @mysql_connect($server, $this->DBUser, $this->DBPassword, $new_link);
}
if (!$this->LinkID) {
$this->halt("Connect failed: " . $this->describe_error(mysql_errno(), mysql_error()));
return 0;
}
if (!mysql_select_db($this->DBDatabase, $this->LinkID)) {
$this->LinkID = 0;
$this->halt($this->describe_error(mysql_errno(), mysql_error()));
return 0;
}
}
return $this->LinkID;
}
``` | A MySQL link is the type of [**resource**](http://php.net/manual/en/language.types.resource.php) returned by [`mysql_connect()`](http://php.net/mysql_connect).
There's not much you can do with it except pass it around to other MySQL functions - it's just a "pointer" (more like an index) to an internal connection.
The 15 doesn't mean anything to *you* - it's used internally in PHP, which uses it to keep track of the *real* mysql connection object (which has no reason to be passed to your PHP script). | Your function creates different connections types to a database depending on your settings. | What is Mysql Link? | [
"",
"php",
"mysql",
"debugging",
""
] |
We have here a pretty big application that is taking a lot of time to compile and I am looking for a way to reduce this compile time. I thought a good way to do this would be to reduce the dependency between the include files. Do you know any good dependency/Includes manager that would be pretty cheap? Something that would draw me a good graphic and show me where are the "dependencies bottleneck".
Thank you. | You could use Source Navigator to analyze the source. Look at the section:
Using the Include Browser in [here](http://sourcenav.sourceforge.net/online-docs/userguide/tutorial.html). Or a better option would be to use [cinclude2dot](http://www.flourish.org/cinclude2dot/) | You can try include graphs in doxygen. | C++ Dependencies manager | [
"",
"c++",
"optimization",
"compiler-construction",
"dependencies",
""
] |
In the same way that you can generate specific content based on browser type is there a way to generate specific content based on the server running PHP without reference to the server or site name?
For example, a way for PHP to automatically detect the environment it was in and configure things like DB connections, ini\_set for errors etc. depending if it was a development, ITS, UAT or production environment.
The 2 ways I thought of were to recognise an HTTP header indicating development and QA environments or to have custom properties in php.ini.
I have woken up slightly and found out the php function to read the http headers but php overrides anything I set in the web server and I do not know if they can be set in php.ini at all.
I have no idea if it is possible to add custom values to php.ini but I had a test and ini\_get would not find it (I had restarted the web server after changing php.ini of course). | Using FastCGI on IIS you can set Environment variables. They do not seem to be available to $\_ENV but can be retrieved with getenv("varname").
To configure FastCGI environment variables in IIS 5 or 6 you need to edit:
C:\%systemdrive%\system32\inetsrv\fcgiext.ini
For example:
```
[Types]
php=d:\Dev\PHP\php-cgi.exe
php:1=PHP Site 1
*=Wildcard Mapping
[d:\Dev\PHP\php-cgi.exe]
QueueLength=999
MaxInstances=20
InstanceMaxRequests=500
[PHP Site 1]
ExePath=d:\Dev\PHP\php-cgi.exe
EnvironmentVars=PHPRC:d:\Dev\PHP\,SiteType:Developer
```
In this instance it is IIS 5 so there is only one site and the site ID is 1 as indicated in line 2 of [Types].
On IIS 6 you may have multiple sites and the following link tells you how to find the Site ID: <http://weblogs.asp.net/owscott/archive/2005/07/29/how-to-find-the-siteid-in-iis5-and-iis6.aspx>.
IIS 7 can be configured via the UI apparently once the Administration Pack for IIS 7 has been installed. | you can specify an environment variable in apache (conf, vhost, .htaccess or as an httpd daem) and then acces it via the ˆ$\_ENVˆsuperglobal | Can I configure environment specific content? | [
"",
"php",
"iis",
"fastcgi",
"isapi",
""
] |
Dropping my lurker status to finally ask a question...
I need to know how I can improve on the performance of a PHP script that draws its data from XML files.
Some background:
* I've already mapped the bottleneck to CPU - but want to optimize the script's performance before taking a hit on processor costs. Specifically, the most CPU-consuming part of the script is the XML loading.
* The reason I'm using XML to store object data because the data needs to be accessible via a browser Flash interface, and we want to provide fast user access in that area. The project is still in early stages though, so if best practice would be to abandon XML altogether, that would be a good answer too.
* Lots of data: Currently plotting for roughly 100k objects, albeit usually small ones - and they must ALL be taken up into the script, with perhaps a few rare exceptions. The data set will only grow with time.
* Frequent runs: Ideally, we'd run the script ~50k times an hour; realistically, we'd settle for ~1k/h runs. This coupled with data size makes performance optimization completely imperative.
* Already taken an optimization step of making several runs on the same data rather than loading it for each run, but it's still taking too long. The runs should generally use "fresh" data with the modifications done by users. | Just to clarify: is the data you're loading coming from XML files for processing in its current state and is it being modified before being sent to the Flash application?
It looks like you'd be better off using a database to store your data and pushing out XML as needed rather than reading it in XML first; if building the XML files gets slow you could cache files as they're generated in order to avoid redundant generation of the same file. | If the XML stays relatively static, you could cache it as a PHP array, something like this:
```
<xml><foo>bar</foo></xml>
```
is cached in a file as
```
<?php return array('foo' => 'bar');
```
It should be faster for PHP to just include the arrayified version of the XML. | How to improve on PHP's XML loading time? | [
"",
"php",
"xml",
"performance",
""
] |
I'm trying to figure out how to upload one file using GWTs FileUpload widget. I'm using GWT and Google AppEngine with Java but I would like to upload file to my own Linux server.
I have the following code already but now I can't figure out how to submit my file to the Google AppServer server and save it to another server:
```
public class FileUploader{
private ControlPanel cp;
private FormPanel form = new FormPanel();
private FileUpload fu = new FileUpload();
public FileUploader(ControlPanel cp) {
this.cp = cp;
this.cp.setPrimaryArea(getFileUploaderWidget());
}
@SuppressWarnings("deprecation")
public Widget getFileUploaderWidget() {
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
// form.setAction(/* WHAT SHOULD I PUT HERE */);
VerticalPanel holder = new VerticalPanel();
fu.setName("upload");
holder.add(fu);
holder.add(new Button("Submit", new ClickHandler() {
public void onClick(ClickEvent event) {
GWT.log("You selected: " + fu.getFilename(), null);
form.submit();
}
}));
form.addSubmitHandler(new FormPanel.SubmitHandler() {
public void onSubmit(SubmitEvent event) {
if (!"".equalsIgnoreCase(fu.getFilename())) {
GWT.log("UPLOADING FILE????", null);
// NOW WHAT????
}
else{
event.cancel(); // cancel the event
}
}
});
form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
public void onSubmitComplete(SubmitCompleteEvent event) {
Window.alert(event.getResults());
}
});
form.add(holder);
return form;
}
}
```
Now, what do I need to do next? What do i need to put in web.xml and how do I write my servlet so i can store file and return url of that object (if possible) | Here's the code from my app:
1) I created a class to accept http request:
```
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUpload extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletFileUpload upload = new ServletFileUpload();
try{
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
// Process the input stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
int maxFileSize = 10*(1024*1024); //10 megs max
if (out.size() > maxFileSize) {
throw new RuntimeException("File is > than " + maxFileSize);
}
}
}
catch(Exception e){
throw new RuntimeException(e);
}
}
}
```
2) Then in my web.xml I've added these lines:
```
<servlet>
<servlet-name>fileUploaderServlet</servlet-name>
<servlet-class>com.testapp.server.FileUpload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileUploaderServlet</servlet-name>
<url-pattern>/testapp/fileupload</url-pattern>
</servlet-mapping>
```
3) And for form.action did this:
```
form.setAction(GWT.getModuleBaseURL()+"fileupload");
``` | I would suggest using [GWTUpload](http://code.google.com/p/gwtupload/) because it's dead simple to use and extend. You can add it to your project in less than 10 minutes and it supports GAE right out of the box (using GWTUpload-GAE). See the [examples](http://gwtupload.alcala.org/gupld/index.html) for some common usage scenarios. | Basic File upload in GWT | [
"",
"java",
"google-app-engine",
"gwt",
"file-upload",
""
] |
How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case.
Correct ouptut but strangely indented:
```
if True:
print "long test long test long test long test long \
test long test long test long test long test long test"
>>> long test long test long test long test long test long test long test long test long test long test
```
Bad output, but looks better in code:
```
if True:
print "long test long test long test long test long \
test long test long test long test long test long test"
>>> long test long test long test long test long test long test long test long test long test long test
```
---
Wow, lots of fast answers. Thanks! | ```
if True:
print "long test long test long test long test long"\
"test long test long test long test long test long test"
``` | Adjacent strings are concatenated at compile time:
```
if True:
print ("this is the first line of a very long string"
" this is the second line")
```
Output:
```
this is the first line of a very long string this is the second line
``` | Lengthy single line strings in Python without going over maximum line length | [
"",
"python",
"string",
""
] |
What do people think of the best guidelines to use in an interface? What should and shouldn't go into an interface?
I've heard people say that, as a general rule, an interface must only define behavior and not state. Does this mean that an interface *shouldn't contain getters and setters?*
My opinion: Maybe not so for setters, but sometimes I think that getters are valid to be placed in an interface. This is merely to enforce the implementation classes to implement those getters and so to indicate that the clients are able to call those getters to check on something, for example. | I think that there are two types of interfaces declared in general:
1. a **service description**. This might be something like `CalculationService`. I don't think that methods `getX` should be in this sort of interface, and *certainly* not `setX`. They quite clearly imply implementation detail, which is not the job of this type of interface.
2. a **data model** - exists solely to abstract out the implementation of data objects in the system. These might be used to aid in testing or just because some people as old as me remember the days when (for example) using a persistence framework tied you down to having a particular superclasss (i.e. you would choose to implement an interface in case you switched your persistence layer). I think that having JavaBean methods in this type of interface is entirely reasonable.
*Note: the collections classes probably fit in to type #2* | I don't see why an interface can't define getters and setters. For instance, `List.size()` is effectively a getter. The interface must define the behaviour rather than the *implementation* though - it can't say how you'll *handle* the state, but it can insist that you can get it and set it.
Collection interfaces are all about state, for example - but different collections can store that state in radically different ways.
EDIT: The comments suggest that getters and setters imply a simple field is used for backing storage. I vehemently disagree with this implication. To my mind there's an implication that it's "reasonably cheap" to get/set the value, but not that it's stored as a field with a trivial implementation.
---
EDIT: As noted in the comments, this is made explicit in the [JavaBeans specification](http://java.sun.com/javase/technologies/desktop/javabeans/docs/spec.html) section 7.1:
> Thus even when a script writer types
> in something such as `b.Label = foo`
> there is still a method call into the
> target object to set the property, and
> the target object has full
> programmatic control.
>
> So properties need not just be simple
> data fields, they can actually be
> computed values. Updates may have
> various programmatic side effects. For
> example, changing a bean’s background
> color property might also cause the
> bean to be repainted with the new
> color."
---
If the supposed implication *were* true, we might just as well expose properties as fields directly. Fortunately that implication *doesn't* hold: getters and setters are perfectly within their rights to compute things.
For example, consider a component with
```
getWidth()
getHeight()
getSize()
```
Do you believe there's an implication that there are three variables there? Would it not be reasonable to either have:
```
private int width;
private int height;
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public Size getSize() {
return new Size(width, height); // Assuming an immutable Size type
}
```
Or (preferrably IMO):
```
private Size size;
public int getWidth() {
return size.getWidth();
}
public int getHeight() {
return size.getHeight();
}
public Size getSize() {
return size;
}
```
Here either the size property or the height/width properties are for convenience only - but I don't see that that makes them invalid in any way. | Java Interface Usage Guidelines -- Are getters and setters in an interface bad? | [
"",
"java",
"interface",
"javabeans",
"setter",
"getter",
""
] |
What's the best way to insert statistics symbols in a `JLabel`'s text? For example, the x-bar? I tried assigning the text field the following with no success:
```
<html>x̄
``` | Html codes will not work in Java. However, you can use the unicode escape in Java `Strings`.
For example:
```
JLabel label = new JLabel(new String("\u0304"));
```
Also, here is a [cool website](http://www.snible.org/java2/uni2java.html) for taking Unicode text and turning it into Java String leterals. | Well, that's completely mal-formed HTML, probably even for Swing (I think you would need the `</html>` at the end for it to work. But I would try to never go that road if you can help it, as Swing's HTML support has many drawbacks and bugs.
You can probably simply insert the appropriate character directly, either directly in the source code if you're using Unicode or with the appropriate Unicode escape:
```
"x\u0304"
```
This should work, actually. But it depends on font support and some fonts are pretty bad in positioning combining characters. But short of drawing it yourself it should be your best option. | How to display X-Bar statistics symbol in Java Swing label? | [
"",
"java",
"swing",
"unicode",
""
] |
**QUESTION** How can I create a MySQL table so, that a field's default value is the output of a function.
Can it be done without an insert trigger?
**BACKGROUND:** Some entities and the groups they belong to need to be observed on a daily basis.
To do that I created the following MySQL table:
```
CREATE TABLE entity (
entity_id VARCHAR(10) NOT NULL,
group_id VARCHAR(10) NOT NULL,
first_seen DATE NOT NULL,
last_seen DATE NOT NULL,
PRIMARY KEY (entity_id,group_id)
)
```
A script parses the entity logs on a daily basis and writes to to entity\_raw, I then want to update the tables using
```
REPLACE INTO entity (entity_id,group_id,last_seen)
SELECT entity_id,group_id,record_date
FROM entity_raw
WHERE (record_date = DATE(DATE_SUB(NOW(),INTERVAL 1 DAY))
```
Naturally I get an error when inserting new (entity\_id,group\_id) pairs, since first\_seen may not be NULL...
Can this be done in one statement, short of using a trigger (I dislike them, too surprising for maintenance)
or do I need to select for existance first, then insert/update accordingly? | After some searching I came up with this .. it solves my "problem", but not the question I asked :-(
```
REPLACE INTO entity (entity_id,group_id,first_seen,last_seen)
SELECT r.entity_id AS entity_id
, r.group_id AS group_id
, ISNULL( e.first_seen
,r.record_date
) AS first_seen
, r.record_date AS last_seen
FROM entity_raw r
LEFT OUTER JOIN entity e ON ( r.entity_id=e.entity_id
AND r.group_id=e.group_id
)
WHERE (record_date = DATE(DATE_SUB(NOW(),INTERVAL 1 DAY))
```
The initial insert needs to be done with the where clause disabled (there were already 5weeks of data in the entity\_raw table) | No, what you're asking isn't possible without triggers. The only example in MySQL where a field can be assigned a default value from a function is the TIMESTAMP type that can have CURRENT\_TIMESTAMP as default. | MYSQL: How can I create a MySQL table so, that a field's default value is the output of a function | [
"",
"sql",
"mysql",
"replace",
"ddl",
""
] |
Does every file need to `#include "stdafx.h"` when using precompiled headers? Or do only source files need to include it.
EDIT: Also, my precompiled header file `#includes` a lot of STL headers. But, in my headers, I sometimes have functions that return `std::vector` or something like that, so I need to `#include <vector>` anyway. Is this worse than including stdafx.h? I need to include the definitions for my unit testing framework. | Every source file needs to include it before any non-comment line. Headers do not need to include it, as every source file will include it before any other header. | You can set whether you want to use a precompiled header file or not at the project level or a file level. For the project setting, go to project properties dialog and click Configuration Properties / C/C++ / Precompiled Headers. There is an option for Create/Use Precompiled Header. You can overwrite the project level setting on each .cpp file by setting the same option on file properties dialog. | MSVC precompiled headers: Which files need to #include "stdafx.h"? | [
"",
"c++",
"visual-c++",
"precompiled-headers",
""
] |
I need to delete elements of an XML file using PHP. It will be done via ajax and I need to find the XML element via an attribute.
This is my XML file
```
<?xml version="1.0" encoding="utf-8"?>
<messages>
<message time="1248083538">
<name>Ben</name>
<email>Ben's Email</email>
<msg>Bens message</msg>
</message>
<message time="1248083838">
<name>John Smith</name>
<email>john@smith.com</email>
<msg>Can you do this for me?</msg>
</message>
</messages>
```
So what I would say is something like delete the element where the time equals 1248083838.
Ive been using Simple XML up until now and I've just realised it can do everything except delete elements.
So how would I do this? | You can use the DOM classes in PHP. ( <https://www.php.net/manual/en/intro.dom.php> ).
You will need to read the XML document into memory, use the DOM classes to do manipulation, and then you can save out the XML as needed (to http or to file).
DOMNode is an object in there that has remove features (to address your question).
It's a little more complicated than SimpleXML but once you get used to it, it's much more powerful
(semi-taken from a code example at php.net)
```
<?php
$doc = new DOMDocument;
$doc->load('theFile.xml');
$thedocument = $doc->documentElement;
//this gives you a list of the messages
$list = $thedocument->getElementsByTagName('message');
//figure out which ones you want -- assign it to a variable (ie: $nodeToRemove )
$nodeToRemove = null;
foreach ($list as $domElement){
$attrValue = $domElement->getAttribute('time');
if ($attrValue == 'VALUEYOUCAREABOUT') {
$nodeToRemove = $domElement; //will only remember last one- but this is just an example :)
}
}
//Now remove it.
if ($nodeToRemove != null)
$thedocument->removeChild($nodeToRemove);
echo $doc->saveXML();
?>
```
This should give you a little bit of an idea on how to remove the element. It will print out the XML without that node. If you wanted to send it to file, just write the string to file. | Dave Morgan is correct in that DOM classes are more powerful, but in case you want to stick with SimpleXML, try using the unset() function on any node, and that node will be removed from the XML.
```
unset($simpleXMLDoc->node1->child1)
``` | PHP - Delete XML Element | [
"",
"php",
"xml",
""
] |
This is my code:
```
int size = 100000000;
double sizeInMegabytes = (size * 8.0) / 1024.0 / 1024.0; //762 mb
double[] randomNumbers = new double[size];
```
Exception:
Exception of type 'System.OutOfMemoryException' was thrown.
**I have 4GB memory on this machine 2.5GB is free** when I start this running, there is clearly enough space on the PC to handle the 762mb of 100000000 random numbers. I need to store as many random numbers as possible given available memory. When I go to production there will be 12GB on the box and I want to make use of it.
**Does the CLR constrain me to a default max memory to start with? and how do I request more?**
**Update**
I thought breaking this into smaller chunks and incrementally adding to my memory requirements would help if the issue is due to **memory fragmentation**, but it doesn't **I can't get past a total ArrayList size of 256mb regardless of what I do tweaking blockSize**.
```
private static IRandomGenerator rnd = new MersenneTwister();
private static IDistribution dist = new DiscreteNormalDistribution(1048576);
private static List<double> ndRandomNumbers = new List<double>();
private static void AddNDRandomNumbers(int numberOfRandomNumbers) {
for (int i = 0; i < numberOfRandomNumbers; i++) {
ndRandomNumbers.Add(dist.ICDF(rnd.nextUniform()));
}
}
```
From my main method:
```
int blockSize = 1000000;
while (true) {
try
{
AddNDRandomNumbers(blockSize);
}
catch (System.OutOfMemoryException ex)
{
break;
}
}
double arrayTotalSizeInMegabytes = (ndRandomNumbers.Count * 8.0) / 1024.0 / 1024.0;
``` | You may want to read this: "[“Out Of Memory” Does Not Refer to Physical Memory](https://learn.microsoft.com/en-nz/archive/blogs/ericlippert/out-of-memory-does-not-refer-to-physical-memory)" by Eric Lippert.
In short, and very simplified, "Out of memory" does not really mean that the amount of available memory is too small. The most common reason is that within the current address space, there is no contiguous portion of memory that is large enough to serve the wanted allocation. If you have 100 blocks, each 4 MB large, that is not going to help you when you need one 5 MB block.
**Key Points:**
* the data storage that we call “process memory” is in my opinion best visualized as a **massive file on disk**.
* RAM can be seen as merely a performance optimization
* Total amount of virtual memory your program consumes is really not hugely relevant to its performance
* "running out of RAM" seldom results in an “out of memory” error. Instead of an error, it results in bad performance because the full cost of the fact that storage is actually on disk suddenly becomes relevant. | Check that you are building a 64-bit process, and not a 32-bit one, which is the default compilation mode of Visual Studio. To do this, right click on your project, Properties -> Build -> platform target : x64. As any 32-bit process, Visual Studio applications compiled in 32-bit have a virtual memory limit of 2GB.
64-bit processes do not have this limitation, as they use 64-bit pointers, so their theoretical maximum address space (the size of their virtual memory) is 16 exabytes (2^64). In reality, Windows x64 limits the virtual memory of processes to 8TB. The solution to the memory limit problem is then to compile in 64-bit.
However, object’s size in .NET is still limited to 2GB, by default. You will be able to create several arrays whose combined size will be greater than 2GB, but you cannot by default create arrays bigger than 2GB. Hopefully, if you still want to create arrays bigger than 2GB, you can do it by adding the following code to you app.config file:
```
<configuration>
<runtime>
<gcAllowVeryLargeObjects enabled="true" />
</runtime>
</configuration>
``` | 'System.OutOfMemoryException' was thrown when there is still plenty of memory free | [
"",
"c#",
"memory-management",
"out-of-memory",
""
] |
**update**: I've modified the code below to reveal some additional information regarding the key that was pressed.
**update #2**: I've discovered the root cause of the issue: we have an HTML control (Gecko rendering engine) on our form. When that Gecko rendering engine navigates to some Flash control, suddenly ~2% of our key presses don't get through, even after we've removed the Gecko HTML control. Wahoo, I get to blame this on Flash! Now the question is, how do I fix this?
**update #3**: Nope, it's not Flash. It's the Gecko rendering engine. Navigating even to Google causes some keys to not come through to our app right. Hrmmm.
We have a strange case in our WinForms app where the user presses a key combination (in this case, `Alt` + `S`), and WinForms tells us some other key combo (value 262162) is pressed:
```
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if(keyData == (Keys.S | Keys.Alt))
{
Console.WriteLine("You pressed Alt+S");
}
else if(keyData == (Keys.Menu | Keys.Alt))
{
Console.WriteLine("What the hell?"); // This sometimes gets hit when I press Alt+S
}
}
```
90% of the time, `You pressed Alt+S` will be shown. But on rare occurrances, we press `Alt` + `S` and it says, `What the hell?`.
Any idea what's wrong? | **EDIT** I've discovered the root cause of the issue! See below.
After more experimenting, I've found that if do the following, it works as expected:
```
this.KeyPreview = true;
this.KeyDown += KeyDownHandler;
...
private void KeyDownHandler(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.S && e.Alt)
{
// This always works.
}
}
```
I can't explain why the ProcessCmdKey didn't work. I wish I knew. Until then, this is an acceptable workaround.
I've discovered the issue. We have an HTML control (Gecko rendering engine) on our form. When that gecko rendering engine is shown on a form, it must be installing a hook or something that changes some key presses, causing us to receive WM\_Char instead of WM\_KeyDown in certain cases. | From my testing, it would appear that 262162 would be the "Alt" key.
**Edit**: I overrode the ProcessCmdKey and put in a break point on the "X = 1;" statement:
```
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
{
int x = (int)keyData;
if (x == 262162)
x = 1;
return true;
}
```
It hits that breakpoint whenever I hit the Alt key. | WinForms key press isn't working right | [
"",
"c#",
"winforms",
"keyboard",
"keyboard-shortcuts",
""
] |
I've been tasked with converting some text log files from a test reporting tool that I've inherited. The tool is a compiled C# (.NET 3.5) application.
I want to parse and convert a group of logically connected log files to a single XML report file, which is not a problem. The System.Xml classes are easy enough to use.
However, I also want to create a more "readable" file to accompany each report. I've chosen HTML, and because I like standardization, I'd prefer to do it in proper XHTML.
My question is how should I go about creating the HTML files along with the XML reports? My initial thought is to build the XML file, then to use LINQ and a simple StreamWriter to build an HTML file within my C# code. I could also use XSLT as opposed to LINQ to make the C# code easier. But since I have to compile this anyway, I don't like the idea of adding more files to the installation/distribution.
Is using LINQ going to cause me any problems as opposed to XSLT? Are there any nice HTML writing libraries for .NET that conform to XHTML? Since I have everything parsed from the log files in working memory, is there an easy way to create both files at the same time easily? | I'd create an xslt transform and just run that against the XML. Linq really isn't designed to transform XML of one schema (e.g., your report) to another (e.g., xhtml). You could brute force it, but xslt is an elegant way to do it. | I would actually recommend using XSL transform. Since you already have the XML doc. If you write a good XSL transform you will get very good results.
<http://www.w3schools.com/xsl/xsl_transformation.asp>
small snippet:
```
XslCompiledTransform xsl = new XslCompiledTransform();
xsl.Load(HttpContext.Current.Server.MapPath(xslPath));
StringBuilder sb = new StringBuilder();
using (TextWriter tw = new StringWriter(sb))
{
// Where the magic happens
xsl.Transform(xmlDoc, null, tw);
//return of text which you could save to file...
return sb.ToString();
}
``` | Converting log files to XML and (X)HTML, recommendedations | [
"",
"c#",
"html",
"xml",
"linq",
""
] |
Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function called with no parameter to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a novice):
```
>>> foo()
[5]
>>> foo()
[5, 5]
>>> foo()
[5, 5, 5]
>>> foo()
[5, 5, 5, 5]
>>> foo()
```
A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)
**Edit**:
[Baczek made an interesting example](https://stackoverflow.com/a/1137164/7487335). Together with most of your comments and [Utaal's in particular](https://stackoverflow.com/a/1134623/7487335), I elaborated further:
```
def a():
print("a executed")
return []
def b(x=a()):
x.append(5)
print(x)
a executed
>>> b()
[5]
>>> b()
[5, 5]
```
To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function, or "together" with it?
Doing the binding inside the function would mean that `x` is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the `def` line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.
The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition. | Actually, this is not a design flaw, and it is not because of internals or performance. It comes simply from the fact that functions in Python are first-class objects, and not only a piece of code.
As soon as you think of it this way, then it completely makes sense: a function is an object being evaluated on its definition; default parameters are kind of "member data" and therefore their state may change from one call to the other - exactly as in any other object.
In any case, the effbot (Fredrik Lundh) has a very nice explanation of the reasons for this behavior in [Default Parameter Values in Python](https://web.archive.org/web/20200221224620id_/http://effbot.org/zone/default-values.htm).
I found it very clear, and I really suggest reading it for a better knowledge of how function objects work. | Suppose you have the following code
```
fruits = ("apples", "bananas", "loganberries")
def eat(food=fruits):
...
```
When I see the declaration of eat, the least astonishing thing is to think that if the first parameter is not given, that it will be equal to the tuple `("apples", "bananas", "loganberries")`
However, suppose later on in the code, I do something like
```
def some_random_function():
global fruits
fruits = ("blueberries", "mangos")
```
then if default parameters were bound at function execution rather than function declaration, I would be astonished (in a very bad way) to discover that fruits had been changed. This would be more astonishing IMO than discovering that your `foo` function above was mutating the list.
The real problem lies with mutable variables, and all languages have this problem to some extent. Here's a question: suppose in Java I have the following code:
```
StringBuffer s = new StringBuffer("Hello World!");
Map<StringBuffer,Integer> counts = new HashMap<StringBuffer,Integer>();
counts.put(s, 5);
s.append("!!!!");
System.out.println( counts.get(s) ); // does this work?
```
Now, does my map use the value of the `StringBuffer` key when it was placed into the map, or does it store the key by reference? Either way, someone is astonished; either the person who tried to get the object out of the `Map` using a value identical to the one they put it in with, or the person who can't seem to retrieve their object even though the key they're using is literally the same object that was used to put it into the map (this is actually why Python doesn't allow its mutable built-in data types to be used as dictionary keys).
Your example is a good one of a case where Python newcomers will be surprised and bitten. But I'd argue that if we "fixed" this, then that would only create a different situation where they'd be bitten instead, and that one would be even less intuitive. Moreover, this is always the case when dealing with mutable variables; you always run into cases where someone could intuitively expect one or the opposite behavior depending on what code they're writing.
I personally like Python's current approach: default function arguments are evaluated when the function is defined and that object is always the default. I suppose they could special-case using an empty list, but that kind of special casing would cause even more astonishment, not to mention be backwards incompatible. | "Least Astonishment" and the Mutable Default Argument | [
"",
"python",
"language-design",
"default-parameters",
"least-astonishment",
""
] |
I'm looking to pull a specific line from a number of table that have a field name criteria1. The problem I'm having is that when I combine the Owner and Table Name and try to call "select criteria1 from @t where linenum = 1" SQL is expecting @t to be a table. I need to know how to construct the full table name and then pass it to this query. I know I can us a programming language to access the DB but i need this to be in SQL. If someone knows of a better way of doing this that would be great too.
```
declare @next as varchar
declare @owner varchar
while 1=1
begin
set @next = (select top 1 o.name FROM syscolumns c inner join sysobjects o on c.id = o.id
where c.name = 'criteria1' and o.id > @next order by o.id)
if @next is null
break
else
begin
set @owner = (select top 1 u.name
FROM syscolumns c inner join
sysobjects o on c.id = o.id left join
sysusers u on o.uid=u.uid
where c.name = 'criteria1' and o.id = @next order by o.id)
declare @t as varchar
set @t = @owner+'.'+@next
select criteria1 from @t where linenum = 1
end
continue
end
``` | You can build the entire query you want as a varchar() and then execute it with the `sp_executesql` stored procedure.
<http://msdn.microsoft.com/en-us/library/ms188001.aspx>
In your case, that bit at the end becomes
```
declare @sql varchar(512);
set @sql = 'select criteria1 from ' + @t + ' where linenum = 1'
sp_executesql @sql
``` | Have you considered the following construct in a stored procedure?
```
CASE @tablename
WHEN 'table1' THEN SELECT * FROM table1
WHEN 'table2' THEN SELECT * FROM table2
WHEN 'table3' THEN SELECT * FROM table3
WHEN 'table4' THEN SELECT * FROM table4
END
```
In case you're married to dynamic SQL (considered to be a bad choice for this problem space), [this guide to dynamic SQL should help a lot](http://www.sommarskog.se/dynamic_sql.html#Dyn_table). It helped me and I've used dynamic SQL extensively. | Constructing the FROM in SQL | [
"",
"sql",
"database",
"t-sql",
"variables",
""
] |
I have a huge table full of records and with PHP I'm making a seperate page for each one. On the page I want to interlink them alphatbetically, for example the page 'Dunn' would have links like this in the sidebar:
* Darren
* Dave
* Doom
* **Dunn**
* Dupp
* Duss
* Dutt
Always with 3 links either side going up and down the alphabet. All the data is going to be inserted into the table at once and the only way I can think of doing this is by setting a number upon insertion of where it will be in the alphabet relative to the other data.
This seems complicated and I'm wondering if there was an easier or simply better solution? I've seen this done on quite a few sites before so hopefully I can find one :) Any help would be appreciated. | Expanding on Gumbo's answer: You can do it in one query if you so wish, by using UNION.
```
(
SELECT `name`
FROM `table`
WHERE `name` < "Dunn"
ORDER BY `name` DESC
LIMIT 3
)
UNION ALL (
SELECT `name`
FROM `table`
WHERE `name` = "Dunn"
LIMIT 1
)
UNION ALL (
SELECT `name`
FROM `table`
WHERE `name` > "Dunn"
ORDER BY `name` ASC
LIMIT 3
)
```
Thus giving a table with all 7 required entries. | You need to do two queries:
1. Get 3 records that preceed *Dunn*:
```
SELECT `name`
FROM `table`
WHERE `name` < "Dunn"
ORDER BY `name` DESC
LIMIT 3
```
2. Get 3 records that follow *Dunn*:
```
SELECT `name`
FROM `table`
WHERE `name` > "Dunn"
ORDER BY `name` ASC
LIMIT 3
``` | PHP MySQL Alphabetical Linking | [
"",
"php",
"mysql",
""
] |
I am using the following query
```
SELECT SS.sightseeingId AS 'sID'
, SS.SightseeingName
, SS.displayPrice AS 'Price'
, SST.fromDate
FROM tblSightseeings SS INNER JOIN
tblSightseeingTours SST ON SS.sightseeingId = SST.sightseeingId
WHERE SS.isActive = 1 AND SS.isDisplayOnMainPage = 1
```
and getting result like this
```
sID | SightseeingName | Price | fromDate
------------------------------------------------------------------------------
2 | Dinner Cruise Bateaux London (Premier) | 40 | 2009-04-01 00:00:00.000
2 | Dinner Cruise Bateaux London (Premier) | 40 | 2009-12-29 00:00:00.000
30 | Jack The Ripper, Ghosts and Sinister | 35.1 | 2009-04-01 00:00:00.000
30 | Jack The Ripper, Ghosts and Sinister | 35.1 | 2009-10-01 00:00:00.000
40 | Grand Tour of London | 0 | 2009-05-01 00:00:00.000
40 | Grand Tour of London | 0 | 2010-05-01 00:00:00.000
87 | Warwick, Stratford, Oxford and The | 25 | 2009-04-01 00:00:00.000
87 | Warwick, Stratford, Oxford and The | 25 | 2009-11-01 00:00:00.000
```
I want to display the unique records 2 one time 30 one time 40 one time. The duplicate records are due to `SST.fromDate`.
How do I correct my query?? | You can try next query:
```
select SS.sightseeingId, SS.SightseeingName, SS.displayPrice, MAX(SST.fromDate)
from tblSightseeings SS inner join
tblSightseeingTours SST on SS.sightseeingId = SST.sightseeingId
where SS.isActive = 1 and SS.isDisplayOnMainPage = 1
GROUP by SS.sightseeingId, SS.SightseeingName, SS.displayPrice
``` | Well, the records aren't actually duplicated, because the dates are different. You could do something like:
```
select SS.sightseeingId, SS.SightseeingName, SS.displayPrice, MIN(SST.fromDate) AS FromDate
from tblSightseeings SS inner join
tblSightseeingTours SST on SS.sightseeingId = SST.sightseeingId
where SS.isActive = 1 and SS.isDisplayOnMainPage = 1
GROUP BY ss.sightseeingid, ss.sightseeingname, ss.displayprice
``` | Removing duplicate records | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
Our project seeks to render calendars similar to outlook's web view (i.e. where you can view a calendar in 'day', 'week', or 'month' view). To clarify: we do *not* need 'date picker' functionality (i.e. used by the out-of-the-box jquery UI calendar plugin).
At this point I've found jquery plugins to render a calendar in "month view" and "week view".
Can anyone recommend a 'day view' jquery plugin or javascript library? We can write our own plugin, but wanted to check with the hive-mind first.
Thanks in advance,
bill
Appendix A. Jquery plugins for Rendering Calendars
# ***Week views***
Jquery week calendar:
<http://www.redredred.com.au/projects/jquery-week-calendar/>
# ***Month views***
Jmonth calendar
Full Calendar | see [Eyecon](http://eyecon.ro/datepicker/) datepicker. The last example on this page has only the current date. Maybe this is what you need. | I did a same search today and found an awesome control.
<http://arshaw.com/fullcalendar/> | Looking for "day view" javascript library/plugin/calendar | [
"",
"javascript",
"jquery",
"plugins",
"calendar",
""
] |
I want JavaScript code to be separated from views.
I got the requirement to implement localization for a simple image button generated by JavaScript:
```
<img src="..." onclick="..." title="Close" />
```
What's the best technique to localize the title of it?
PS: I found [a solution](http://ayende.com/Blog/archive/2007/10/07/Handling-javascript-localization-in-Mono-Rail.aspx) by Ayende. This is the right direction.
Edit:
I got Localization helper class which provides the `Controller.Resource('foo')` extension method.
I am thinking about to extend it (helper) so it could return all JavaScript resources (from "ClientSideResources" subfolder in `App_LocalResources`) for the specified controller by its name. Then - call it in `BaseController`, add it to `ViewData` and render it in `Layout`.
Would that be a good idea? | **EDIT**
Consider writing the necessary localized resources to a JavaScript object (hash) and then using it for lookup for your dynamically created objects. I think this is better than going back to the server for translations. This is similar to adding it via viewdata, but may be a little more flexible. FWIW, I could consider the localization resources to be part of the View, not part of the controller.
In the View:
```
<script type="text/javascript"
src='<%= Url.Content( "~/Resources/Load?translate=Close,Open" %>'></script>
```
which would output something like:
```
var local = {};
local.Close = "Close";
local.Open = "Open";
```
Without arguments it would output the entire translation hash. Using arguments gives you the ability to customize it per view.
You would then use it in your JavaScript files like:
```
$(function(){
$('#button').click( function() {
$("<img src=... title='" + local.Close + "' />")
.appendTo("#someDiv")
.click( function() { ... } );
});
});
```
Actually, I'm not too fussed about keeping my JavaScript code out of my views as long as the JavaScript code is localized in a container. Typically I'll set my master page up with 4 content area: title, header, main, and scripts. Title, header, and main go where you would expect and the scripts area goes at the bottom of the body.
I put all my JavaScript includes, including any for viewusercontrols, into the scripts container. View-specific JavaScript code comes after the includes. I refactor shared code back to scripts as needed. I've thought about using a controller method to collate script includes, that is, include multiple scripts using a single request, but haven't gotten around to that, yet.
This has the advantage of keeping the JavaScript code separate for readability, but also allows me to easily inject model or view data into the JavaScript code as needed. | Actually ASP.NET Ajax has a built-in localization mechanism: [Understanding ASP.NET AJAX Localization](http://www.asp.net/ajax/tutorials/understanding-asp-net-ajax-localization) | How to handle localization in JavaScript files? | [
"",
"javascript",
"asp.net-mvc",
"localization",
""
] |
**Edit**: Though I've accepted [David's](https://stackoverflow.com/questions/1047157/preferred-method-to-set-the-value-of-a-get-only-property-constructor-vs-backing/1047165#1047165) answer, [Jon's](https://stackoverflow.com/questions/1047157/preferred-method-to-set-the-value-of-a-get-only-property-constructor-vs-backing/1047607#1047607) answer should be considered as well.
Which method is preferred for setting the value of a read only (get only?) Property: using a backing field or using the constructor? Assume the design is for a Property and not a Field (in the future, there may be an update that requires the Property to have a setter which would preclude using a Field).
Given the following simple example, which method is preferred? If one is preferred over the other, why?
**Option 1 (backing field)**:
```
class SomeObject
{
// logic
}
class Foo
{
private SomeObject _myObject;
public SomeObject MyObject
{
get
{
if( _myObject == null )
{
_myObject = new SomeObject();
}
return _myObject;
}
}
public Foo()
{
// logic
}
}
```
**Option 2 (constructor)**:
```
class SomeObject
{
// logic
}
class Foo
{
public SomeObject MyObject { get; private set; }
public Foo()
{
MyObject = new SomeObject();
// logic
}
}
``` | It depends on the time needed by "new SomeObject();" and the likelihood that the getter is going to be called at all.
If it's costly to create MyObject, and won't be used every time you create an instance of Foo(), option 1 is a good idea, and that's called lazy initialization. Programs like Google Chrome use it heavily to reduce startup time.
If you're going to create MyObject every time anyways, and the getter is called very often, you'll save a comparison on each access with option 2. | In many cases I like to make types immutable. Where possible, I like to make them *properly* immutable, which means avoiding automatically implemented properties entirely - otherwise the type is still mutable within the same class, which feels like a bug waiting to happen.
"Proper" immutability will include making the backing field readonly, which means you *have* to set it in the constructor... usually initializing it from another parameter. I find it quite rare that I can lazily create an instance without any more information, as you do in your question. In other words, this is a more common pattern for me:
```
public class Person
{
private readonly string name;
public string Name { get { return name; } }
public Person(string name)
{
this.name = name;
}
}
```
This becomes unwieldy when you have a lot of properties - passing them all into a single constructor can get annoying. That's where you'd want to use the builder pattern, with a mutable type used to collect the initialization data, and then a constructor taking just the builder. Alternatively, the named arguments and optional parameters available in C# 4 should make this slightly easier.
To get back to your exact situation, I'd usually write:
```
class Foo
{
private readonly MyObject myObject;
public SomeObject MyObject { get { return myObject; } }
public Foo()
{
myObject = new MyObject();
// logic
}
}
```
That is, unless constructing `SomeObject` is particularly expensive. It's just simpler than doing it lazily in the property and potentially having to worry about threading issues.
Now, I've been assuming that immutability is a useful goal here - but you've been talking about adding a setter. I'm not sure why you think that precludes using a field, but it certainly doesn't. For instance, you could combine the lazy instantiation from your first piece of code and having a setter like this:
```
class Foo
{
private SomeObject _myObject;
public SomeObject MyObject
{
get
{
if( _myObject == null )
{
_myObject = new SomeObject();
}
return _myObject;
}
set
{
// Do you want to only replace it if
// value is non-null? Or if _myObject is null?
// Whatever logic you want would go here
_myObject = value;
}
}
public Foo()
{
// logic
}
}
```
I think the major decisions should be:
* Do you want the type to be properly immutable?
* Do you need lazy initialization?
* Do you need any other logic in your properties?
If the answer to all of these is no, use an automatically implemented property. If the third answer changes to yes, you can always convert the automatically implemented property into a "normal" one later. | Preferred method to set the value of a get only Property: constructor vs backing field | [
"",
"c#",
"properties",
"class-design",
""
] |
I'm writing a console application which is looking up information about SSIS packages in SQL Server. I have it working and writing to a .csv file. I just added in the ability to pass command line switches for servername, foldername and outputfile. If an output file is not specified, I'd just like to output to the console, which I'm already doing.
The way I've handled the file writing seems awkward, and is probably wrong.
In my main method I create a StreamWriter. I need to write the entire output of the program to this file. I explore folders under my specified folder by recursively calling a function.
I pass the StreamWriter object along in all calls - it is a parameter in functions which don't use it, so it can be passed to the one that does. It seems like I should be able to make it a global variable, but I see that c# doesn't have globals and "if you are using a global, you are probably doing it wrong".
I'd planned on revisiting this issue eventually after plugging away at this little utility for a while, but I now have the problem that all the functions want the StreamWriter object - and if I make it optional, then it won't be there for the functions. And it also seems c# doesn't do optional arguments.
I'm sure you can tell I'm no c# expert and only dabble when I need to. Thanks for your assistance. | You want to use a [singleton](http://en.wikipedia.org/wiki/Singleton_pattern) pattern to refer to the StreamWriter you're using. The singleton is a way to "simulate" the functionality of global variables, without having the problems of them.
Essentially, what the singleton provides is a class-specific instance of a resource you want to be shared among many different parts in your application. The resource is accessed through the a static class instance.
Effectively, what you'll want to do is to define a class which has as a public **static** member the StreamWriter that you'll want to use; in that way, any method that you use in the rest of your code can get access to that SAME instance of the StreamWriter by accessing it from the containing class (without needing to create an instance of the class, because it's static). | Something like
```
public static class CsvWriter
{
private static StreamWriter _writer = new StreamWriter(...);
public static StreamWriter Writer
{
get { return _writer; }
}
}
```
Some variation is possible, the main item is the static property here. It's like a global but not (entirely) as bad. | Optional output file in console application - make StreamWriter global | [
"",
"c#",
""
] |
I set cookies based on the referral links and they all start with the same letters, lets say "google", but they end with \_xxx, \_yyy, \_zzz or whatever is the reference.
Now, when I try to get the cookies later, I have the problem that I don't want to check for all of the different cookies, I would like to check for all cookies that start with "google" and based on that I will start a script that goes on with processing.
```
if (Request.Cookies("google"))
{
run other stuff
}
```
Any idea how I can add StartWith or something to it? I am a newbie, so not really that into C# yet.
Thanks in advance,
Pat | You have to check all the cookies if you want to find ones with a certain suffix (Randolpho's answer will work).
It's not a particularly good idea to do it that way. The problem is that the more cookies you create, the more overhead you put on the server and connection. Say you have 10 cookies: `google_aaa`, `google_bbb`, etc. Each request will send all 10 cookies to your server (this includes requests for images, css, etc.
You're better off using a single cookie which is some sort of key to all the information stored on your server. Something like this:
```
var cookie = Cookies["google"];
if(cookie!=null)
{
// cookie.Value is a unique key for this user. Lookup this
// key in your database or other store to find out the
// information about this user.
}
``` | Well.. HttpRequest.Cookies *is* a collection. So use LINQ:
```
var qry = from cookieName in Request.Cookies.Keys
where cookieName.StartsWith("google")
select cookieName;
foreach(var item in qry)
{
// get the cookie and deal with it.
var cookie = Request.Cookies[item];
}
```
Bottom line: you can't get away from iterating over the entire cookie collection. But you can do it easily using LINQ. | C#, getting cookies with different names | [
"",
"c#",
"asp.net",
"cookies",
""
] |
What is the difference between data adapter and data reader? | Please see [DataReader, DataAdapter & DataSet - When to use?](https://web.archive.org/web/20200217202925/http://geekswithblogs.net:80/ranganh/archive/2005/04/25/37618.aspx) :
> ADO.NET provides two central Data
> Access Components. The excellent thing
> is that, they are common across all
> Databases, be it SQL Server or other
> competitive databases. Its only the
> namespace to be used, that differs,
> while using a Database other than SQL
> Server. | A DataReader is an object returned from the ExecuteReader method of a DbCommand object. It is a forward-only cursor over the rows in the each result set. Using a DataReader, you can access each column of the result set, read all rows of the set, and advance to the next result set if there are more than one.
A DataAdapter is an object that contains four DbCommand objects: one each for SELECT, INSERT, DELETE and UPDATE commands. It mediates between these commands and a DataSet though the Fill and Update methods. | what is the difference between data adapter and data reader? | [
"",
"c#",
".net",
"ado.net",
""
] |
HI,
I have a .NET application which uses threads excessively. At the time of exit the process does not kill itself. Is there is any tool that can show what is causing the problem? although I have checked thoroughly but was unable to find the problem.
Abdul Khaliq | See: [Why doesn't my process terminate even after main thread terminated](http://blogs.msdn.com/neerajag/archive/2005/09/04/why-doesn-t-my-process-terminate-even-after-main-thread-terminated.aspx) | That means you have some foreground thread running. A .net application will not terminate unless all the foreground threads complete execution.
You can mark threads as Background Threads and then check (Thread.IsBackground property). Please note that all background threads terminate immediately when application exits. If you are doing some important work in those threads like serializing data to database then you should keep them as foreground threads only. Background threads are good for non critical things like spell cheker etc. | Process exit issue thread not exited successfully | [
"",
"c#",
".net",
"multithreading",
"process",
""
] |
If I have little to no experience in either of them, but know enough Java and Ruby to be comfortable, is one framework harder to learn than the other? Is one easier to use for the beginner on these?
I know it is hard to answer. Just looking for general thoughts on it. | Both Spring and Ruby on Rails share the "convention over configuration" moto. This reduces code lines significantly. Ruby on Rails is a Web Framework and it could be compared with Spring MVC, together with an ORM tool like Hibernate.
One could say that Spring together with Spring MVC or another MVC framework and Hibernate are the closest that you can get to Ruby on Rails for the Java world.
However, Spring has a much wider scope than RoR. | I don't like this comparison.
You should compare Grails or Spring Roo to Rails. Groovy Grails is a RoR like system built on Spring that uses Groovy for rails-like DSLs. Roo is a vaguely railish pure java DSL for RoR like apps.
I really hate to say it this way but Spring is a platform. You use it to wire Java technologies together. You can use it for non-web, non-database, zero UI apps. You can use it to write batch servers. You can use it to write clients.
Rails isn't the same. I really like rails for data driven web apps but I shudder at the thought of writing a batch processing system in rails. | Is Spring hard compared to Ruby on Rails? | [
"",
"java",
"ruby-on-rails",
"spring",
""
] |
hi i have more than 10 arraylist in my project, i need to compare all arraylist for their count(same or not). here i need shortest way to find that.
am not sorting i need to find length of all arraylist count(same or not). | Put them in an array and compare their counts:
```
private static bool CountsAreEqual(ICollection[] lists)
{
int previousCount = lists[0].Count;
for (int i = 1; i < lists.Count; i++)
{
if (lists[i].Count != previousCount)
{
return false;
}
}
return true;
}
```
Used like so:
```
ArrayList arr1 = GetFirstList();
ArrayList arr2 = GetSecondList();
CountsAreEqual(new[] {arr1, arr2});
``` | It would be better if you add all those arraylist in another arraylist and then run an iterator over it comparing length.
you have 10 variables, and you performing some task on all of them, a good candidate for a collection | arraylist count | [
"",
"c#",
""
] |
I'd like to use Javascript to make IE6 download a file. It'll be created on the fly using Javascript. This file doesn't exist on a webserver. Here's a small example:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
function clicked() {
var xml = "<data>Just for testing</data>";
document.open("text/xml", "replace");
document.write(xml);
}
</script>
</head>
<body>
<input type="button" value="Download" onclick="clicked();" />
</body>
</html>
```
Instead of loading the xml in the browser window, I want it to cause IE6 to prompt the user where to download the data to so that it can be saved without them having to use File -> Save as. Any ideas? | For IE6 you should be able to use [`document.execCommand()`](http://msdn.microsoft.com/en-us/library/ms536419%28VS.85%29.aspx) after your `document.write()`:
```
document.execCommand('SaveAs',true,'file.xml');
```
This is not part of any standard and will only work in IE flavor browsers. | If your data must be generated client side, then you can post it back to the server so that it can be returned as a downloadable file. | Download Javascript generated XML in IE6 | [
"",
"javascript",
""
] |
i am facing one problem.
i want to save settings in app.config file
i wrote separate class and defined section in config file..
but when i run the application. it does not save the given values into config file
here is SettingsClass
```
public class MySetting:ConfigurationSection
{
private static MySetting settings = ConfigurationManager.GetSection("MySetting") as MySetting;
public override bool IsReadOnly()
{
return false;
}
public static MySetting Settings
{
get
{
return settings;
}
}
[ConfigurationProperty("CustomerName")]
public String CustomerName
{
get
{
return settings["CustomerName"].ToString();
}
set
{
settings["CustomerName"] = value;
}
}
[ConfigurationProperty("EmailAddress")]
public String EmailAddress
{
get
{
return settings["EmailAddress"].ToString();
}
set
{
settings["EmailAddress"] = value;
}
}
public static bool Save()
{
try
{
System.Configuration.Configuration configFile = Utility.GetConfigFile();
MySetting mySetting = (MySetting )configFile.Sections["MySetting "];
if (null != mySetting )
{
mySetting .CustomerName = settings["CustomerName"] as string;
mySetting .EmailAddress = settings["EmailAddress"] as string;
configFile.Save(ConfigurationSaveMode.Full);
return true;
}
return false;
}
catch
{
return false;
}
}
}
```
and this is the code from where i am saving the information in config file
```
private void SaveCustomerInfoToConfig(String name, String emailAddress)
{
MySetting .Settings.CustomerName = name;
MySetting .Settings.EmailAddress = emailAddress
MySetting .Save();
}
```
and this is app.config
```
<configuration>
<configSections>
<section name="MySettings" type="TestApp.MySettings, TestApp"/>
</configSections>
<MySettings CustomerName="" EmailAddress="" />
</configuration>
```
can u tell me where is the error.. i tried alot and read from internet. but still unable to save information in config file..
i ran the application by double clicking on exe file also. | According to the [MSDN: ConfigurationManager.GetSection Method](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.getsection.aspx),
The [`ConfigurationManager.GetSection`](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.getsection.aspx) method accesses run-time configuration information ***that it cannot change***. To change the configuration, you use the [`Configuration.GetSection`](http://msdn.microsoft.com/en-us/library/system.configuration.configuration.getsection.aspx) method on the configuration file that you obtain by using one of the following Open methods:
* [OpenExeConfiguration](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openexeconfiguration.aspx)
* [OpenMachineConfiguration](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openmachineconfiguration.aspx)
* [OpenMappedExeConfiguration](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openmappedexeconfiguration.aspx)
However, if you want to update app.config file, I would read it as an xml document and manipulate it as a normal xml document.
Please see the following example:
Note: this sample is just for proof-of-concept. Should not be used in production as it is.
```
using System;
using System.Linq;
using System.Xml.Linq;
namespace ChangeAppConfig
{
class Program
{
static void Main(string[] args)
{
MyConfigSetting.CustomerName = "MyCustomer";
MyConfigSetting.EmailAddress = "MyCustomer@Company.com";
MyConfigSetting.TimeStamp = DateTime.Now;
MyConfigSetting.Save();
}
}
//Note: This is a proof-of-concept sample and
//should not be used in production as it is.
// For example, this is not thread-safe.
public class MyConfigSetting
{
private static string _CustomerName;
public static string CustomerName
{
get { return _CustomerName; }
set
{
_CustomerName = value;
}
}
private static string _EmailAddress;
public static string EmailAddress
{
get { return _EmailAddress; }
set
{
_EmailAddress = value;
}
}
private static DateTime _TimeStamp;
public static DateTime TimeStamp
{
get { return _TimeStamp; }
set
{
_TimeStamp = value;
}
}
public static void Save()
{
XElement myAppConfigFile = XElement.Load(Utility.GetConfigFileName());
var mySetting = (from p in myAppConfigFile.Elements("MySettings")
select p).FirstOrDefault();
mySetting.Attribute("CustomerName").Value = CustomerName;
mySetting.Attribute("EmailAddress").Value = EmailAddress;
mySetting.Attribute("TimeStamp").Value = TimeStamp.ToString();
myAppConfigFile.Save(Utility.GetConfigFileName());
}
}
class Utility
{
//Note: This is a proof-of-concept and very naive code.
//Shouldn't be used in production as it is.
//For example, no null reference checking, no file existence checking and etc.
public static string GetConfigFileName()
{
const string STR_Vshostexe = ".vshost.exe";
string appName = Environment.GetCommandLineArgs()[0];
//In case this is running under debugger.
if (appName.EndsWith(STR_Vshostexe))
{
appName = appName.Remove(appName.LastIndexOf(STR_Vshostexe), STR_Vshostexe.Length) + ".exe";
}
return appName + ".config";
}
}
}
```
I also added "TimeStamp" attribute to MySettings in app.config to check the result easily.
```
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="MySettings" type="TestApp.MySettings, TestApp"/>
</configSections>
<MySettings CustomerName="" EmailAddress="" TimeStamp=""/>
</configuration>
``` | In many cases (in a restricted user scenario) the user do not have write access directly to the application config file. To come around this, you need to use the usersettings.
If you right-click your project and select the tab named "Settings", you can make a list of settings that are stored with the config file. If you select the "Scope" to be "User", the setting are automatically stored in the config file using a type that will automatically store the settings under the users AppData area, where the user allways has write access. The settings are also automatically provided as properties created in the Properties\Settings.Designer.cs code file, and are accessible in your code in `Properties.Settings.Default` .
## Example:
Let's say you add a user setting called **CustomerName**:
On loading the app, you would want to retreive the value from the stored setting ( either default value as it is in the app config, or if it is stored for this user, the config file for the user):
```
string value = Properties.Settings.Default.CustomerName;
```
When you want to change the value, just write to it:
```
Properties.Settings.Default.CustomerName = "John Doe";
```
When you want to save all the settings, just call Save:
```
Properties.Settings.Default.Save();
```
Note that when you develop, the user file will occationally be reset to the default, but this only happens when building the app. When you just run the app, the settings you store will be read from the user-config file for the app.
If you still want to create your own handling of the settings, you can try this once, and look at what VisualStudio has automatically created for you to get an idea of what you need to get this working. | unable to save settings in app.exe.config | [
"",
"c#",
"configuration",
"app-config",
""
] |
I want to send data from my Windows form to client wep page(.aspx).Pls help me. | I would say use httpwebrequest and httpwebresponse to do this. it will be easy to do also.check the link below
<http://www.codeproject.com/KB/IP/httpwebrequest_response.aspx> | You could use Web Services within your ASP .NET application and consume them them from your WinForms app.
Give a look to these articles:
* [Web Services with ASP.NET](http://msdn.microsoft.com/en-us/library/ms972326.aspx)
* [Using ASP.NET Web Services](http://msdn.microsoft.com/en-us/library/t745kdsh.aspx)
* [Walkthrough: Calling XML Web Services from Windows Forms](http://msdn.microsoft.com/en-us/library/scf355x6%28VS.80%29.aspx) | Send Data from aspx to C# windows app | [
"",
"c#",
""
] |
Sample console program.
```
class Program
{
static void Main(string[] args)
{
// ... code to build dll ... not written yet ...
Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
// don't know what or how to cast here
// looking for a better way to do next 3 lines
IRunnable r = assembly.CreateInstance("TestRunner");
if (r == null) throw new Exception("broke");
r.Run();
}
}
```
I want to dynamically build an assembly (.dll), and then load the assembly, instantiate a class, and call the Run() method of that class. Should I try casting the TestRunner class to something? Not sure how the types in one assembly (dynamic code) would know about my types in my (static assembly / shell app). Is it better to just use a few lines of reflection code to call Run() on just an object? What should that code look like?
UPDATE:
William Edmondson - see comment | ## Use an AppDomain
It is safer and more flexible to load the assembly into its own [`AppDomain`](http://msdn.microsoft.com/en-us/library/system.appdomain.aspx) first.
So instead of [the answer given previously](https://stackoverflow.com/a/1138426/184528):
```
var asm = Assembly.LoadFile(@"C:\myDll.dll");
var type = asm.GetType("TestRunner");
var runnable = Activator.CreateInstance(type) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();
```
I would suggest the following (adapted from [this answer to a related question](https://stackoverflow.com/questions/88717/loading-dlls-into-a-separate-appdomain)):
```
var domain = AppDomain.CreateDomain("NewDomainName");
var t = typeof(TypeIWantToLoad);
var runnable = domain.CreateInstanceFromAndUnwrap(@"C:\myDll.dll", t.Name) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();
```
Now you can unload the assembly and have different security settings.
If you want even more flexibility and power for dynamic loading and unloading of assemblies, you should look at the Managed Add-ins Framework (i.e. the `System.AddIn` namespace). For more information, see this article on [Add-ins and Extensibility on MSDN](http://msdn.microsoft.com/en-us/library/bb384200.aspx). | If you do not have access to the `TestRunner` type information in the calling assembly (it sounds like you may not), you can call the method like this:
```
Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
Type type = assembly.GetType("TestRunner");
var obj = Activator.CreateInstance(type);
// Alternately you could get the MethodInfo for the TestRunner.Run method
type.InvokeMember("Run",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
obj,
null);
```
If you have access to the `IRunnable` interface type, you can cast your instance to that (rather than the `TestRunner` type, which is implemented in the dynamically created or loaded assembly, right?):
```
Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
Type type = assembly.GetType("TestRunner");
IRunnable runnable = Activator.CreateInstance(type) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();
``` | Correct Way to Load Assembly, Find Class and Call Run() Method | [
"",
"c#",
".net",
"reflection",
""
] |
I built a GIS application around Twitter and now its getting some interest.
But one of the requirements is that they don't want any outside dependencies.
So I'll need to mimic Twitters functions.
Anyone know of any open source Twitter projects? | [Jaiku](http://www.jaiku.com/) is a microblogging service very similar to Twitter. Google bought Jaiku a few years ago and made its engine open source. You can find it here:
<http://code.google.com/p/jaikuengine/>
If you're looking for a .NET alternative. There is [Yonkly](http://yonkly.com/). Is an open source Twitter clone written using ASP.NET MVC. You can find the source here:
<http://www.codeplex.com/yonkly> | Laconica?
<http://laconi.ca/trac/>
Identica demos it nicely:
<http://identi.ca/> | Does anyone know of any open source versions of Twitter? | [
"",
"c#",
"web-applications",
"open-source",
"twitter",
""
] |
the following is my HTML DOM element...
```
<input type="text" style="width: 200px;" id="input1"/>
```
I want to keep the date value in it..But somewhere i need to specify that it is going to hold date value in the Dom element..
How can i do so..Please suggest me | Looks like you are trying to hide data inside the control.
An easier way would be to assign a css class to the element.
and jquery has lots of methods for retrieving the class names out of an element.
Or you could go with the html 5 standard for adding data like this:
```
<input id='ctrl' type='text' data-attr='date' />
```
Then you can retrieve the attribute value like this:
```
var value = $("#ctrl").attr("data-attr");
``` | JQuery is returning the runtime type of the input element from the DOM. Since "date" isn't a valid type for a form input, it is returning the default value : "text".
These are the valid input types:
```
* "text"
* "password"
* "checkbox"
* "radio"
* "submit"
* "reset"
```
If you try the same code snippet with one of the above instead of "date", it works fine. | JQuery attributes | [
"",
"javascript",
"jquery",
"html",
""
] |
If I have a application that accepts a query that returns 4 columns, 1 of which is an extra info column that can be empty, and the column doesn't exist in the database I am using how could I 'create' it so that the data retrieved using the query always has 4 columns, 1 nbeing empty? | ```
select c1, c2, c3, null as c4 from table;
``` | This would work in Oracle, haven't tried in anything else:
```
select null thiscolumnisempty, id,id2,id3 from table
``` | SQL select statement that shows non-existant column? | [
"",
"sql",
"select",
""
] |
Can any body help me in knowing how to pass a parameter from a Java program to a Batch file which is also used in the same java program.
The following stub indicates the piece of code where I run the batch file
```
Runtime rt = Runtime.getRuntime();
rt.exec("C:/test.bat");
```
I need to know if I could pass some parameters to test.bat which is used in the above snippet. | you can use a string array as the arg to Runtime.getRuntime().exec(). see the [JavaDoc](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runtime.html#exec(java.lang.String[]))
```
public Process exec(String[] cmdarray) throws IOException
``` | This should work:
```
String[] cmd = { "C:/test.bat", "param1", "param2" }
Runtime rt = Runtime.getRuntime();
rt.exec(cmd);
``` | Java to batch file | [
"",
"java",
"batch-file",
""
] |
I'm trying to optimize the following code below to avoid having to copy and paste and just use SlaveForce and SlavePos properly, which are float[6] type, and baseForce and basePos are vector type:
```
typedef struct _NodeCoord
{
float coords[6];
} NodeCoord;
int main()
{
...
memcpy(tempNodeCoord.coords, SlaveForce, 6*sizeof(float));
baseForce.push_back(tempNodeCoord);
memcpy(tempNodeCoord.coords, SlavePos, 6*sizeof(float));
basePos.push_back(tempNodeCoord);
...
}
```
I have tried some test codes. Only this appear to work:
```
std::vector<NodeCoord> tallon;
NodeCoord m;
memset(m.coords, 0, sizeof(m.coords));
tallon.push_back(m);
```
while this is along the lines of what I want to accomplish, but it doesn't work:
```
std::vector<float[6]> ed;
float e[6];
tallon.push_back(e);
```
I also tried writing a "typedef float[6] mytype;" line before the main function, but it doesn't work well either. Is there anything that I can do to eliminate the memcpy function calls (or rather push\_back the float[6] variables directly)? Thanks in advance. | In order to be storable in a vector, a type must be copyable and assignable, and C-style arrays are neither. You should instead use another vector, or possibly wrap the array in a struct. | Try a vector of vectors:
```
std::vector<std::vector<float> > ed;
ed.push_back(std::vector<float>(6, 0.0f));
```
In this case I'm pushing a temp vector of floats, with 6 elements with the value of 0.0f;
[Info on vector's constructors](http://www.cppreference.com/wiki/stl/vector/vector_constructors). | C++ vector manipulation optimization | [
"",
"c++",
"vector",
""
] |
Is there a book or a tutorial which teaches how to build a shopping cart with django or any other python framework ? | There's a book coming out that talks about just that. See here:
<http://www.apress.com/book/view/9781430225355>
Edit: The above link is dead, so here's a working link for the book: <https://play.google.com/store/books/details?id=LwO1GzMN_QsC>
It's called Beginning Django E-Commerce by James McGaw. | Satchmo project is a known open source shopping cart.
<http://www.satchmoproject.com/> | How to build an Ecommerce Shopping Cart in Django? | [
"",
"python",
"django",
"shopping-cart",
""
] |
When you get a third-party library (c, c++), open-source (LGPL say), that does not have good documentation, what is the best way to go about understanding it to be able to integrate into your application?
The library usually has some example programs and I end up walking through the code using gdb. Any other suggestions/best-practicies?
For an example, I just picked one from sourceforge.net, but it's just a broad engineering/programming question:
<http://sourceforge.net/projects/aftp/> | I frequently use a couple of tools to help me with this:
* [GNU Global](http://www.gnu.org/software/global). It generates cross-referencing databases and can produce hyperlinked HTML from source code. Clicking function calls will take you to their definitions, and you can see lists of all references to a function. Only works for C and perhaps C++.
* [Doxygen](http://www.doxygen.org). It generates documentation from Javadoc-style comments. If you tell it to generate documentation for undocumented methods, it will give you nice summaries. It can also produce hyperlinked source code listings (and can link into the listings provided by htags).
These two tools, along with just reading code in Emacs and doing some searches with recursive grep, are how I do most of my source reverse-engineering. | One of the better ways to understand it is to attempt to document it yourself. By going and trying to document it yourself, it forces you to really dive in and test and test and test and make sure you know what each statement is doing at what times. Then you can really start to understand what the previous developer may have been thinking (or not thinking for that matter). | Reading/Understanding third-party code | [
"",
"c++",
""
] |
I'm trying to programmatically close a Facebox modal with JavaScript code that's called
within the iframe. That doesn't seem to work well with the JavaScript DOM.
<https://github.com/defunkt/facebox>
More generally, how would I close a generic modal that embeds an iframe with the code to close it inside the iframe. (sorry for the tounge(or eye) twisting)
Here's my example:
I have a facebox with something like this:
```
jQuery.facebox("stuff goes here <iframe src="example.php"...." more stuff"); //opens the modal(works great)
```
Then INSIDE the iframe, I want to call `jQuery(document).trigger('close.facebox');`. It only seems to work if I call it on the parent page or on the modal page, but not in the actual iframe. Is there a way I can make it close by calling it within an iframe `example.php`?
Edit: I was asking how I can access the parent frame from inside an iframe with jQuery to oversimplify the question. | You can't modify an element that "belongs" to the parent page from within that popup page. As far as I know you will have to issue your hide code from the parent. You could always have your code inside the dialog do something like this:
```
parent.$("#dialog").hide();
```
I think that's what you're asking... | Here's what worked for me:
My page has an IFRAME inside a DIV, the DIV is what facebox is supposed to fadeIn and fadeOut. The SRC of the IFRAME is a page that has a link on it that looks like this:
```
<a href="#" onclick="parent.close_QM_facebox()">close this facebox modal</a>
```
In the HEAD of the page that contains the DIV and IFRAME (NOT the page called into the IFRAME), I have the JavaScript function "close\_QM\_facebox()" that looks like this:
```
function close_QM_facebox() { jQuery(document).trigger('close.facebox'); }
```
That's all. Not tested cross-browser or in production yet. I spent hours Googling this problem and trying everything from changing single quotes to double quotes, document-dot-this and parent-dot-that, window.frames['whatever'], and this one-line function does it. If you're trying to trigger the function from the page that is called into the IFRAME, you have to be sure to use **parent**.close\_QM\_facebox(). Hope this helps.
BTW, see lines 47 and 49 of facebox.js ver 1.2 - this solution was right there in the commented-out "Usage" section of the .js file itself. I copied & pasted line 49 into my function, didn't change a thing except un-commenting it :) | Closing a modal box with an iframe inside the iframe | [
"",
"javascript",
"modal-dialog",
""
] |
I am writing C extensions, and I'd like to make the signature of my methods visible for introspection.
```
static PyObject* foo(PyObject *self, PyObject *args) {
/* blabla [...] */
}
PyDoc_STRVAR(
foo_doc,
"Great example function\n"
"Arguments: (timeout, flags=None)\n"
"Doc blahblah doc doc doc.");
static PyMethodDef methods[] = {
{"foo", foo, METH_VARARGS, foo_doc},
{NULL},
};
PyMODINIT_FUNC init_myexample(void) {
(void) Py_InitModule3("_myexample", methods, "a simple example module");
}
```
Now if (after building it...) I load the module and look at its help:
```
>>> import _myexample
>>> help(_myexample)
```
I will get:
```
Help on module _myexample:
NAME
_myexample - a simple example module
FILE
/path/to/module/_myexample.so
FUNCTIONS
foo(...)
Great example function
Arguments: (timeout, flags=None)
Doc blahblah doc doc doc.
```
I would like to be even more specific and be able to replace **foo(...)** by **foo(timeout, flags=None)**
Can I do this? How? | My usual approach to finding out about things like this is: "use the source".
Basically, I would presume that the standard modules of python would use such a feature when available. Looking at the source ([for example here](http://svn.python.org/view/python/branches/release26-maint/Modules/fcntlmodule.c?revision=72888&view=markup)) should help, but in fact even the standard modules add the prototype after the automatic output. Like this:
```
torsten@pulsar:~$ python2.6
>>> import fcntl
>>> help(fcntl.flock)
flock(...)
flock(fd, operation)
Perform the lock operation op on file descriptor fd. See the Unix [...]
```
So as upstream is not using such a feature, I would assume it is not there. :-)
Okay, I just checked current python3k sources and this is still the case. That signature is generated in `pydoc.py` in the python sources here: [pydoc.py](http://svn.python.org/view/python/trunk/Lib/pydoc.py?revision=73529&view=markup). Relevant excerpt starting in line 1260:
```
if inspect.isfunction(object):
args, varargs, varkw, defaults = inspect.getargspec(object)
...
else:
argspec = '(...)'
```
inspect.isfunction checks if the object the documentation is requested for is a Python function. But C implemented functions are considered builtins, therefore you will always get `name(...)` as the output. | It has been 7 years **but you can include the signature for C-extension function and classes**.
Python itself uses the [Argument Clinic](https://docs.python.org/3/howto/clinic.html) to dynamically generate signatures. Then some mechanics create a `__text_signature__` and this can be introspected (for example with `help`). @MartijnPieters explained this process quite well in [this answer](https://stackoverflow.com/a/25847066/5393381).
You may actually get the argument clinic from python and do it in a dynamic fashion but I prefer the manual way: Adding the signature to the docstring:
In your case:
```
PyDoc_STRVAR(
foo_doc,
"foo(timeout, flags=None, /)\n"
"--\n"
"\n"
"Great example function\n"
"Arguments: (timeout, flags=None)\n"
"Doc blahblah doc doc doc.");
```
I made heavy use of this in my package: [`iteration_utilities/src`](https://github.com/MSeifert04/iteration_utilities/tree/master/src/iteration_utilities/_iteration_utilities). So to demonstrate that it works I use one of the C-extension functions exposed by this package:
```
>>> from iteration_utilities import minmax
>>> help(minmax)
Help on built-in function minmax in module iteration_utilities._cfuncs:
minmax(iterable, /, key, default)
Computes the minimum and maximum values in one-pass using only
``1.5*len(iterable)`` comparisons. Recipe based on the snippet
of Raymond Hettinger ([0]_) but significantly modified.
Parameters
----------
iterable : iterable
The `iterable` for which to calculate the minimum and maximum.
[...]
```
The docstring for this function is defined [this file](https://github.com/MSeifert04/iteration_utilities/blob/v0.10.1/src/iteration_utilities/_iteration_utilities/docsfunctions.h).
It is important to realize that this **isn't possible for python < 3.4** and you need to follow some rules:
* You need to include `--\n\n` after the signature definition line.
* The signature must be in the first line of the docstring.
* The signature must be valid, i.e. `foo(a, b=1, c)` fails because it's not possible to define positional arguments after arguments with default.
* You can only provide one signature. So it doesn't work if you use something like:
```
foo(a)
foo(x, a, b)
--
Narrative documentation
``` | Python C extension: method signatures for documentation? | [
"",
"python",
"documentation",
"python-c-api",
""
] |
I am having issues integrating junit with a working ant build.xml file. My test class is in the same directory as my source classes. As I am learning how to use ant, I simply want to compile all the source and the test classes.
I am using eclipse and the junit test classes work fine when execute through eclipse. Which means the classpath is set up correctly (at least from eclipse's point of view) with junit.jar and ant-junit-1.7.0.jar, although I am not sure if the latter jar is absolutely necessary.
My folder structure is:
src/code/MyClass.java
src/code/MyClassTest.java
and the ant file contain only one target, just to compile MyClass and MyClassTest, I do not include any junit tasks at the moment, and do not mind to have the build files in the same directory as well:
```
<target name="compile" >
<javac srcdir="src/" />
</target>
```
Ant worked fine until I added MyClassTest.java (Junit with annotations) in my folder. The output is:
```
[javac] C:\....\src\MyClassTest.java:3: package org.junit does not exist
cannot find symbol
```
My thinking is that somehow Ant can't find the junit libraries. Since I do not specify a classpath, I was assuming that Ant would look at the same location as the source files to find to find what it needs...How can I tell Ant that the junit jars are right there?
Any ideas, are really appreciated.
Regards | Jars have to be specified by name, not by directory. Use:
```
<javac srcdir="src/" classpath="pathtojar/junit.jar"/>
```
Where "pathtojar" is the path containing the junit jar. | Yes, you do have to specify a CLASSPATH.
It's been a long time since I last used Eclipse, but I believe you have to right click on the project root, choose "Properties", and add the JUnit JAR to the CLASSPATH.
Ant has to know the CLASSPATH when you use it to build. Have a look at their <path> stuff.
Here's how I do it:
```
<path id="production.class.path">
<pathelement location="${production.classes}"/>
<pathelement location="${production.resources}"/>
<fileset dir="${production.lib}">
<include name="**/*.jar"/>
<exclude name="**/junit*.jar"/>
<exclude name="**/*test*.jar"/>
</fileset>
</path>
<path id="test.class.path">
<path refid="production.class.path"/>
<pathelement location="${test.classes}"/>
<pathelement location="${test.resources}"/>
<fileset dir="${test.lib}">
<include name="**/junit*.jar"/>
<include name="**/*test*.jar"/>
</fileset>
</path>
``` | problem compiling a junit test class with ant | [
"",
"java",
"eclipse",
"ant",
"junit",
""
] |
I have an application that loads assemblies and looks for types that are subclasses of a class C1 defined in another assembly A1 that the application references. I've defined a type T in A1 that is a subclass of C1 but when I load A1 using Assembly.Load(...) then call t.IsSubclassOf(typeof(C1)) on an instance of T I get false. I've noticed that there are 2 instances of the assembly A1 in the current appdomain and t.IsSubclassOf(C1) works if I grab the type C1 out of one of the instances but not both. I don't quite understand this behavior, can anyone explain? Futhermore how can I fix my app so that this works whether load A1 or some other assembly to look for subtypes of C1? | In order for the CLR to uniquely identify types, it includes assembly information in the type identifier. Your problem is that the CLR is classifying the two instances of A1 as different assemblies, hence you are effectively executing:
```
A1::T1.IsSubClassOf(A1Copy::C1) // No relationship between A1 and A1Copy
```
... instead of:
```
A1::T1.IsSubClassOf(A1::C1)
```
An assembly is uniquely identified by its name, version, culture, and public key. Please check these values (via [`Assembly.GetName()`](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getname.aspx)) from both assembly instances in the app-domain; I suspect there is a mismatch in one of the attributes, which is causing the CLR to load the offending assembly. | Yeah, i just built two projects with this, I defined in one project parent and child classes:
```
namespace ClassLibrary1
{
public class Parent
{
public string name;
}
public class Child : Parent
{
}
}
```
and then tried to load the information:
```
{
Type parent = typeof(Parent);
Type c1 = typeof(Child);
bool isChild1 = (c1.IsSubclassOf(parent).ToString());
Assembly a = Assembly.Load(File.ReadAllBytes("ClassLibrary1.dll"));
Type c2 = a.GetType(c1.FullName);
bool isChild2 = (c2.IsSubclassOf(parent).ToString());
}
```
and I got
isChild1 being true and isChild2 being false.
Checking out this link by Suzanne Cook on Loading Contexts provided some more light:
<http://blogs.msdn.com/suzcook/archive/2003/06/13/57180.aspx> | Type.IsSubclassOf does not behave as expected | [
"",
"c#",
".net-3.5",
"assemblies",
"appdomain",
""
] |
I recently ran up against a problem that challenged my programming abilities, and it was a very accidental infinite loop. I had rewritten some code to dry it up and changed a function that was being repeatedly called by the exact methods it called; an elementary issue, certainly. Apache decided to solve the problem by crashing, and the log noted nothing but "spawned child process". The problem was that I never actually finished debugging the issue that day, it cropped up in the afternoon, and had to solve it today.
In the end, my solution was simple: log the logic manually and see what happened. The problem was immediately apparent when I had a log file consisting of two unique lines, followed by two lines that were repeated some two hundred times apiece.
What are some ways to protect ourselves against infinite loops? And, when that fails (and it will), what's the fastest way to track it down? Is it indeed the log file that is most effective, or something else?
Your answer could be language agnostic if it were a best practice, but I'd rather stick with PHP specific techniques and code. | You could use a debugger such as xdebug, and walk through your code that you suspect contains the infinite loop.
[Xdebug - Debugger and Profiler Tool for PHP](http://www.xdebug.org)
You can also set
```
max_execution_time
```
to limit the time the infinite loop will burn before crashing. | I sometimes find the safest method is to incorporate a limit check in the loop. The type of loop construct doesn't matter. In this example I chose a 'while' statement:
```
$max_loop_iterations = 10000;
$i=0;
$test=true;
while ($test) {
if ($i++ == $max_loop_iterations) {
echo "too many iterations...";
break;
}
...
}
```
A reasonable value for $max\_loop\_iterations might be based upon:
* a constant value set at runtime
* a computed value based upon the size of an input
* or perhaps a computed value based upon relative runtime speed
Hope this helps,
- N | How to debug, and protect against, infinite loops in PHP? | [
"",
"php",
"apache",
"debugging",
"infinite-loop",
""
] |
I have following structure
```
<div onClick="javascript:Myfunction('value');">
<div title="Mytitle"> </div>
</div>
```
Can I access in the javascript Myfunction, the title of the inner div.
There are no ids here. | If you do not want to change the html code then you can use this.
```
function MyFunction ( elem )
{
var child = jQuery(elem).find("div");
alert ( child.attr("title") );
}
<div onclick="MyFunction(this);">
<div title="Mytitle"> </div>
</div>
```
Otherwise try this
```
$(document).ready ( function () {
$('#divMain').click(function() {
var titleElem = $(this).find("div");
alert ( titleElem.attr("title") );
});
});
<div id="divMain" style="width: 100px; height: 100px;">
<div title="Mytitle">
</div>
</div>
``` | If it's the only div with the title you can use this selector:
```
$('div[title]')
```
The easiest solution would to add a class or id to the div with `onClick` defined (I suggest moving onlick to JS code as well)
```
<div class="myClass">
<div title="MyTitle"> ... </div>
</div>
```
And in JS:
```
$('.myClass').click(function() {
MyFunction('value');
});
```
Then you can find inner div with
```
$('.myClass div')
``` | Accessing a inner div value in javascript, with no ids to help | [
"",
"javascript",
"jquery",
""
] |
I'm using PHP 5.3.0 and have encountered something that might be a bug (in which case I'll report it) or might be me - so I'm asking to make sure.
When running this code:
```
<?php
ini_set('upload_max_filesize', '10M');
echo ini_get('upload_max_filesize'), ", " , ini_get('post_max_size')
```
I end up with:
```
2M, 8M
```
This is despite my php.ini setting these higher:
```
upload_max_filesize = 10M
post_max_size = 10M
```
(occuring only once)
Because the error occurs after setting the value as well as it being set in php.ini I'm inclined to think it's a bug. Can anyone confirm or point me where I'm going wrong?
**Update**: Looks like restarting Apache fixed this - I always thought it didn't need to be restarted if you changed php.ini. | You can't use [shorthand notation](http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes) to set configuration values outside of PHP.ini. I assume it's falling back to 2MB as the compiled default when confronted with a bad value.
On the other hand, I don't think `upload_max_filesize` could be set using `ini_set()`. The ["official" list](http://www.php.net/manual/en/ini.list.php) states that it is `PHP_INI_PERDIR` . | Are you using a shared hosting provider? It could be master settings overriding anything you're trying to change. Have you tried adding those into your .htaccess?
```
php_value upload_max_filesize 10M
php_value post_max_size 10M
``` | Changing upload_max_filesize on PHP | [
"",
"php",
"upload",
""
] |
I'm trying to convert a current Django project in development to use zc.buildout So far, I've got all the bits figured except for Haystack figured out.
The Haystack source is available on GitHub, but I don't want to force users to install git. A suitable alternative seems to be to fetch a tarball from [here](http://github.com/toastdriven/django-haystack/tarball/master)
That tarball contains a setuptools setup.py, and it seems like it should be so *easy* to get buildout to install it. Halp! | It seems they've fixed the package to work from the tarball. James' fork is not working right now, but you can use the same recipe passing it the standard url:
```
[haystack]
recipe = collective.recipe.distutils
url = http://github.com/toastdriven/django-haystack/tarball/master
```
This worked for me and is 100% hack free. | I figured this one out, without posting it to PyPI. (There is no actually tagged release version of django-haystack, so posting to to PyPI seems unclean. It's something the maintainer should and probably will handle better themselves.)
The relevant section is as follows:
```
[haystack]
recipe = collective.recipe.distutils
url = http://github.com/ephelon/django-haystack/tarball/master
```
I had to create a fork of the project to remove `zip_safe=False` from setup.py. Once I'd done that the above works flawlessly, even the redirect sent by the above url. | How to install django-haystack using buildout | [
"",
"python",
"buildout",
""
] |
I have this
```
var checkBox = e.target;
var tableRow = checkBox.parentNode.parentNode;
var key = tableRow.attributes["key"];
var aKey = key.nodeValue;
```
at this point aKey = "[123]"
what the best way to return 123 as an int in javascript? note that aKey could just as likely be "[5555555555555555555]" so I can't just grab characters 2-4. I need something more dynamic. I was hoping this could be parsed as like a one element array, but I see this is not correct. This is really a dataKey for an Infragisitcs grid. Their support is not very helpful.
Thanks for any advice.
Cheers,
~ck in San Diego | I think if it's always in that format, you could safely use `eval()` to turn it into an array and get the first element.
```
var aKey = eval( key.nodeValue );
var nKey = aKey[0];
``` | As long as your key fits into an int without overflowing, you could do
```
numericKey = parseInt(aKey.substr(1, aKey.length - 2))
``` | Parse a JavaScript string best practice | [
"",
"javascript",
"arrays",
"string",
"parsing",
""
] |
I writing a SP that accepts as parameters column to sort and direction.
I don't want to use dynamic SQL.
The problem is with setting the direction parameter.
This is the partial code:
```
SET @OrderByColumn = 'AddedDate'
SET @OrderDirection = 1;
…
ORDER BY
CASE WHEN @OrderByColumn = 'AddedDate' THEN CONVERT(varchar(50), AddedDate)
WHEN @OrderByColumn = 'Visible' THEN CONVERT(varchar(2), Visible)
WHEN @OrderByColumn = 'AddedBy' THEN AddedBy
WHEN @OrderByColumn = 'Title' THEN Title
END
``` | You could have two near-identical `ORDER BY` items, one `ASC` and one `DESC`, and extend your `CASE` statement to make one or other of them always equal a single value:
```
ORDER BY
CASE WHEN @OrderDirection = 0 THEN 1
ELSE
CASE WHEN @OrderByColumn = 'AddedDate' THEN CONVERT(varchar(50), AddedDate)
WHEN @OrderByColumn = 'Visible' THEN CONVERT(varchar(2), Visible)
WHEN @OrderByColumn = 'AddedBy' THEN AddedBy
WHEN @OrderByColumn = 'Title' THEN Title
END
END ASC,
CASE WHEN @OrderDirection = 1 THEN 1
ELSE
CASE WHEN @OrderByColumn = 'AddedDate' THEN CONVERT(varchar(50), AddedDate)
WHEN @OrderByColumn = 'Visible' THEN CONVERT(varchar(2), Visible)
WHEN @OrderByColumn = 'AddedBy' THEN AddedBy
WHEN @OrderByColumn = 'Title' THEN Title
END
END DESC
``` | You can simplify the CASE by using ROW\_NUMBER which sorts your data and effectively converts it into a handy integer format. Especially since the question is tagged SQL Server 2005
This also expands easily enough to deal with secondary and tertiary sorts
I've used multiplier to again simplify the actual select statement and reduce the chance of RBAR evaluation in the ORDER BY
```
DECLARE @multiplier int;
SELECT @multiplier = CASE @Direction WHEN 1 THEN -1 ELSE 1 END;
SELECT
Columns you actually want
FROM
(
SELECT
Columns you actually want,
ROW_NUMBER() OVER (ORDER BY AddedDate) AS AddedDateSort,
ROW_NUMBER() OVER (ORDER BY Visible) AS VisibleSort,
ROW_NUMBER() OVER (ORDER BY AddedBy) AS AddedBySort,
ROW_NUMBER() OVER (ORDER BY Title) AS TitleSort
FROM
myTable
WHERE
MyFilters...
) foo
ORDER BY
CASE @OrderByColumn
WHEN 'AddedDate' THEN AddedDateSort
WHEN 'Visible' THEN VisibleSort
WHEN 'AddedBy' THEN AddedBySort
WHEN 'Title' THEN TitleSort
END * @multiplier;
``` | Dynamic order direction | [
"",
"sql",
"sql-server",
"stored-procedures",
"sql-order-by",
"case",
""
] |
In a stored procedure (which has a date parameter named 'paramDate' ) I have a query like this one
```
select id, name
from customer
where period_aded = to_char(paramDate,'mm/yyyy')
```
will Oracle convert paramDate to string for each row?
I was sure that Oracle wouldn't but I was told that Oracle will.
In fact I thought that if the parameter of the function was constraint (not got a fierld nor a calculated value inside the query) the result should be allways the same, and that's why Oracle should perform this conversion only once.
Then I realized that I've sometimes executed DML sentences in several functions, and perhaps this could cause the resulting value to change, even if it does not change for each row.
This should mean that I should convert such values before I add them to the query.
Anyway, perhaps well 'known functions' (built in) are evaluated once, or even my functions would also be.
Anyway, again...
Will oracle execute that to\_char once or will Oracle do it for each row?
Thanks for your answers | I do not think this is generally the case, as it would prevent an index from being used.
At least for built-in functions, Oracle should be able to figure out that it could evaluate it only once. (For user-defined functions, see below).
Here is a case where an index is being used (and the function is not evaluated for every row):
```
SQL> select id from tbl_table where id > to_char(sysdate, 'YYYY');
--------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
--------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 35 | 140 | 1 (0)| 00:00:01 |
|* 1 | INDEX RANGE SCAN| SYS_C004274 | 35 | 140 | 1 (0)| 00:00:01 |
--------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
1 - access("ID">TO_NUMBER(TO_CHAR(SYSDATE@!,'YYYY')))
```
---
For user-defined functions check out this [article](http://www.inside-oracle-apex.com/caution-when-using-plsql-functions-in-sql-statement/). It mentions two ways to ensure
that your function gets called only once:
1. Since Oracle 10.2, you can define the function as DETERMINISTIC.
2. On older versions you can re-phrase it to use "scalar subquery caching":
SELECT COUNT(\*)
FROM EMPLOYEES
WHERE SALARY = (SELECT getValue(1) FROM DUAL); | The concern about to\_char does not ring a bell with me. However, in your pl/sql,
you could have
```
create or replace procedure ........
some_variable varchar2(128);
begin
some_variable := to_char(paramDate,'mm/yyyy');
-- and your query could read
select id, name from customer where period_aded = some_variable;
.
.
.
end;
/
```
Kt | Oracle performance using functions in where clause | [
"",
"sql",
"oracle",
"where-clause",
"performance",
""
] |
Is that even possible ?
Lets say that the code has a lot of scanf lines. Instead of manually running and adding values by hand when debugging, is it possible to "feed" stdin with data so that when the scanf starts reading, it will read the inputted data without any need to interact with the terminal. | Put the test lines into a file, and run the program like this:
```
myprogram < mytestlines.txt
```
Better than hacking your program to somehow do that itself.
When you're debugging the code, you can set up the debugger to run it with that command line. | To make your program a little more versatile, you might want to consider rewriting your program to use `fscanf`, `fprintf`, etc. so that it can already handle file IO as opposed to just console IO; then when you want to read from stdin or write to stdout, you would just do something along the lines of:
```
FILE *infile, *outfile;
if (use_console) {
infile = stdin;
outfile = stdout;
} else {
infile = fopen("intest.txt", "r");
outfile = fopen("output.txt", "w");
}
fscanf(infile, "%d", &x);
fprintf(outfile, "2*x is %d", 2*x);
```
Because how often do programs only handle stdin/stdout and not allow files? Especially if you end up using your program in shell scripts, it can be more explicit to specify input and outputs on the command line. | C/C++ add input to stdin from the program? | [
"",
"c++",
"c",
"input",
"stdin",
""
] |
hi i have a datagridview in a form... users by clicking the column name can sort the row data in that column either in ascending or descending orders... how is it possible to disable it? so that the data in rows of every columns stays in that order in which they were on the start of the form... thanks! | **Programmatically:**
YourDataColumn.SortMode = DataGridViewColumnSortMode.NotSortable;
**In the designer:**
1. Right click your DGV and select 'Edit Columns...' from the popup menu. The 'Edit Columns' dialog appears.
2. In the 'Edit Columns' dialog, update the SortMode property to 'NotSortable' for the column(s) you want to disable sorting on. | Like the other answers state, there is no global property on the DataGrid, you will have to set on each column individually.
```
for(int x = 0; x < dataGridView1.Columns/Count; x++)
dataGridView1.Columns[x].SortMode = DataGridViewColumnSortMode.NotSortable;
``` | c# datagridview datatable | [
"",
"c#",
"winforms",
""
] |
I'm trying to read an Excel (xlsx) file using the code shown below. I get an "External table is not in the expected format." error unless I have the file already open in Excel. In other words, I have to open the file in Excel first before I can read if from my C# program. The xlsx file is on a share on our network. How can I read the file without having to open it first?
Thanks
```
string sql = "SELECT * FROM [Sheet1$]";
string excelConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathname + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1;\"";
using (OleDbDataAdapter adaptor = new OleDbDataAdapter(sql, excelConnection)) {
DataSet ds = new DataSet();
adaptor.Fill(ds);
}
``` | "External table is not in the expected format." typically occurs when trying to use an Excel 2007 file with a connection string that uses: Microsoft.Jet.OLEDB.4.0 and Extended Properties=Excel 8.0
Using the following connection string seems to fix most problems.
```
public static string path = @"C:\src\RedirectApplication\RedirectApplication\301s.xlsx";
public static string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
``` | Thanks for this code :) I really appreciate it. Works for me.
```
public static string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
```
So if you have diff version of Excel file, get the file name, if its extension is *.xlsx*, use this:
```
Private Const connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
```
and if it is *.xls*, use:
```
Private Const connstring As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" + path + ";Extended Properties=""Excel 8.0;HDR=YES;"""
``` | Excel "External table is not in the expected format." | [
"",
"c#",
"excel-2007",
"xlsx",
"import-from-excel",
""
] |
I am using C++ hash\_map to store some C-style string pairs. And all keys should be unique for this case...
My problem is a serious memory leak when stress testing this over multiple runs.
When none of these keys in the test are not identical, there is no memory leak. But with identical keys its a different story...
The hash\_map (this is Google's [sparsehash](http://google-sparsehash.googlecode.com/svn/trunk/doc/sparse_hash_map.html) but it implements the SGI functions entirely)
```
sparse_hash_map<const char*, char *, hash<const char*>, eqstr> values;
```
I searched and could not find a function to replace a key/val pair that has an identical key.
```
values[k]=v;
```
will only add a new pair, even if the key is the same. (a behavior I think should be toggleable) - this is nothing but a hash\_map.insert()
So I have a function to check if the key exists, and if it does replace the val, and if not just add a new pair:
```
char *confFile::replaceOrStoreVal( char *k, char *v ) {
char *ret = NULL;
values.set_deleted_key(_DIST_KEY);
sparse_hash_map<const char*, char *, hash<const char*>, eqstr>::iterator it =
values.find(k);
if(it == values.end())
values[k] = v;
else {
// ret = it->second; // option 1
//it->second = v; // end option 1
//option 2
char *t = (char *) it->first;
ret = it->second;
values.erase( iter ); <--- seg fault here
free(t);
values[k] = v; // end option 2
}
return ret;
} ... and ret is later free()ed
```
initially pairs are added like this:
```
old = replaceOrStoreVal(recordname, value);
```
It crashes on the first duplicate key.
2 ways I have tried this. Option 1 results in a segfault on erase (something that also puzzles me). Option 2 just doesn't fix the problem, still have a memory leak. Maybe I am just doing this all wrong.
Yes, I know I could use C++ strings, but I don't want to. Trying to keep this real light, for an embedded system. Any help is appreciated... | You can change a value directly inside hash\_map through iterator:
```
ret = it->second;
it->second = v; // end option 2
}
```
It will be faster and safer solution.
You can also try another hash\_map method to erase by key, not by iterator:
```
size_type erase(const key_type& k)
``` | Seems like something strange is going on. I suspect you are misusing the hash\_map, as what you are doing should work. In fact, what you were doing originally should have worked.
ie.
```
values[k] = v;
```
Should replace what was already present with key "k" if it existed.
Might I suggest you replace the usage of Google's sparse\_hash\_map with the standard STL map? That way you can verify that your algorithm works.
Then, if you replace std::map with sparse\_hash\_map and it breaks, the problem is either with the sparse\_hash\_map, or the way you're using it. | trouble deleting keys/values on STL hash_map when duplicate keys | [
"",
"c++",
"stl",
"hashmap",
""
] |
I have a PHP web application built with CodeIgniter MVC framework. I wish to test various controller classes. I'm using [Toast](http://jensroland.com/projects/toast/) for unit testing. My controllers have no state, everything they process is either saved into session or passed to view to display. Creating a mock session object and testing whether that works properly is straightforward (just create a mock object and inject it with $controller->session = $mock).
What I don't know, is how to work with views. In CodeIgniter, views are loaded as:
```
$this->load->view($view_name, $vars, $return);
```
Since I don't want to alter CI code, I though I could create a mock Loader and replace the original. And here lies the problem, I cannot find a way to derive a new class from CI\_Loader.
If I don't include the system/libraries/Loader.php file, the class CI\_Loader is undefined and I cannot inherit from it:
```
class Loader_mock extends CI_Loader
```
If I do include the file (using require\_once), I get the error:
```
Cannot redeclare class CI_Loader
```
Looks like CI code itself does not use require\_once from whatever reason.
Does anyone here have experience with unit testing CodeIgniter powered applications?
**Edit:** I tried to inject a real loader object at run-time into a mock class, and redirect all calls and variables with \_\_call, \_\_set, \_\_get, \_\_isset and \_\_unset. But, it does not seem to work (I don't get any errors though, just no output, i.e. blank page from Toast). Here's the code:
```
class Loader_mock
{
public $real_loader;
public $varijable = array();
public function Loader_mock($real)
{
$this->real_loader = $real;
}
public function __call($name, $arguments)
{
return $this->real_loader->$name($arguments);
}
public function __set($name, $value)
{
return $this->real_loader->$name = $value;
}
public function __isset($name)
{
return isset($this->real_loader->$name);
}
public function __unset($name)
{
unset($this->loader->$name);
}
public function __get($name)
{
return $this->real_loader->$name;
}
public function view($view, $vars = array(), $return = FALSE)
{
$varijable = $vars;
}
}
``` | Alternatively, you could do this:
```
$CI =& get_instance();
$CI = load_class('Loader');
class MockLoader extends CI_Loader
{
function __construct()
{
parent::__construct();
}
}
```
Then in your controller do $this->load = new MockLoader(). | My current solution is to alter the CodeIgniter code to use require\_once instead of require. Here's the patch I'm going to send to CI developers in case someone needs to do the same until they accept it:
```
diff --git a/system/codeigniter/Common.php b/system/codeigniter/Common.php
--- a/system/codeigniter/Common.php
+++ b/system/codeigniter/Common.php
@@ -100,20 +100,20 @@ function &load_class($class, $instantiate = TRUE)
// folder we'll load the native class from the system/libraries folder.
if (file_exists(APPPATH.'libraries/'.config_item('subclass_prefix').$class.EXT))
{
- require(BASEPATH.'libraries/'.$class.EXT);
- require(APPPATH.'libraries/'.config_item('subclass_prefix').$class.EXT);
+ require_once(BASEPATH.'libraries/'.$class.EXT);
+ require_once(APPPATH.'libraries/'.config_item('subclass_prefix').$class.EXT);
$is_subclass = TRUE;
}
else
{
if (file_exists(APPPATH.'libraries/'.$class.EXT))
{
- require(APPPATH.'libraries/'.$class.EXT);
+ require_once(APPPATH.'libraries/'.$class.EXT);
$is_subclass = FALSE;
}
else
{
- require(BASEPATH.'libraries/'.$class.EXT);
+ require_once(BASEPATH.'libraries/'.$class.EXT);
$is_subclass = FALSE;
}
}
``` | How to test controllers with CodeIgniter? | [
"",
"php",
"codeigniter",
""
] |
I need to store a U.S. `$` dollar amount in a field of a Django model. What is the best model field type to use? I need to be able to have the user enter this value (with error checking, only want a number accurate to cents), format it for output to users in different places, and use it to calculate other numbers. | A [decimal field](https://docs.djangoproject.com/en/2.2/ref/models/fields/#decimalfield) is the right choice for the
currency value.
It will look something like:
```
credit = models.DecimalField(max_digits=6, decimal_places=2)
``` | The other answers are 100% right but aren't very practical as you'll still have to manually manage output, formatting etc.
I would suggest using [django-money](https://github.com/django-money/django-money):
```
from djmoney.models.fields import MoneyField
from django.db import models
def SomeModel(models.Model):
some_currency = MoneyField(
decimal_places=2,
default=0,
default_currency='USD',
max_digits=11,
)
```
Works automatically from templates:
```
{{ somemodel.some_currency }}
```
Output:
```
$123.00
```
It has a powerful backend via python-money and it's essentially a drop-in replacement for standard decimal fields. | What is the best django model field to use to represent a US dollar amount? | [
"",
"python",
"django",
"django-models",
"django-model-field",
""
] |
I am using DataSets for access to Sql Server 200x in a C# project. Our common practice is, in almost all tables, to not delete the record. Instead we have a field which simply holds a bit for whether the record is deleted. I can manually edit each table in the DataSet and make their select command include Where Deleted = 0 and the delete command be an update instead. However, this is tedious.
Is there any way to change the method that VS uses to generate the commands for the tableadaptor to add this functionality for them automatically?
Edit:
In effect, this would be some sort of way to customize the GenerateDBDirectMethods functionality. | I don't think you will be able to auto generate this using something like the SqlCommandBuilder.
Instead what you may be looking to do is utilize the fact that the strongly typed datasets and data adapters in the dataset auto generated code use partial classes and you should therefore be able to add some additional logic to a partial class which will override the default implementation.
For example you should be able to override the InitCommandCollection method on the generated data table adapter which you could then substitute in your Update isDeleted = 1, instead of the delete command.
You will have to write some smarts around this but it should help you. I would recommend having the table adapter check a list to see if the table name is within the list, if it is then you know you are dealing with a deleted column, if not then it's a deletable table record. | You could access your data through database views and do your filtering there.
Personally I do not like SQL commmands in DataSet definitions.
EDIT:
There is not a built-in possibility to do this AFAIK. You could make an VS add-in and invoke it on a context menu from Solution Explorer (right click on .xsd) or open DS and invoke add-in from main menu. The add in would then parse xsd and identify select and update text and make corrections. Probably this would be useful only right after generating the DS (drag drop from sql server).
For add.in look at:
* [Creating a Visual Studio.NET add-in to write SQL statements](https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-1045818.html)
* [Writing a Visual Studio 2005 & 2008 Add-In](http://www.codeproject.com/KB/macros/LineCounterAddin.aspx)
* [Tutorial : Creating Visual Studio Add-Ins](http://www.c-sharpcorner.com/UploadFile/mgold/AddIns11292005015631AM/AddIns.aspx)
I personally would go the DB way. Make views that do the filtering for you and add delete triggers on those views that would perform an update instead of delete. This way you are removing the burden to do that on application and make this the responsibility of the person that makes a physical DB model. This would be done once per table. On the contrary you probably have multiple points in code that deal with single table (multiple datasets that use the same db table). | How to auto-build custom commands in a DataSet based on non-"DELETE" deletion method? | [
"",
"c#",
".net",
"dataset",
""
] |
Is there a tool available that can scan code and check for possible null reference exceptions, i.e. where there is no code to check for null before calling a method / accessing a property? | ReSharper can do this. | Resharper will offer suggestions for when you might have accessed a member on an object that could be null.
In 4.0, "code-contracts" support this at compile time - for example, it will stop you passing a possible-null into a method that states it doesn't want one. | Is there a tool that can check for null reference exceptions? | [
"",
"c#",
"nullreferenceexception",
""
] |
I have a [Camel](http://camel.apache.org/) Route Definition written in Java DSL like this:
```
from(myEndpoint)
.throttle(200)
.to(myOtherEndpoint);
```
This connects my two endpoints using a Throttler which limits the message flow to 200 messages per second.
I'm looking for a way to change the maximumRequestCount / second during runtime.
So I need to somehow get to the Throttler instance which is called and change the property.
How can I access the Throttler? | Ok, I figured it out by myself ...
You need to define your Throttler instance yourself.
```
Throttler throttler = new Throttler(null, 200);
```
Then you can use it in your routes like this, because Throttler implements the Processor interface:
```
from(myEndpoint)
.process(throttler)
.to(myOtherEndpoint);
```
Any time you like you can change the properties of the throttler. | Yeah that is a neat solution.
In Camel 2.0 you can now navigate the runtime processors in the route and thus find any Throttlers and then be able to change it dynamically.
But we are also working on improving the JMX in Camel 2.1 so you can change throttler/delayer and the likes from JMX.
And maybe also improve the Navigate API so you can find in a one liner, eg maybe lookup by id if you provide an id in the route. Or by types so you can filter and only get the Throttlers etc. | How to change Processor properties during runtime using Camel? | [
"",
"java",
"apache-camel",
""
] |
I'm writing a set of PHP scripts that'll be run in some different setups, some of them shared hosting with magic quotes on (the horror). Without the ability to control PHP or Apache configuration, can I do anything in my scripts to disable PHP quotes at runtime?
It'd be better if the code didn't assume magic quotes are on, so that I can use the same scripts on different hosts that might or might not have magic quotes. | Only [*magic\_quoted\_runtime*](http://php.net/manual/en/info.configuration.php#ini.magic-quotes-runtime) can be disabled at runtime. But [*magic\_quotes\_gpc*](http://php.net/manual/en/info.configuration.php#ini.magic-quotes-gpc) can’t be disabled at runtime ([*PHP\_INI\_ALL*](http://php.net/configuration.changes.modes) changable until PHP 4.2.3, since then [*PHP\_INI\_PERDIR*](http://php.net/configuration.changes.modes)); you can only remove them:
```
if (get_magic_quotes_gpc()) {
$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
while (list($key, $val) = each($process)) {
foreach ($val as $k => $v) {
unset($process[$key][$k]);
if (is_array($v)) {
$process[$key][stripslashes($k)] = $v;
$process[] = &$process[$key][stripslashes($k)];
} else {
$process[$key][stripslashes($k)] = stripslashes($v);
}
}
}
unset($process);
}
```
For further information see [Disabling Magic Quotes](http://php.net/security.magicquotes.disabling). | Magic quotes cannot be disabled at runtime, but you can use a .htaccess file in the directory to disable it.
```
php_flag magic_quotes_gpc off
```
The only real advantage this has is you can put it once in a directory and it works for the whole directory and subdirectories. Really nice if you need this for an application you didn't write and need to get it to work without magic quotes. | How can I disable PHP magic quotes at runtime? | [
"",
"php",
"runtime",
"magic-quotes",
""
] |
I am working on a project where I use `mysql_fetch_assoc` to return an associative array.
However, I am puzzled as to why it would return `TRUE`
I have looked at the PHP manual page, and the only boolean value it should be returning is `FALSE`, and then only on a fail.
Although I am using a custom set of abstraction classes, it is *basically* doing this:
```
$result = mysql_query("SELECT * FROM table WHERE filename = 'test1.jpg'");
var_dump(mysql_fetch_assoc($result)); // bool(true)
```
Does anyone know why it would be returning `TRUE` instead of an array?
**Update**
Well, after trying a few things, I've determined its my library, as running the above code returns an associative array. I don't know why exactly it was returning `TRUE`, but for now, I am going to stop making things more complicated than they have to be (a problem of mine) and just use mysqli (thanks for the tip, Michael) instead of my own ActiveRecord classes, which apparently don't work.
Thanks! | Start using [mysqli\_query](https://www.php.net/manual/en/mysqli.query.php) mysqli\_fetch\_assoc, . The old version is soon to be outdated - the new one is better anyways. | I ran into the same thing. It was a stupid coding error on my part.
I started out with:
```
$result = mysql_query($someSql);
while($row = mysql_fetch_assoc($result)) {
// do stuff
}
```
which worked fine. Then I changed it to:
```
$result = mysql_query($someSql);
while($row = mysql_fetch_assoc($result) && $someCondition) {
// do stuff
}
```
This is interpreted as `$row = (mysql_fetch_assoc($result) && $someCondition)`, which means `$row` becomes `true` while there are rows left and the second condition is `true`.
What I meant to write was:
```
$result = mysql_query($someSql);
while(($row = mysql_fetch_assoc($result)) && $someCondition) {
// do stuff
}
``` | mysql_fetch_assoc() returning unexpected value | [
"",
"php",
"mysql",
""
] |
After I submit a form the position will return to the top of the window. Instead of going to the previous position.
Looking at using scrolltop to rememeber the positon or do you have a better idea?
I'm using stuff like PHP5, jQuery and MySQL. | Check this out:
```
<script type="text/javascript" src="der/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="der/jquery.cookie.js"></script>
<script type="text/javascript">
function get_position(){
var top_position = document.documentElement.scrollTop;
$.cookie('pos', top_position);
};
function set_position(){
var top_position = $.cookie('pos');
window.scrollTo(0,top_position)
$.cookie('pos', null);
};
</script>
</head>
<body onload="set_position();">
.
.
.
<form method="post" action="" onsubmit="return get_position();">
</form>
``` | First create an anchor in your page where you want the visitor to get to when they submit the form.
Then in your form action or redirect point to file with the anchor
e.g.
```
<div id="view_from_here" >.....
```
then
```
<form action="myfile.php#view_from_here" ....
``` | back button scroll position | [
"",
"php",
"jquery",
"forms",
"position",
""
] |
I am trying to do a simple JSON return but I am having issues I have the following below.
```
public JsonResult GetEventData()
{
var data = Event.Find(x => x.ID != 0);
return Json(data);
}
```
I get a HTTP 500 with the exception as shown in the title of this question. I also tried
```
var data = Event.All().ToList()
```
That gave the same problem.
Is this a bug or my implementation? | It seems that there are circular references in your object hierarchy which is not supported by the JSON serializer. Do you need all the columns? You could pick up only the properties you need in the view:
```
return Json(new
{
PropertyINeed1 = data.PropertyINeed1,
PropertyINeed2 = data.PropertyINeed2
});
```
This will make your JSON object lighter and easier to understand. If you have many properties, [AutoMapper](http://www.codeplex.com/AutoMapper) could be used to [automatically](http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/06/29/how-we-do-mvc-view-models.aspx) map between DTO objects and View objects. | I had the same problem and solved by `using Newtonsoft.Json;`
```
var list = JsonConvert.SerializeObject(model,
Formatting.None,
new JsonSerializerSettings() {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});
return Content(list, "application/json");
``` | A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'. | [
"",
"c#",
".net",
"json",
"entity-framework",
"subsonic",
""
] |
My C# coded application uses an Infragistics.Win.UltraWinGrid.UltraGrid to display some data. The data is basically a collection of computers. The application is able to filter these computers (like "Workstations", "Servers" etc) for viewing. This is how I filter:
```
private DataView FilterTableDataForViewing(DataTable originalTable, string filterString, UltraGrid viewGrid)
{
DataView dataView = new DataView(originalTable);
dataView.RowStateFilter = DataViewRowState.CurrentRows;
dataView.RowFilter = filterString;
DataTable filteredTable = dataView.ToTable(originalTable.TableName + "_" + dataView.RowFilter);
viewGrid.DataSource = filteredTable;
gridDiscoveryMain.DisplayLayout.ViewStyleBand = ViewStyleBand.OutlookGroupBy;
SetFlagImagesAndColumnWidthsOfDiscoveryGrid();
return dataView;
}
```
**Note that I set the table name to a potentially huge filter string.**
This is how I use the above method:
```
string filterString = "([Build] = '4.0' AND NOT([OS Plus Version] LIKE '%Server%'))";
filterString += " OR ([Build] = '4.10')";
filterString += " OR ([Build] = '4.90')";
filterString += " OR ([Build] = '5.0' AND NOT([OS Plus Version] LIKE '%Server%'))";
filterString += " OR ([Build] = '5.1')";
filterString += " OR ([Build] = '6.0' AND ";
filterString += "(NOT([OS Plus Version] LIKE '%Server%')) OR (NOT([OS] LIKE '%Server%')))";
FilterTableDataForViewing(dataSet.Tables["DiscoveryData"], filterString, gridDiscoveryMain);
```
Everything upto that point is fine. UltraGrids have a facility that allows you to choose which columns you want hidden and create new custom columns. When this facility is started an event of the UltraGrid called `BeforeColumnChooserDisplayed` is fired. Here's my handler:
```
private void gridDiscoveryMain_BeforeColumnChooserDisplayed(object sender, BeforeColumnChooserDisplayedEventArgs e)
{
if (gridDiscoveryMain.DataSource == null)
return;
e.Cancel = true;
gridDiscoveryMain.DisplayLayout.Override.RowSelectors = DefaultableBoolean.True;
gridDiscoveryMain.DisplayLayout.Override.RowSelectorHeaderStyle = RowSelectorHeaderStyle.ColumnChooserButton;
ShowCustomColumnChooserDialog();
this.customColumnChooserDialog.CurrentBand = e.Dialog.ColumnChooserControl.CurrentBand;
this.customColumnChooserDialog.ColumnChooserControl.Style = ColumnChooserStyle.AllColumnsWithCheckBoxes;
}
```
And here is the `ShowCustomColumnChooserDialog` method implementation:
```
private void ShowCustomColumnChooserDialog()
{
DataTable originalTable = GetUnderlyingDataSource(gridDiscoveryMain);
if (this.customColumnChooserDialog == null || this.customColumnChooserDialog.IsDisposed)
{
customColumnChooserDialog = new CustomColumnChooser(ManageColumnDeleted);
customColumnChooserDialog.Owner = Parent.FindForm();
customColumnChooserDialog.Grid = gridDiscoveryMain;
}
this.customColumnChooserDialog.Show();
}
```
customColumnChooserDialog is basically a form which adds a little extra to the Infragistics default one. The most important thing that it's code takes care of is this method:
```
private void InitializeBandsCombo( UltraGridBase grid )
{
this.ultraComboBandSelector.SetDataBinding( null, null );
if ( null == grid )
return;
// Create the data source that we can bind to UltraCombo for displaying
// list of bands. The datasource will have two columns. One that contains
// the instances of UltraGridBand and the other that contains the text
// representation of the bands.
UltraDataSource bandsUDS = new UltraDataSource( );
bandsUDS.Band.Columns.Add( "Band", typeof( UltraGridBand ) );
bandsUDS.Band.Columns.Add( "DisplayText", typeof( string ) );
foreach ( UltraGridBand band in grid.DisplayLayout.Bands )
{
if ( ! this.IsBandExcluded( band ) )
{
bandsUDS.Rows.Add( new object[] { band, band.Header.Caption } );
}
}
this.ultraComboBandSelector.DisplayMember = "DisplayText";
this.ultraComboBandSelector.ValueMember= "Band";
this.ultraComboBandSelector.SetDataBinding( bandsUDS, null );
// Hide the Band column.
this.ultraComboBandSelector.DisplayLayout.Bands[0].Columns["Band"].Hidden = true;
// Hide the column headers.
this.ultraComboBandSelector.DisplayLayout.Bands[0].ColHeadersVisible = false;
// Set some properties to improve the look & feel of the ultra combo.
this.ultraComboBandSelector.DropDownWidth = 0;
this.ultraComboBandSelector.DisplayLayout.Override.HotTrackRowAppearance.BackColor = Color.LightYellow;
this.ultraComboBandSelector.DisplayLayout.AutoFitStyle = AutoFitStyle.ResizeAllColumns;
this.ultraComboBandSelector.DisplayLayout.BorderStyle = UIElementBorderStyle.Solid;
this.ultraComboBandSelector.DisplayLayout.Appearance.BorderColor = SystemColors.Highlight;
}
```
If I step through the code, it's all cool until I exit the event handler (the point at which the control returns to the form). I get an ArgumentException thrown at me **only** when I try and show the CustomColumnChooser dialog from a grid that displays **filtered data**. Not the kind that shows the offending line in your code, but the type that brings up a "Microsoft .NET Framework" error message box that says "Unhandled exception has occurred in your application...". This means I can't trace what's causing it. The app doesn't fall apart after that, but the would-be CustomColumnChooser dialog comes up with the container containing nothing but a white background and a big red "X".
And the stack trace:
```
See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.
************** Exception Text **************
System.ArgumentException: Child list for field DiscoveryData_([Build] = '4 cannot be created.
at System.Windows.Forms.BindingContext.EnsureListManager(Object dataSource, String dataMember)
at System.Windows.Forms.BindingContext.EnsureListManager(Object dataSource, String dataMember)
at System.Windows.Forms.BindingContext.EnsureListManager(Object dataSource, String dataMember)
at System.Windows.Forms.BindingContext.EnsureListManager(Object dataSource, String dataMember)
at System.Windows.Forms.BindingContext.EnsureListManager(Object dataSource, String dataMember)
at System.Windows.Forms.BindingContext.EnsureListManager(Object dataSource, String dataMember)
at System.Windows.Forms.BindingContext.EnsureListManager(Object dataSource, String dataMember)
at System.Windows.Forms.BindingContext.get_Item(Object dataSource, String dataMember)
at Infragistics.Win.UltraWinGrid.UltraGridLayout.ListManagerUpdated(BindingManagerBase bindingManager)
at Infragistics.Win.UltraWinGrid.UltraGridLayout.ListManagerUpdated()
at Infragistics.Win.UltraWinGrid.UltraGridBase.Set_ListManager(Object newDataSource, String newDataMember)
at Infragistics.Win.UltraWinGrid.UltraGridBase.SetDataBindingHelper(Object dataSource, String dataMember, Boolean hideNewColumns, Boolean hideNewBands)
at Infragistics.Win.UltraWinGrid.UltraGridBase.SetDataBinding(Object dataSource, String dataMember, Boolean hideNewColumns, Boolean hideNewBands)
at Infragistics.Win.UltraWinGrid.UltraGridBase.SetDataBinding(Object dataSource, String dataMember, Boolean hideNewColumns)
at Infragistics.Win.UltraWinGrid.UltraGridBase.SetDataBinding(Object dataSource, String dataMember)
at Infragistics.Win.UltraWinGrid.UltraGridColumnChooser.CreateColumnChooserGridDataStructure()
at Infragistics.Win.UltraWinGrid.UltraGridColumnChooser.Initialize()
at Infragistics.Win.UltraWinGrid.UltraGridColumnChooser.VerifyInitialized()
at Infragistics.Win.UltraWinGrid.ColumnChooserGridCreationFilter.BeforeCreateChildElements(UIElement parent)
at Infragistics.Win.UIElement.VerifyChildElements(ControlUIElementBase controlElement, Boolean recursive)
at Infragistics.Win.UltraWinGrid.UltraGridUIElement.VerifyChildElements(ControlUIElementBase controlElement, Boolean recursive)
at Infragistics.Win.UIElement.VerifyChildElements(Boolean recursive)
at Infragistics.Win.UltraWinGrid.UltraGridUIElement.InternalInitializeRect(Boolean verify)
at Infragistics.Win.UltraWinGrid.UltraGridLayout.GetUIElement(Boolean verify, Boolean forceInitializeRect)
at Infragistics.Win.UltraWinGrid.UltraGrid.OnPaint(PaintEventArgs pe)
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
at System.Windows.Forms.Control.WmPaint(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
```
**Child list for field DiscoveryData([Build] = '4 cannot be created** is not very helpful. What does it really mean? | I'm not too well up on WinForms and have never used Infragistics Ultragrid. My guess would be that **Child list for field DiscoverData([Build] = '4** is thrown deep down in the framework in some of the data-binding code. It seems to be looking for child members of a class called **([Build] = '4** as it stops at the dot or period (.) in your string literal.
I try to avoid working with `DataSet`s and `DataView`s because of some of the crazy hoops they jump through.
Might be worth firing up Reflector and having a poke around `System.Windows.Forms.BindingContext` | Check you DataBindings.
The problem is often caused due to your binding path.
If you have something like this:
```
labelFirstName.DataBindings.Add("Text", "_Person.Info.FName", true, DataSourceUpdateMode.OnPropertyChanged);
```
you will probably have to update it to another Add-method overload:
```
labelFirstName.DataBindings.Add("Text", _Person.Info, "FName", true, DataSourceUpdateMode.OnPropertyChanged);
``` | What does "Child list for field ... cannot be created" mean? | [
"",
"c#",
"infragistics",
"system.data",
""
] |
I have 3 arrays coming from a webservice...
```
Countries : Consists of Key - Value
Regions : Consists of Id - Name - CountryCode(fk: countries)
Areas : Consists of Id - Name - CountryCode - RegionID(fk: regions)
```
(the fk is just showing that its the bit of information, foreign key, associating it to the previous array)
I'm stuck on what the best way (most optimal) is to link these together, LINQ Joining looks like a headache and I'm not sure about HashSets.
Any Ideas?
\*\*\* Additional;\* This will be stored in the application state as the APP as it needs to be refreshed once a day (which in my opinion is quicker to do by simply refreshing the app once a day than storing in a database and updating based on a date stamp. | I'm curious why you say that LINQ Joining looks like a headache: it is exactly what LINQ to Objects is for (querying your in-memory objects and providing services such as joins between those objects).
A potential downside in LINQ is performance overhead, but to be honest it hasn't turned up as a major problem for me yet.
The syntax is simply `from obj1 in source1 join obj2 in source2 on <conditional> select {obj1.prop, obj2.prop}`
This mirrors SQL pretty heavily, which was the intent.
(To use your example:
```
from a in Areas
join r in Regions
on a.RegionID equals r.Id
join c in Countries
on r.CountryCode equals c.Key
select new {c.Value, r.Name, a.Name, a.Id };
```
) | Can't you dump them into a [DataSet](http://msdn.microsoft.com/en-us/library/system.data.dataset.aspx)? It's a collection of [DataTables](http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx) that you can predefine [Relations](http://msdn.microsoft.com/en-us/library/system.data.datarelation.aspx) for.
```
private void CreateRelation()
{
// Get the DataColumn objects from two DataTable objects
// in a DataSet. Code to get the DataSet not shown here.
DataColumn parentColumn =
DataSet1.Tables["Customers"].Columns["CustID"];
DataColumn childColumn =
DataSet1.Tables["Orders"].Columns["CustID"];
// Create DataRelation.
DataRelation relCustOrder;
relCustOrder = new DataRelation("CustomersOrders",
parentColumn, childColumn);
// Add the relation to the DataSet.
DataSet1.Relations.Add(relCustOrder);
}
``` | Optimal Way to Link Multiple Arrays in C# ASP.net | [
"",
"c#",
"asp.net-mvc",
".net-3.5",
"c#-3.0",
""
] |
I want to access some .NET assemblies written in C# from Python code.
A little research showed I have two choices:
* [IronPython](http://www.codeplex.com/IronPython) with .NET interface capability/support built-in
* Python with the [Python .NET](https://github.com/pythonnet/pythonnet) package
What are the trade-offs between both solutions? | If you want to mainly base your code on the .NET framework, I'd highly recommend IronPython vs Python.NET. IronPython is pretty much native .NET - so it just works great when integrating with other .NET langauges.
Python.NET is good if you want to just integrate one or two components from .NET into a standard python application.
There are notable differences when using IronPython - but most of them are fairly subtle. Python.NET uses the standard CPython runtime, so [this Wiki page](http://ironpython.codeplex.com/Wiki/View.aspx?title=IPy1.0.xCPyDifferences&referringTitle=Home) is a relevant discussion of the differences between the two implementations. The largest differences occur in the cost of exceptions - so some of the standard python libraries don't perform as well in IronPython due to their implementation. | While agreeing with the answers given by Reed Copsey and Alex Martelli, I'd like to point out one further difference - the Global Interpreter Lock (GIL). While IronPython doesn't have the limitations of the GIL, CPython does - so it would appear that for those applications where the GIL is a bottleneck, say in certain multicore scenarios, IronPython has an advantage over Python.NET.
From the Python.NET documentation:
> **Important Note for embedders:** Python
> is not free-threaded and uses a global
> interpreter lock to allow
> multi-threaded applications to
> interact safely with the Python
> interpreter. Much more information
> about this is available in the Python
> C API documentation on the
> `www.python.org` Website.
>
> When embedding Python in a managed
> application, you have to manage the
> GIL in just the same way you would
> when embedding Python in a C or C++
> application.
>
> Before interacting with any of the
> objects or APIs provided by the
> `Python.Runtime` namespace, calling code
> must have acquired the Python global
> interpreter lock by calling the
> `PythonEngine.AcquireLock` method. The
> only exception to this rule is the
> `PythonEngine.Initialize` method, which
> may be called at startup without
> having acquired the GIL.
>
> When finished using Python APIs,
> managed code must call a corresponding
> `PythonEngine.ReleaseLock` to release
> the GIL and allow other threads to use
> Python.
>
> The `AcquireLock` and `ReleaseLock`
> methods are thin wrappers over the
> unmanaged `PyGILState_Ensure` and
> `PyGILState_Release` functions from the
> Python API, and the documentation for
> those APIs applies to the managed
> versions.
Another issue is IDE support. CPython probably has better IDE support at present than IronPython - so this may be a factor in the choosing of one over the other. | IronPython vs. Python .NET | [
"",
"python",
".net",
"ironpython",
"cpython",
"python.net",
""
] |
Can someone tell me which one is more efficient between `List<int>` and `int[]`. Because I am working on a project and as you might know efficiency is way so important concern now.
If you added some introductory note to your post, it'd be great tho :) | ```
(list should be resizable) ? List<int> : int[]
```
`List<int>` is a wrapper for `int[]` that resizes as needed. With JIT inlining, they should perform *almost* identically, but the JIT will have an easier time edging out the extra performance from `int[]` because it's a CLI primitive with dedicated IL instructions. | Just for the fun of it, I ran this:
```
int cap = 100000;
Stopwatch sw1 = new Stopwatch();
sw1.Start();
int[] ix = new int[cap];
for (int x = 0; x < cap; x++)
{
ix[x] = 1;
}
sw1.Stop();
Stopwatch sw2 = new Stopwatch();
sw2.Start();
List<int> iy = new List<int>(cap);
for (int y = 0; y < cap; y++)
{
iy.Add(y);
}
sw2.Stop();
Console.WriteLine(cap.ToString() + " int[]=" + sw1.ElapsedTicks.ToString());
Console.WriteLine(cap.ToString() + " List<int>=" + sw2.ElapsedTicks.ToString());
Console.ReadKey();
```
And got this:
```
100000 int[]=1796542
100000 List=2517922
```
I tried it in elapsed milliseconds and got 0 and 1 respectively. Clearly the int[] is way faster, but unless you're talking huge arrays, I'd say it is just nominal. | Which one is more efficient : List<int> or int[] | [
"",
"c#",
"list",
""
] |
Let's say I had a table full of records that I wanted to pull random records from. However, I want certain rows in that table to appear more often than others (and which ones vary by user). What's the best way to go about this, using SQL?
The only way I can think of is to create a temporary table, fill it with the rows I want to be more common, and then pad it with other randomly selected rows from the table. Is there a better way? | One way I can think of is to create another column in the table which is a rolling sum of your weights, then pull your records by generating a random number between 0 and the total of all your weights, and pull the row with the highest rolling sum value less than the random number.
For example, if you had four rows with the following weights:
```
+---+--------+------------+
|row| weight | rollingsum |
+---+--------+------------+
| a | 3 | 3 |
| b | 3 | 6 |
| c | 4 | 10 |
| d | 1 | 11 |
+---+--------+------------+
```
Then, choose a random number `n` between 0 and 11, inclusive, and return row `a` if `0<=n<3`, `b` if `3<=n<6`, and so on.
Here are some links on generating rolling sums:
<http://dev.mysql.com/tech-resources/articles/rolling_sums_in_mysql.html>
<http://dev.mysql.com/tech-resources/articles/rolling_sums_in_mysql_followup.html> | I don't know that it can be done very easily with SQL alone. With T-SQL or similar, you could write a loop to duplicate rows, or you can use the SQL to generate the *instructions* for doing the row duplication instead.
I don't know your probability model, but you could use an approach like this to achieve the latter. Given these table definitions:
```
RowSource
---------
RowID
UserRowProbability
------------------
UserId
RowId
FrequencyMultiplier
```
You could write a query like this (SQL Server specific):
```
SELECT TOP 100 rs.RowId, urp.FrequencyMultiplier
FROM RowSource rs
LEFT JOIN UserRowProbability urp ON rs.RowId = urp.RowId
ORDER BY ISNULL(urp.FrequencyMultiplier, 1) DESC, NEWID()
```
This would take care of selecting a random set of rows as well as how many should be repeated. Then, in your application logic, you could do the row duplication and shuffle the results. | Pulling items out of a DB with weighted chance | [
"",
"sql",
"database",
"temp-tables",
""
] |
I am working on porting a Java codebase to Cocoa/Objective-C for use on desktop Mac OS X. The Java code has *lots* and *lots* of methods with checked exceptions like:
```
double asNumber() throws FooException {
...
}
```
What's the best way to represent these in Objective-C? Exceptions or error out-parameters?
```
- (CGFloat)asNumber {
... // possibly [FooException raise:format:];
}
```
or
```
- (CGFloat)asNumberError:(NSError **)outError {
...
}
```
I have the sense that out-errors are generally the better solution for Objective-C, but as you can see... a lot of methods like the one above will be quite awkward-looking. And again, there are *lots* of these.
Of course keep in mind that since these are *checked* exceptions in Java, I will need to add either `@try` blocks or `if (*outError) {...}` checks wherever these methods are called (*lots* of places).
I recall hearing that while entering `@try` blocks was once expensive in Objective-C, it is cheap in 64-bit or SL or some other new env (don't recall exactly). I am not at all concerned about backwards compatibility, so i am *definitely* willing to design only for the new hotness. | You should **definitely avoid exceptions** for things like parsing numbers from strings. In Objective-C, exceptions represent programmer error, not user input error, or even unavailable files. (Part of the reason is that exception handling is always more costly and complex than more "conventional" error handling. Regardless of the fact that [entering `@try` blocks is "zero cost" in 64-bit](http://developer.apple.com/ReleaseNotes/Cocoa/RN-ObjectiveC/index.html#//apple_ref/doc/uid/TP40004309-DontLinkElementID_11), it's still slow whenever an exception is actually raised.) Of course, you're allowed to use exceptions as you like, but it's not the Cocoa way, and you'll find yourself at odds with other Objective-C code. People who use your code will be incredibly annoyed that you throw exceptions in cases that should just result in an error.
From [Apple's own docs](http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocExceptionHandling.html):
> *"In many environments, use of exceptions is fairly commonplace. For example, you might throw an exception to signal that a routine could not execute normally—such as when a file is missing or data could not be parsed correctly. Exceptions are resource-intensive in Objective-C. You should not use exceptions for general flow-control, or simply to signify errors. Instead you should use the return value of a method or function to indicate that an error has occurred, and provide information about the problem in an error object."*
Look at how built-in Cocoa classes handle errors like this. For example, [NSString](http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/) has methods like `-floatValue` that return 0 if it fails. A better solution for your particular situation might be how [NSScanner](http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSScanner_Class/) does it, such as in `-scanFloat:` — accept a pointer to the field where the result should be stored, and return `YES` or `NO` based on whether the parse was successful.
Aside from Obejctive-C convention and best practices, NSError is much more robust and flexibly than NSException, and allows the caller to effectively ignore the problem if they want to. I suggest reading through the [Error Handling Programming Guide For Cocoa](http://developer.apple.com/documentation/Cocoa/Conceptual/ErrorHandlingCocoa/). **Note:** If you accept an `NSError**` param, I strongly suggest you also design to allow the client to pass `NULL` if they don't want to receive any error information. Every Cocoa class I'm aware of does this for errors, including NSString.
Although the ported code may end up looking totally different from the Java code, recognize that it will be used by Objective-C code, not the same clients of the Java equivalent. Definitely match the idioms of the language. The port will not be a mirror image of the Java code, but it will be much more correct (for Objective-C) as a result. | In Cocoa, exceptions are really only supposed to be used for "programming errors;" the philosophy is to let the app catch them, give the user the option to save what they're doing, and quit. For one thing, not all frameworks or code paths may be 100% exception-safe, so this can be the only safe course of action. For errors that can be anticipated and recovered from, you should use NSError, typically via an out-parameter. | When porting Java code to ObjC, how best to represent checked exceptions? | [
"",
"java",
"objective-c",
"cocoa",
"macos",
"porting",
""
] |
The code below works great. It prints out items in a MySQL database as an HTML table. However, the database has entries where the first column (the variable "site") is blank. How can I have this table exclude rows / entries where "site" is blank?
```
$result=mysql_query("SHOW TABLES FROM database LIKE '$find'")
or die(mysql_error());
if(mysql_num_rows($result)>0){
while($table=mysql_fetch_row($result)){
print "<p class=\"topic\">$table[0]</p>\n";
$r=mysql_query("SELECT * , itemsa - itemsb AS itemstotal FROM `$table[0]` ORDER BY itemstotal DESC");
print "<table class=\"navbar\">\n";
while($row=mysql_fetch_array($r)){
$itemstotal = $row['itemsa'] - $row['itemsb'];
print "<tr>";
print "<td class='sitename'>".'<a type="amzn" category="books" class="links2">'.$row['site'].'</a>'."</td>";
print "<td class='class1'>".'<span class="class1_count" id="class1_count'.$row['id'].'">'.number_format($itemstotal).'</span>'."</td>";
print "<td class='selector'>".'<span class="button" id="button'.$row['id'].'">'.'<a href="javascript:;" class="cell1" id="'.$row['id'].'">'.Select.'</a>'.'</span>'."</td>";
}
print "</tr>\n";
}
print "</table>\n";
}
else{
print "";
}
``` | Add a where clause to the SQL query.
```
WHERE `site` <> ''
or
WHERE `site` != ''
```
should work.
However, if you want the rows where site is blank for other PHP options, it would be better to filter out the blank sites in the PHP and not the MySQL query. | Just put the following before the `print` calls in your `while` loop:
```
if (trim($row['site']) == '') {
// skip output of this row if site is empty
continue;
}
``` | PHP - Excluding blank rows when printing a table | [
"",
"php",
""
] |
If i create a control on the fly, as below
```
private void button10_Click(object sender, EventArgs e)
{
CheckedListBox CheckedListBox1 = new CheckedListBox();
CheckedListBox1.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(224)), ((System.Byte)(192)));
CheckedListBox1.ItemHeight = 16;
CheckedListBox1.Location = new System.Drawing.Point(12, 313);
CheckedListBox1.Name = "CheckedListBox1";
CheckedListBox1.Size = new System.Drawing.Size(168, 244);
CheckedListBox1.TabIndex = 0;
Controls.Add(CheckedListBox1);
Button button12 = new Button();
button12.Location = new Point(900, 500);
button12.Size = new Size(75, 23);
button12.Click += new System.EventHandler(button12_Click);
button12.Name = "button12";
button12.Text = "Toggle All";
Controls.Add(button12);
}
```
what is the best way to reference that control from a function outside of the local scope? would it be best creating a static class to somehow hold a reference to the control that can be accessed outside the local scope or is there a findcontrol function for winforms ( i think findcontrol is just for web).
i want
```
private void button12_Click(object sender, EventArgs e)
{
for (int i = 0; i <= (CheckedListBox1.Items.Count - 1); i++)
{
if (CheckedListBox1.GetItemCheckState(i) == CheckState.Checked)
{
CheckedListBox1.SetItemCheckState(i, CheckState.Indeterminate);
}
else if (CheckedListBox1.GetItemCheckState(i) == CheckState.Indeterminate)
{
CheckedListBox1.SetItemCheckState(i, CheckState.Checked);
}
}
}
```
to be able to work but im going wrong because of scope? pls help a newbie
thanks | I'm assuming the two functions *button12\_Click* and *button10\_Click* are members of a From class. In this case, your should make your *CheckListBox1* and *button12* members of the From class. That way, the button12\_Click will be able to reference the controls you will have created.
```
public partial class Form1 : Form
{
CheckedListBox CheckedListBox1 = null;
Button button12 = null;
private void button10_Click(object sender, EventArgs e)
{
CheckedListBox1 = new CheckedListBox();
CheckedListBox1.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(224)), ((System.Byte)(192)));
CheckedListBox1.ItemHeight = 16;
CheckedListBox1.Location = new System.Drawing.Point(12, 313);
CheckedListBox1.Name = "CheckedListBox1";
CheckedListBox1.Size = new System.Drawing.Size(168, 244);
CheckedListBox1.TabIndex = 0;
Controls.Add(CheckedListBox1);
button12 = new Button();
button12.Location = new Point(900, 500);
button12.Size = new Size(75, 23);
button12.Click += new System.EventHandler(button12_Click);
button12.Name = "button12";
button12.Text = "Toggle All";
Controls.Add(button12);
}
private void button12_Click(object sender, EventArgs e)
{
for (int i = 0; i <= (CheckedListBox1.Items.Count - 1); i++)
{
if (CheckedListBox1.GetItemCheckState(i) == CheckState.Checked)
{
CheckedListBox1.SetItemCheckState(i, CheckState.Indeterminate);
}
else if (CheckedListBox1.GetItemCheckState(i) == CheckState.Indeterminate)
{
CheckedListBox1.SetItemCheckState(i, CheckState.Checked);
}
}
}
}
``` | When there is only one `CheckedListBox` make it a class variable. But when you have always only one `CheckedListBox` - why do you create it dynamically? | Referencing a newly created control | [
"",
"c#",
"controls",
"scope",
""
] |
```
$modules = array(
'home' => 'home',
'login' => 'login',
'forum' => 'forum',
'topic' => 'topic',
'post' => 'post',
'profile' => 'profile',
'moderate' => 'moderate',
'search' => 'search',
'ucp' => 'usercp',
'ucc' => 'usercp',
'pm' => 'pm',
'members' => 'members',
'boardrules' => 'boardrules',
'groups' => 'groupcp',
'help' => 'help',
'misc' => 'misc',
'tags' => 'tags',
'attach' => 'attach'
);
if (in_array($modules, $_GET['module'])) {
include $_GET['module'].'.php';
}
```
gives:
```
Warning: in_array() [function.in-array]: Wrong datatype for second argument in d:\public_html\forte.php on line 24
```
What's wrong? | You've got the arguments mixed up - see [`in_array()`](http://php.net/in_array):
```
if (in_array($_GET['module'], $modules)) {
include $_GET['module'].'.php';
}
``` | wrong order of variable passed to [`in_array`](http://docs.php.net/in_array)
```
bool in_array ( mixed $needle , array $haystack [, bool $strict ] )
``` | Problem with array | [
"",
"php",
"arrays",
""
] |
Is there any linux command I could use to find out `JAVA_HOME` directory? I've tried print out the environment variables ("env") but I can't find the directory. | `echo $JAVA_HOME` will print the value if it's set. However, if you didn't set it manually in your startup scripts, it probably isn't set.
If you try `which java` and it doesn't find anything, Java may not be installed on your machine, or at least isn't in your path. Depending on which Linux distribution you have and whether or not you have root access, you can go to <http://www.java.com> to download the version you need. Then, you can set JAVA\_HOME to point to this directory. Remember, that this is just a convention and shouldn't be used to determine if java is installed or not. | On Linux you can run `$(dirname $(dirname $(readlink -f $(which javac))))`
On Mac you can run `$(dirname $(readlink $(which javac)))/java_home`
I'm not sure about windows but I imagine `where javac` would get you pretty close | JAVA_HOME directory in Linux | [
"",
"java",
"linux",
"directory",
""
] |
I am developing a quick app in C#. One thing that I want to do is the equivalent of Swing's (java) `pack()`. This is a call that allows me to say to a form (Frame in Java), resize yourself to the size of the sum of the components within yourself.
I have searched and searched (the components change dynamically so I cannot simply hardcode the form to the right size) but I cannot find the equivalent method in C#.
Does anyone know what it is called? | You don't even need write code in order to 'pack' the form. In the forms designer, set the form's `AutoSize` property to `true`, and set the `AutoSizeMode` property to `GrowAndShrink`, repeat this for any controls on the form which may also change size.
And voila!
At runtime (only), the form will dynamically resize itself to accommodate all the controls. If you want it to keep a little distance from the controls so that the controls won't 'stick' to the edges, you can set the `Padding` property (I'd recommend at least a value of 12,12,12,12). | Also in xaml:
```
<Window SizeToContent="WidthAndHeight" />
``` | Equivalent of Swing's pack in C# | [
"",
"c#",
"user-interface",
"swing",
""
] |
We're developing a web application that is going to be used by external clients on the internet. The browsers we're required to support are IE7+ and FF3+. One of our requirements is that we use AJAX wherever possible. Given this requirement I feel that we shouldn't have to cater for users without javascript enabled, however others in the team disagree.
My question is, if, in this day and age, we should be required to cater for users that don't have javascript enabled? | Coming back more than 10 years later, it's worth noting my first two bullet points have faded to insignificance, and the situation has improved marginally for the third (accessible browsers do better) and fourth (Google runs more js) as well.
---
There are a lot more users on the public internet who may have trouble with javascript than you might think:
* Mobile browsers (smartphones) often have very poor or buggy javascript implementations. These will often show up in statistics on the side of those that *do* support javascript, even though they in effect don't. This is getting better, but there are still lots of people stuck with old or slow android phones with very old versions of Chrome or bad webkit clones.
* Things like NoScript are becoming more popular, so you should at least have a nice initial page for those users.
* If your customer is in any way part of the U.S. Goverment, you are legally required to support screen readers, which typically don't do javascript, or don't do it well.
* Search engines will, *at best*, only run a limited set of your javascript. You want to work well enough without javascript to allow them to still index your site.
Of course, you need to know your audience. You might be doing work for a corporate intranet where you *know* that *everyone* has javascript (though even here I'd argue there's a growing trend where these sites are made available to teleworkers with unknown/unrestricted browsers). Or you might be building an app for the blind community where *no one* has it. In the case of the public internet, you can typically figure about 95% of your users will support it in some fashion (source cited by someone else in one of the links below). That number sounds pretty high, but it can be misleading; turn it around, and if you don't support javascript you're turning away 1 visitor in 20.
See these:
* <https://stackoverflow.com/questions/121108/how-many-people-disable-javascript>
* [https://stackoverflow.com/questions/822872/do-web-sites-really-need-to-cater-for-browsers-that-dont-have-javascript-enabled>](https://stackoverflow.com/questions/822872/do-web-sites-really-need-to-cater-for-browsers-that-dont-have-javascript-enabled%3E) | You should weigh the options and ask yourself:
1) what percentage of users will have javascript turned off. (according to [this site](http://www.w3schools.com/browsers/browsers_stats.asp), only 5% of the world has it turned off or not available.)
2) will those users be willing to turn it on
3) of those that aren't willing to turn it on, or switch to another browser or device that has javascript enabled, is the lost revenue more than the effort to build a separate non-javascript version?
Instinctively, I say most times the answer is no, don't waste the time building two sites. | Should your website work without JavaScript | [
"",
"javascript",
"browser",
""
] |
I am trying to make use of the yahoo exceptional performance rule : [avoiding duplicate script](http://developer.yahoo.com/performance/rules.html#js_dupes)
To do so i would like to be able to know whether or not a script was already added to the page before injecting it in the page. It looks like i can't figure what has been added in asp.net code behind unless i have a scriptmanager added to the page. but i would like to avoid using asp.net AJAX. From the description of the rule, it looks like it is something possible in php though.
Assuming that i can't do the check in my code behind, i was considering using jQuery $.getString function but it doesn't check before fetching the script. If i was to choose the javascript file, would i have to parse the whole http response in order to figure out which script was loaded on the page? | If the page is registering the scripts with the ASP.NET Page.ClientScript Register APIs then you can use Page.ClientScript.IsClientScriptIncludeRegistered. On the other hand, if you are using those APIs you don't really need to call it, since it already ensures only one of each is registered.
<http://msdn.microsoft.com/en/us/library/system.web.ui.clientscriptmanager.isclientscriptincluderegistered.aspx>
If the page just has regular ole script elements statically in the markup, and you need to detect if a script is loaded on the client side, you will have to get all the script elements on the page and look at their .src values. The thing with that is that some browsers automatically resolve that url to a full path, not just the one you declared. So, you can account for that in various ways -- you can just search for the end of the string being the script you want, or you can cause the url you want to compare with to also be resolved by setting it onto a dynamically created script element (which you never add to the DOM but is still resolved for you).
This is just off the top of my head, sorry if I get something wrong:
```
var s = document.createElement("script");
s.src = "foo.js";
var loaded, scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].src === s.src) {
loaded = true;
break;
}
}
if (loaded) {
// this script is already loaded
// assuming you dont have multiple copies in different locations
}
``` | You don't need to use any client-side scripting to do this... you can do this in your code behind using the ClientScriptManager without needing to make use of ASP.NET AJAX (I think you're confusing [ClientScriptManager](http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.aspx) with [ScriptManager](http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.aspx)\*) in your control/page just use:
```
ClientScript.RegisterClientScriptInclude("some-script", "myScript.js");
```
or from your user controls:
```
Page.ClientScript.RegisterClientScriptInclude("some-script", "myScript.js");
```
This will use the key "some-script" & only register one copy of the script on the page.
\*To be clear I think the confusion is arrising from the difference between these:
* [ClientScriptManager](http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.aspx) if a server-side helper class which is used to manage client side scripts (in other words its whole purpose is to do exactly what you are trying to do). It is accessed via the Page's [ClientScript](http://msdn.microsoft.com/en-us/library/system.web.ui.page.clientscript.aspx) property.
* [ScriptManager](http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.aspx) is a *Control* used to aid client side Ajax scripting in ASP.NET AJAX
(hell I even confused myself & gave the wrong example code initially) | removing duplicate script from page | [
"",
"asp.net",
"javascript",
"code-behind",
""
] |
Using jQuery what's the way to get all elements of a queried set EXCEPT the first. I forget offhand. | You can do:
```
$(selector).not(':first');
```
Or:
```
$('selector:not(:first)');
``` | I believe you are refering to the [NOT selector](http://docs.jquery.com/Selectors/not) . | Using jQuery what's the way to get all elements of a queried set EXCEPT the first. | [
"",
"javascript",
"jquery",
"set",
""
] |
Is there a way to get the available arguments for a PHP function?
Example: I want to call `function1($arg1, $arg2=null)`. How can I find out, before calling the function, the number of arguments this function takes, and, if it's possible, what arguments?
As you can see, I am dynamically calling functions. | [ReflectionFunction](http://www.php.net/manual/en/language.oop5.reflection.php#language.oop5.reflection.reflectionfunction) | You can use the following functions from inside the function that is being called to determine how many arguments were passed and to get their values. I'm not sure how you would check what arguments a function expects.
[func\_num\_args()](http://www.php.net/manual/en/function.func-num-args.php)
[func\_get\_arg()](http://www.php.net/manual/en/function.func-get-arg.php)
[func\_get\_args](http://php.net/manual/en/function.func-get-args.php) | How can I get the list of available arguments for a PHP function? | [
"",
"php",
""
] |
I'm working on a PHP web application with PostgreSQL. All of the SQL queries are being called from the PHP code. I've seen no Views, Functions or Stored Procedures. From what I've learned, it's always better to use these database subroutines since they are stored in the database with the advantages:
* Encapsulation
* Abstraction
* Access rights (limited to DB Admin) and responsibility
* Avoid compilation
I think I read something about performance improvements too. I really don't see why the team hasn't used these yet. In this particular case, I would like to know, from experience, is there any good reason to NOT use them?
Mostly when there are so many "SELECT" queries along the code, why not use Views?
I am planning on refactoring the code and start coding the subroutines on the DB Server. I would like to know opinions in favor or against this. The project is rather big (many tables), and expects lots of data to be stored. The amount of data you would have in a social network with some more stuff in it, so yeah, pretty big. | I. Views offer encapsulation, but if not carefully designed they can slow down the application. Use with caution.
II. Use functions if needed, no reason to put them in if they are unneeded.
III. Stored Procedures are a godsend, use them everywhere there is a static query!!
In response to the views vs. queries, try to use views with Stored Procedure's, the Stored Procedure's will mitigate some of the performance hit taken with ***most*** views. | In my opinion, views and stored procedures are usually just extra trouble with little benefit.
I have written and worked with a bunch of different web apps, though none with bazillions of users. The ones with stored procedures are awkward. The ones with ad-hoc SQL queries are plenty fast (use placeholders and other best practices to avoid SQL injection). My favorite use database abstraction (ORM) so your code deals with PHP classes and objects rather than directly with the database. I have increasingly been turning to the symfony framework for that.
Also: in general you should not optimize for performance prematurely. Optimize for good fast development now (no stored procedures). After it's working, benchmark your app, find the bottlenecks, and optimize them. You just waste time and make complexity when you try to optimize from the start. | PHP and Databases: Views, Functions and Stored Procedures performance | [
"",
"php",
"database-design",
"postgresql",
""
] |
Say,is the following possible:
```
textNode.appendChild(elementNode);
```
`elementNode` refers to those with `nodeType` set to 1
`textNode` refers to those with `nodeType` set to 2
It's not easy to produce.
The reason I ask this is that I find a function that adds a cite link to the end of a quotation:
```
function displayCitations() {
var quotes = document.getElementsByTagName("blockquote");
for (var i=0; i<quotes.length; i++) {
if (!quotes[i].getAttribute("cite")) continue;
var url = quotes[i].getAttribute("cite");
var quoteChildren = quotes[i].getElementsByTagName('*');
if (quoteChildren.length < 1) continue;
var elem = quoteChildren[quoteChildren.length - 1];
var link = document.createElement("a");
var link_text = document.createTextNode("source");
link.appendChild(link_text);
link.setAttribute("href",url);
var superscript = document.createElement("sup");
superscript.appendChild(link);
elem.appendChild(superscript);
}
}
```
**see the last line "`elem.appendChild(superscript);`" where `elem` can be a `textNode`?**
I think the reason it's difficult to prove it because it's hard to get access to a specified `textNode`. Have anyone any way to achieve that? | No, text nodes are always leafs. Instead you must add new nodes to the text node's parent - making them siblings of the text node.
## EDIT
Here's an example where I attempt to add a child to a text node.
```
<div id="test">my only child is this text node</div>
<script type="text/javascript">
var div = document.getElementById( 'test' );
var textNode = div.childNodes[0];
var superscript = document.createElement("sup");
superscript.text = 'test';
textNode.appendChild( superscript );
</script>
```
Firefox gives the error
> uncaught exception: Node cannot be
> inserted at the specified point in the
> hierarchy
> (NS\_ERROR\_DOM\_HIERARCHY\_REQUEST\_ERR) | I don't think so; I'm fairly certain that something like
```
<div>this is some <a href="...">text</a> with an element inside it.</div>
```
ends up being:
```
<div>
<textnode/>
<a>
<textnode/>
</a>
<textnode/>
</div>
```
I don't believe textNodes can have children.
If I had to guess, I'd think that the result of adding a child node to a text node would be to add the element to the text node's parent instead, but I've not tested that at all. | can a textNode have a childNode which is an elementNode? | [
"",
"javascript",
"dom",
""
] |
I need to add the current year as a variable in an SQL statement, how can I retrieve the current year using SQL?
i.e.
```
BETWEEN
TO_DATE('01/01/**currentYear** 00:00:00', 'DD/MM/YYYY HH24:MI:SS')
AND
TO_DATE('31/12/**currentYear** 23:59:59', 'DD/MM/YYYY HH24:MI:SS')
``` | Using to\_char:
```
select to_char(sysdate, 'YYYY') from dual;
```
In your example you can use something like:
```
BETWEEN trunc(sysdate, 'YEAR')
AND add_months(trunc(sysdate, 'YEAR'), 12)-1/24/60/60;
```
The comparison values are exactly what you request:
```
select trunc(sysdate, 'YEAR') begin_year
, add_months(trunc(sysdate, 'YEAR'), 12)-1/24/60/60 last_second_year
from dual;
BEGIN_YEAR LAST_SECOND_YEAR
----------- ----------------
01/01/2009 31/12/2009
``` | Another option is:
```
SELECT *
FROM TABLE
WHERE EXTRACT( YEAR FROM date_field) = EXTRACT(YEAR FROM sysdate)
``` | How do I get the current year using SQL on Oracle? | [
"",
"sql",
"oracle",
"date",
""
] |
What is the best method to detect xml in JavaScript
e.g. is it possible to detect the mime type of a document - particularly if it is text/xml in JavaScript.
this needs to work in Chrome.
thanks,
Josh | If you are using `XMLHttpRequest` to get this data, then you can simply check for the `Content-Type` header using the `getResponseHeader` method (granted that the server sends the appropriate headers).
```
var getFile = function(address, responseHandler) {
var req = new XMLHttpRequest();
req.open('get', address, true);
req.onreadystatechange = responseHandler;
req.send(null);
}
var responseHandler = function(resp) {
if ( this.readyState < 4 ) { return; }
console.log(this.getResponseHeader("Content-Type"));
};
getFile("http://zebrakick.com/some/file", responseHandler);
```
(I seem to be using this code sample a lot...) | You can't determine what the mime-type is with Javascript. I would recommend doing checks on the data returned to see if it is valid XML before you try to parse it. (I'm only assuming what you're trying to do. I can provide a more rigid example if you clarify what your goal is.) | What is the best method to detect xml in JavaScript | [
"",
"javascript",
"google-chrome",
"mime-types",
""
] |
I always assumed that if I was using `Select(x=> ...)` in the context of LINQ to objects, then the new collection would be immediately created and remain static. I'm not quite sure WHY I assumed this, and its a very bad assumption but I did. I often use `.ToList()` elsewhere, but often not in this case.
This code demonstrates that even a simple 'Select' is subject to deferred execution :
```
var random = new Random();
var animals = new[] { "cat", "dog", "mouse" };
var randomNumberOfAnimals = animals.Select(x => Math.Floor(random.NextDouble() * 100) + " " + x + "s");
foreach (var i in randomNumberOfAnimals)
{
testContextInstance.WriteLine("There are " + i);
}
foreach (var i in randomNumberOfAnimals)
{
testContextInstance.WriteLine("And now, there are " + i);
}
```
This outputs the following (the random function is called every time the collection is iterated through):
```
There are 75 cats
There are 28 dogs
There are 62 mouses
And now, there are 78 cats
And now, there are 69 dogs
And now, there are 43 mouses
```
I have many places where I have an `IEnumerable<T>` as a member of a class. Often the results of a LINQ query are assigned to such an `IEnumerable<T>`. Normally for me, this does not cause issues, but I have recently found a few places in my code where it poses more than just a performance issue.
In trying to check for places where I had made this mistake I thought I could check to see if a particular `IEnumerable<T>` was of type `IQueryable`. This I thought would tell me if the collection was 'deferred' or not. It turns out that the enumerator created by the Select operator above is of type ``` System.Linq.Enumerable+WhereSelectArrayIterator``[System.String,System.String] ``` and not `IQueryable`.
I used [Reflector](http://www.red-gate.com/products/reflector/) to see what this interface inherited from, and it turns out not to inherit from anything that indicates it is 'LINQ' at all - so there is no way to test based upon the collection type.
I'm quite happy now putting `.ToArray()` everywhere now, but I'd like to have a mechanism to make sure this problem doesn't happen in future. Visual Studio seems to know how to do it because it gives a message about 'expanding the results view will evaluate the collection.'
The best I have come up with is :
```
bool deferred = !object.ReferenceEquals(randomNumberOfAnimals.First(),
randomNumberOfAnimals.First());
```
**Edit:** This only works if a new object is created with 'Select' and it not a generic solution. I'm not recommended it in any case though! It was a little tongue in the cheek of a solution. | Deferred execution of LINQ has trapped a lot of people, you're not alone.
The approach I've taken to avoiding this problem is as follows:
*Parameters to methods* - use `IEnumerable<T>` unless there's a need for a more specific interface.
*Local variables* - usually at the point where I create the LINQ, so I'll know whether lazy evaluation is possible.
*Class members* - never use `IEnumerable<T>`, always use `List<T>`. And always make them private.
*Properties* - use `IEnumerable<T>`, and convert for storage in the setter.
```
public IEnumerable<Person> People
{
get { return people; }
set { people = value.ToList(); }
}
private List<People> people;
```
While there are theoretical cases where this approach wouldn't work, I've not run into one yet, and I've been enthusiasticly using the LINQ extension methods since late Beta.
BTW: I'm curious why you use `ToArray();` instead of `ToList();` - to me, lists have a much nicer API, and there's (almost) no performance cost.
**Update**: A couple of commenters have rightly pointed out that arrays have a theoretical performance advantage, so I've amended my statement above to "... there's (almost) no performance cost."
**Update 2**: I wrote some code to do some micro-benchmarking of the difference in performance between Arrays and Lists. On my laptop, and in my specific benchmark, the difference is around 5ns (that's *nano*seconds) per access. I guess there are cases where saving 5ns per loop would be worthwhile ... but I've never come across one. I had to hike my test up to 100 *million* iterations before the runtime became long enough to accurately measure. | In general, I'd say you should try to avoid worrying about whether it's deferred.
There are advantages to the streaming execution nature of `IEnumerable<T>`. It is true - there are times that it's disadvantageous, but I'd recommend just always handling those (rare) times specifically - either go `ToList()` or `ToArray()` to convert it to a list or array as appropriate.
The rest of the time, it's better to just let it be deferred. Needing to frequently check this seems like a bigger design problem... | How to tell if an IEnumerable<T> is subject to deferred execution? | [
"",
"c#",
"linq",
"linq-to-entities",
""
] |
How can I implement the so called "repository pattern" that Rob Conery shows in [MVC Storefront][1] when I use two different generated linq codes? Do I need to implement a real repository pattern as Fredrik Normen discusses at [What purpose does the Repository Pattern have?](http://weblogs.asp.net/fredriknormen/archive/2008/04/24/what-purpose-does-the-repository-pattern-have.aspx)? The thing is that I want pass some of the nice features that LINQ provides from my "repository" so that I can use it later, so if not required I do not want to implement a real repository pattern as Fredrik discussed about.
Now to my problem. I have downloaded [dblinq ][3] which is a Linq Provider for MySql, Oracle and PostgreSQL. In my project I have now generated LINQ code for MySQL and SQL(microsoft). The problem is that they both need to generate classes with same names but with somewhat different content. Can I use somehow implement this with namespaces or something so that I can be able to use them both, as is the idea with the "repository pattern"?
Example for a Language table
SQl
```
[Table(Name="dbo.Language")]
public partial class Language : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _Id;
private string _Name;
private EntitySet<Book> _Books;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(int value);
partial void OnIdChanged();
partial void OnNameChanging(string value);
partial void OnNameChanged();
#endregion
public Language()
{
this._Books = new EntitySet<Book>(new Action<Book>(this.attach_Books), new Action<Book>(this.detach_Books));
OnCreated();
}
[Column(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[Column(Storage="_Name", DbType="NVarChar(100) NOT NULL", CanBeNull=false)]
public string Name
{
get
{
return this._Name;
}
set
{
if ((this._Name != value))
{
this.OnNameChanging(value);
this.SendPropertyChanging();
this._Name = value;
this.SendPropertyChanged("Name");
this.OnNameChanged();
}
}
}
[Association(Name="Language_Book", Storage="_Books", ThisKey="Id", OtherKey="Language")]
public EntitySet<Book> Books
{
get
{
return this._Books;
}
set
{
this._Books.Assign(value);
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private void attach_Books(Book entity)
{
this.SendPropertyChanging();
entity.Language1 = this;
}
private void detach_Books(Book entity)
{
this.SendPropertyChanging();
entity.Language1 = null;
}
}
```
MySQL
```
[Table(Name = "asp.Language")]
public partial class Language : INotifyPropertyChanged
{
#region INotifyPropertyChanged handling
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
#region int ID
private int _id;
[DebuggerNonUserCode]
[Column(Storage = "_id", Name = "Id", DbType = "int", IsPrimaryKey = true, IsDbGenerated = true, CanBeNull = false)]
public int ID
{
get
{
return _id;
}
set
{
if (value != _id)
{
_id = value;
OnPropertyChanged("ID");
}
}
}
#endregion
#region string Name
private string _name;
[DebuggerNonUserCode]
[Column(Storage = "_name", Name = "Name", DbType = "varchar(100)", CanBeNull = false)]
public string Name
{
get
{
return _name;
}
set
{
if (value != _name)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
#endregion
#region Children
private EntitySet<Book> _book;
[Association(Storage = "_book", OtherKey = "Language", ThisKey = "ID", Name = "Book_ibfk_1")]
[DebuggerNonUserCode]
public EntitySet<Book> Book
{
get
{
return _book;
}
set
{
_book = value;
}
}
#endregion
#region Attachement handlers
private void Book_Attach(Book entity)
{
entity.LanguageLanguage = this;
}
private void Book_Detach(Book entity)
{
entity.LanguageLanguage = null;
}
#endregion
#region ctor
public Language()
{
_book = new EntitySet<Book>(Book_Attach, Book_Detach);
}
#endregion
}
``` | Ideally, you would create each class only once and the database differences should be taken care of by the ORM (this is how NHibernate and Subsonic work).
If you really need different classes for each database, then yes, **you can have classes with the same name as long as they are in different namespaces**. If you are writing the code for the classes yourself this is very easy:
```
// C# sample
namespace MyCompany.MyApp.Entities.Oracle
{
public class MyClass
{
// ...
}
}
namespace MyCompany.MyApp.Entities.SqlServer
{
public class MyClass
{
// ...
}
}
```
If the classes are being auto-generated, you should check in the code generation tool how to specify namespaces. For example, with LINQ to SQL designer, you can specify the namespace in the table/class properties, or by editing the DBML file yourself. | This is a little offtopic but it might help.
If you're using Linq, repositories, MySql and MS Sql, and Rob Connery's advice you might as well use SubSonic 3 and make your life a little easier.
Here is a 5 minute demo: <http://subsonicproject.com/docs/Simple_Repo_5_Minute_Demo> | Reposity pattern using linq | [
"",
"c#",
"asp.net-mvc",
"linq",
"repository-pattern",
""
] |
I would like to ask for help with this, I wanted to check for a string
matching a decimal followed by a letter (15M, 15.3M, 15T or 15.3T) and
replace it with zeroes.
Like these:
15M -> 15000000
15.3M -> 15300000
15T -> 15000
15.3T -> 15300
I tried doing this with `str_replace` but can't get it right. Hope
someone can help me. | "T" could be "thousand" or "trillion", you know.
```
$s = "15.7T";
$factors = Array('T' => 1000, 'M' => 1000000, 'B' => 1000000000.);
$matches = Array();
if (0 < preg_match('/([0-9]+(?:\.[0-9]*)?)([TMB])/', $s, $matches)) {
print("$s -> " . $matches[1] * $factors[$matches[2]]);
}
```
prints:
```
15.7T -> 15700
```
edit:
Anchoring (makes any garbage on the front or back mean no match):
```
'/^(...)$/'
```
You may want to make whitespace allowed, however:
```
'/^\s*(...)\s*$/'
```
You can also use "\d" in place of "[0-9]:
```
'/(\d+(?:\.\d*)?)([TMB])/'
```
Case insensitivity:
```
'/.../i'
...
print("$s -> " . $matches[1] * $factors[strtoupper($matches[2])]);
```
Optional factor:
```
'/([0-9]+(?:\.[0-9]*)?)([TMB])?/'
$value = $matches[1];
$factor = isset($matches[2]) ? $factors[$matches[2]] : 1;
$output = $value * $factor;
```
Use printf to control output formatting:
```
print($value) -> 1.57E+10
printf("%f", $value); -> 15700000000.000000
printf("%.0f", $value); -> 15700000000
```
[Stephan202 recommended](https://stackoverflow.com/questions/1134973/regular-expressions-to-replace-money-pattern/1135023#1135023) a clever trick, put the "?" (optional) within the parens and you're guaranteed a match string, it just might be blank. Then you can use the blank as an array key to get the default value without having to test whether it matched or not.
Putting all that together:
```
$factors = Array('' => 1, 'T' => 1e3, 'M' => 1e6, 'B' => 1e9);
if (0 < preg_match('/^\s*(\d+(?:\.\d*)?)([TMB]?)\s*$/i', $s, $matches)) {
$value = $matches[1];
$factor = $factors[$matches[2]];
printf("'%s' -> %.0f", $s, $value * $factor);
}
``` | Alternative version which performs a conversion on all prices found:
```
$multiply = array('' => 1, 'T' => 1000, 'M' => 1000000);
function convert($matches) {
global $multiply;
return $matches[1] * $multiply[$matches[3]];
}
$text = '15M 15.3M 15.3T 15';
print(preg_replace_callback('/(\d+(\.\d+)?)(\w?)/', 'convert', $text));
``` | regular expressions to replace money pattern | [
"",
"php",
"regex",
""
] |
I'm a bit out of my depth here and I'm hoping this is actually possible.
I'd like to be able to call a function that would sort all the items in my list alphabetically.
I've been looking through the jQuery UI for sorting but that doesn't seem to be it. Any thoughts? | You do *not* need jQuery to do this...
```
function sortUnorderedList(ul, sortDescending) {
if(typeof ul == "string")
ul = document.getElementById(ul);
// Idiot-proof, remove if you want
if(!ul) {
alert("The UL object is null!");
return;
}
// Get the list items and setup an array for sorting
var lis = ul.getElementsByTagName("LI");
var vals = [];
// Populate the array
for(var i = 0, l = lis.length; i < l; i++)
vals.push(lis[i].innerHTML);
// Sort it
vals.sort();
// Sometimes you gotta DESC
if(sortDescending)
vals.reverse();
// Change the list on the page
for(var i = 0, l = lis.length; i < l; i++)
lis[i].innerHTML = vals[i];
}
```
Easy to use...
```
sortUnorderedList("ID_OF_LIST");
```
**[Live Demo →](http://jsfiddle.net/stodolaj/De8Ku/)** | Something like this:
```
var mylist = $('#myUL');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
```
From this page: <http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/>
Above code will sort your unordered list with id 'myUL'.
OR you can use a plugin like TinySort. <https://github.com/Sjeiti/TinySort> | How may I sort a list alphabetically using jQuery? | [
"",
"javascript",
"jquery",
"dom",
"sorting",
""
] |
I’m using `Zend_Filter_Input` to validate form data and want to customize the error messages, if a user does not enter a value. It is important that each field gets a different error message.
With Zend Framework 1.8.0 I used the following array for the “validator” parameter of `Zend_Filter_Input`:
```
$validators = array(
'salutation' => array(
new Zend_Validate_NotEmpty(),
Zend_Filter_Input::MESSAGES => array(
Zend_Validate_NotEmpty::IS_EMPTY => "Please enter a salutation"
)
),
/* ... */
);
```
Since I’ve upgraded to ZF 1.8.4, I always get the default message for empty fields (“You must give a non-empty value for field '%field%'”). Obviously `Zend_Filter_Input` does not call the `Zend_Validate_NotEmpty` validator anymore, if the field is empty.
Is there a way to change this behavior or another way to get customized “empty” messages for each field? | It seems that `Zend_Filter_Input` changed its behaviour when handling empty fields. Empty fields are never processed by rule validators. If a field is empty and allowEmpty is set to true, none of your validators are used. If the field is empty and allowEmpty is set to false, then the default message for empty values is set. Currently there is no way to customize this message for a specific field. | The behavior has not changed. This is a bug (<http://framework.zend.com/issues/browse/ZF-7394>) | Zend_Filter_Input and empty values | [
"",
"php",
"zend-framework",
"validation",
""
] |
im trying to pass back from a user control a list of strings that are part of an enum, like this:
```
<bni:products id="bnProducts" runat="server" ProductsList="First, Second, Third" />
```
and in the code behid do something like this:
```
public enum MS
{
First = 1,
Second,
Third
};
private MS[] _ProductList;
public MS[] ProductsList
{
get
{
return _ProductList;
}
set
{
_ProductList = how_to_turn_string_to_enum_list;
}
}
```
my problem is I dont know how to turn that string into a list of enum, so what should be "how\_to\_turn\_string\_to\_enum\_list"? or do you know of a better way to use enums in user controls? I really want to be able to pass a list that neat | `Enum.Parse` is the canonical way to parse a string to get an enum:
```
MS ms = (MS) Enum.Parse(typeof(MS), "First");
```
but you'll need to do the string splitting yourself.
However, your property is currently of type `MS[]` - the `value` variable in the setter won't be a string. I suspect you'll need to make your property a string, and parse it there, storing the results in a `MS[]`. For example:
```
private MS[] products;
public string ProductsList
{
get
{
return string.Join(", ", Array.ConvertAll(products, x => x.ToString()));
}
set
{
string[] names = value.Split(',');
products = names.Select(name => (MS) Enum.Parse(typeof(MS), name.Trim()))
.ToArray();
}
}
```
I don't know whether you'll need to expose the array itself directly - that depends on what you're trying to do. | This is a *short* solution, but it doesn't cover some very important things like localization and invalid inputs.
```
private static MS[] ConvertStringToEnumArray(string text)
{
string[] values = text.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
return Array.ConvertAll(values, value => (MS)Enum.Parse(typeof(MS), value));
}
``` | how do I create an enum from a string representation? c# | [
"",
"c#",
"asp.net",
"user-controls",
"enums",
""
] |
I need a way to count the number of pages of a PDF in PHP. I've done a bit of Googling and the only things I've found either utilize shell/bash scripts, perl, or other languages, but I need something in native PHP. Are there any libraries or examples of how to do this? | You can use the ImageMagick extension for PHP. ImageMagick understands PDF's, and you can use the `identify` command to extract the number of pages. The PHP function is [Imagick::identifyImage()](https://www.php.net/manual/en/function.imagick-identifyimage.php). | If using Linux, this is much faster than using `identify` to get the page count (especially with a high number of pages):
```
exec('/usr/bin/pdfinfo '.$tmpfname.' | awk \'/Pages/ {print $2}\'', $output);
```
You do need pdfinfo installed. | Count the number of pages in a PDF in only PHP | [
"",
"php",
"pdf",
""
] |
I'm trying to optimize the following. The code bellow does this :
If a = 0.775 and I need precision 2 dp then a => 0.78
Basically, if the last digit is 5, it rounds upwards the next digit, otherwise it doesn't.
My problem was that 0.45 doesnt round to 0.5 with 1 decimalpoint, as the value is saved as 0.44999999343.... and setprecision rounds it to 0.4.
Thats why setprecision is forced to be higher `setprecision(p+10)` and then if it really ends in a 5, add the small amount in order to round up correctly.
Once done, it compares a with string b and returns the result. The problem is, this function is called a few billion times, making the program craw. Any better ideas on how to rewrite / optimize this and what functions in the code are so heavy on the machine?
```
bool match(double a,string b,int p) { //p = precision no greater than 7dp
double t[] = {0.2, 0.02, 0.002, 0.0002, 0.00002, 0.000002, 0.0000002, 0.00000002};
stringstream buff;
string temp;
buff << setprecision(p+10) << setiosflags(ios_base::fixed) << a; // 10 decimal precision
buff >> temp;
if(temp[temp.size()-10] == '5') a += t[p]; // help to round upwards
ostringstream test;
test << setprecision(p) << setiosflags(ios_base::fixed) << a;
temp = test.str();
if(b.compare(temp) == 0) return true;
return false;
}
``` | I wrote an integer square root subroutine with nothing more than a couple dozen lines of ASM, with no API calls whatsoever - and it still could only do about 50 million SqRoots/second (this was about five years ago ...).
The point I'm making is that if you're going for billions of calls, even today's technology is going to choke.
But if you really want to make an effort to speed it up, remove as many API usages as humanly possible. This may require you to perform API tasks manually, instead of letting the libraries do it for you. Specifically, remove any type of stream operation. Those are slower than dirt in this context. You may really have to improvise there.
The only thing left to do after that is to replace as many lines of C++ as you can with custom ASM - but you'll have to be a perfectionist about it. Make sure you are taking full advantage of every CPU cycle and register - as well as every byte of CPU cache and stack space.
You may consider using integer values instead of floating-points, as these are far more ASM-friendly and much more efficient. You'd have to multiply the number by 10^7 (or 10^p, depending on how you decide to form your logic) to move the decimal all the way over to the right. Then you could safely convert the floating-point into a basic integer.
You'll have to rely on the computer hardware to do the rest.
`<--Microsoft Specific-->`
I'll also add that C++ identifiers (including static ones, as Donnie DeBoer mentioned) are directly accessible from ASM blocks nested into your C++ code. This makes inline ASM a breeze.
`<--End Microsoft Specific-->` | You could save some major cycles in your posted code by just making that double t[] static, so that it's not allocating it over and over. | C/C++ rounding up decimals with a certain precision, efficiently | [
"",
"c++",
"c",
"optimization",
"double",
"decimal",
""
] |
.NET has the [HttpWebRequest](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx) and [WebClient](http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx) classes for simulating a browser's requests.
I'd google it, but I'm not sure what keyword to use.
I want to write code that does does HTTP GETs and POSTs, along with cookies, in an applet or local `.jar` and gives me back the response in a text string or some other parseable structure. | [`HttpURLConnection`](http://java.sun.com/j2se/1.5.0/docs/api/javax/net/ssl/HttpsURLConnection.html) is Java's equivalent of `HttpWebRequest`.
```
URL iurl = new URL(url);
HttpURLConnection uc = (HttpURLConnection)iurl.openConnection();
uc.connect();
if (uc.getContentType().equalsIgnoreCase("image/jpeg"))
{
result = true;
}
``` | [Apache HTTPClient](http://hc.apache.org/httpclient-3.x/features.html) has equivalent functionality, though the APIs are not exactly the same. Oakland Software has a [table](http://www.oaklandsoftware.com/product_http/compare.html) comparing their commercial product with various alternatives, including the Apache product. Apache's own opinion of the built-in HttpUrlConnection (quoted from the above linked-to page) is:
> The jdk has the HttpUrlConnection
> which is limited and in many ways
> flawed.
Here's a link to the HTTPClient [tutorial](http://hc.apache.org/httpclient-3.x/tutorial.html). | Equivalent of .NET's WebClient and HttpWebRequest in Java? | [
"",
"java",
".net",
"language-comparisons",
""
] |
An object I mapped with hibernate has strange behavior. In order to know why the object behaves strangely, I need to know what makes that object dirty. Can somebody help and give me a hint?
The object is a Java class in a Java/Spring context. So I would prefer an answer targetting the Java platform.
Edit: I would like to gain access to the Hibernate dirty state and how it changes on an object attached to a session. I don't know how a piece of code would help.
As for the actual problem: inside a transaction managed by a Spring TransactionManager I do some (read) queries on Objects and without doing an explicit save on these Objects they are saved by the TransactionManager because Hibernate thinks that some of these (and not all) are dirty. Now I need to know why Hibernate thinks those Objects are dirty. | I would use an interceptor. The onFlushDirty method gets the current and previous state so you can compare them. Implement the Interceptor interface and extend EmptyInterceptor, overriding onFlushDirty. Then add an instance of that class using configuration.setInterceptor (Spring may require you to do this differently). You can also add an interceptor to the session rather than at startup.
[Here is the documentation on interceptors.](http://docs.jboss.org/hibernate/stable/core/reference/en/html/events.html) | 1. create a Test Case or similar, so you can reproduce the problem with a single click.
2. enable logging for org.hibernate check the logging for the string "dirty" (actually you don't need all of org.hibernate, but I don't know the exact logger.
3. Find to spots in the program, one where the entity is not dirty, one where it is dirty. Find the middle of the code between the two points, and put a logging statement there, for logging the isdirty Value. Continue with the strategy until you have reduced the code to a single line.
4. Check out the hibernate code. Find the code that does the dirty checking. Use a debugger to step through it. | How to know what made a hibernate persisted object dirty? | [
"",
"java",
"hibernate",
"debugging",
""
] |
I'm modifying a globalized web application which uses stored CultureInfo for each logged in user.
The client would like time data entry to be localized. Displaying is not a problem as the formatting is already available. However I need to detect if the current cultureinfo is for 24 hour time or am/pm so I can display the correct input boxes (not just a textfield).
My initial idea was to check the DateTimeInfo property of CultureInfo and see if the ShortTimePattern contained a capital H or a lower case h but this didn't feel robust enough for me.
Is there a better way? I've read the class properties of both but unless I'm missing something, I can't see any existing methods or properties. | I don't think there is a better way to obtain that information. The time pattern for a culture could contain anything (a user could even create a custom culture where the ShortTimePattern is "\hello" and then `DateTime.ToString()` would return "hello" for any time). In that case how could the framework determine if that CultureInfo is in 24-hour or 12-hour format?
So a "normal" `DateTimeFormatInfo.ShortTimePattern` will necessarily contain either a 'h' or a 'H', otherwise the hour will not be displayed. I think you can follow your initial idea and check for that. You can also check that the 'h' or 'H' is not escaped with a \ like in my "\hello" example because that would not represent the hour :) | Checking for 'H'/'h' seems more robust than checking for the AM/PM Designator.
A good example is en-gb:
The time format string is HH:mm and the AM/PM designators are set to AM/PM
Windows will display the time in 24h format!
This seems to be an inconsistent definition but checking for 'H' fixed my bug. | CultureInfo & DateTimeInfo: How to check if is 24 hour time? | [
"",
"c#",
"globalization",
"cultureinfo",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.