Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm looking for some guidance on the best way to authenticate to my WebService. Right now, I have a standard WebService on .NET 3.5, and a MVC website that sits on top of this WebService.
The MVC website uses OpenID to authenticate users, and during the development phase, we have simply been passing the user's OpenID Claimed Identifier to the WebService to authenticate. Obviously this is not what we will be releasing to the customer when we go live.
So my question is this: **What's the best way to authenticate to the WebService?**
Some of the API's I've played around with use Authentication Tokens. Another idea we had was to, upon connection to the WebService, pass the client an encryption key which they could use for all transfers.
I'm thinking out loud here, and again, any help is greatly appreciated! Thanks!
...
UPDATE: Right now I have created a custom SoapAuthenticationHeader which has an OpenIdURL property. This is used on all service calls to authenticate the user. The problem is two-fold:
1. If a hacker know's a user's OpenIdURL, they can easily gain access to the WebService.
2. The OpenIdURL is currently passed in plain-text.
So I could pass an encryption key to the client upon connection to the WebService, and have the client encrypt the OpenIdURL in the SoapAuthentication header. But I'm not sure about how to best go about that... | You might want to take a look at OAuth:
<http://oauth.net/>
(Use <http://oauth.net/code/> for coding.)
As it is geared specifically for this scenario (Open ID isn't, really).
There is another question on SA which asks about the best way to secure a web service, and Open ID and OAuth are both discussed:
[Web Service Authentication using OpenID](https://stackoverflow.com/questions/386973/web-service-authentication-using-openid) | This isn't really an answer, but I can't leave comments...
You say "I have a standard WebService on .NET 3.5, and a MVC website that sits on top of this WebService".
I might be way off base here, but the language implies that these two sit on the same server. If so, why can't you just share the users database and the cookie token?
James | Using OpenID with a WebService: Best way to authenticate? | [
"",
"c#",
"asp.net-mvc",
"web-services",
"openid",
"oauth",
""
] |
I am trying to execute the following query but I get the wrong results back.
```
foreach (var item in (from project in db.Projects
where project.Id == pProjectId
from task in project.Tasks
from taskItem in task.TaskItems
where taskItem.Velocities.Count() == 0 // not finished yet
select new
{
ProjectId = pProjectId,
PriorityId = task.Priorities.Id,
TaskId = task.Id,
ResourceId = taskItem.Resources.Id,
EstimatedDuration = taskItem.EstimatedDuration,
TaskItemId = taskItem.Id
}))
{
}
```
I am trying to generate objects from all the taskItems that don't have velocity related objects. The table structure is that every taskItem may have many velocities. Right before this call I give velocities to some of the items, yet they are not filtered by this where clause. Am I doing something obvious wrong?
Edit: I think (after staring at the code for a while) that I need to specify some kind of grouping. I don't actually require any of the Velocity record details, but rather just a count of them that relate to the taskItems | You could try moving the taskItem.Velocities.Count() inside the select new { }
Then do a select on the resultant list where the velicties count == 0 | You need to have joins to reflect the relationships, currently you are doing a cartesian (cross) join (i.e. all combinations of project, task and taskItem).
Try something like:
```
var res = from project in db.Projects
where project.Id == pProjectId
join task in project.Tasks on task.projectId equals project.projectId
join ttaskItem in task.TaskItems on taskItem.taskId equals task.taskId
where taskItem.Velocities.Count() == 0 // not finished yet
select new {
ProjectId = pProjectId,
PriorityId = task.Priorities.Id,
TaskId = task.Id,
ResourceId = taskItem.Resources.Id,
EstimatedDuration = taskItem.EstimatedDuration,
TaskItemId = taskItem.Id
};
``` | ado.net entity framework using count in a where clause | [
"",
"c#",
"linq",
"entity-framework",
".net-3.5",
"ado.net",
""
] |
I'm writing a simple tcp server application using sockets. As far as I know I can obtain the client's ip address and port after calling accept().
Now lets assume I have a banlist and I want to ban some ip addresses from my server. Is there a better way than accepting the connection and then dropping it?
Is there a way to get the client's ip and port before accepting the connection? If we have accept() why don't we have something like refuse()? Is there a way to refuse the connection or simply ignore connection attempt from a host? | The TCP implementation normally completes the TCP 3-way handshake before the user process even has access to the connection, and the `accept()` function merely gets the next connection off the queue. So it is too late to pretend that the server is down. This works the same way for regular TCP data; the TCP implementation does not wait for the application to actually `recv()` the data before a TCP ACK is sent. This keeps the other side from needlessly retransmitting packets that were received correctly, and allows the throughput to remain high, even when the application is bogged down with other things. In the case of new connections (SYN packets), this also allows the kernel to protect itself (and the application) from SYN flood attacks.
Although not portable, many platforms provide some sort of firewall capability that will allow filtering incoming connections based on IP address/port. However that is usually configured system-wide and not by an individual application. | On **windows**: look at WSAAccept, may be it is what you need:
```
SOCKET WSAAccept(
__in SOCKET s,
__out struct sockaddr *addr,
__inout LPINT addrlen,
__in LPCONDITIONPROC lpfnCondition,
__in DWORD dwCallbackData
);
```
lpfnCondition -- the address of an optional, application-specified condition function that will make an accept/reject decision based on the caller information passed in as parameters, and optionally create or join a socket group by assigning an appropriate value to the result parameter g of this function. If this parameter is NULL, then no condition function is called.
For **linux** solution look at: GNU Common C++ -- TCPSocket class, it has onAccept(), and reject() methods.
```
virtual bool TCPSocket::onAccept ( const InetHostAddress & ia,
tpport_t port
) [inline, protected, virtual]
```
A method to call in a derived TCPSocket class that is acting as a server when a connection request is being accepted.
The server can implement protocol specific rules to exclude the remote socket from being accepted by returning false. The Peek method can also be used for this purpose.
---
However, you can just close socket after accept if pre-condition is false :) | Refusing connection from a host | [
"",
"c++",
"sockets",
"cross-platform",
"network-programming",
""
] |
I have a directory that continually fills up with "artefact" files. Many different programs dump their temporary files in this directory and it's unlikely that these programs will become self-cleaning any time soon.
Meanwhile, I would like to write a program that continually deletes files in this directory as they become stale, which I'll define as "older than 30 minutes".
A typical approach would be to have a timed mechanism that lists the files in the directory, filters on the old stuff, and deletes the old stuff. However, this approach is not very performant in my case because this directory could conceivably contain 10s or hundreds of thousands of files that do not yet qualify as stale. Consequently, this approach would continually be looping over the same thousands of files to find the old ones.
What I'd *really* like to do is implement some kind of directory listener that was notified of any new files added to the directory. This listener would then add those files to a queue to be deleted down the road. However, there doesn't appear to be a way to implement such a solution in the languages I program in (JVM languages like Java and Scala).
So: I'm looking for the most efficient way to keep a directory "as clean as it can be" on Windows, preferably with a JVM language. Also, though I've never programmed with Powershell, I'd consider it if it offered this kind of functionality. Finally, if there are 3rd party tools out there to do such things, I'd like to hear about them.
Thanks. | Why can't you issue a directory [system command](http://www.linglom.com/2007/06/06/how-to-run-command-line-or-execute-external-application-from-java/) sorted by oldest first:
c:>dir /OD
Take the results and delete all files older than your threshold or sleep if no files are old enough.
Combine that with a [Timer or Executor](https://stackoverflow.com/questions/409932/java-timer-vs-executorservice) set to a granularity 1 second - 1 minute which guarantees that the files don't keep piling up faster than you can delete them. | If you don't want to write C++, you can use Python. Install [pywin32](http://sourceforge.net/projects/pywin32/) and you can then use the win32 API as such:
```
import win32api, win32con
change_handle = win32api.FindFirstChangeNotification(
path_to_watch,
0,
win32con.FILE_NOTIFY_CHANGE_FILE_NAME
)
```
Full explanation of what to do with that handle by Tim Golden here: [`http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html`](http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html). | What's the most efficient method of continually deleting files older than X hours on Windows? | [
"",
"java",
"windows",
"algorithm",
"scala",
"filesystems",
""
] |
I want to pull a number out the middle of a string in [JavaScript](http://en.wikipedia.org/wiki/JavaScript). In [Ruby](http://en.wikipedia.org/wiki/Ruby_%28programming_language%29) (my main language) I would do this:
Ruby:
```
name = "users[107][teacher_type]"
num = name.scan(/\d+/).first
```
But in JavaScript I have to do this, which seems a bit clunky.
JavaScript:
```
var name = "users[107][teacher_type]"
var regexp = new RegExp(/\d+/)
var num = regexp.exec(name)[0]
```
Is there way to pull out the matching parts without building a RegExp object? I.e. a one-liner equivalent of Ruby's String#scan?
Also, as a side note, since this string will always have the same format, I could potentially do it using .replace. This isn't as clever a solution but again I have problems in JavaScript.
In Ruby:
```
num = name.gsub(/users\[|\]\[teacher_type\]/,"")
```
But when I try this in JavaScript it doesn't like the or (|) in the middle of the regex:
In JavaScript:
```
//works
num = name.replace(/users\[/, "").replace(/\]\[teacher_type\]/,"")
//doesn't work
num = name.gsub(/users\[|\]\[teacher_type\]/,"")
```
Can anyone set me straight? | You only need to use the `new RegExp()` part when creating dynamic regular expressions. You can use literals at other times. /\d+/ is the equivalent of `new RegExp("\\d+")`. Note that you have to escape special characters when using the latter.
Also noteworthy is that `String#match` returns null or an array. This is not apparent based on the supplied solutions (`parseInt(name.match(/\d+/), 10)`). It just so happens that it is converted to a string when passed to `parseInt`. [ParseInt](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/parseInt) converts string values to integers (when possible).
```
name.match(/\d+/)[0]
/\d+/.exec(name)[0]
```
Those two are functionally identical in this case.
The other match you were referring to (the negative matching) requires a special flag. To duplicate the functionality of gsub you need to tell the regex to be applied more than once with the `g` flag.
```
'users[107][teacher_type]'.replace(/users\[|\]\[teacher_type\]/g,'')
```
Or if you had to use `new RegExp` for some reason you'd accomplish the same as above like so:
'users[107][teacher\_type]'.replace(new RegExp('users\[|\]\[teacher\_type\]', 'g'),'')
Notice again how I had to escape all the backslashes. Mozilla's Developer Center is a good [reference](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp) to familiarize yourself with regex in javascript. | ```
var num = name.replace(/\D+/, '');
```
Be aware, though, that this one-liner does not validate the name format. It just strips out all non-digits (`\D` being the opposite of `\d`). | How to pull a number out of a string in JavaScript? | [
"",
"javascript",
"regex",
""
] |
I plan to add functionalities to TextBox with the following:
```
public class TextBoxExt : TextBox
{
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
}
}
```
The question is how can we use this TextBoxExt? Is there anyway to get this class onto the ToolBox so that we can just drag and drop it onto the form? If not, what is the best way to use the TextBoxExt? | I believe there are a couple of ways to get your control to appear in the toolbox:
1. The project it's in must be included in your open solution and the project must have been compiled/built into an assembly. This is the route to go if you're working on the control and a project that uses the control at the same time (*e.g., building the solution will also re-build the control's project*).
2. You can right-click the toolbox to add new items... in the resulting dialog, you can browse to the assembly containing the control and add it that way (or add it to the GAC, in which case you can pick it right from the list without browsing). This is the route to go if the project containing your control won't be a part of your solution and you're dealing only with the compiled DLL (*e.g., building the solution doesn't re-build the control's project*). | There is an another simple option to add a control into Toolbox is,
1. **Create a new toolbox tab** in the VS Toolbox. Say for e.g. "My Own Control".
2. **Drag the assembly** which has your control into the newly created tab and **drop it**.
3. You can see your **control added** in your Toolbox.
Main advantage of this method is, if you have more than a control in your single assembly, you do not need to search in the Add Components dialog and choose them. VS will do it for you and will add all those automatically in Toolbox.
Hope this helps. | How to put extended WinForms Control on ToolBox | [
"",
"c#",
"visual-studio",
"winforms",
""
] |
When I perform an asynchronous request with jQuery Ajax, sometimes the response is returned quickly in 800 ms, somtimes it's slow and the response is returned in 2.50s (avg), and sometimes it hangs, and just shows the loading images. I'm not sure if it's because of my PHP code or jQuery Ajax code. I send some values using jQuery Ajax:
```
function get_detail_product(obj)
{
var id = obj.id ;
var $this = jQuery('#'+id);
var Thumb = jQuery('#Scroller div.Container') ;
jQuery.each(Thumb , function(){
jQuery(this).css('border' , '#ccc 2px solid');
});
$this.parent().css('border' , '#ff8500 2px solid') ;
var load_area = jQuery('.detail') ;
//ajax request
load_area.html("");
load_area.html('<div id="loading" style="margin-top:60px;margin-left:350px;"><img src="../images/loading.gif"><br>Loding ... </div>');
jQuery.ajax({
url: 'index.php?module=product&popup=on ',
type: 'POST',
data: 'pid=' + id ,
success: function(result) {
jQuery('#response').remove();
load_area.html(result);
jQuery('#loading').fadeOut(500, function() {
jQuery(this).remove();
});
}
});
}
```
and in the PHP file I have the following code to retrieve the requested data:
```
//ajax requests
if(isset($_POST['subcatid']) && is_numeric($_POST['subcatid']))
{
$subcatid = $_POST['subcatid'] ;
$products = $dbc->getAll("select * from xxproduct where xsubcatid='$subcatid'") ;
//send result
echo '<table cellpadding="0" cellspacing="0" border="0" id="ScrollerTable"><tr>';
foreach ($products as $p) : echo '<td><div style="border:#ccc 2px solid ; padding:0px;margin-top:20px ; margin-bottom:20px ; margin-left:8px ; margin-right:8px;" class="Container"><a href="javascript:void(0)" id="'.$p['xproductid'].'" onclick="get_detail_product(this)" ><img src="imgsize.phpw=100&h=100&img=../uploads/product/'.$p['xproductid'].'/'.$p['xproductid'].'__1.jpg" border="0"/></a><div style="background-color:#ccc ;text-align:center ; padding:5px; ">'.$p['xproductname'].'</div></div></td>';
endforeach ;
echo ' </tr></table>';
}
```
I wonder if you can find any mistakes in my code that cause the delay; additionally I'm using a PEAR DB object to interact with the database.
When i type the title of my question in this page, suggestions are returned in about 500 ms. Why is this ajax interaction so fast but mine is not? | I'm assuming you're getting the response times (the 800ms - 2.5s you mentioned) via FireBug? If that's the case, then that's the time of the request itself. At that point, all of your developer-land JS has already executed and the only JS that's running is the jQuery code in the `ajax()` function.
So I think you can be reasonably sure that it's your PHP code.
What I would do is use some php `microtime()` calls and hit that script directly (from a browser or commandline, not via an ajax call) and print out the microtime result.
Specifically, you'd add this at the top of your script:
```
$start = microtime(true);
```
And this at the end:
```
echo "Time: " . (microtime(true) - $start);
```
Then, try to isolate what params/etc are used during any consistently slow queries. As in most cases with CRUD apps, the DB is most often the culprit.
**Edit:**
After looking more closely at your code, there's nothing obviously wrong. What I wonder is if this is the only request that has such crazy response times. If it is, that suggests that the connection between your client and server is not the issue. That it's specifically this script.
And by doing what I mentioned above--hitting the script directly via your browser rather than an ajax call--you can isolate the PHP code and then, by moving the placement of those microtime statements, isolate the specific lines of code.
But if it were me, I'd focus first on that SQL Query. Most like you're not using any bytecode caching like APC. It's a great tool it's just not in such widespread use right now.
So the only caching mechanism that code is using is probably the MySQL Query Cache. If there's no index on the subcatid field, it could be that MySQL is doing a table scan. But the next time you request that same query (with that same subcatid value), the results will be in the query cache and MySQL will return them instantly.
You could test this out by isolation even further: Forget the AJAX call *and* the PHP code, just copy and paste that query, plug in some valid subcatid values, and run it directly into phpMyAdmin or the MySQL CLI or your favorite MySQL tool. If you're seeing intermittent performance as you plug-in new and different subcatid values, then you know where your problem lies. | Possibly caching both in the browser and any php mem-caching going on. | Variable speed of response with jQuery Ajax requests | [
"",
"php",
"jquery",
"ajax",
"timedelay",
""
] |
I have this code:
```
Thread t = new Thread(() => UpdateImage(origin));
t.Name = "UpdateImageThread";
t.Start();
```
If method UpdateImage(origin) throw an exception, it is necessary to stop thread or it will be stoped after the exception?
Thank you! | If `UpdateImage` throws an exception, it is probably going to take down your whole process. Any thread that raises a top-level exception indicates a big problem. You should wrap this, for example by putting `try`/`catch` around `UpdateImage` and doing something suitable. And yes, if an exception gets to the top of a thread, the thread is dead:
```
Thread t = new Thread(() => {
try {UpdateImage(origin); }
catch (Exception ex) {Trace.WriteLine(ex);}
});
t.Name = "UpdateImageThread";
t.Start();
```
(or your choice of error handling) | Since .NET 2.0, when a background thread throws an exception (that is not handled), the .NET runtime will take down your process. In a Windows.Forms application, this is different; you can use the Application.ThreadException event to catch the exception.
This was different in .NET 1.0/1.1, you can read about the whole topic here (e.g. how to enable the legacy behavior with .NET 2.0 or later): <http://msdn.microsoft.com/en-us/library/ms228965.aspx#ChangeFromPreviousVersions>.
No matter whether you use Windows.Forms or the legacy behavior - if the process does not exit, you do not need to explicitly stop the thread; the exception will stop it. | C#: Stopping a thread after an Exception | [
"",
"c#",
"exception",
"multithreading",
""
] |
I have a link inside a label. The problem is, when user clicks 'back' after having read the terms, the checkbox is unchecked, because when they clicked on the link they also unchecked the box at the same time, since the link is inside a label.
```
<input type="checkbox" id="terms" name="terms" checked="checked" />
<label for="terms">I agree to be bound by the <a href="/terms">Terms</a></label>
```
How can I prevent the checkbox from being checked when link is clicked? Tried doing `event.preventDefault()` on label click, but that doesn't prevent checkbox from being checked/unchecked.
I could just take out the link from inside a label (which means more CSS styling). But now I'm curious whether the above is possible. | You can cancel the click event by routing it through an onclick event.
The "return false;" part will prevent the click event from moving up to the label.
```
<input type="checkbox" id="terms" name="terms" checked="checked" />
<label for="terms">I agree to be bound by the <a href="#" onclick="window.open('/terms','_blank');return false;">Terms</a></label>
``` | Also good practice to allow opening links with `target="_blank"` in new tabs.
```
/*
Fix links inside of labels.
*/
$( 'label a[href]' ).click( function ( e ) {
e.preventDefault();
if ( this.getAttribute( 'target' ) === '_blank' ) {
window.open( this.href, '_blank' );
}
else {
window.location = this.href;
}
});
``` | how to prevent checkbox check when clicking on link inside label | [
"",
"javascript",
"jquery",
""
] |
I have about a hundred short-text data items (this number can vary substantially) that I would like to put in a page and have the browser manage that into three columns within a surrounding div, arranged with the items going down and then across, like this:
```
A F L
B G M
C H N
D I O
E K ...
```
Is there a way to render this out as li's (or maybe just individual lines), and have the browser automatically collate it into **three equal-height columns**, possibly using CSS?
Are there any browser compatibility issues? | Without browser compatibility issues:
```
<% var rows = source.Count() % 3 == 0 ? source.Count / 3 : (source.Count / 3) + 1; %>
<table>
<% for(int i=0; i<rows; i++) { %>
<tr>
<td><%= source.Skip(i).FirstOrDefault() %></td>
<td><%= source.Skip(i+rows).FirstOrDefault() %></td>
<td><%= source.Skip(i+rows*2).FirstOrDefault() %></td>
</tr>
<% } %>
</table>
```
We use the modulus operator to let us know if the division is even or not... if it is not, we're not going to add an extra row for the leftover columns. For more information, see <http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx>
For example look at <https://stackoverflow.com/users> HTML source - it uses `<table>` | In the CSS world this is the only way I know to do three columns outside of a table of course.
```
<html>
<div style="width:100px">
<div style="float:left; width:33%;">a</div>
<div style="float:left; width:33%;">bsdf</div>
<div style="float:left; width:33%;">c</div>
<div style="float:left; width:33%;">d</div>
<div style="float:left; width:33%;">e</div>
<div style="float:left; width:33%;">f</div>
<div style="float:left; width:33%;">g</div>
</div>
</html>
```
Clearly you wouldn't use all those style tags, instead you'd use an actual style. Notice the 33% as the width.
I tried this in IE and FirFox and no probs on either. | How do I create a two-column snaking layout in ASP.NET MVC? | [
"",
"c#",
"asp.net-mvc",
"css",
"layout",
"rendering",
""
] |
I have added multiple app.config (each with a differet name) files to a project, and set them to copy to the output directory on each build.
I try and access the contents of each file using this:
```
System.Configuration.Configuration o = ConfigurationManager.OpenExeConfiguration(@"app1.config");
```
The code runs, but o.HasFile ends up False, and o.FilePath ends up "app1.config.config". If I change to code:
```
System.Configuration.Configuration o = ConfigurationManager.OpenExeConfiguration(@"app1");
```
Then the code bombs with "An error occurred loading a configuration file: The parameter 'exePath' is invalid. Parameter name: exePath".
If I copy/paste the config file (so I end up with app1.config and app1.config.config) then the code runs fine, however, I posit this is not a good solution. My question is thus: how can I use ConfigurationManager.OpenExeConfiguration to load a config file corretly? | According to <http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/3943ec30-8be5-4f12-9667-3b812f711fc9> the parameter is the location of an exe, and the method then looks for the config corresponding to that exe (I guess the parameter name of exePath makes sense now!). | I can't remember where I found this solution but here is how I managed to load a specific exe configuration file:
```
ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = "EXECONFIG_PATH" };
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
``` | ConfigurationManager.OpenExeConfiguration - loads the wrong file? | [
"",
"c#",
"configurationmanager",
""
] |
Calling System.gc() requests that garbage collection takes place, and isn't guaranteed. The part about it not being guaranteed is interesting to me: can someone explain the exact process that takes place when you make this call? | There are no guarantees that a garbage collection will take place, because there are no guarantees that the JVM supports garbage collection (I don't believe it's mentioned in the JLS at all, certainly not in the [index](http://java.sun.com/docs/books/jls/third_edition/html/j3IX.html)).
However, I think this belief that "it's not guaranteed" is a little misplaced. From the Sun [API docs](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#gc()):
> When control returns from the method
> call, the Java Virtual Machine has
> made a best effort to reclaim space
> from all discarded objects.
OK, so maybe it's not guaranteed, but this indicates to me that a normal JVM will actually start a GC cycle when you call this method. Perhaps some JVMs won't, and perhaps some future garbage collector won't, but for now, it does what's advertised.
Of course, that said, there's almost never a reason for application code to call this method. The JVM will collect the garbage when it needs to do so. | The exact process is JVM specific, and is actually an area where a lot of research is taking place. This is possible because the specification is so vague on what actually should happen.
Originally Java had a "stop everything and look at every object to see which ones are still alive". This was 1) slow and 2) stopped everything while this happened.
Today, Sun-based JVM's have several pools of objects as most objects do not live long, so by keeping the separate pools much work can be avoided.
Suns documentation on how to tweak the gc in java 5 is quite instructive on what goes on:
<http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html> | What exactly takes place behind the scenes when you call System.gc()? | [
"",
"java",
"garbage-collection",
""
] |
Do you know of a popular library (Apache, Google, etc, collections) which has a reliable Java implementation for a min-max heap, that is a heap which allows to peek its minimum and maximum value in `O(1)` and to remove an element in `O(log n)`? | From Guava: [`MinMaxPriorityQueue`](https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/MinMaxPriorityQueue.html). | Java has good tools in order to implement min and max heaps. My suggestion is using the priority queue data structure in order to implement these heaps. For implementing the max heap with priority queue try this:
```
import java.util.PriorityQueue;
public class MaxHeapWithPriorityQueue {
public static void main(String args[]) {
// create priority queue
PriorityQueue<Integer> prq = new PriorityQueue<>(Collections.reverseOrder());
// insert values in the queue
prq.add(6);
prq.add(9);
prq.add(5);
prq.add(64);
prq.add(6);
//print values
while (!prq.isEmpty()) {
System.out.print(prq.poll()+" ");
}
}
}
```
For implementing the min heap with priority queue, try this:
```
import java.util.PriorityQueue;
public class MinHeapWithPriorityQueue {
public static void main(String args[]) {
// create priority queue
PriorityQueue< Integer > prq = new PriorityQueue <> ();
// insert values in the queue
prq.add(6);
prq.add(9);
prq.add(5);
prq.add(64);
prq.add(6);
//print values
while (!prq.isEmpty()) {
System.out.print(prq.poll()+" ");
}
}
}
```
For more information, please visit:
* <https://github.com/m-vahidalizadeh/foundations/blob/master/src/data_structures/MaxHeapWithPriorityQueue.java>
* <https://github.com/m-vahidalizadeh/foundations/blob/master/src/data_structures/MinHeapWithPriorityQueue.java> | Java implementation for Min-Max Heap? | [
"",
"java",
"data-structures",
"minmax-heap",
""
] |
### Abstract
I am writing an application which has a few object caches. The way it needs to work is when an object is retrieved from the cache:
```
object foo = CacheProvider.CurrentCache.Get("key");
```
foo should be a local copy of the original object, not a reference. What is the best way to implement this? The only way I have in mind so far is to use a BinarySerializer to create a copy, but I feel like I am missing a better way.
### Details
The backing for the cache implementation is arbitrary, as it is provider-based. I need to support any number of caches, from the HttpRuntime cache to something like Velocity. The focus here is on the layer between the cache backing and the consumer code - that layer must ensure a copy of the object is returned. Some caches will already do this, but some do not (HttpRuntime cache being one). | Rex - we implemented something very similar in a big enterprise web product, and we ended up explicitly creating an IDeepCloneable interface that many of our objects implemented. The interesting thing is that we backed it with BinarySerializer, simply because it's a convienent and virtually foolproof way to make a deep copy of an object without all the hassle of reflection or forcing developers to write and test clone methods.
It works like a charm. Our team has stopped to mull over it several times and we have yet to come up with a better option. | Sorry, I must be underthinking this. Why not lookup the objects in a dictionary and then create a deep copy of the object (e.g., `IDeepCopyable`) or use reflection to do the job?
Roughly:
```
public interface IDeepCopyable {
object DeepCopy();
}
public class Cache<TKey, TValue> where TValue : IDeepCopyable {
Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();
// omit dictionary-manipulation code
public TValue this[TKey key] {
get {
return dictionary[key].DeepCopy(); // could use reflection to clone too
}
}
}
```
If you go the reflection route, Marc Gravell has some nice [cloning code](http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/d9722a51b04300a/0edae91abc1c0f1a?pli=1) easily modified to make a deep copy. | Get objects by value out of cache | [
"",
"c#",
".net",
"caching",
""
] |
So I'm learning C++ at the moment and I'm trying to work things out with pointers. Could anybody explain the following scenario:
```
bool testFalse = false; //testFalse = false
bool *thisIsFalse = &testFalse; //value of address of thisIsFalse shows that the address contains false
bool shouldBeFalse = &thisIsFalse; //shouldBeFalse = true is what I get here
```
shouldBeFalse (as the name implies) should be false, but it certainly doesn't turn out that way. Could someone explain why it ends up as true and how to make it so it takes on the proper value? Thanks! | You're using & where you should use \*:
```
bool shouldBeFalse = *thisIsFalse
``` | It isn't entirely clear what you're trying to do, but my guess would be that you actually wanted to dereference the pointer (i.e. retrieve the pointed value). For this you need operator `*`, not `&`:
```
bool shouldBeFalse = *thisIsFalse;
```
What your code did was take the address of variable `thisIsFalse` instead, producing a pointer to pointer. Now in C++, pointers are considered "false" if they are NULL, and "true" otherwise; and the compiler will implicitly convert pointer to `bool` under those rules if you pass a pointer where a `bool` is expected. Since you had a non-NULL pointer there, it got converted to `true`. | C++ pointer issue | [
"",
"c++",
"pointers",
""
] |
Say you've got a database like this:
```
books
-----
id
name
```
And you wanted to get the total number of books in the database, easiest possible sql:
```
"select count(id) from books"
```
But now you want to get the total number of books *last month*...
> Edit: but some of the books have been
> deleted from the table since last month
Well obviously you cant total for a month thats already past - *the "books" table is always current* and some of the records have already been deleted
My approach was to run a cron job (or scheduled task) at the end of the month and store the total in another table, called report\_data, but this seems clunky. Any better ideas? | Add a [default column](http://msdn.microsoft.com/en-us/library/ms173565.aspx) that has the value [GETDATE()](http://msdn.microsoft.com/en-us/library/ms188383.aspx), call it "DateAdded". Then you can query between any two dates to find out how many books there were during that date period or you can just specify one date to find out how many books there were before a certain date (all the way into history).
Per comment: You should not delete, you should [soft delete](http://databaserefactoring.com/IntroduceSoftDelete.html). | You have just taken a baby step down the road of history databases or data warehousing.
A data warehouse typically stores data about the way things were in a format such that later data will be added to current data instead of superceding current data. There is a lot to learn about data warehousing. If you are headed down that road in a serious way, I suggest a book by Ralph Kimball or Bill Inmon. I prefer Kimball.
Here's the websites: <http://www.ralphkimball.com/>
<http://www.inmoncif.com/home/>
If, on the other hand, your first step into this territory is the only step you plan to take, your proposed solution is good enough. | Is there a better way to get old data? | [
"",
"php",
"database",
"database-design",
"application-design",
""
] |
For a web-app product which would need to be installed by the customer on their own servers (think FogBugz or the self-hosted Wordpress package), which technology stack would result in a smoother/easier installation?
Our target platforms are known: Windows/IIS/SQLSever and Linux/Apache/MySQL.
But the technology stack to be used is being debated around the office: PHP w/ no frameworks, PHP with Codeigniter, Python, ASP.Net with C# (running Mono for the Linux installations), Rails, Java, etc.
Some of the things to consider would be whether an average "out of the box" web server running IIS or Apache would have the required libraries to install the product if it were built using one technology rather than the other (for example, a PHP-based solution would probably be easier for the customer to deploy on a Linux machine as opposed to having to install mono and whatever other dependencies would be required to run an ASP.Net solution on a Linux machine as a web app).
We're working on the assumption that the customer has some access to a system administrator, but perhaps not a full-time/dedicated one -- something like a shared web host account.
Given that, we want the customer to be able to have the least amount of friction in installing the web app on their web server, and we're debating the right technology stack to use for that. | PHP/MySql is brainless simple to set up on a unix stack. You can run in to problems with extensions and version-incompatibilities, but these are relatively minor compared to most other platforms. It's a bit outside my main territory, but from what I hear PHP is quite well integrated into ISS these days. Microsoft has taken upon them selves to make PHP more compatible with their stack, and quite a few improvements in this area went into the newly released version 5.3.
If you use Python or Ruby, you could go with a strategy of supplying a web-server out-of-the-box. There are full-featured web servers implemented in both languages. They aren't as robust as IIS or Apache of course, but for a low/medium traffic site they are OK. The customer could still set their main web server up to proxy your application. This makes it much easier to get started, since you can basically have a fully self-contained package.
In the end, I don't think I would pick the technology solely based on how easy it is to deploy. With a little legwork, you can create installer packages for your major platforms, using any of the mentioned platforms (Well, perhaps mono/asp is a bit dodgy, but it could work). | Since you're going to run into troubleshooting issues, I would pick the one with the most online help available. From the choices you've given and the experiences I've had, I would definitely choose ASP.NET. (I don't know what it would take to run ASP.NET on Linux, but the Mono project should have some information.) | Which technology stack would result in easiest deployment for a customer-hosted web app? | [
"",
"php",
"asp.net",
"deployment",
"web-applications",
""
] |
Anyone knows how to solve the error below?
> Deprecated: Function ereg() is deprecated in C:\wamp\www\includes\file.inc on line 895
It is happening after installing Drupal 6.13 on wamp server 2.0i with PHP 5.3.0 | Drop your error reporting level [below E\_DEPRECATED](http://www.php.net/manual/en/errorfunc.constants.php).
PHP 5.3 introduced two new error reporting levels, E\_DEPRECATED and E\_USER\_DEPRECATED and - for the first time in PHP's history - they've started to walk away from older parts of their API. The ereg\_\* function will still work, but this warning is intended to let you know that "hey, these function will be going away soon, probably in the next major revision). | Use
```
preg_match('/\.([^\.]*$)/', $this->file_src_name, $extension);
```
Instead of
```
ereg('\.([^\.]*$)', $this->file_src_name, $extension);
``` | How to solve the use of deprecated function ereg() of PHP 5.3.0 in Drupal 6.13 | [
"",
"php",
"drupal",
"drupal-6",
""
] |
Is there such a list? I don't expect to get a complete one, but the list of most well-known ones must be enough. | the list of recently fixed bugs could be found here: <http://msdn.microsoft.com/en-us/library/cc713578.aspx>
They call it "Breaking changes". | Try <http://connect.microsoft.com/feedback/default.aspx?SiteID=210>
Which version of the .Net framework btw?
I believe that the CLR has been largely stable and bug free since .Net 1.1 SP 1, certainly if in doubt, assume that its a bug in your code not .Net! | List of known bugs in C# compiler | [
"",
"c#",
"compiler-construction",
""
] |
I want to alter a field from a table which has about 4 million records. I ensured that all of these fields values are NOT NULL and want to ALTER this field to NOT NULL
```
ALTER TABLE dbo.MyTable
ALTER COLUMN myColumn int NOT NULL
```
... seems to take forever to do this update. Any ways to speed it up or am I stuck just doing it overnight during off-hours?
Also could this cause a table lock? | You can alter a field and make it not null without it checking the fields. If you are really concerned about not doing it off hours you can add a constraint to the field which checks to make sure it isn't null instead. This will allow you to use the with no check option, and not have it check each of the 4 million rows to see if it updates.
```
CREATE TABLE Test
(
T0 INT Not NULL,
T1 INT NUll
)
INSERT INTO Test VALUES(1, NULL) -- Works!
ALTER TABLE Test
WITH NOCHECK
ADD CONSTRAINT N_null_test CHECK (T1 IS NOT NULL)
ALTER COLUMN T1 int NOT NULL
INSERT INTO Test VALUES(1, NULL) -- Doesn't work now!
```
Really you have two options (added a third one see edit):
1. Use the constraint which will prevent any new rows from being updated and leave the original ones unaltered.
2. Update the rows which are null to something else and then apply the not null alter option. This really should be run in off hours, unless you don't mind processes being locked out of the table.
Depending on your specific scenario, either option might be better for you. I wouldn't pick the option because you have to run it in off hours though. In the long run, the time you spend updating in the middle of the night will be well spent compared the headaches you'll possibly face by taking a short cut to save a couple of hours.
This all being said, if you are going to go with option two you can minimize the amount of work you do in off hours. Since you have to make sure you update the rows to not null before altering the column, you can write a cursor to slowly (relative to doing it all at once)
1. Go through each row
2. Check to see if it is null
3. Update it appropriately.
This will take a good while, but it won't lock the whole table block other programs from accessing it. (Don't forget the [with(rowlock)](http://www.developerfusion.com/article/1688/sql-server-locks/4/) table hint!)
**EDIT**: I just thought of a third option:
You can create a new table with the appropriate columns, and then export the data from the original table to the new one. When this is done, you can then drop the original table and change the name of the new one to be the old one. To do this you'll have to disable the dependencies on the original and set them back up on the new one when you are done, but this process will greatly reduce the amount of work you have to do in the off hours. This is the same approach that sql server uses when you make column ordering changes to tables through the management studio. For this approach, I would do the insert in chunks to make sure that you don't cause undo stress on the system and stop others from accessing it. Then on the off hours, you can drop the original, rename the second, and apply dependencies etc. You'll still have some off hours work, but it will be minuscule compared to the other approach.
Link to using [sp\_rename](http://msdn.microsoft.com/en-us/library/ms188351.aspx). | The only way to do this "quickly" (\*) that I know of is by
* creating a 'shadow' table which has the required layout
* adding a trigger to the source-table so any insert/update/delete operations are copied to the shadow-table (mind to catch any NULL's that might popup!)
* copy all the data from the source to the shadow-table, potentially in smallish chunks (make sure you can handle the already copied data by the trigger(s), make sure the data will fit in the new structure (ISNULL(?) !)
* script out all dependencies from / to other tables
* when all is done, do the following inside an explicit transaction :
+ get an exclusive table lock on the source-table and one on the shadowtable
+ run the scripts to drop dependencies to the source-table
+ rename the source-table to something else (eg suffix \_old)
+ rename the shadow table to the source-table's original name
+ run the scripts to create all the dependencies again
You might want to do the last step outside of the transaction as it might take quite a bit of time depending on the amount and size of tables referencing this table, the first steps won't take much time at all
As always, it's probably best to do a test run on a test-server first =)
PS: please do not be tempted to recreate the FK's with NOCHECK, it renders them futile as the optimizer will not trust them nor consider them when building a query plan.
(\*: where quickly comes down to : with the least possible downtime) | SQL Server ALTER field NOT NULL takes forever | [
"",
"sql",
"sql-server",
"nullable",
"blocking",
"ddl",
""
] |
There is a bug in Java 6u13 and 6u14.
<https://bugs.java.com/bugdatabase/view_bug?bug_id=6835450>
Simply put, the following code is supposed to open a browser window, but because of a bug in the framework, it stopped working in Java 1.6 update 13. Nothing opens anymore. There was a similar bug for Java applets (that was fixed in update 14), but this one still exists in update 14 for Java WebStart/JNLP.
```
getAppletContext().showDocument(new URL("http://www.sun.com"),"_blank");
```
Do you know of any workarounds? | I've not tried it in JNLP, but normally this should work:
```
java.awt.Desktop.getDesktop().browse(new URI("http://www.sun.com"));
``` | Does `BasicService.showDocument` work? I can't remember how that is implemented off hand.
Alternatively, use LiveConnect to execute JavaScript yourself (although that might run into the same problems). | Launching a browser window from Java WebStart (JNLP) in Java 6u13+ | [
"",
"java",
"java-web-start",
""
] |
I'm doing a book exercise that says to write a program that generates psuedorandom numbers. I started off simple with.
```
#include "std_lib_facilities.h"
int randint()
{
int random = 0;
random = rand();
return random;
}
int main()
{
char input = 0;
cout << "Press any character and enter to generate a random number." << endl;
while (cin >> input)
cout << randint() << endl;
keep_window_open();
}
```
I noticed that each time the program was run, there would be the same "random" output. So I looked into random number generators and decided to try seeding by including this first in randint().
```
srand(5355);
```
Which just generated the same number over and over (I feel stupid now for implementing it.)
So I thought I'd be clever and implement the seed like this.
```
srand(rand());
```
This basically just did the same as the program did in the first place but outputted a different set of numbers (which makes sense since the first number generated by rand() is always 41.)
The only thing I could think of to make this more random is to:
1. Have the user input a number and set that as the seed (which would be easy to implement, but this is a last resort)
OR
2. Somehow have the seed be set to the computer clock or some other constantly changing number.
Am I in over my head and should I stop now? Is option 2 difficult to implement? Any other ideas?
Thanks in advance. | Option 2 isn't difficult, here you go:
```
srand(time(NULL));
```
you'll need to include `stdlib.h` for `srand()` and `time.h` for `time()`. | srand() should only be used once:
```
int randint()
{
int random = rand();
return random;
}
int main()
{
// To get a unique sequence the random number generator should only be
// seeded once during the life of the application.
// As long as you don't try and start the application mulitple times a second
// you can use time() to get a ever changing seed point that only repeats every
// 60 or so years (assuming 32 bit clock).
srand(time(NULL));
// Comment the above line out if you need to debug with deterministic behavior.
char input = 0;
cout << "Press any character and enter to generate a random number." << endl;
while (cin >> input)
{
cout << randint() << endl;
}
keep_window_open();
}
``` | What's the Right Way to use the rand() Function in C++? | [
"",
"c++",
"random",
""
] |
I am having four different project, and i am using Weblogic to deploy my projects. There are several libraries ( jar files ) which are common for all projects. Currently each of my project are having **lib** directory and have almost same set of libraries. Now, is it possible to have this lib directory outside WAR files and access them. | Resist the temptation of putting the jar files in the "shared" folder of your container. It is better to keep the jar files where they are now. It may sound a good idea to use a shared folder now, but in the future you may need to deploy an application that requires a shared library, but a different version.
That being said, I have no experience with WebLogic. In Tomcat there is a shared folder with libraries common for all deployed applications. It is not a good idea to use this. If WebLogic can be configured to use a shared folder per a set of applications (and not for all deployed applications) you could go for it. | Do you want to do this ? Unless you're stuck for deployment space, I would (perhaps) advise against it.
Why ? At the moment you have 4 solutions running off these libs. If you have to upgrade one of the libs (say, if you discover a bug, or if you require a new feature), then you're going to have to test compatibility and functionality for all 4 solutions. If each solution has its own set of libs, then they're sandboxed and you don't have to move all 4 in step.
Note that all this hinges on how easy it is to regression-test your solutions. You may find it easy, in which case using the same set of libs is feasible. | How to use common libraries for multiple Java web project | [
"",
"java",
"jakarta-ee",
"weblogic",
""
] |
I am using PHP and the codeigniter framework for a project I am working on, and require a user login/authentication system.
For now I'd rather not use SSL (might be overkill and the fact that I am using shared hosting discourages this). I have considered using openID but decided that since my target audience is generally not technical, it might scare users away (not to mention that it requires mirroring of login information etc.). I know that I could write a hash based authentication (such as sha1) since there is no sensitive data being passed (I'd compare the level of sensitivity to that of stackoverflow).
That being said, before making a custom solution, it would be nice to know if there are any good libraries or packages out there that you have used to provide semi-secure authentication? I am new to codeigniter, but something that integrates well with it would be preferable. Any ideas? (i'm open to criticism on my approach and open to suggestions as to why I might be crazy not to just use ssl). Thanks in advance.
**Update**: I've looked into some of the suggestions. I am curious to try out zend-auth since it seems well supported and well built. Does anyone have experience with using zend-auth in codeigniter (is it too bulky?) and do you have a good reference on integrating it with CI? I do not need any complex authentication schemes..just a simple login/logout/password-management authorization system.
Also, dx\_auth seems interesting as well, however I am worried that it is too buggy. Has anybody else had success with this?
I realized that I would also like to manage guest users (i.e. users that do not login/register) in a similar way to stackoverflow..so any suggestions that have this functionality would be great | I've found [dx\_auth](http://dexcell.shinsengumiteam.com/dx_auth/) to be quite good in Codeigniter, and have used it before. It is certainly the most full featured authentication library for Codeigniter.
There were a few things i needed to do to change it, so I extended their User class with a few functions for my purposes (some of their functions don't do exactly what you might expect..). Here is a segment of some of the customizations I made:
```
$CI = &get_instance();
$CI->load->model("dx_auth/users");
/**
* For most things, try and use the dx_auth models,
* because it's already done, and some stuff is more
* annoying to figure out than might be expected.
*
* For anything site-specific, use this model instead.
*
*/
class UserModel extends Users {
/**
* Sometimes when dx_auth sucks, you have to compensate
* functions that return useful results.
*
* @param int $id id of user to check if banned
* @return int $banned returns the result (0 or 1)
*/
public function is_banned($id) {
$query = "SELECT banned FROM users WHERE id=".(int)$id;
$result=$this->db->query($query);
$row = $result->row_array();
return $row['banned'];
}
}
``` | I use Zend\_Auth. But I work with Zend Framework in general. To what I've heard it integrates well with CI. With Zend\_Auth I use a Db\_Table Adapter and SHA1 with a global salt. That's enough for many purposes I think. | php user authentication libraries / frameworks ... what are the options? | [
"",
"php",
"authentication",
"ssl",
"codeigniter",
""
] |
My project has been using a base page to hold common page functionality. Its worked until the base page grew to be huge, so I tried to factor the base page into several classes. Then I realized that I can't write
```
public MyPage : SecurePage, PageWithGridViewSorting, PageWithSessionWarning
```
given something like:
```
public class SecurePage : RadAjaxPage
{
// Add session id to ViewStateUserKey
}
public class PageWithGridViewSorting : RadAjaxPage
{
// add sorting to all grids on page
}
public class PageWithSessionWarning : RadAjaxPage
{
// inject javascript to warn user of impending session end
}
```
Which way am I supposed to take this? And I think the fact that this is the ASP.NET page is relevant because it is a class that gets constructed by the framework, not me. My first thought was to make a override for the constructor and pass in the features and that wont work with System.Web.UI.Page. | Do the functions provided by `SecurePage`, `PageWithGridViewSorting` and `PageWithSessionWarning` actually need to be overloaded or overridden by their derived classes?
If all you're doing is using inheritance to group functions, you should consider using a different method of organizing functions into classes. Like, for example, the [Strategy pattern](http://en.wikipedia.org/wiki/Strategy_pattern). A page with sorting is a page, with sorting. It's a page that *has* sorting. Using inheritance isn't the right way to approach this problem.
If they *do* need to differ in the derived classes, you might want to approach the problem with interfaces instead of inheritance. Since you'll be redefining the functions anyway this shouldn't increase complexity or make you repeat yourself.
EDIT: Given the specifics of your problem, it really sounds to me like you should investigate [aspect-oriented programming](http://en.wikipedia.org/wiki/Aspect-oriented_programming) and how you can [fit it into your language](http://www.developerfusion.com/article/5307/aspect-oriented-programming-using-net/). | I would try to move over some of the content from BasePage to UserControls.
Lets say PageWithSessionWarning. This could be a control that you put on the masterpage. | How to simulate multiple inheritance for ASP.NET base pages? | [
"",
"c#",
"asp.net",
""
] |
When designing a class, should logic to maintain valid state be incorporated in the class or outside of it ? That is, should properties throw exceptions on invalid states (i.e. value out of range, etc.), or should this validation be performed when the instance of the class is being constructed/modified ? | It belongs in the class. Nothing but the class itself (and any helpers it delegates to) should know, or be concerned with, the rules that determine valid or invalid state. | Yes, properties should check on valid/invalid values when being set. That's what it's for. | C# / Object oriented design - maintaining valid object state | [
"",
"c#",
"oop",
"state",
""
] |
How to get difference between two dates in Year/Month/Week/Day in an efficient way?
eg. difference between two dates is 1 Year, 2 Months, 3 Weeks, 4 Days.
Difference represents count of year(s), month(s), week(s) and day(s) between two dates. | This is actually quite tricky. A different total number of days can result in the same result. For example:
* 19th June 2008 to 19th June 2010 = 2 years, but also 365 \* 2 days
* 19th June 2006 to 19th June 2008 = 2 years, but also 365 + 366 days due to leap years
You may well want to subtract years until you get to the point where you've got two dates which are less than a year apart. Then subtract months until you get to the point where you've got two dates which are less than a month apart.
Further confusion: subtracting (or adding) months is tricky when you might start with a date of "30th March" - what's a month earlier than that?
Even further confusion (*may* not be relevant): even a day isn't always 24 hours. Daylight saving anyone?
Even further confusion (almost certainly *not* relevant): even a minute isn't always 60 seconds. Leap seconds are highly confusing...
I don't have the time to work out the exact right way of doing this right now - this answer is mostly to raise the fact that it's not nearly as simple as it might sound.
EDIT: Unfortunately I'm not going to have enough time to answer this fully. I would suggest you start off by defining a struct representing a `Period`:
```
public struct Period
{
private readonly int days;
public int Days { get { return days; } }
private readonly int months;
public int Months { get { return months; } }
private readonly int years;
public int Years { get { return years; } }
public Period(int years, int months, int days)
{
this.years = years;
this.months = months;
this.days = days;
}
public Period WithDays(int newDays)
{
return new Period(years, months, newDays);
}
public Period WithMonths(int newMonths)
{
return new Period(years, newMonths, days);
}
public Period WithYears(int newYears)
{
return new Period(newYears, months, days);
}
public static DateTime operator +(DateTime date, Period period)
{
// TODO: Implement this!
}
public static Period Difference(DateTime first, DateTime second)
{
// TODO: Implement this!
}
}
```
I suggest you implement the + operator first, which should inform the `Difference` method - you should make sure that `first + (Period.Difference(first, second)) == second` for all `first`/`second` values.
Start with writing a whole slew of unit tests - initially "easy" cases, then move on to tricky ones involving leap years. I know the normal approach is to write one test at a time, but I'd personally brainstorm a bunch of them before you start any implementation work.
Allow yourself a day to implement this properly. It's tricky stuff.
Note that I've omitted weeks here - that value at least is easy, because it's always 7 days. So given a (positive) period, you'd have:
```
int years = period.Years;
int months = period.Months;
int weeks = period.Days / 7;
int daysWithinWeek = period.Days % 7;
```
(I suggest you avoid even thinking about negative periods - make sure everything is positive, all the time.) | Partly as a preparation for trying to answer this question correctly (and maybe even definitively...), partly to examine how much one can trust code that is pasted on SO, and partly as an exercise in finding bugs, I created a bunch of unit tests for this question, and applied them to many proposed solutions from this page and a couple of duplicates.
The results are conclusive: not a single one of the code contributions accurately answers the question. **Update: I now have four correct solutions to this question, including my own, see updates below.**
## Code tested
From this question, I tested code by the following users:
Mohammed Ijas Nasirudeen, ruffin, Malu MN, Dave, pk., Jani, lc.
These were all the answers which provided all three of years, months, and days in their code. Note that two of these, Dave and Jani, gave the total number of days and months, rather than the total number of months left after counting the years, and the total number of days left after counting the months. I think the answers are wrong in terms of what the OP seemed to want, but the unit tests obviously don't tell you much in these cases. **(Note that in Jani's case this was my error and his code was actually correct - see Update 4 below)**
The answers by Jon Skeet, Aghasoleimani, Mukesh Kumar, Richard, Colin, sheir, just i saw, Chalkey and Andy, were incomplete. This doesn't mean that the answers weren't any good, in fact several of them are useful contributions towards a solution. It just means that there wasn't code taking two `DateTime`s and returning 3 `int`s that I could properly test. Four of these do however talk about using `TimeSpan`. As many people have mentioned, `TimeSpan` doesn't return counts of anything larger than days.
The other answers I tested were from
* question 3054715 - LukeH, ho1 and this. \_\_\_curious\_geek
* question 6260372 - Chuck Rostance and Jani (same answer as this question)
* question 9 (!) - Dylan Hayes, Jon and Rajeshwaran S P
this.\_\_\_curious\_geek's answer is code on a page he linked to, which I don't think he wrote. Jani's answer is the only one which uses an external library, Time Period Library for .Net.
All other answers on all these questions seemed to be incomplete. Question 9 is about age in years, and the three answers are ones which exceeded the brief and calculated years, months and days. If anyone finds further duplicates of this question please let me know.
## How I tested
Quite simply: I made an interface
```
public interface IDateDifference
{
void SetDates(DateTime start, DateTime end);
int GetYears();
int GetMonths();
int GetDays();
}
```
For each answer I wrote a class implementing this interface, using the copied and pasted code as a basis. Of course I had to adapt functions with different signatures etc, but I tried to make the minimal edits to do so, preserving all the logic code.
I wrote a bunch of NUnit tests in an abstract generic class
```
[TestFixture]
public abstract class DateDifferenceTests<DDC> where DDC : IDateDifference, new()
```
and added an empty derived class
```
public class Rajeshwaran_S_P_Test : DateDifferenceTests<Rajeshwaran_S_P>
{
}
```
to the source file for each `IDateDifference` class.
NUnit is clever enough to do the rest.
## The tests
A couple of these were written in advance and the rest were written to try and break seemingly working implementations.
```
[TestFixture]
public abstract class DateDifferenceTests<DDC> where DDC : IDateDifference, new()
{
protected IDateDifference ddClass;
[SetUp]
public void Init()
{
ddClass = new DDC();
}
[Test]
public void BasicTest()
{
ddClass.SetDates(new DateTime(2012, 12, 1), new DateTime(2012, 12, 25));
CheckResults(0, 0, 24);
}
[Test]
public void AlmostTwoYearsTest()
{
ddClass.SetDates(new DateTime(2010, 8, 29), new DateTime(2012, 8, 14));
CheckResults(1, 11, 16);
}
[Test]
public void AlmostThreeYearsTest()
{
ddClass.SetDates(new DateTime(2009, 7, 29), new DateTime(2012, 7, 14));
CheckResults(2, 11, 15);
}
[Test]
public void BornOnALeapYearTest()
{
ddClass.SetDates(new DateTime(2008, 2, 29), new DateTime(2009, 2, 28));
CheckControversialResults(0, 11, 30, 1, 0, 0);
}
[Test]
public void BornOnALeapYearTest2()
{
ddClass.SetDates(new DateTime(2008, 2, 29), new DateTime(2009, 3, 1));
CheckControversialResults(1, 0, 0, 1, 0, 1);
}
[Test]
public void LongMonthToLongMonth()
{
ddClass.SetDates(new DateTime(2010, 1, 31), new DateTime(2010, 3, 31));
CheckResults(0, 2, 0);
}
[Test]
public void LongMonthToLongMonthPenultimateDay()
{
ddClass.SetDates(new DateTime(2009, 1, 31), new DateTime(2009, 3, 30));
CheckResults(0, 1, 30);
}
[Test]
public void LongMonthToShortMonth()
{
ddClass.SetDates(new DateTime(2009, 8, 31), new DateTime(2009, 9, 30));
CheckControversialResults(0, 1, 0, 0, 0, 30);
}
[Test]
public void LongMonthToPartWayThruShortMonth()
{
ddClass.SetDates(new DateTime(2009, 8, 31), new DateTime(2009, 9, 10));
CheckResults(0, 0, 10);
}
private void CheckResults(int years, int months, int days)
{
Assert.AreEqual(years, ddClass.GetYears());
Assert.AreEqual(months, ddClass.GetMonths());
Assert.AreEqual(days, ddClass.GetDays());
}
private void CheckControversialResults(int years, int months, int days,
int yearsAlt, int monthsAlt, int daysAlt)
{
// gives the right output but unhelpful messages
bool success = ((ddClass.GetYears() == years
&& ddClass.GetMonths() == months
&& ddClass.GetDays() == days)
||
(ddClass.GetYears() == yearsAlt
&& ddClass.GetMonths() == monthsAlt
&& ddClass.GetDays() == daysAlt));
Assert.IsTrue(success);
}
}
```
Most of the names are slightly silly and don't really explain why code might fail the test, however looking at the two dates and the answer(s) should be enough to understand the test.
There are two functions that do all the `Assert`s, `CheckResults()` and `CheckControversialResults()`. These work well to save typing and give the right results, but unfortunately they make it harder to see exactly what went wrong (because the `Assert` in `CheckControversialResults()` will fail with "Expected true", rather than telling you which value was incorrect. If anyone has a better way to do this (avoid writing the same checks each time, but have more useful error messages) please let me know.
`CheckControversialResults()` is used for a couple of cases where there seem to be two different opinions on what is right. I have an opinion of my own, but I thought I should be liberal in what I accepted here. The gist of this is deciding whether one year after Feb 29 is Feb 28 or Mar 1.
These tests are the crux of the matter, and there could very well be errors in them, so please do comment if you find one which is wrong. It would be also good to hear some suggestions for other tests to check any future iterations of answers.
No test involves time of day - all `DateTime`s are at midnight. Including times, as long as it's clear how rounding up and down to days works (I think it is), might show up even more flaws.
## The results
The complete scoreboard of results is as follows:
```
ChuckRostance_Test 3 failures S S S F S S F S F
Dave_Test 6 failures F F S F F F F S S
Dylan_Hayes_Test 9 failures F F F F F F F F F
ho1_Test 3 failures F F S S S S F S S
Jani_Test 6 failures F F S F F F F S S
Jon_Test 1 failure S S S S S S F S S
lc_Test 2 failures S S S S S F F S S
LukeH_Test 1 failure S S S S S S F S S
Malu_MN_Test 1 failure S S S S S S S F S
Mohammed_Ijas_Nasirudeen_Test 2 failures F S S F S S S S S
pk_Test 6 failures F F F S S F F F S
Rajeshwaran_S_P_Test 7 failures F F S F F S F F F
ruffin_Test 3 failures F S S F S S F S S
this_curious_geek_Test 2 failures F S S F S S S S S
```
**But note that Jani's solution was actually correct and passed all tests - see update 4 below.**
The columns are in alphabetical order of test name:
* AlmostThreeYearsTest
* AlmostTwoYearsTest
* BasicTest
* BornOnALeapYearTest
* BornOnALeapYearTest2
* LongMonthToLongMonth
* LongMonthToLongMonthPenultimateDay
* LongMonthToPartWayThruShortMonth
* LongMonthToShortMonth
Three answers failed only 1 test each, Jon's, LukeH's and Manu MN's. Bear in mind these tests were probably written specifically to address flaws in those answers.
Every test was passed by at least one piece of code, which is slightly reassuring that none of the tests are erroneous.
Some answers failed a lot of tests. I hope no-one feels this is a condemnation of that poster's efforts. Firstly the number of successes is fairly arbitrary as the tests don't evenly cover the problem areas of the question space. Secondly this is not production code - answers are posted so people can learn from them, not copy them exactly into their programs. Code which fails a lot of tests can still have great ideas in it. At least one piece which failed a lot of tests had a small bug in it which I didn't fix. I'm grateful to anyone who took the time to share their work with everyone else, for making this project so interesting.
## My conclusions
There are three:
1. Calendars are hard.
I wrote nine tests, including three where two answers are possible. Some of the tests where I only had one answer might not be unanimously agreed with. Just thinking about exactly what we mean when we say '1 month later' or '2 years earlier' is tricky in a lot of situations. And none of this code had to deal with all the complexities of things like working out when leap years are. All of it uses library code to handle dates. If you imagine the 'spec' for telling time in days, weeks, months and years written out, there's all sorts of cruft. Because we know it pretty well since primary school, and use it everyday, we are blind to many of the idiosyncracies. The question is not an academic one - various types of decomposition of time periods into years, quarters and months are essential in accounting software for bonds and other financial products.
2. Writing correct code is hard.
There were a lot of bugs. In slightly more obscure topics or less popular questions than the chances of a bug existing without having been pointed out by a commenter are much, much higher than for this question. You should really never, never copy code from SO into your program without understanding exactly what it does. The flipside of this is that you probably shouldn't write code in your answer that is ready to be copied and pasted, but rather intelligent and expressive pseudo-code that allows someone to understand the solution and implement their own version (with their own bugs!)
3. Unit tests are helpful.
I am still meaning to post my own solution to this when I get round to it (for someone else to find the hidden, incorrect assumptions in!) Doing this was a great example of 'saving the bugs' by turning them into unit tests to fix the next version of the code with.
## Update
The whole project is now at <https://github.com/jwg4/date-difference>
This includes my own attempt `jwg.cs`, which passes all the tests I currently have, including a few new ones which check for proper time of day handling. Feel free to add either more tests to break this and other implementations or better code for answering the question.
## Update 2
@MattJohnson has added an implementation which uses Jon Skeet's NodaTime. It passes all the current tests.
## Update 3
@KirkWoll's answer to [Difference in months between two dates](https://stackoverflow.com/questions/4638993/) has been added to the project on github. It passes all the current tests.
## Update 4
@Jani pointed out in a comment that I had used his code wrongly. He did suggest methods that counted the years, months and days correctly, (alongside some which count the total number of days and months, not the remainders) however I mistakenly used the wrong ones in my test code. I have corrected my wrapper around his code and it now passes all tests. There are now **four** correct solutions, of which Jani's was the first. Two use libraries (Intenso.TimePeriod and NodaTime) and two are written from scratch. | How to get difference between two dates in Year/Month/Week/Day? | [
"",
"c#",
".net",
"datetime",
""
] |
In C++ it is possible to create a struct:
```
struct MyStruct
{
...
}
```
And also possible to do the following:
```
typedef struct
{
...
} MyStruct;
```
And yet as far as I can tell, no discernable difference between the two. Which is preferable? Why do both ways exist if there is no difference? Is one better than the other in style or readability? | The typedef version is a special case of
```
typedef foo bar;
```
which defines a new "type" bar as an alias for foo. In your case, foo happens to be a struct. In C, this was the only way to introduce new "types" (in quotes, because they are not really equivalent to int, float and co). In C++, this is not so useful, because C++ was designed to make definition of new types easier and more complete than C (at least at the beginnings of C++), and the typedef is not even necessary to refer to a previously declared struct (or class). | Here are the differences between the two declarations/definitions:
---
> 1) You cannot use a typedef name to identify a constructor or a destructor
```
struct MyStruct { MyStruct(); ~MyStruct(); }; // ok
typedef struct { MyStructTD(); ~MyStructTD(); } MyStructTD; // not ok
// now consider
typedef struct MyStruct2 { MyStruct2(); } MyStructTD2; // ok
MyStructTD2::MyStruct2() { } // ok
MyStructTD2::MyStructTD2() { } // not ok
```
---
> 2) You cannot hide a typedef name like you can a name introduced via the class-head - or conversely if you already have a function or an object with a certain name, you can still declare a class with that name using the class-head but not via the typedef approach.
```
struct MyStruct { }; // ok
typedef struct { } MyStructTD; // ok
void MyStruct() { } // (1) - ok Hides struct MyStruct
void MyStructTD() { } // (2) - not-ok - ill-formed
//> Or if you flip it around, consider in a new translation unit:
void MyStruct() { } // ok
void MyStructTD() { } // ok
struct MyStruct { }; // ok
typedef struct { } MyStructTD; // Not ok
```
---
> 3) You cannot use a typedef name in an elaborated type specifier
```
struct MyStruct { }; // ok
typedef struct { } MyStructTD; // ok
int main()
{
void MyStruct();
void MyStructTD(); // ok - new declarative region
struct MyStruct ms; // ok - names the type
struct MyStructTD ms2; // not ok - cannot use typedef-name here
}
struct AnotherStruct
{
friend struct MyStruct; // ok
friend struct MyStructTD; // not ok
};
```
---
> 4) You cannot use it to define nested structs
```
struct S { struct M; };
typedef struct { } S::M; // not ok
struct S::M { }; // ok
```
As you can see, there is a discernible difference between the two. Some of the quirks of typedefs are a result of C compatibility (which is mainly why both ways exist i believe) - and in most cases, declaring the name in the class-head is more natural C++ - it has its advantages (especially when you need to define constructors and destructors), and is therefore preferable. If you are writing code that needs to be C and C++ compatible, then there is benefit to using both approaches. But if you are writing pure C++, I find specifying the class name in the class-head to be more readable. | Purpose of struct, typedef struct, in C++ | [
"",
"c++",
"struct",
""
] |
How can I order the mysql result by varchar column that contains day of week name?
Note that MONDAY should goes first, not SUNDAY. | Either redesign the column as suggested by Williham Totland, or do some string parsing to get a date representation.
If the column *only* contains the day of week, then you could do this:
```
ORDER BY FIELD(<fieldname>, 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY');
``` | Why not this?
```
ORDER BY (
CASE DAYOFWEEK(dateField)
WHEN 1 THEN 7 ELSE DAYOFWEEK(dateField)
END
)
```
I believe this orders Monday to Sunday... | Order by day_of_week in MySQL | [
"",
"mysql",
"sql",
"sql-order-by",
"dayofweek",
""
] |
I have a 3rd party component which requires me to give it the bitsperpixel from a bitmap.
What's the best way to get "bits per pixel"?
My starting point is the following blank method:-
```
public int GetBitsPerPixelMethod( system.drawing.bitmap bitmap )
{
//return BitsPerPixel;
}
``` | Use the [Pixelformat property](http://msdn.microsoft.com/en-us/library/system.drawing.image.pixelformat.aspx), this returns a [Pixelformat enumeration](http://msdn.microsoft.com/en-us/library/system.drawing.imaging.pixelformat.aspx) which can have values like f.e. `Format24bppRgb`, which obviously is 24 bits per pixel, so you should be able to do something like this:
```
switch(Pixelformat)
{
...
case Format8bppIndexed:
BitsPerPixel = 8;
break;
case Format24bppRgb:
BitsPerPixel = 24;
break;
case Format32bppArgb:
case Format32bppPArgb:
...
BitsPerPixel = 32;
break;
default:
BitsPerPixel = 0;
break;
}
``` | Rather than creating your own function, I'd suggest using this existing function in the framework:
```
Image.GetPixelFormatSize(bitmap.PixelFormat)
``` | how to get Bitsperpixel from a bitmap | [
"",
"c#",
"drawing",
""
] |
I do not know Python, I have installed it only and downloaded the libgmail package. So, please give me verbatim steps in installing the libgmail library. My python directory is c:\python26, so please do not skip any steps in the answer.
Thanks! | All you have to do is extract it, and put it somewhere (I prefer the Libs folder in your Python directory). Then read the readme. It explains that you need to do:
```
python setup.py
```
in your command line. Then you're done. | The easiest way might be to install [easy\_install](http://pypi.python.org/pypi/setuptools) using the instructions at that page and then typing the following at the command line:
```
easy_install libgmail
```
If it can't be found, then you can point it directly to the file that you downloaded:
```
easy_install c:\biglongpath\libgmail.zip
``` | How to install Python 3rd party libgmail-0.1.11.tar.tar into Python in Windows XP home? | [
"",
"python",
""
] |
I understand the benefits of using the standard MS event handler delegate signature as it allows you to easily expand on the information passed through the event with out breaking any old relationships that are based on the old delegate signature.
What I'm wondering is in practice how often do people follow this rule? Say I have a simple event like this
```
public event NameChangedHandler NameChanged;
public delegate void NameChangedHandler(Object sender, string oldName, string newName);
```
It's a simple event, and I'm nearly positive that the only arguments I'm ever going to need to know from the NameChanged event is the object whose name changed, the old name, and the new name. So is it worth it to create a separate NameChangedEventArgs class, or for simple events like this is it acceptable to just return the the arguments directly through the delegate arguments? | You can do anything the wrong way if you're the only one who has to deal with it. But it's not a bad idea to learn standards and stick to them so that you keep good habits when you're working on code with others.
So I'll make you a deal. If you promise to do it the right way, I'll give you a code snippet that'll make it much less of a pain. Just put this in a .snippet file, and put that file in:
My Documents\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets\
(or Visual Studio 2005 if applicable)
And here's the snippet; use it in VS by typing ev2Generic and hitting Tab:
```
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Generic event with two types/arguments.</Title>
<Shortcut>ev2Generic</Shortcut>
<Description>Code snippet for event handler and On method</Description>
<Author>Kyralessa</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type1</ID>
<ToolTip>Type of the first property in the EventArgs subclass.</ToolTip>
<Default>propertyType1</Default>
</Literal>
<Literal>
<ID>arg1Name</ID>
<ToolTip>Name of the first argument in the EventArgs subclass constructor.</ToolTip>
<Default>property1Name</Default>
</Literal>
<Literal>
<ID>property1Name</ID>
<ToolTip>Name of the first property in the EventArgs subclass.</ToolTip>
<Default>Property1Name</Default>
</Literal>
<Literal>
<ID>type2</ID>
<ToolTip>Type of the second property in the EventArgs subclass.</ToolTip>
<Default>propertyType2</Default>
</Literal>
<Literal>
<ID>arg2Name</ID>
<ToolTip>Name of the second argument in the EventArgs subclass constructor.</ToolTip>
<Default>property2Name</Default>
</Literal>
<Literal>
<ID>property2Name</ID>
<ToolTip>Name of the second property in the EventArgs subclass.</ToolTip>
<Default>Property2Name</Default>
</Literal>
<Literal>
<ID>eventName</ID>
<ToolTip>Name of the event</ToolTip>
<Default>NameOfEvent</Default>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[public class $eventName$EventArgs : System.EventArgs
{
public $eventName$EventArgs($type1$ $arg1Name$, $type2$ $arg2Name$)
{
this.$property1Name$ = $arg1Name$;
this.$property2Name$ = $arg2Name$;
}
public $type1$ $property1Name$ { get; private set; }
public $type2$ $property2Name$ { get; private set; }
}
public event EventHandler<$eventName$EventArgs> $eventName$;
protected virtual void On$eventName$($eventName$EventArgs e)
{
var handler = $eventName$;
if (handler != null)
handler(this, e);
}]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
``` | Use the `EventHandler<T>` generic delegates for your events and create a type derived from `EventArgs` to hold your event data. So in other words, always. It's something that you always know exactly how it works when you come across it because it's never done otherwise.
Edit:
Code analysis [CA1003: Use generic event handler instances](http://msdn.microsoft.com/en-us/library/ms182178.aspx)
Code analysis [CA1009: Declare event handlers correctly](http://msdn.microsoft.com/en-us/library/ms182133.aspx) | How wrong is it to create an event handler delegate with out the standard (Obj sender, EventArgs args) signature? | [
"",
"c#",
"events",
"eventargs",
""
] |
I know how to do this in MVC:
```
<title> <%= Model.Title %> </title>
```
I also know how to bind a SQLDataSource or ObjectDataSource to a control on a form or listview.
But how do I render a field from my SQLDataSource or ObjectDataSource directly into the HTML? | You can use the `Page.Title` property to set the title in code behind.
Once you've run your SelectCommand or equivalent on your data source, just simply assign Page.Title a value from the result set.
Alternately, you can use the aspx page itself, and just inside the html assign a text string, like this:
```
<title>
<%= dataSource.Select(...) %>
</title>
``` | You can declare a property and set its value using your desired field's value.
Code-behind:
```
private string myTitle;
protected string MyTitle
{
get { return myTitle; }
set { myTitle = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
MyTitle = "Testing 123!";
}
```
Markup: `<title><%= MyTitle %></title>` | How do I bind a database field to an HTML TITLE element in ASP.NET 2.0? | [
"",
"c#",
"asp.net",
"html",
"rendering",
""
] |
I have a PHP script vieworder.php that includes other scripts at the top.
```
<?php
include "../includes/config.php";
include "../includes/session.php";
include "../includes/functions.php";
//...
?>
```
I get an error on this PHP script. It tells me this:
```
Warning: mysql_num_rows(): supplied argument ... in vieworder.php on line 185
```
Do I need to refer only to line 185 of that vieworder.php script or do I need to take into account the included scripts? I am guessing the latter?
Also when it says "Warning" - can I pretty much ignore it? Or is this something I should be very concerned with?
I notice this error causes other errors for me such as:
```
Warning: Division by zero in ... vieworder.php on line 340
```
I am guessing its because 0 rows have been returned.
Apologies, for this messy question but I am noob and things are inter-related.
## Update
So everyone can see this:
The first occurrence of mysql\_num\_rows() in vieworder.php is line 235. On line 185 there is an empty line and before that all the way to the top there is only 1 mysql\_query?!!
## Update 2
I will actually put this in another question. | A *supplied argument is not a valid MySQL result resource* is often caused by a preceding MySQL query that failed for some reason and [`mysql_query`](http://docs.php.net/mysql_query) returned a *false* instead of the MySQL resource.
So you might want to check if the query was successful (see [`mysql_error`](http://docs.php.net/mysql_error) and [`mysql_errno`](http://docs.php.net/mysql_errno)) before you do anything with that MySQL resource. | ```
Warning: mysql_num_rows(): supplied argument ... in vieworder.php on line 185
```
Means that you should look for the error around line 185 in vieworder.php, not in any of the included files.
Warnings may be ignored, but it's rarely a good idea, they're there for a reason. | Error Levels and Error on which line? | [
"",
"php",
"mysql",
""
] |
I got this error on my image generation script :
> Warning: imageftbbox() [function.imageftbbox]: Problem loading glyph:
I think because of this I can't generate images from text properly - how do I fix this! | there was a problem loading a font file. check the path, filename etc. | If there is a problem with the path/filename you'll get a "Invalid font filename" warning.
"Problem loading glyph" means that there is an actual problem with the file's format, i.e. [FT\_Load\_Glyph](http://freetype.sourceforge.net/freetype2/docs/reference/ft2-base_interface.html#FT_Load_Glyph) of the gd library wasn't able to interpret the font definition. | Warning: imageftbbox() [function.imageftbbox] - what is this error | [
"",
"php",
"gd",
"image-manipulation",
""
] |
I tried adding a `frontpage.php` file to the content directory, but that wasn't being loaded. Now I've added the following snippet to assure I'm getting a context of 'frontpage':
```
add_filter('cfct_context', 'scompt_front_page_context');
function scompt_front_page_context($context) {
if( is_front_page() )
return 'frontpage';
return $context;
}
```
That is allowing me to create a `frontpage.php` file in the loop directory, but I'm still unable to get it to use my file for the content. | Not exaclty sure what you're trying to do, but in order to use a page template in Wordpress, you must have this at the top of the file:
```
<?php
/*
Template Name: mypage
*/
?>
```
and that goes before
```
<?php get_header(); ?>
```
And in order for Wordpress to use the template, you have to select it in the page editing area in admin.
So, for a "frontpage," use a template named home.php - with the template name as above - and select it as the template to use in the page editor. | you need two pages to get this to work.
1. page\_example.php (make newfile in same directory as page.php)
2. pages/page\_example.php (copy and rename page\_default.php)
page\_example.php
must have this header only
```
<?php
/*
Template Name: Page example
*/
if (__FILE__ == $_SERVER['SCRIPT_FILENAME']) { die(); }
if (CFCT_DEBUG) { cfct_banner(__FILE__); }
cfct_page('page_example');
?>
```
and
pages/page\_example.php is the page it calls so really all your changes need to be in here.
ie remove the side bar, get\_sidebar();
now select this page as usual when you are creating a page. | How do you make a WordPress front page template in the Carrington blog theme? | [
"",
"php",
"wordpress",
"themes",
"carrington",
""
] |
i have a class and have declared an enum in it like
```
public enum file_type {readonly, readwrite, system}
```
Now based on a condition i want to set the enum file\_type to a value something like
```
if("file is markedreadonly")
file_type = readonly;
```
is it possible to do so in c# | By writing file\_type = readonly, you are trying to change the definition of an Enum at runtime, which is not allowed.
Create variable of type file\_type and then set it to readonly.
Also, please use .NET naming standards to name your variable and types. Additionally for Enums, it is recommended to have a 'None' enum as the first value.
```
public enum FileType { None, ReadOnly, ReadWrite, System}
FileType myFileType = FileType.None;
if( //check if file is readonly)
myFileType = FileType.ReadOnly;
``` | Your syntax is wrong. file\_type is a type, not a variable. Also, you need @readonly, since readonly is a reserved word. | assign an enum value to an enum based on a condition in c# | [
"",
"c#",
"enums",
""
] |
I found this Perl script while [migrating my SQLite database to mysql](https://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/25860)
I was wondering (since I don't know Perl) how could one rewrite this in Python?
Bonus points for the shortest (code) answer :)
**edit**: sorry I meant shortest code, not strictly shortest answer
```
#! /usr/bin/perl
while ($line = <>){
if (($line !~ /BEGIN TRANSACTION/) && ($line !~ /COMMIT/) && ($line !~ /sqlite_sequence/) && ($line !~ /CREATE UNIQUE INDEX/)){
if ($line =~ /CREATE TABLE \"([a-z_]*)\"(.*)/){
$name = $1;
$sub = $2;
$sub =~ s/\"//g; #"
$line = "DROP TABLE IF EXISTS $name;\nCREATE TABLE IF NOT EXISTS $name$sub\n";
}
elsif ($line =~ /INSERT INTO \"([a-z_]*)\"(.*)/){
$line = "INSERT INTO $1$2\n";
$line =~ s/\"/\\\"/g; #"
$line =~ s/\"/\'/g; #"
}else{
$line =~ s/\'\'/\\\'/g; #'
}
$line =~ s/([^\\'])\'t\'(.)/$1THIS_IS_TRUE$2/g; #'
$line =~ s/THIS_IS_TRUE/1/g;
$line =~ s/([^\\'])\'f\'(.)/$1THIS_IS_FALSE$2/g; #'
$line =~ s/THIS_IS_FALSE/0/g;
$line =~ s/AUTOINCREMENT/AUTO_INCREMENT/g;
print $line;
}
}
```
Some additional code was necessary to successfully migrate the sqlite database (handles one line Create table statements, foreign keys, fixes a bug in the original program that converted empty fields `''` to `\'`.
I [posted the code on the migrating my SQLite database to mysql Question](https://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/1067365#1067365) | Here's a pretty literal translation with just the minimum of obvious style changes (putting all code into a function, using string rather than re operations where possible).
```
import re, fileinput
def main():
for line in fileinput.input():
process = False
for nope in ('BEGIN TRANSACTION','COMMIT',
'sqlite_sequence','CREATE UNIQUE INDEX'):
if nope in line: break
else:
process = True
if not process: continue
m = re.search('CREATE TABLE "([a-z_]*)"(.*)', line)
if m:
name, sub = m.groups()
line = '''DROP TABLE IF EXISTS %(name)s;
CREATE TABLE IF NOT EXISTS %(name)s%(sub)s
'''
line = line % dict(name=name, sub=sub)
else:
m = re.search('INSERT INTO "([a-z_]*)"(.*)', line)
if m:
line = 'INSERT INTO %s%s\n' % m.groups()
line = line.replace('"', r'\"')
line = line.replace('"', "'")
line = re.sub(r"([^'])'t'(.)", r"\1THIS_IS_TRUE\2", line)
line = line.replace('THIS_IS_TRUE', '1')
line = re.sub(r"([^'])'f'(.)", r"\1THIS_IS_FALSE\2", line)
line = line.replace('THIS_IS_FALSE', '0')
line = line.replace('AUTOINCREMENT', 'AUTO_INCREMENT')
print line,
main()
``` | [Alex Martelli's solution above](https://stackoverflow.com/questions/1067060/translating-perl-to-python/1067151#1067151) works good, but needs some fixes and additions:
In the lines using regular expression substitution, the insertion of the matched groups must be double-escaped OR the replacement string must be prefixed with r to mark is as regular expression:
```
line = re.sub(r"([^'])'t'(.)", "\\1THIS_IS_TRUE\\2", line)
```
or
```
line = re.sub(r"([^'])'f'(.)", r"\1THIS_IS_FALSE\2", line)
```
Also, this line should be added before print:
```
line = line.replace('AUTOINCREMENT', 'AUTO_INCREMENT')
```
Last, the column names in create statements should be backticks in MySQL. Add this in line 15:
```
sub = sub.replace('"','`')
```
Here's the complete script with modifications:
```
import re, fileinput
def main():
for line in fileinput.input():
process = False
for nope in ('BEGIN TRANSACTION','COMMIT',
'sqlite_sequence','CREATE UNIQUE INDEX'):
if nope in line: break
else:
process = True
if not process: continue
m = re.search('CREATE TABLE "([a-z_]*)"(.*)', line)
if m:
name, sub = m.groups()
sub = sub.replace('"','`')
line = '''DROP TABLE IF EXISTS %(name)s;
CREATE TABLE IF NOT EXISTS %(name)s%(sub)s
'''
line = line % dict(name=name, sub=sub)
else:
m = re.search('INSERT INTO "([a-z_]*)"(.*)', line)
if m:
line = 'INSERT INTO %s%s\n' % m.groups()
line = line.replace('"', r'\"')
line = line.replace('"', "'")
line = re.sub(r"([^'])'t'(.)", "\\1THIS_IS_TRUE\\2", line)
line = line.replace('THIS_IS_TRUE', '1')
line = re.sub(r"([^'])'f'(.)", "\\1THIS_IS_FALSE\\2", line)
line = line.replace('THIS_IS_FALSE', '0')
line = line.replace('AUTOINCREMENT', 'AUTO_INCREMENT')
if re.search('^CREATE INDEX', line):
line = line.replace('"','`')
print line,
main()
``` | Translating Perl to Python | [
"",
"python",
"perl",
"url-rewriting",
""
] |
Or, practically, how can I sort a list of dictionaries by multiple keys?
I have a list of dicts:
```
b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0},
{u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0},
{u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0},
{u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0},
{u'TOT_PTS_Misc': u'Lawson, Roman', u'Total_Points': 80.0},
{u'TOT_PTS_Misc': u'Lempke, Sam', u'Total_Points': 80.0},
{u'TOT_PTS_Misc': u'Gnezda, Alex', u'Total_Points': 78.0},
{u'TOT_PTS_Misc': u'Kirks, Damien', u'Total_Points': 78.0},
{u'TOT_PTS_Misc': u'Worden, Tom', u'Total_Points': 78.0},
{u'TOT_PTS_Misc': u'Korecz, Mike', u'Total_Points': 78.0},
{u'TOT_PTS_Misc': u'Swartz, Brian', u'Total_Points': 66.0},
{u'TOT_PTS_Misc': u'Burgess, Randy', u'Total_Points': 66.0},
{u'TOT_PTS_Misc': u'Smugala, Ryan', u'Total_Points': 66.0},
{u'TOT_PTS_Misc': u'Harmon, Gary', u'Total_Points': 66.0},
{u'TOT_PTS_Misc': u'Blasinsky, Scott', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Carter III, Laymon', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Coleman, Johnathan', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Venditti, Nick', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Blackwell, Devon', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Kovach, Alex', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Bolden, Antonio', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Smith, Ryan', u'Total_Points': 60.0}]
```
and I need to use a multi key sort reversed by Total\_Points, then not reversed by `TOT_PTS_Misc`.
This can be done at the command prompt like so:
```
a = sorted(b, key=lambda d: (-d['Total_Points'], d['TOT_PTS_Misc']))
```
But I have to run this through a function, where I pass in the list and the sort keys. For example, `def multikeysort(dict_list, sortkeys):`.
How can the lambda line be used which will sort the list, for an arbitrary number of keys that are passed in to the multikeysort function, and take into consideration that the sortkeys may have any number of keys and those that need reversed sorts will be identified with a '-' before it? | This answer works for any kind of column in the dictionary -- the negated column need not be a number.
```
def multikeysort(items, columns):
from operator import itemgetter
comparers = [((itemgetter(col[1:].strip()), -1) if col.startswith('-') else
(itemgetter(col.strip()), 1)) for col in columns]
def comparer(left, right):
for fn, mult in comparers:
result = cmp(fn(left), fn(right))
if result:
return mult * result
else:
return 0
return sorted(items, cmp=comparer)
```
You can call it like this:
```
b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0},
{u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0},
{u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0},
{u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0},
{u'TOT_PTS_Misc': u'Lawson, Roman', u'Total_Points': 80.0},
{u'TOT_PTS_Misc': u'Lempke, Sam', u'Total_Points': 80.0},
{u'TOT_PTS_Misc': u'Gnezda, Alex', u'Total_Points': 78.0},
{u'TOT_PTS_Misc': u'Kirks, Damien', u'Total_Points': 78.0},
{u'TOT_PTS_Misc': u'Worden, Tom', u'Total_Points': 78.0},
{u'TOT_PTS_Misc': u'Korecz, Mike', u'Total_Points': 78.0},
{u'TOT_PTS_Misc': u'Swartz, Brian', u'Total_Points': 66.0},
{u'TOT_PTS_Misc': u'Burgess, Randy', u'Total_Points': 66.0},
{u'TOT_PTS_Misc': u'Smugala, Ryan', u'Total_Points': 66.0},
{u'TOT_PTS_Misc': u'Harmon, Gary', u'Total_Points': 66.0},
{u'TOT_PTS_Misc': u'Blasinsky, Scott', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Carter III, Laymon', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Coleman, Johnathan', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Venditti, Nick', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Blackwell, Devon', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Kovach, Alex', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Bolden, Antonio', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Smith, Ryan', u'Total_Points': 60.0}]
a = multikeysort(b, ['-Total_Points', 'TOT_PTS_Misc'])
for item in a:
print item
```
Try it with either column negated. You will see the sort order reverse.
Next: change it so it does not use extra class....
---
2016-01-17
Taking my inspiration from this answer [What is the best way to get the first item from an iterable matching a condition?](https://stackoverflow.com/questions/2361426/what-is-the-best-way-to-get-the-first-item-from-an-iterable-matching-a-condition), I shortened the code:
```
from operator import itemgetter as i
def multikeysort(items, columns):
comparers = [
((i(col[1:].strip()), -1) if col.startswith('-') else (i(col.strip()), 1))
for col in columns
]
def comparer(left, right):
comparer_iter = (
cmp(fn(left), fn(right)) * mult
for fn, mult in comparers
)
return next((result for result in comparer_iter if result), 0)
return sorted(items, cmp=comparer)
```
In case you like your code terse.
---
Later 2016-01-17
This works with python3 (which eliminated the `cmp` argument to `sort`):
```
from operator import itemgetter as i
from functools import cmp_to_key
def cmp(x, y):
"""
Replacement for built-in function cmp that was removed in Python 3
Compare the two objects x and y and return an integer according to
the outcome. The return value is negative if x < y, zero if x == y
and strictly positive if x > y.
https://portingguide.readthedocs.io/en/latest/comparisons.html#the-cmp-function
"""
return (x > y) - (x < y)
def multikeysort(items, columns):
comparers = [
((i(col[1:].strip()), -1) if col.startswith('-') else (i(col.strip()), 1))
for col in columns
]
def comparer(left, right):
comparer_iter = (
cmp(fn(left), fn(right)) * mult
for fn, mult in comparers
)
return next((result for result in comparer_iter if result), 0)
return sorted(items, key=cmp_to_key(comparer))
```
Inspired by this answer [How should I do custom sort in Python 3?](https://stackoverflow.com/questions/2531952/how-should-i-do-custom-sort-in-python-3) | [This article](https://web.archive.org/web/20150222160237/stygianvision.net/updates/python-sort-list-object-dictionary-multiple-key/) has a nice rundown on various techniques for doing this. If your requirements are simpler than "full bidirectional multikey", take a look. It's clear the accepted answer and the blog post I just
referenced influenced each other in some way, though I don't know which order.
In case the link dies here's a very quick synopsis of examples not covered above:
```
mylist = sorted(mylist, key=itemgetter('name', 'age'))
mylist = sorted(mylist, key=lambda k: (k['name'].lower(), k['age']))
mylist = sorted(mylist, key=lambda k: (k['name'].lower(), -k['age']))
``` | How to sort objects by multiple keys? | [
"",
"python",
"sorting",
"dictionary",
""
] |
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps JavaScript API Example: Simple Streetview Example</title>
<script src="http://maps.google.com/maps?file=api&v=2.x&key=<?=APIKEY?>"
type="text/javascript"></script>
<script type="text/javascript">
var myPano;
var newPoint;
function initialize() {
var fenwayPark = new GLatLng(42.345573,-71.098326);
var address = "1600 Amphitheatre Parkway, Mountain View, CA, USA";
var geocoder = new GClientGeocoder();
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
newPoint = point;
alert("inside of function: " + newPoint);
}
});
alert("outside of function: " + newPoint);
panoramaOptions = { latlng:fenwayPark };
myPano = new GStreetviewPanorama(document.getElementById("pano"), panoramaOptions);
GEvent.addListener(myPano, "error", handleNoFlash);
}
function handleNoFlash(errorCode) {
if (errorCode == FLASH_UNAVAILABLE) {
alert("Error: Flash doesn't appear to be supported by your browser");
return;
}
}
</script>
```
when I run this code, the alert("outside of function: " + newPoint); have not got any value, but in the function alert("inside of function: " + newPoint); it gets.
complete code:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps JavaScript API Example: Simple Streetview Example</title>
<script src="http://maps.google.com/maps?file=api&v=2.x&key=ABQIAAAAgVzm2syhpm0A5rAKFMg3FBS-DTtkk0JB-Y_gKL-3MRZwBHch9RSjWJj17-fEEecjCvYeo1i7w_1yPw"
type="text/javascript"></script>
<script type="text/javascript">
var myPano;
function initialize() {
var geocoder = new GClientGeocoder();
var address = "1600 Amphitheatre Parkway, Mountain View, CA, USA";
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
panoramaOptions = { latlng:point };
myPano = new GStreetviewPanorama(document.getElementById("pano"), panoramaOptions);
GEvent.addListener(myPano, "error", handleNoFlash);
}
});
}
function handleNoFlash(errorCode) {
if (errorCode == FLASH_UNAVAILABLE) {
alert("Error: Flash doesn't appear to be supported by your browser");
return;
}
}
</script>
```
I want to show the street view of address:1600 Amphitheatre Parkway, Mountain View, CA, USA when opening the page | You fixed the problem with the asynchronous `getLatLng()`. The only problem with your new code is that there is no panorama at the address you requested (take the '1600' out and it will work). There is a function that will return the point of the nearest panorama: [getNearestPanoramaLatLng()](http://code.google.com/apis/maps/documentation/reference.html#GStreetviewClient.getNearestPanoramaLatLng). It will return null if there isn't a nearby panorama. Here's how to use it in your code:
```
function initialize() {
var geocoder = new GClientGeocoder();
var panoClient = new GStreetviewClient();
var address = "1600 Amphitheatre Parkway, Mountain View, CA, USA";
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
panoClient.getNearestPanoramaLatLng(point, function(newPoint) {
if (newPoint == null) {
alert("no panorama found");
return;
}
panoramaOptions = { latlng:newPoint};
myPano = new GStreetviewPanorama(document.getElementById("pano"), panoramaOptions);
GEvent.addListener(myPano, "error", handleNoFlash);
});
}
});
}
``` | The inner function is a callback function. Meaning, it waits until the geocode api call has finished running before it executes. This is known as asynchronous execution. You'll notice that the outside alert fires before the inside alert even though the inside alert is written earlier.
Any code that needs a valid newPoint value will need to be executed from within the call back function, just like the inside alert. | javascript global variable question | [
"",
"javascript",
"google-maps",
""
] |
How can I do this in XAML:
*PSEUDO-CODE:*
```
<TextBox Text="{Binding Password}" Type="Password"/>
```
so that the user sees stars or dots when he is typing in the password.
I've tried [various examples](http://pstaev.blogspot.com/2007/01/password-textbox-in-wpf.html) which suggest **PasswordChar** and **PasswordBox** but can't get these to work.
e.g. I can do this as shown [here](http://www.a2zdotnet.com/View.aspx?id=84):
```
<PasswordBox Grid.Column="1" Grid.Row="1"
PasswordChar="*"/>
```
but I of course want to bind the Text property to my ViewModel so I can send the value the bound TextBox when the button is clicked (not working with code behind), I want to do this:
```
<TextBox Grid.Column="1" Grid.Row="0"
Text="{Binding Login}"
Style="{StaticResource FormTextBox}"/>
<PasswordBox Grid.Column="1" Grid.Row="1"
Text="{Binding Password}"
PasswordChar="*"
Style="{StaticResource FormTextBox}"/>
```
But PasswordBox doesn't have a Text property. | To get or set the Password in a PasswordBox, use the Password property. Such as
```
string password = PasswordBox.Password;
```
This doesn't support Databinding as far as I know, so you'd have to set the value in the codebehind, and update it accordingly. | As Tasnim Fabiha mentioned, it is possible to change font for TextBox in order to show only dots/asterisks. But I wasn't able to find his font...so I give you my working example:
```
<TextBox Text="{Binding Password}"
FontFamily="pack://application:,,,/Resources/#password" />
```
Just copy-paste won't work. Firstly you have to download mentioned font "password.ttf"
link: <https://github.com/davidagraf/passwd/blob/master/public/ttf/password.ttf>
Then copy that to your project Resources folder (Project->Properties->Resources->Add resource->Add existing file). Then set it's Build Action to: Resource.
After this you will see just dots, but you can still copy text from that, so it is needed to disable CTRL+C shortcut like this:
```
<TextBox Text="{Binding Password}"
FontFamily="pack://application:,,,/Resources/#password" >
<TextBox.InputBindings>
<!--Disable CTRL+C (COPY) -->
<KeyBinding Command="ApplicationCommands.NotACommand"
Key="C"
Modifiers="Control" />
<!--Disable CTRL+X (CUT) -->
<KeyBinding Command="ApplicationCommands.NotACommand"
Key="X"
Modifiers="Control" />
</TextBox.InputBindings>
<TextBox.ContextMenu>
<!--Hide context menu where you could copy/cut as well -->
<ContextMenu Visibility="Collapsed" />
</TextBox.ContextMenu>
</TextBox>
```
EDIT:
Added Ctrl+X and Context menu disabling based on @CodingNinja comment, thank you. | How can I make a TextBox be a "password box" and display stars when using MVVM? | [
"",
"c#",
"wpf",
"xaml",
"mvvm",
"textbox",
""
] |
Take two lists, second with same items than first plus some more:
```
a = [1,2,3]
b = [1,2,3,4,5]
```
I want to get a third one, containing only the new items (the ones not repeated):
```
c = [4,5]
```
The solution I have right now is:
```
>>> c = []
>>> for i in ab:
... if ab.count(i) == 1:
... c.append(i)
>>> c
[4, 5]
```
Is there any other way more pythonic than this?
Thanx folks! | at the very least use a list comprehension:
```
[x for x in a + b if (a + b).count(x) == 1]
```
otherwise use the [set](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset) class:
```
list(set(a).symmetric_difference(set(b)))
```
there is also a more compact form:
```
list(set(a) ^ set(b))
``` | If the order is not important and you can ignore repetitions within `a` and `b`, I would simply use sets:
```
>>> set(b) - set(a)
set([4, 5])
```
Sets are iterable, so most of the times you do not need to explicitly convert them back to list. If you have to, this does it:
```
>>> list(set(b) - set(a))
[4, 5]
``` | Get the items not repeated in a list | [
"",
"python",
""
] |
I am running an executable jar and wish to find a list of classes WITHIN the jar so that I can decide at run-time which to run. It's possible that I don't know the name of the jar file so cannot unzip it | You can not enumerate classes from a package of jar using Reflection API. This is also made clear in the related questions [how-can-i-enumerate-all-classes-in-a-package](https://stackoverflow.com/questions/176527/how-can-i-enumerate-all-classes-in-a-package-and-add-them-to-a-list) and
[can-i-list-the-resources-in-a-given-package](https://stackoverflow.com/questions/186496/can-i-list-the-resources-in-a-given-package). I once wrote a tool that lists all classes found in a certain classpath. It's too long to paste here, but here is the general approach:
1. find the used classpath. This is shown nicely by eirikma in another answer.
2. add other places where the ClassLoader might search for classes, e.g. bootclasspath, endorsed lib in JRE etc. (If you just have a simple app, then 1 + 2 are easy, just take the class path from property.)
* `readAllFromSystemClassPath("sun.boot.class.path");`
* `readAllFromSystemClassPath("java.endorsed.dirs");`
* `readAllFromSystemClassPath("java.ext.dirs");`
* `readAllFromSystemClassPath("java.class.path");`
3. Scan the classpath and split folders from JARs.
* `StringTokenizer pathTokenizer = new StringTokenizer(pPath, File.pathSeparator);`
4. Scan the folders with `File.listFiles` and open the JARs with `ZipFile.entries`. Pay attention to inner classes and package access classes, you propably do not want them.
* `isInner = (pClassName.indexOf('$') > -1);`
5. Convert the file name or path in the JAR to a proper classname (/ -> .)
* `final int i = fullName.lastIndexOf(File.separatorChar);`
* `path = fullName.substring(0, i).replace(File.separatorChar, '.');`
* `name = fullName.substring(i + 1);`
6. Now you can use Reflection to load that class and have a look into it. If you just want to know stuff of about the class you can load it without resolving, or use a byte code engineering library like [BCEL](http://jakarta.apache.org/bcel/index.html) to open the class without loading it into the JVM.
* `ClassLoader.getSystemClassLoader().loadClass(name).getModifiers() & Modifier.PUBLIC` | I am not sure if there is a way to list all classes visible to the current classloader.
Lacking that, you could
a) try to find out the name of the jar file from the classpath, and then look at its contents.
or
b) supposing that you have a candidate list of classes you are looking for, try each of them with Class.forName(). | How to find classes when running an executable jar | [
"",
"java",
"reflection",
"jar",
""
] |
I'm studying how to build java webapps for JBossAS 5.1.0 and I'm trying to build a very basic jsp web app on JBossAS5 using a JNDI datasource for data access.
When trying to open a connection I get this exception:
```
21:42:52,834 ERROR [STDERR] Cannot get connection: org.jboss.util.NestedSQLException:
Unable to get managed connection for hedgehogDB; - nested throwable:
(javax.resource.ResourceException: Unable to get managed connection for hedgehogDB)
```
The datasource is deployed ok, I can see it in the jmx-console & the database files are getting created ok.
Java code in question where the exception is thrown:
```
static public Connection getHedgehogConnection()
{
Connection result = null;
try
{
String DS_Context = "java:comp/env/jdbc/hedgehogDB";
Context initialContext = new InitialContext();
if ( initialContext == null)
log("JNDI problem. Cannot get InitialContext.");
DataSource datasource = (DataSource)initialContext.lookup(DS_Context);
if (datasource != null)
result = datasource.getConnection();
else
log("Failed: datasource was null");
}
catch(Exception ex)
{
log("Cannot get connection: " + ex);
}
return result;
}
```
web.xml:
```
<web-app>
<resource-ref>
<res-ref-name>jdbc/hedgehogDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
```
jboss-web.xml:
```
<jboss-web>
<resource-ref>
<res-ref-name>jdbc/hedgehogDB</res-ref-name>
<jndi-name>java:/hedgehogDB</jndi-name>
</resource-ref>
</jboss-web>
```
hedgehogdb-ds.xml
```
<datasources>
<local-tx-datasource>
<jndi-name>hedgehogDB</jndi-name>
<connection-url>jdbc:hsqldb:${jboss.server.data.dir}${/}hypersonic${/}hedgehogDB</connection-url>
<driver-class>org.hsqldb.jdbcDriver</driver-class>
<user-name>sa</user-name>
<password></password>
<min-pool-size>5</min-pool-size>
<max-pool-size>20</max-pool-size>
<idle-timeout-minutes>0</idle-timeout-minutes>
<track-statements/>
<security-domain>HsqlDbRealm</security-domain>
<prepared-statement-cache-size>32</prepared-statement-cache-size>
<metadata>
<type-mapping>Hypersonic SQL</type-mapping>
</metadata>
<depends>jboss:service=Hypersonic,database=hedgehogDB</depends>
</local-tx-datasource>
<mbean code="org.jboss.jdbc.HypersonicDatabase"
name="jboss:service=Hypersonic,database=hedgehogDB">
<attribute name="Database">hedgehogDB</attribute>
<attribute name="InProcessMode">true</attribute>
</mbean>
</datasources>
```
This is my first time in this environment and I suspect that I'm missing something really basic. | Figured it out:
The culprit was this in hedgehogdb-ds.xml :
```
<security-domain>HsqlDbRealm</security-domain>
```
HsqlDbRealm was configured for a different DS & was causing the connection to fail. | it's also possible to in -ds.xml use < application-managed-security / > instead of < security-domain >, at lease in Jboss6 | can't get DB Connection using JNDI datasource on JBoss | [
"",
"java",
"jboss",
"jndi",
"jboss5.x",
""
] |
What is the correct way to declare a multidimensional array and assign values to it?
This is what I have:
```
int x = 5;
int y = 5;
String[][] myStringArray = new String [x][y];
myStringArray[0][x] = "a string";
myStringArray[0][y] = "another string";
``` | Try replacing the appropriate lines with:
```
myStringArray[0][x-1] = "a string";
myStringArray[0][y-1] = "another string";
```
Your code is incorrect because the sub-arrays have a length of `y`, and indexing starts at 0. So setting to `myStringArray[0][y]` or `myStringArray[0][x]` will fail because the indices `x` and `y` are out of bounds.
`String[][] myStringArray = new String [x][y];` is the correct way to initialise a rectangular multidimensional array. If you want it to be jagged (each sub-array potentially has a different length) then you can use code similar to [this answer](https://stackoverflow.com/questions/1067073/java-multidimensional-array/1067087#1067087). Note however that John's assertion that you have to create the sub-arrays manually is incorrect in the case where you want a perfectly rectangular multidimensional array. | Java doesn't have "true" multidimensional arrays.
For example, `arr[i][j][k]` is equivalent to `((arr[i])[j])[k]`. In other words, `arr` is simply **an array, of arrays, of arrays**.
So, if you know how arrays work, you know how multidimensional arrays work!
---
**Declaration:**
```
int[][][] threeDimArr = new int[4][5][6];
```
or, with initialization:
```
int[][][] threeDimArr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };
```
---
**Access:**
```
int x = threeDimArr[1][0][1];
```
or
```
int[][] row = threeDimArr[1];
```
---
**String representation:**
```
Arrays.deepToString(threeDimArr);
```
yields
```
"[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]"
```
## Useful articles
* [Java: Initializing a multidimensional array](https://programming.guide/java/initialize-multidimensional-array.html)
* [Java: Matrices and Multidimensional Arrays](https://programming.guide/java/matrices-and-multidimensional-arrays.html) | Initialising a multidimensional array in Java | [
"",
"java",
"multidimensional-array",
""
] |
I need a fast method to determine if a given string is in a list of strings.
The list of strings is not known until runtime but thereafter it will not change.
I could simply have a `List<String>` called `strings` and then do:
```
if (strings.Contains(item))
```
However this will perform poorly if there are many strings in the list.
I could also use a `HashSet<String>`, but this would necessitate calling `GetHashCode` on every incoming string as well as `Equals`, which would be a waste if there are e.g. only 3 strings in the list. Did I mention this needs to be **fast**?
I could when setting up, decide to use a `List` or a `HashSet` depending on the number of strings (e.g. use List for less than 10 strings, HashSet otherwise), rather like the logic in `HybridDictionary`.
As the strings are unicode, a standard Trie structure will not work, although a Radix tree/Patricia trie might. Are there any good C# implementations out there with benchmarks?
Some have mentioned bypassing `String`'s `GetHashCode` and using a faster performing hash function. Are there any benchmarks out there?
Using LINQ expressions to essentially create an optimised switch statement is a novel approach which looks very interesting.
What else would work? Setup cost is not important, just the search speed.
If it matters, the incoming string values will rarely appear in the list. | Check out these:
[Jomo Fisher - Fast Switching with LINQ](http://blogs.msdn.com/jomo_fisher/archive/2007/03/28/fast-switching-with-linq.aspx)
[Gustavo Guerra - StaticStringDictionary - Fast Switching with LINQ revisited](http://functionalflow.co.uk/blog/2008/08/28/staticstringdictionary-fast-switching-with-linq-revisited/) | You could use a [trie](http://en.wikipedia.org/wiki/Trie) to hold the list of strings; tries were designed for fast re*trie*val. Here's [one example](http://www.kerrywong.com/2006/04/01/implementing-a-trie-in-c/) of implementing a trie in C#.
**Update**: [Powerpoint presentation on folded tries for Unicode](http://icu-project.org/docs/papers/foldedtrie_iuc21.ppt) and [Ifo on implementation of a folded trie for Unicode (not C#)](http://icu-project.org/repos/icu/icuhtml/trunk/design/properties/utrie2.html) | Fast string comparison with list | [
"",
"c#",
"list",
"string",
""
] |
My gateway sends(posts) my server an xml datafeed when a purchase is made. The XML looks something like this:
```
<?xml version='1.0' standalone='yes'?>
<foxydata>
<datafeed_version>XML FoxyCart Version 0.6</datafeed_version>
<transactions>
<transaction>
<id>616</id>
<transaction_date>2007-05-04 20:53:57</transaction_date>
<customer_id>122</customer_id>
<customer_first_name>Dirk</customer_first_name>
<customer_last_name>Gently</customer_last_name>
<shipping_total>4.38</shipping_total>
<order_total>24.38</order_total>
<order_total>24.38</order_total>
<customer_password>1aab23051b24582c5dc8e23fc595d505</customer_password>
<custom_fields>
<custom_field>
<custom_field_name>My_Cool_Text</custom_field_name>
<custom_field_value>Value123</custom_field_value>
</custom_field>
</custom_fields>
<transaction_details>
<transaction_detail>
<product_name>foo</product_name>
<product_price>20.00</product_price>
<product_quantity>1</product_quantity>
<product_weight>0.10</product_weight>
<product_code></product_code>
<subscription_frequency>1m</subscription_frequency>
<subscription_startdate>2007-07-07</subscription_startdate>
<next_transaction_date>2007-08-07</next_transaction_date>
<shipto>John Doe</shipto>
<category_description>Default for all products</category_description>
<category_code>DEFAULT</category_code>
<product_delivery_type>shipped</product_delivery_type>
<transaction_detail_options>
<transaction_detail_option>
<product_option_name>color</product_option_name>
<product_option_value>blue</product_option_value>
<price_mod></price_mod>
<weight_mod></weight_mod>
</transaction_detail_option>
</transaction_detail_options>
</transaction_detail>
</transaction_details>
<shipto_addresses>
<shipto_address>
<address_name>John Doe</address_name>
<shipto_first_name>John</shipto_first_name>
<shipto_last_name>Doe</shipto_last_name>
<shipto_address1>2345 Some Address</shipto_address1>
<shipto_address2></shipto_address2>
<shipto_city>Some City</shipto_city>
<shipto_state>TN</shipto_state>
<shipto_postal_code>37013</shipto_postal_code>
<shipto_country>US</shipto_country>
<shipto_shipping_service_description>DHL: Next Afternoon</shipto_shipping_service_description>
<shipto_subtotal>52.15</shipto_subtotal>
<shipto_tax_total>6.31</shipto_tax_total>
<shipto_shipping_total>15.76</shipto_shipping_total>
<shipto_total>74.22</shipto_total>
<shipto_custom_fields>
<shipto_custom_field>
<shipto_custom_field_name>My_Custom_Info</shipto_custom_field_name>
<shipto_custom_field_value>john's stuff</shipto_custom_field_value>
</shipto_custom_field>
<shipto_custom_field>
<shipto_custom_field_name>More_Custom_Info</shipto_custom_field_name>
<shipto_custom_field_value>more of john's stuff</shipto_custom_field_value>
</shipto_custom_field>
</shipto_custom_fields>
</shipto_address>
</shipto_addresses>
</transaction>
</transactions>
</foxydata>
XML;
```
As a first time XML parsing experiencing, I was hoping somebody could show me how I would go about going through and turning this into a php array or something like that so I can then insert the data I want into a mysql table.
Whats the easiest way to go about doing this? | You can use the [builtin XML parser](http://php.net/manual/en/book.xml.php), the manual should give you everything you need. But speaking from experience, I would really recommend learning [Xpath](http://www.w3schools.com/XPath/xpath_examples.asp), since it is *much* faster and much easier to use then anything else you can get with PHP. You could start with the [introduction@w3schools](http://www.w3schools.com/XPath/xpath_syntax.asp), have a look at the [nice examples in the specs](http://www.w3.org/TR/xpath20/#unabbrev) and eventually use the [PHP functions](http://php.net/manual/en/class.domxpath.php).
A sample query for selecting the transaction id would be
```
$document = new DOMDocument();
$document->load('YourFile.xml');
$xpath = new DOMXPath($document);
# Query id
$ids = $xpath->query('/transactions/transaction/id/text()');
# $ids is a DOMNodeList object
assert($ids->length === 1);
$id = $ids->item(0);
# Query date
$dates = $xpath->query('/transactions/transaction/transaction_date/text()');
# $dates is a DOMNodeList object
assert($dates->length === 1);
$id = $dates->item(0);
``` | you can use a PHP XML parser, like [SimpleXML](https://www.php.net/simplexml) | How do I process an XML file with php? | [
"",
"php",
"xml",
""
] |
I have a configurable report. For each field that can be included on the report, there's a key (stored in report preferences), a label, potentially an access level, and a SQL descriptor -- something like `foo as my_foo`.
In a Java app, I would create a class called ReportField with each of the properties listed above. I'd use a private constructor, and list each of the fields in the class like this:
```
public final static ReportField FOO = new ReportField('foo', 'Foo', 1, 'foo as my_foo');
```
I'd probably create a static array of all of the fields, add a static method that allows a field to be looked up by key, and so forth. Then in other places I could write code like:
```
List<String> selectFields = new ArrayList<String>();
for (ReportPref pref : reportPrefs) {
selectFields.add(ReportField.getByKey(pref.getField()).getFieldSql());
}
```
Apologies for the Java code, but hopefully you get my point.
Is there an idiomatic way to solve the same problem in PHP? I can think of a number of solutions -- nested associative arrays will do the trick -- but I'd like to avoid a hackish solution. | I don't know Java super well, but you can do most of that - just have to do it differently, unless I misunderstand your question.
Data members on PHP classes can't have runtime-calculated values, such as new object instances. So, this would not work
```
class ReportField
{
public static $foo = new ReportField()
}
```
*Note: `final` properties are not allowed except on methods*
It's actually really curious to me that you're making one class responsible for two things - an object blueprint AND static storage for instances of itself as well.
Anyway, here's what I *think* your code would look like in PHP
```
<?php
class ReportField
{
public static $store = array();
private
$key,
$label,
$accessLevel,
$sql;
private function __construct( $key, $label, $accessLevel, $sql )
{
$this->key = $key;
$this->label = $label;
$this->accessLevel = $accessLevel;
$this->sql = $sql;
}
public static function initializeStore()
{
if ( empty( self::$store ) )
{
self::$store['foo'] = new self( 'foo', 'Foo', 1, 'foo as my_foo' );
// repeat
}
}
public static function getByKey( $key )
{
if ( empty( self::$store ) )
{
self::initializeStore();
}
if ( isset( self::$store[$key] ) )
{
return self::$store[$key];
}
throw new Exception( __CLASS__ . " instance identified by key $key not found" );
}
public function getFieldSql()
{
return $this->sql;
}
}
// Usage
$selectFields = array();
foreach ( $reportPrefs as $pref )
{
$selectFields[] = ReportField::getByKey( $pref->getField() )->getFieldSql();
}
``` | Why not create objects in PHP like you would in Java?
```
class ReportField {
private $key;
public __construct($key, $label, $access_level, $sql) {
$this->key = $key;
...
}
public getKey() { return $this->key; }
...
}
$fields = array(
new ReportField(...),
new ReportField(...),
);
foreach ($fields as $field) {
echo $field->getKey();
}
```
and so on.
Other than that, associative arrays can be just fine. | PHP solution for creating a list of static value objects | [
"",
"php",
"oop",
""
] |
How to check whether the PHP variable is an array?
$value is my PHP variable and how to check whether it is an array? | echo is\_array($variable);
<https://www.php.net/is_array> | php has function named is\_array($var) which returns bool to indicate whether parameter is array or not
<http://ir.php.net/is_array> | How to identify a PHP variable is an array or not | [
"",
"php",
""
] |
Operator overloading in C++ is considered by many to be A Bad Thing(tm), and a mistake not to be repeated in newer languages. Certainly, it was one feature specifically dropped when designing Java.
Now that I've started reading up on Scala, I find that it has what looks very much like operator overloading (although technically it doesn't have operator overloading because it doesn't have operators, only functions). However, it wouldn't seem to be qualitatively different to the operator overloading in C++, where as I recall operators are defined as special functions.
So my question is what makes the idea of defining "+" in Scala a better idea than it was in C++? | C++ inherits true blue operators from C. By that I mean that the "+" in 6 + 4 is very special. You can't, for instance, get a pointer to that + function.
Scala on the other hand doesn't have operators in that way. It just has great flexibility in defining method names plus a bit of built in precedence for non-word symbols. So technically Scala doesn't have operator overloading.
Whatever you want to call it, operator overloading isn't inherently bad, even in C++. The problem is when bad programmers abuse it. But frankly, I'm of the opinion that taking away programmers ability to abuse operator overloading doesn't put a drop in the bucket of fixing all the things that programmers can abuse. The real answer is mentoring. <http://james-iry.blogspot.com/2009/03/operator-overloading-ad-absurdum.html>
None-the-less, there are differences between C++'s operator overloading and Scala's flexible method naming which, IMHO, make Scala both less abusable and more abusable.
In C++ the only way to get in-fix notation is using operators. Otherwise you must use object.message(argument) or pointer->messsage(argument) or function(argument1, argument2). So if you want a certain DSLish style to your code then there's pressure to use operators.
In Scala you can get infix notation with any message send. "object message argument" is perfectly ok, which means you don't need to use non-word symbols just to get infix notation.
C++ operator overloading is limited to essentially the C operators. Combined with the limitation that only operators may be used infix that puts pressure on people to try to map a wide range of unrelated concepts onto a relatively few symbols like "+" and ">>"
Scala allows a huge range of valid non-word symbols as method names. For instance, I've got an embedded Prolog-ish DSL where you can write
```
female('jane)! // jane is female
parent('jane,'john)! // jane is john's parent
parent('jane, 'wendy)! // jane is wendy's parent
mother('Mother, 'Child) :- parent('Mother, 'Child) & female('Mother) //'// a mother of a child is the child's parent and is female
mother('X, 'john)? // find john's mother
mother('jane, 'X)? // find's all of jane's children
```
The :-, !, ?, and & symbols are defined as ordinary methods. In C++ only & would be valid so an attempt to map this DSL into C++ would require some symbols that already evoke very different concepts.
Of course, this also opens up Scala to another kind of abuse. In Scala you can name a method $!&^% if you want to.
For other languages that, like Scala, are flexible in the use of non-word function and method names see Smalltalk where, like Scala, every "operator" is just another method and Haskell which allows the programmer to define precedence and fixity of flexibly named functions. | > Operator overloading in C++ is
> considered by many to be A Bad
> Thing(tm)
Only by the ignorant. It is absolutely required in a language like C++, and it is noticeable that other languages that started off taking a "purist" view, have added it once their designers found out how necessary it is. | What makes Scala's operator overloading "good", but C++'s "bad"? | [
"",
"c++",
"scala",
"operator-overloading",
""
] |
I have a text file like so
```
{word} definition
{another word} another definition {word} they don't have to be on different lines
```
The regex I was using was
```
$regex = '/\{([a-z]+?)\}(.+?)\{/i';
```
This however, causes problems in that it *swallows* the last brace {, and then it won't match the next { in the next word.
To demonstrate, I did this for debugging purposes
```
echo preg_replace($regex, '<b style="background-color: red;">$1</b><b style="background-color: yellow;">$2</b>', $content);
```
Here is an example of my output (notice the opening brace in the next word isn't there, therefore it is not matched in the regex)
```
<b style="background-color: red;">shrub</b><b style="background-color: yellow;"> Multi stemmed woody plant</b>Abaxial} side or face away from the axis
```
How can I amend my regex to get this to work? Thank you
**EDIT**
Many thanks for your answers. I've changed my regex like so
```
$regex = '/\{([a-z\-\s]+?)\}([^\{]+)/i';
```
I'll also look into the lookahead articles. | For this specific case, you could do:
```
$regex = '/\{([a-z]+?)\}([^\{]+)/i';
```
`[^\{]` means "match any character that is not a left brace". This also has the advantage of not requiring a `{` at the end of your input.
More generally, you can also use lookahead assertions as others have mentioned. | You'll want to use the [Look Ahead](http://www.phpro.org/tutorials/Introduction-to-PHP-Regex.html#10) feature to find a character, without capturing it.
You could restructure your regex as so.
```
$regex = '/\{([a-z]+?)\}(.+?)(?={)';
``` | How do I make a regex not 'swallow' a character? | [
"",
"php",
"regex",
""
] |
I have an image slider that I built for my website, and I have it set to slide every 3 seconds (will be slower after diagnostics, but I don't like waiting 10 seconds to see what's wrong). I also have it set so that before it auto-slides, it checks if the `toSlide` variable is set to 1 (default) or not. When the user clicks on a next/previous link or to a certain slide, it sets `toSlide` to 0.
My problem is that it auto-slides again, then sets `toSlide` back to 1, and I can't figure out why. Could anybody help me please?
You can see the HTML on [my site](http://www.kerrickdesign.com/), and here is the Javascript:
```
//Featured Work Image Slider
// sC = sliderCount
// sA = slideAmount
// pH = pictureHeight
// sT = slideTime
var sC = 1;
var pH = 364;
var sT = 364
var toSlide = 1;
function slide(ms) {
$('#featured-box li').stop().animate({'top':sA},ms);
$('.sN').css({color:'#598dbe'});
$('#sN'+sC).css({color:'#464646'});
$('#fD > div').fadeOut(ms,function(){
$(this).css({display:'none'});
});
$('#fD-'+sC).fadeIn(ms,function(){
$('#fD-'+sC).css({display:'block'});
});
console.log(toSlide);
}
function autoSlide(ms) {
if(sC < 4) {
sC++;
sA = -(sC - 1) * pH;
} else {
sC = 1;
sA = 0;
}
slide(ms);
if(toSlide = 1) {
setTimeout ( "autoSlide(sT)", 3000 );
}
}
$(document).ready(function() {
setTimeout ( "autoSlide(sT)", 3000 );
$('#sL').click(function(){
toSlide = 0;
if(sC > 1) {
sC--;
sA = -(sC - 1) * pH;
} else {
sC = 4;
sA = -3 * pH;
}
slide(sT);
return false;
});
$('#sN').click(function(){
toSlide = 0;
if(sC < 4) {
sC++;
sA = -(sC - 1) * pH;
} else {
sC = 1;
sA = 0;
}
slide(sT);
return false;
});
$('.sN').click(function(){
toSlide = 0;
var sNid = this.id.split('sN');
sC = sNid[1];
sA = -(sC - 1) * pH;
slide(sT);
return false;
});
});
``` | ```
if (toSlide = 1) {
```
This is an assignment not a comparison. You want to do:
```
if (toSlide === 1) {
```
The altered full function:
```
function autoSlide(ms) {
if(sC < 4) {
sC++;
sA = -(sC - 1) * pH;
} else {
sC = 1;
sA = 0;
}
slide(ms);
if(toSlide === 1) {
setTimeout ( "autoSlide(sT)", 3000 );
}
}
``` | if(toSlide = 1) should be if(toSlide == 1)
This has bitten many people in c style languages | Why does my variable keep resetting itself? | [
"",
"javascript",
"jquery",
"html",
"variables",
""
] |
I plan to add functionalities to TextBox with the following:
```
public class TextBoxExt : TextBox
{
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
}
}
```
The question is how can we use this TextBoxExt? Is there anyway to get this class onto the ToolBox so that we can just drag and drop it onto the form? If not, what is the best way to use the TextBoxExt? | 1. Build you project with TextBoxExt, make sure it compiles ok.
2. With the form that you want TextBoxExt on, open the toolbox, right click and select "choose items"
3. Browse to you .exe or dll that you compiled in 1)
4. make sure that TextBoxExt has a tick next to it, press ok
5. TextBoxExt should appear in the toolbox, drag it onto your form
(There is another way of doing this, opening the designer file and renaming the instances of TextBox to TextBoxExt but manual editing of designer files can be considered hazardous by some) | I know this is super old question, but maybe still useful for someone else that has same problem like me - as it's still on the top Google :)
You might interest to use ToolboxItemAttribute (<http://msdn.microsoft.com/en-us/library/system.componentmodel.toolboxitemattribute(v=vs.110).aspx>).
I did this at my end to resolve the problem.
```
[ToolboxItem(true)]
public class PanelTitle : LabelControl {
// Whatever code to override LabelControl here...
}
```
Rebuild the solution and the extended control should be shown in the toolbox. | How to put an extended WinForms Control on ToolBox | [
"",
"c#",
"winforms",
""
] |
I dynamically load a library in C++ like described [here](https://stackoverflow.com/questions/496664/c-dynamic-shared-library-on-linux).
My abstract base class looks like this:
```
#include <boost/ptr_container/ptr_list.hpp>
class Base {
public:
virtual void get_list(boost::ptr_list<AnotherObject>& list) const = 0;
};
```
And my library now provides a derived class `Derived`
```
class Derived : public Base { ... };
void Derived::get_list(boost::ptr_list<AnotherObject& list) const {
list.push_back(new AnotherObject(1));
list.push_back(new AnotherObject(2));
}
```
and `create` and `destroy` functions
```
extern "C" {
Base* create() { new Derived; }
destroy(Base* p) { delete p; }
}
```
My client program loads the library and the two `create` and `destroy` functions. Then it creates an instance of `Derived` and uses it:
```
Base* obj = create();
boost::ptr_list<AnotherObject> list;
obj->get_list(list);
```
Now my problem: When the list is filled by the library the library's `new` is called to create the `AnotherObject`s. On the other hand when the list is destroyed the client's `delete` is called for destroying the `AnotherObject`s. What can I do to avoid this problem? | 1. Use a `std::list<shared_ptr<AnotherObject> >`.
2. Pass a custom deleter to the shared\_ptr that calls the proper delete. | The easy answer is to insist that both application and library are compiled with the same version of the compiler, in which case they will both get the same new/delete versions. | Transfer a boost::ptr_list from a library to a client | [
"",
"c++",
"linux",
"boost",
"shared-libraries",
""
] |
The only one I know of is called "e" which is used for test bench design in hardware design and verification but I want something for general purpose programming. | Aspect oriented programming isn't so much a defining feature of a language, it's a paradigm that can be applied to many existing programming languages. You'd be hard-pressed to find a specific language that's aspect oriented in nature, though one could exist that makes adding cross-cutting concerns easy out of the box. Starting with [Wikipedia's entry on Aspect-oriented programming](http://en.wikipedia.org/wiki/Aspect-oriented_programming#Implementations) should point you to several implementations specifically for C++. | Although there's a few limitations - C# can be used for AOP.
You might want to look [at c-sharpcorner](http://www.c-sharpcorner.com/UploadFile/raviraj.bhalerao/aop12062005022058AM/aop.aspx) and [developerfusion](http://www.developerfusion.com/article/5307/aspect-oriented-programming-using-net/3/). | What aspect oriented language is a good place to start for a c++ programmer | [
"",
"c++",
"aop",
""
] |
Note: This is a long winded question and requires a good understanding of the MVVM "design pattern", JSON and jQuery....
So I have a theory/claim that MVVM in DHTML is **possible** and **viable** and want to know if you agree/disagree with me and why. Implementing MVVM in DHTML revolves around using ajax calls to a server entity that returns JSON and then using html manipulation via javascript to control the html.
So to break it down. Lets say I'm building a search page that searches for People in a database.....
The **View** would look something like this:
```
<body viewmodel="SearchViewModel">
Search:<br />
<input type="text" bindto="SearchString" /><br />
<input type="button" value="Search" command="Search" />
<br />
<table bindto="SearchResults">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>${FirstName}</td>
<td>${LastName}</td>
</tr>
</tbody>
</table>
</body>
```
Using some non standard attributes on my html elements, I have declaritively defined a **View** and how it will interact with my **ViewModel**. I've created a **MVVM parser in javascript** that interprets the non-standard attributes and associates the View with a JSON object that represents the ViewModel.
The **ViewModel** would be a JSON object:
```
//View Model SearchViewModel would be assocaited with View because of <body viewmodel="SearchViewModel">
var SearchViewModel = {
//SearchString variable has a TwoWay binding
//to <input type="text" bindto="SearchString" /><
//if a user types into the text box, the SearchString property will "auto-magically" be updated
//because of the two way binding and how the element was interpreted via my MVVM parser
SearchString: '',
//SearchResults has a OneWay binding to <table bindto="SearchResults">
SearchResults: new Array(),
//Search function will get "auto-magically" get called because of
//the command binding to <input type="button" command="Search" />
Search: function() {
//using jquery to call into the server asynchronously
//when the server call is completed, the PopulateSearchResults method will be called
$.getJSON("www.example.com/SearchForPerson",
{ searchString: SearchViewModel.SearchString },
SearchViewModel.PopulateSearchResults);
}
PopulateSearchResults: function(data) {
//set the JSON array
SearchViewModel.SearchResults = data;
//simulate INotifyPropertyChanged using the MVVM parser
mvvmParser.notifyPropertyChanged("SearchResults");
}
}
```
The **Model** can be any server side asset that returns JSON...in this example, I used asp MVC as a restful facade:
```
public JsonResult SearchForPerson(string searchString)
{
PersonDataContext personDataContext = new PersonDataContext(); //linq to sql.....
//search for person
List<Person> results =
personDataContext.Persons
.Where(p => p.FirstName.Contains(searchString)
|| p.LastName.Contains(searchString))
.ToList();
return Json(results);
}
```
So, again the question:
**Is MVVM possible/viable in a DHTML RIA application (no Silverlight/WPF) or have I lost my mind?**
**Could this "MVVM framework" be a good idea?**
**Proof of Concept: [kaboom.codeplex.com](http://kaboom.codeplex.com).** | This would probably be a good time to link to [knockout JS](http://knockoutjs.com/), which is a javascript mvvm framework.
You may also want to look at [backbone](http://documentcloud.github.com/backbone/), a javascript MVC framework: | Take a look at the ASP.NET data binding features in .NET 4.0 - comes out with Visual Studio 2010. This is exactly what you are looking for if you are ok with MS technology.
[Blog that details the feature](http://blogs.visoftinc.com/archive/2009/05/27/ASP.NET-4.0-AJAX-Preview-4-Data-Binding.aspx)
Community technology preview on [codeplex](http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24645)
Theoretically you could just include the ASP.NET AJAX js file from your HTML files & make the solution cross-platform.
So to directly answer your question - it absolutely is a viable solution to the problem of creating maintainable, loosely coupled web user interfaces. And yes, the server side of your application is doing less - it becomes more of a true service layer, where all it deals with is data exchange. This is actually a good thing, b/c it promotes reuse across clients. Imagine your WPF app and your web app using the same middle tier server to send/receive data? Clients have a lot of available processing power anyway - why not leverage it to make you solution more scalable (the less the server is doing, the more work your clients are doing, which is distributed across ALL clients)
The tricky part is two way binding - where you hook into the event that some object had changed, and the event that something in the user interface has changed (user typed something into an input control, for example). One way binding would still be useful.
It seems like Microsoft is the only company right now building a full solution in the pattern you want. Yahoo's YUI library does do data binding that is semi-coherent, but not in the same pattern as WPF/Silverlight like you have built. | Is MVVM possible/viable in a DHTML RIA application (no Silverlight/WPF)? | [
"",
"javascript",
"asp.net-mvc",
"json",
"mvvm",
"dhtml",
""
] |
I'm using a static analyzer in Eclipse to examine my code. One class, foo, has an inner class, bar. I am getting the following error:
```
JAVA0043 Inner class 'bar' does not use outer class 'foo'
```
Why is this an error? As long as the outer class uses the inner class isn't that sufficient to make this information hiding useful and correct?
The inner class is not static. | If the inner class can only ever be used by the outer class, yet the inner class needs no reference to the outer class, then you can make it `private static`.
If the inner class is known to someone other than the outer class, then it might as well be a top-level class in its own right. | Looks like an [Enerjy Error](http://www.enerjy.com/explorer/help/rules/JAVA0043.html):
```
// Incorrect
class Log {
// Position never uses the enclosing Log instance,
// so it should be static
class Position {
private int line;
private int column;
Position(int line, int column) {
this.line = line;
this.column = column;
}
}
}
```
A nested class that does not use any instance variables or methods from any of its outer classes **can be declared static**.
This reduces the dependency between the two classes, which enhances readability and maintenance.
```
// Correct
class Log {
static class Position {
private int line;
private int column;
Position(int line, int column) {
this.line = line;
this.column = column;
}
}
}
``` | What is wrong with an inner class not using an outer class in Java? | [
"",
"java",
"static-analysis",
""
] |
I'm learning C# now and a beginner in the programming world.
I have a book called The Complete Reference by Herbert Schildt. So far its a good book and I'm in the middle of learning about methods and constructors.
I'm quite confused what's the difference of methods and constructors. Because in the book it has almost the same example. I don't know how to differentiate them.
I would appreciate your idea.
By the way I have several definition here of both, I just would like to know how to differentiate them
Thanks for your help
Cheers | A constructor only works when you create a new instance of a class. This is the very first method to run on an instance, it has to run, and it runs exactly once.
A method on an instance can be called anywhere between zero times to infinite times on an instance once it is created.
A constructor is run implicitly. When a new instance of a class is created, it runs automatically. A method is run explicitly. It has to be called either from some outside source or from a method -or a constructor- in the class.
A constructor is intended to be used for wiring. In the constructor, you want to avoid doing actual work. You basically prepare the class to be used. A method is intended to do actual work.
```
public class MyType
{
private SomeType _myNeeds;
// constructor
MyType(SomeType iWillNeedThis)
{
_myNeeds = iWillNeedThis;
}
// method
public void MyMethod()
{
DoSomethingAbout(_myNeeds);
}
}
``` | A constructor is a method.. a special method that is being called upon "construction" of the class.
> **Definition**: A constructor is a class
> member function in C++ and C# that has
> the same name as the class itself.
>
> The purpose of the constructor is to
> initialize all member variables when
> an object of this class is created.
> Any resources acquired such as memory
> or open files are typically released
> in the class destructor.
From [About.com](http://cplus.about.com/od/glossar1/g/constructor.htm) | methods and constructors | [
"",
"c#",
""
] |
In Python `remove()` will remove the first occurrence of value in a list.
How to remove *all* occurrences of a value from a list?
This is what I have in mind:
```
>>> remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
[1, 3, 4, 3]
``` | Functional approach:
**Python 3.x**
```
>>> x = [1,2,3,2,2,2,3,4]
>>> list(filter((2).__ne__, x))
[1, 3, 3, 4]
```
or
```
>>> x = [1,2,3,2,2,2,3,4]
>>> list(filter(lambda a: a != 2, x))
[1, 3, 3, 4]
```
or
```
>>> [i for i in x if i != 2]
```
**Python 2.x**
```
>>> x = [1,2,3,2,2,2,3,4]
>>> filter(lambda a: a != 2, x)
[1, 3, 3, 4]
``` | You can use a list comprehension:
```
def remove_values_from_list(the_list, val):
return [value for value in the_list if value != val]
x = [1, 2, 3, 4, 2, 2, 3]
x = remove_values_from_list(x, 2)
print x
# [1, 3, 4, 3]
``` | Remove all occurrences of a value from a list? | [
"",
"python",
"list",
""
] |
I'm learning *C++*, then i was searching for some codes for learn something in the area that i love: *File I/O*, but i want to know how i can tweak my code for the user type the file that he wants to see, like in *wget*, but with my program like this:
```
C:\> FileSize test.txt
```
The code of my program is here:
```
// obtaining file size
#include <iostream>
#include <fstream>
using namespace std;
int main () {
long begin,end;
ifstream myfile ("example.txt");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size is: " << (end-begin) << " bytes.\n";
return 0;
}
```
Thanks! | In the example below argv contains command line arguments as null terminated string array and argc contains an integer telling you how many arguments where passed.
```
#include <iostream>
#include <fstream>
using namespace std;
int main ( int argc, char** argv )
{
long begin,end;
if( argc < 2 )
{
cout << "No file was passed. Usage: myprog.exe filetotest.txt";
return 1;
}
ifstream myfile ( argv[1] );
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size is: " << (end-begin) << " bytes.\n";
return 0;
}
``` | `main()` takes parameters:
```
int main(int argc, char** argv) {
...
ifstream myfile (argv[1]);
...
}
```
You could also get clever, and loop for each file specified on the command line:
```
int main(int argc, char** argv) {
for (int file = 1; file < argc; file++) {
...
ifstream myfile (argv[file]);
...
}
}
```
Note that argv[0] is a string pointing to the name of your own program. | Enter File Name When Executing Program In C++ | [
"",
"c++",
"file-io",
""
] |
I am a C# programmer, and after going through some wonderful discussions regarding functional programming and declarative programming. I feel I am not good at both :P, so, I was thinking of starting learning prolog, and haskell. Please suggest about the feasibility in doing so. And if I learn F#, then learning Haskell makes any sense ? What qualities these languages would provide me which can help me in writing better c# programs ? | 1. Like the first time you went from imperative to object-oriented, working with functional programming requires a rewiring of how you think things out. The first time you tend to do things in a hybrid fashion until you get the gist of it all. Since you are coming from C# background, I would suggest trying F# as you are likely to get used to it much more quickly since the .net languages share a common framework which is good enough to get you started.
2. That said going directly to Prolog and Haskell is not a bad idea but you might have to first adjust to the different syntax and libraries of the languages when compared to the leap between C# and F#. Personally, I went from C#/Java to Haskell by means of 2 books: [RealWorldHaskell](http://book.realworldhaskell.org/read/) and [The Craft of Functional Programming](http://www.cs.kent.ac.uk/people/staff/sjt/craft2e/), and managed fine, so there is no reason for you not to be able to do so. :)
3. Learning F# and then Haskell still requires some work because F# and Haskell are different: the first is "impure" while the second is "pure". Impurity means that certain "side-effects" such as state and IO are intrinsically allowed, while purity means that you don't get them immediately but have to use certain methods (such as monads). Coming from C# it would be perhaps easier to try F# and then Haskell cause of this.
4. I believe (personal opinion warning), that if you want to become a better C# programmer, learning about F# and Haskell (or anything for that matter) can never hurt! Especially in the case of F# which can be integrated with C#. Functional programming may facilitate certain things for you and knowing it might become useful sooner or later especially since it seems, like the others said, that there is a current trend towards functional language programs. | There are very few languages X, if any for which you could not write a Reg Braithwaite approved post of the form "[What I learned from Language X that makes me a better programmer when I use Language Y](http://weblog.raganwald.com/2007/10/three-blog-posts-id-love-to-read-and.html)"
C# itself is accumulating a number of functional constructs -- lambda expressions and the `System.Linq` extension methods -- so learning to think functionally will definitely help you get the best out of the day-job language, as well as being fun in and of itself. As it happened Erlang was the first functional/pattern-matching language I picked up after C#, but that alone was enough to make me look again at my C# style and how I approached problems.
FP is becoming the next big thing, and there's no dearth of languages to look at and decide which suits you most for learning -- Haskell, Erlang, as well as newcomers F#, Scala & Clojure are all riding this wave. | Need to learn Prolog, Haskell for a C# programmer | [
"",
"c#",
"haskell",
"prolog",
""
] |
I have a std::map that is used by multiple threads to store data. The map is declared like this:
```
std::map<int, Call> calls;
```
From each thread, I have to acquire a mutex lock, obtain a pointer or reference to the object belonging to that thread, then release the mutex lock. I can modify the object after that because each object is used only by one thread. As soon as the thread dies, the corresponding pair in the map would also get deleted.
I would like to know the best way to implement this. I was thinking of two ways:
1) I know this one could look outrageously crazy, but still
```
std::map<int, Call> calls;
...
{
mutex.lock();
Call* callptr = &calls[id];
mutex.unlock();
// use callptr
}
```
or 2) I think this one looks more sensible
```
std::map<int, std::auto_ptr<Call> > calls;
...
{
mutex.lock();
std::auto_ptr<Call> callptr = map[id];
mutex.unlock();
// use callptr
mutex.lock();
map[id] = callptr;
mutex.unlock();
}
```
The threads actually are created in a different dll and I don't have the code for that. This dll that I'm writing now gets imported by that dll and used. So it has to be implemented with std::map only, but could anyone tell me if one of these methods is ok or if there are ways to make it more stable.
Thanks | You should use iterators:
```
mutex.lock();
std::map<int, Call>::iterator callptr = calls.find(id);
callptr->second.foo();
...
mutex.unlock();
```
Your first solution with pointers is problematic, because the lifetime of the object in the map is uncertain - it may be moved when the tree is rebalanced when elements are inserted or deleted.
Your second solution won't work at all, because `std::auto_ptr` does not fulfil the requirements for `mapped_type` of `std::map` - mostly because its copy constructor and `operator=` don't actually copy. You likely won't get a compiler error, but you'll get very weird behavior at run-time. | According to me [Thread Local storage](http://msdn.microsoft.com/en-us/library/ms686749%28VS.85%29.aspx) is the best option for you.
If you need thread specific data, you can make use of Thread Local Storage and completely eliminate the need for map and mutex locking. | Pointer to Value in a std::map | [
"",
"c++",
"stl",
""
] |
Okay, I've checked `Environment.SpecialFolder`, but there's nothing in there for this.
I want to get the home directory of the current user in C#. (e.g. `c:\documents and settings\user` under XP, `c:\users\user` under Vista, and `/home/user` under Unix.)
I know I can read enviroment variables to find this out, but I want to do this in a cross-platform way.
Is there any way I can do this with .NET (preferably using mscorlib)?
**UPDATE**: Okay, this is the code I ended up using:
```
string homePath = (Environment.OSVersion.Platform == PlatformID.Unix ||
Environment.OSVersion.Platform == PlatformID.MacOSX)
? Environment.GetEnvironmentVariable("HOME")
: Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%");
``` | `Environment.SpecialFolder.Personal` doesn't actually return the home folder, it returns the *My Documents* folder. The safest way to get the home folder on Win32 is to read `%HOMEDRIVE%%HOMEPATH%`. Reading environment variables is actually very portable to do (across Unix and Windows), so I'm not sure why the poster wanted to *not* do it.
*Edited to add:* For crossplatform (Windows/Unix) C#, I'd read `$HOME` on Unix and OSX and `%HOMEDRIVE%%HOMEPATH%` on Windows. | You are looking for `Environment.SpecialFolder.UserProfile` which refers to `C:\Users\myname` on Windows and `/home/myname` on Unix/Linux:
```
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
```
Note that `Environment.SpecialFolder.Personal` is My Documents (or Documents in win7 and above), but same as home directory on Unix/Linux. | Getting the path of the home directory in C#? | [
"",
"c#",
".net",
""
] |
I need to check that result of expression in where clause is in range of Integers.
something lke this:
```
select * from table where (col1 / col2 ) in (1..8).
```
With `(1..8)` representing a range of integers.
I mean that it must be integer, not float. So that I cant use `between 1 and 8`, because 1.2 will be correct. | You can of course do this:
```
select * from table where (col1 / col2 ) in (1,2,3,4,5,6,7,8);
```
or
```
select * from table where (col1 / col2 ) between 1 and 8
and mod (col1 , col2 ) = 0;
``` | How about
```
select *
from table
where (col1 / col2 ) BETWEEN 1 AND 8
and (col1 / col2 ) = FLOOR(col1 / col2 )
```
This simply checks if the fraction is in the interval, *and* integer. | Is there integer ranges for Where Clause? | [
"",
"sql",
"oracle",
""
] |
I want to track IP addresses visited my website. I want to know what time and what page they visit. I store ip address in VISITORIP, date entered in DATEENTERED and page URL in HTTPADDRESS columns.
I want to group them by dates. My outcome should be like:
```
TIME PAGE
7/12/2009
3:16:27 PM ?Section=products&SubSection=products&CATEGORYID=1
2:46:50 PM ?Section=products&SubSection=products&CATEGORYID=8
2:20:45 PM ?Section=products&SubSection=products&CATEGORYID=11
7/11/2009
9:34:28 AM ?Section=products&SubSection=products&CATEGORYID=7
9:33:31 AM ?Section=products&SubSection=products&CATEGORYID=2
7/10/2009
9:53:16 PM ?Section=products&SubSection=products&CATEGORYID=9
9:34:14 PM ?Section=products&SubSection=products&CATEGORYID=4
9:27:11 PM ?Section=products&SubSection=products&CATEGORYID=3
9:15:47 PM ?Section=products&SubSection=products&CATEGORYID=15
```
Problem is, I could not group them by dates. I get the outcome as:
```
07/12/2009
7/12/2009 3:16:27 PM /html/default.aspProcess=HomeNewSeason&IMAGECONTENT=bg_home_newtaste.gif
7/12/2009 3:16:27 PM /html/default.aspProcess=HomeBestSeller&IMAGECONTENT=bg_home_customerschoice.gif
07/12/2009
7/12/2009 3:16:27 PM /html/default.aspProcess=HomeNewSeason&IMAGECONTENT=bg_home_newtaste.gif
7/12/2009 3:16:27 PM /html/default.aspProcess=HomeBestSeller&IMAGECONTENT=bg_home_customerschoice.gif
07/09/2009
7/9/2009 5:37:02 PM /html/default.aspSection=checkout
07/09/2009
7/9/2009 5:37:02 PM /html/default.aspSection=checkout
07/09/2009
7/9/2009 5:37:02 PM /html/default.aspSection=checkout
```
My codes:
```
<%
Case "TrackIP"
IPADDRESS = Request.QueryString("IPADDRESS")
SQL = "SELECT CONVERT(VARCHAR(10), DATEENTERED, 101) AS DATEENTERED"
SQL = SQL & " FROM STATS"
SQL = SQL & " WHERE VISITORIP = '"& IPADDRESS &"'"
SQL = SQL & " GROUP BY DATEENTERED"
SQL = SQL & " ORDER BY DATEENTERED DESC"
Set objDateEntered = objConn.Execute(SQL)
%>
<table>
<thead>
<tr>
<th>Time</th>
<th>Page</th>
</tr>
</thead>
<tbody>
<% Do While Not objDateEntered.EOF %>
<tr class="row-title">
<td colspan="2"><%=objDateEntered("DATEENTERED")%></td>
</tr>
<%
SQL = "WITH LASTVISIT AS ("
SQL = SQL & " SELECT VISITORIP, MAX(DATEENTERED) AS DATEENTERED"
SQL = SQL & " FROM STATS"
SQL = SQL & " WHERE VISITORIP = '"& IPADDRESS &"' AND CONVERT(VARCHAR(10), DATEENTERED, 101) = CONVERT(VARCHAR(10), '"& objDateEntered("DATEENTERED") &"', 101)"
SQL = SQL & " GROUP BY VISITORIP"
SQL = SQL & " )"
SQL = SQL & " SELECT STATS.VISITORIP, STATS.HTTPADDRESS, STATS.DATEENTERED"
SQL = SQL & " FROM STATS"
SQL = SQL & " INNER JOIN LASTVISIT"
SQL = SQL & " ON LASTVISIT.VISITORIP = STATS.VISITORIP AND LASTVISIT.DATEENTERED = STATS.DATEENTERED"
SQL = SQL & " ORDER BY STATS.DATEENTERED DESC"
Set objTrackIP = objConn.Execute(SQL)
%>
<% Do While Not objTrackIP.EOF %>
<tr class="row-a">
<td><%=objTrackIP("DATEENTERED")%></td>
<td class=""><%=objTrackIP("HTTPADDRESS")%></td>
</tr>
<%
objTrackIP.MoveNext
Loop
%>
<%
objDateEntered.MoveNext
Loop
%>
</tbody>
</table>
```
edit: I think problem is with my outer query. But I grouped them by DATEENTERED field, I dont know what else can I do. | First query should be
```
"SELECT
DISTINCT CONVERT(VARCHAR(10), DATEENTERED, 101) AS vDATE
FROM
STATS
WHERE
VISITORIP = '"& IPADDRESS &"'"
ORDER BY
DATEENTERED DESC"
```
then print the vData column
and the 2nd SQL
```
SELECT
VISITORIP, HTTPADDRESS, CONVERT(VARCHAR(8), DATEENTERED, 8) AS vTIME
FROM
STATS
WHERE
CONVERT(VARCHAR(10), DATEENTERED, 101) = '" & objDateEntered("vDATE") &"'
AND VISITORIP = '"& IPADDRESS &"'
ORDER BY VISITORIP ASC, DATEENTERED DESC
```
I think this will do the trick.. | The problem is in next code line:
```
SELECT CONVERT(VARCHAR(10), DATEENTERED, 101) AS DATEENTERED
```
and then you group by this date
```
GROUP BY DATEENTERED
ORDER BY DATEENTERED DESC
```
You group and order by the varchar.
As I think, you need to use another alias to date when you convert it ro varchar, but you really need to order by dateentered that is datetime type. | tracking IP addresses | [
"",
"sql",
"sql-server",
"asp-classic",
""
] |
I am having a trouble mapping an embedded attribute of a class. I have created some classes that are similar to what I am trying to do to illustrate. Basically, I have an @Embeddable class hierarchy that uses Inheritance. The top level class "Part Number" has only one attribute, and the extending classes add no attributes to the "Part Number" class, they only add some validation/logic.
Here is what I mean:
**PART**
```
@Entity
@Table(name="PART")
public class Part {
private Integer id;
private String name;
private PartNumber partNumber;
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name="PART_NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Embedded
public PartNumber getPartNumber() {
return partNumber;
}
public void setPartNumber(PartNumber partNumber) {
this.partNumber = partNumber;
}
}
```
**PARTNUMBER**
```
@Embeddable
public abstract class PartNumber {
protected String partNumber;
private String generalPartNumber;
private String specificPartNumber;
private PartNumber() {
}
public PartNumber(String partNumber) {
this.partNumber = partNumber;
}
@Column(name = "PART_NUMBER")
public String getPartNumber() {
return partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
/**
* @param partNumber
* @return
*/
public boolean validate(String partNumber) {
// do some validation
return true;
}
/**
* Returns the first half of the Part Number
*
* @return generalPartNumber
*/
@Transient
public String getGeneralPartNumber() {
return generalPartNumber;
}
/**
* Returns the last half of the Part Number
* which is specific to each Car Brand
*
* @return specificPartNumber
*/
@Transient
public String getSpecificPartNumber() {
return specificPartNumber;
}
}
```
**FORD PARTNUMBER**
```
public class FordPartNumber extends PartNumber {
/**
* Ford Part Number is formatted as 1234-#1234
*
* @param partNumber
*/
public FordPartNumber(String partNumber) {
super(partNumber);
validate(partNumber);
}
/*
* (non-Javadoc)
*
* @see com.test.PartNumber#validate(java.lang.String)
*/
@Override
public boolean validate(String partNumber) {
// do some validation
return true;
}
/*
* (non-Javadoc)
*
* @see com.test.PartNumber#getGeneralPartNumber()
*/
@Override
public String getGeneralPartNumber() {
return partNumber;
}
/*
* (non-Javadoc)
*
* @see com.test.PartNumber#getSpecificPartNumber()
*/
@Override
public String getSpecificPartNumber() {
return partNumber;
}
}
```
**CHEVY PARTNUMBER**
```
public class ChevyPartNumber extends PartNumber {
/**
* Chevy Part Number is formatted as 1234-$1234
*
* @param partNumber
*/
public ChevyPartNumber(String partNumber) {
super(partNumber);
validate(partNumber);
}
/*
* (non-Javadoc)
*
* @see com.test.PartNumber#validate(java.lang.String)
*/
@Override
public boolean validate(String partNumber) {
// do some validation
return true;
}
/*
* (non-Javadoc)
*
* @see com.test.PartNumber#getGeneralPartNumber()
*/
@Override
public String getGeneralPartNumber() {
return partNumber;
}
/*
* (non-Javadoc)
*
* @see com.test.PartNumber#getSpecificPartNumber()
*/
@Override
public String getSpecificPartNumber() {
return partNumber;
}
}
```
Of course this does not work, because Hibernate ignores the Inheritance Hierarchy and doesn't like the fact that PartNumber is abstract. **Is there some way to do this using JPA or Hibernate Annotations?** I have tried using the @Inheritance JPA annotation.
I am not able to refactor the "PartNumber" part of the hierarchy because the original Developer wants to be able to extend PartNumber with N many XXXXPartNumber classes.
**Does anyone know if anything like this will be a part of the JPA 2.0 or a new version of Hibernate?** | Component (e.g. @Embeddable) inheritance is not supported and most likely never will be. There is a good reason for that - entity identifier plays a critical role in all inheritance strategies supported by Hibernate and components don't have (mapped) identifiers.
You have three choices:
A) Map PartNumber (and all its descendants) as entities. PartNumber may remain abstract:
```
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="part_type", discriminatorType=DiscriminatorType.STRING)
public abstract class PartNumber {
...
}
@Entity
@DiscriminatorValue("Ford")
public class FordPartNumber extends PartNumber {
...
}
```
B) Based on your example it seems that all PartNumber descendants differ in behavior only (they don't introduce any new properties to be stored). If that's indeed the case, you can map PartNumber properties plus your own discriminator value (so you know which class to instantiate) as @Embedded private property and have get/setPartNumber() accessors in Part class marshall / unmarshall appropriate subclasses. You can even write your own Hibernate custom type to do that for you (it's pretty straightforward).
C) If PartNumber descendants DO differ in properties that have to be stored and mapping them as entities is unacceptable for whatever reason, you can use marshall / unmarshall them to string (as XML or anything else that fits the bill) and store that. I'm using XStream for this exact purpose and I wrote a simple Hibernate type to go with it. Your Part mapping would look something like
```
@Type(type="xmlBean")
public PartNumber getPartNumber() {
return partNumber;
}
public void setPartNumber(PartNumber partNumber) {
this.partNumber = partNumber;
}
```
and PartNumber descendants won't have to be mapped at all. The downside, of course, is that dealing with XML in the database is a bit more of a hassle so that may not be the ideal approach for something you would potentially need to report on. OTOH, I'm using this for storing plugin settings and it saved me **a lot** of trouble with mappings / DB maintenance. | I have a similar problem in my own schema so what I've resorted to at the moment is like this:
Parent class:
```
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@SequenceGenerator(name="SEQ", sequenceName="part_id_seq", initialValue=1, allocationSize=1)
public abstract class BasePart {
@Id
@Column(name="part_id")
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ")
protected Long partId;
@YourBusinessKeyAnnotation
@Column(name="part_number")
protected String partNumber
...
}
```
Child classes:
```
@Entity
public class FordPart extends BasePart {
...
}
@Entity
public class ChevyPart extends BasePart {
...
}
```
Now I could then manipulate the biz key however I needed to and this worked out well because each of the different part types got their own table (which is useful for us).
You also could use `@Embedded` with `@AttributeOverrides` I think to specify the column names differently however you needed... There is an example from the [annotation docs](http://docs.jboss.org/hibernate/stable/annotations/reference/en/html/entity.html).
```
@Entity
public class Person implements Serializable {
// Persistent component using defaults
Address homeAddress;
@Embedded
@AttributeOverrides( {
@AttributeOverride(name="iso2", column = @Column(name="bornIso2") ),
@AttributeOverride(name="name", column = @Column(name="bornCountryName") )
} )
Country bornIn;
...
}
```
...
```
@Entity
public class Person implements Serializable {
// Persistent component using defaults
Address homeAddress;
@Embedded
@AttributeOverrides( {
@AttributeOverride(name="iso2", column = @Column(name="bornIso2") ),
@AttributeOverride(name="name", column = @Column(name="bornCountryName") )
} )
Country bornIn;
...
}
```
...
```
@Embedded
@AttributeOverrides( {
@AttributeOverride(name="city", column = @Column(name="fld_city") ),
@AttributeOverride(name="nationality.iso2", column = @Column(name="nat_Iso2") ),
@AttributeOverride(name="nationality.name", column = @Column(name="nat_CountryName") )
//nationality columns in homeAddress are overridden
} )
Address homeAddress;
```
You may be able to abuse this enough that you won't care... | JPA/Hibernate - Embedding an Attribute | [
"",
"java",
"hibernate",
"jpa",
"jakarta-ee",
""
] |
When using Null Object pattern, how would you 'check' if a situation is invalid?
for e.g
when there's no item found in the repository, display message 'not found' to the user.
Do I have to do a glorified null check?
1. if obj.equals(new NullObject()) { showNotFound(); }
2. if obj.ID.equals( INVALID\_ID) { showNotFound(); }
Those techniques seem to defeat the purpose of Null Object pattern itself | The problem is you are using the Null Object pattern in a scenario where there is not neutral behaviour. Adding to what Matthew has stated, using this pattern only makes sense when you want to invoke an operation without worrying that the reference is null.
[c2.com wiki](http://c2.com/cgi/wiki?NullObjectImplementation) sums it up nicely:
> I have recently come across this issue
> with the null object pattern (see
> NullObjectAndRefactoring). My opinion
> is that if application code needs to
> check whether it is using a NullObject
> or not, then the system is no longer
> using the null object pattern at all,
> because the NullObject class has been
> "promoted" from being a mere
> implementation detail to being a
> concept in the application domain. | In my opinion, you are right. If you need this sort of functionality, just use null, and do null checking and respond for your null state.
Personally, I only really find this useful where an 'empty' value makes sense and you can run with that, hence avoiding null checks. If you need null value (or invalid value) semantics, then null makes sense (and will throw exceptions if you forget to check for it, instead of silently failing). | Checking invalid state when using Null Object pattern | [
"",
"c#",
"design-patterns",
"null-object-pattern",
""
] |
So I have a class with a single string parameter in its constructor:
```
public MyClass(string name)
{
this.Name = name;
}
```
but I never want to worry about some one initializing an instance of MyClass with name that is NULL or a zero length string. What is the best was to validate the parameter? With a property or method you can always just do nothing, return null, or not set anything if an invalid argument is provided. But once a constructor is called the instance of the object is already created regardless of whether it was passed valid arguments.
Is throwing an exception as shown below the best way? Or is there some other method that's more preferred?
```
public MyClass(string name)
{
if (name == null | name == "") throw new ArgumentException("Name can not be null or blank", "name");
this.Name = name;
}
```
Of course I could always set the name to some default like "Unnamed MyClass" if the argument is invalid, but in this case I'd rather just prevent an invalid name then trying to assume some alternate behavior. | 1. Throw an `ArgumentNullException`
2. Document that the ctor throws `ArgumentNullException` if *name* is `null`
3. If you are using [Code Contracts](http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx), add a Contract.EndContractBlock() line after your parameter validation.
Edit: Instead of this:
```
if (name == null || name == "")
```
Use this:
```
if (string.IsNullOrEmpty(name))
``` | The preferred solution here is to throw an exception. Fail early, fail often. Document what the valid parameters are for your constructor and that it throws an `ArgumentNullException` or `ArgumentOutOfRangeException` on invalid parameters.
In my opinion, the salient point is that you don't want to silently absorb failures. Suppose the user typed in a name incorrectly (accidentally left it null, for example). Better to have the operation fail and return notification to the user than to swallow the failure (with, say, a default) and have the user unaware they mistyped their entry.
I asked a similar [question](https://stackoverflow.com/questions/635519/business-validation-logic-code-smell) awhile back to settle an argument with some colleagues.
"But once a constructor is called the instance of the object is already created regardless of whether it was passed valid arguments."
The object is created (i.e., non-null) only if the constructor returns normally. | What is the correct way to validate the arguments of a constructor | [
"",
"c#",
"validation",
"constructor",
""
] |
I am thinking to start writing some REST web services as a way to provide data. I guess that when my REST web services are available, then some of my web applications and console applications will be able to use REST web service as data service to get, add, update and delete data to databases. In addition to that, I would like to add authentication feature to identify any request.
My question is that where should I start? I saw [Microsoft ADO.Net Data Services](http://msdn.microsoft.com/en-us/data/bb931106.aspx). Not sure if this is a good start place? Are there any examples available? | Check out the [REST in WCF MSDN site](http://msdn.microsoft.com/en-us/netframework/cc950529.aspx) and the [starter kit](http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24644). Good article [here](http://www.developer.com/net/article.php/3695436) too. | You may also want to check out **[servicestack.net](http://www.servicestack.net)** An Open Source, cross-platform, high-performance web service framework that lets you develop web services using code-first, strongly-typed DTO's which will automatically (without any configuration) be immediately available on a variety of different endpoints out-of-the-box (i.e. XML, JSON, JSV, SOAP 1.1/1.2).
### REST, RPC and SOAP out of the box
In addition, your same web services can also be made available via any ReST-ful url of your choice where the preferred serialization format can be specified by your REST client i.e.
* Using the HTTP **Accept:** header
* Appending the preferred format to the query string e.g. **?format=xml**
See the [Nothing but REST!](http://www.servicestack.net/ServiceStack.MovieRest/) web service example for how to develop a complete REST-ful Ajax CRUD app with only **1 page of jQuery** and **1 page of C#**.
A good place to start is the **[Hello World example](http://www.servicestack.net/ServiceStack.Hello/)** to see how to easily add ServiceStack web services to any existing ASP.NET web application.
### Performance
For the performance conscience, ServiceStack makes an excellent Ajax server as it comes bundled with the [fastest JSON Serializer for .NET](http://www.servicestack.net/mythz_blog/?p=344) (> 3x faster than other JSON Serializers).
Checkout [this live Ajax app](http://www.servicestack.net/RedisAdminUI/AjaxClient/) for a taste (Live demo hosted on Linux/Nginx/MONO).
## Simple Northwind Example
[ServiceStack](http://www.servicestack.net) also makes it easy to create strong-typed frictionless web services where with just the code below is all you need to return a List of Customer POCOs:
```
public class CustomersService : RestServiceBase<Customers>
{
public IDbConnectionFactory DbFactory { get; set; }
public override object OnGet(Customers request)
{
return new CustomersResponse { Customers = DbFactory.Exec(dbCmd =>
dbCmd.Select<Customer>())
};
}
```
With no other config, you can now call the above webservice REST-fully returning all of:
* [XML](http://www.servicestack.net/ServiceStack.Northwind/customers?format=xml)
* [JSON](http://www.servicestack.net/ServiceStack.Northwind/customers?format=json)
* [CSV](http://www.servicestack.net/ServiceStack.Northwind/customers?format=csv)
* [HTML](http://www.servicestack.net/ServiceStack.Northwind/customers?format=html)
* [JSV](http://www.servicestack.net/ServiceStack.Northwind/customers?format=jsv)
* [SOAP](http://www.servicestack.net/ServiceStack.Hello/soap12/metadata?op=Hello)
## Accessing web services on the client
You can call the above web service re-using the same DTOs that your web services were defined with (i.e. no code-gen is required) using your preferred generic ServiceClient (i.e Json, Xml, etc). This allows you to call your web services using a strong-typed API with just 1 Line of code:
**C# Sync Example**
```
IServiceClient client = new JsonServiceClient("http://host/service");
var customers = client.Send<CustomersResponse>(new Customers());
```
And since your web services are also REST services, it works seamlessly with JavaScript ajax clients, e.g:
**Using jQuery**
```
$.getJSON("http://host/service", function(r) { alert(r.Customers.length); });
``` | Where to start REST web service in C# or ASP.Net | [
"",
"c#",
"rest",
""
] |
I have been learning some of the more detailed loopholes of JS here and there, and have a few things I need to get help on.
```
;(function($){
$.fn.makeRed1 = function() {
return $.each(this, function() {
$(this).css('background-color', '#FF0000');
});
}
})(jQuery)
;(function($){
$.fn.makeRed2 = function() {
$(this).css('background-color', '#FF0000');
}
})(jQuery)
```
**Both** of these work correctly. Why?
Anyone who talks about writing plugins always says to use the 'return each' method. What is the reason? I need someone to tell me exactly what happens when each of these methods are used, so I can understand the flow.
Thanks. | In the first case you are explicitly returning the results of the each function. The each function iterates over the matching elements and applies the callback specified to each one. The return value of the function is the jQuery object matching the selected elements. This allows you to chain your newly defined function in the way that users of jQuery would expect and apply additional jQuery functions to the selected elements.
In the second case, you have a simple statement that applies the same callback, albeit directly. Because you don't return anything, you aren't able to chain with this function. This breaks the jQuery paradigm. | Without the `each` loop, your function will only operate of the first selected element. While, using `each` will allow you to manipulate multiple selected elements with a single method call.
Ending your function by returning `this` is what facilitates the jQuery style method chaining.
Using:
```
return this.each(function() { /* do stuff */ });
```
is just shorthand for:
```
this.each(function(){ /* do stuff */);
return this;
```
**Re: comment:** The reason why *not* using `each` works in your example, is because the `.css()` method uses `each` internally. If you were actually doing something custom, like manually manipulating the DOM, or native Element objects, in your example plugin, you'd have to use each to apply your changes to all selected elements. | Javascript Reference Comprehension | [
"",
"javascript",
"jquery",
""
] |
How does the userAccountControl property work in AD?
Let's say I want to create a new user account and set it to enabled (it's disable by default), and also set the 'password never expires' option to true. I can do something like this and it works:
```
//newUser is a DirectoryEntry object
newUser.Properties["userAccountControl"].Value = 0x200; // normal account
newUser.Properties["userAccountControl"].Value = 0x10000; //password never expires
```
Normally, I would think the second line would wipe the first one out, but it doesn't. How does that work? Can I combine them in one line? How would I then take away that value if I wanted to have their password expire?
Thanks! | Actually, setting the second value will indeed wipe out the first - point is though, the first is really a bit "unnecessary".....
And of course you can combine them (and multiple ones, really) into a single value and set it with a single assignment:
```
const int UF_ACCOUNTDISABLE = 0x0002;
const int UF_PASSWD_NOTREQD = 0x0020;
const int UF_PASSWD_CANT_CHANGE = 0x0040;
const int UF_NORMAL_ACCOUNT = 0x0200;
const int UF_DONT_EXPIRE_PASSWD = 0x10000;
const int UF_SMARTCARD_REQUIRED = 0x40000;
const int UF_PASSWORD_EXPIRED = 0x800000;
int userControlFlags = UF_PASSWD_NOTREQD + UF_NORMAL_ACCOUNT + UF_DONT_EXPIRE_PASSWD;
newUser.Properties["userAccountControl"].Value = userControlFlags;
```
Marc | [(Almost) Everything In Active Directory via C#](http://www.codeproject.com/KB/system/everythingInAD.aspx)
How to set a flag:
```
int val = (int)newUser.Properties["userAccountControl"].Value;
newUser.Properties["userAccountControl"].Value = val | 0x10000; //password never expires
newUser.CommitChanges();
``` | How does the userAccountControl property work in AD? (C#) | [
"",
"c#",
"active-directory",
""
] |
```
//A query to a local object
var deletionCommands = commands
.Where(a => a.Operation != Operation.Addition)
.Select(a => new { a.Prestador.cod_prestador, a.Prestador.cod_desdobramento })
;
//A Linq-To-SQL query
var toDelete = db.Prestadors
.Where(a => deletionCommands.Contains(new { a.cod_prestador, a.cod_desdobramento }))
;
db.Prestadors.DeleteAllOnSubmit(toDelete);
db.SubmitChanges();
```
The only thing that solved the problem was an explicit loop:
```
foreach (var command in commands)
{
if(command.Operation != Operation.Addition)
{
var toDelete = db.Prestadors
.Where(a =>
a.cod_prestador == command.Prestador.cod_prestador &&
a.cod_desdobramento == command.Prestador.cod_desdobramento
);
db.Prestadors.DeleteAllOnSubmit(toDelete);
}
}
db.SubmitChanges();
``` | That was really a bug, and was corrected in LINQ 4.0
<http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40>
> Query stability
> Contains now detects self-referencing IQueryable and doesn't cause a stack overflow
**EDIT** In .NET 3.5 to resolve the problem: When using 'Auto Generated Value' = True, then you must set 'Delay Loaded' to False - otherwise you get the recursion error.
**EDIT2** The solution above didn't work. | Put a breakpoint on the last line, then run the code. Then when it stops on the breakpoint, add another breakpoint at the start of that chunk of code. Then continue in the debugger (step over). It should hit the new breakpoint, and you can examine the stack to see how it has called back on itself.
What's the implementation of the `Operation` property? Maybe that calls back into some other code in a recursive way. | Why this Linq code always throws System.StackOverflowException? | [
"",
"c#",
".net",
"linq",
"linq-to-sql",
"stack-overflow",
""
] |
I have several projects, some using managed code and some using only unmanaged. All have the XML comments have been added and the XML documentation is being generated correctly (the generated xml file and intermediate the xdc files).
Surely there's something that can take these files (the output of xdcmake) and generate MSDN style chm help! ?
From what I understand, both doxygen and sandcastle ignore that obvious step and re-invent the wheel to re-scan your code. (there's also the fact that sandcastle is apparently useless for non-.NET projects).
Having tried doxygen (horrible output, but fast) and sandcastle (nice MSDN style output, but sloooooow) both are begging to be outdone by something much simpler.
It would also be nice if there was some kind of editor associated that we can also write the 'Getting Started' and 'Information' kind of pages that are also needed with any API documentation.
Does anyone know of any solutions? | You might want to try [DoxyComment](http://doxycomment.sourceforge.net/). Here is the description from Doxygen's [Helper tools & scripts](http://www.doxygen.nl/helpers.html):
> An addin for Visual Studio 2005 called
> DoxyComment was created by Troels
> Gram. It is designed to assist you in
> inserting context sensitive comment
> blocks into C/C++ source files.
> DoxyComment also comes with an xslt
> template that lets you generate
> documentation like the MSDN library. | Honestly, Sandcastle is your best bet. I know it can be a bit of a pain to configure, but the documentation is exactly the style you are looking for. | C++ XML comments to generate MSDN style CHM | [
"",
"c++",
"documentation",
"msdn",
"chm",
""
] |
I have this log4j configuration in my grails config.groovy
```
log4j = {
error 'org.codehaus.groovy.grails.web.servlet', // controllers
'org.codehaus.groovy.grails.web.pages' // GSP
warn 'org.mortbay.log'
appenders {
rollingFile name:'infoLog', file:'info.log', threshold: org.apache.log4j.Level.INFO, maxFileSize:1024
rollingFile name:'warnLog', file:'warn.log', threshold: org.apache.log4j.Level.WARN, maxFileSize:1024
rollingFile name:'errorLog', file:'error.log', threshold: org.apache.log4j.Level.ERROR, maxFileSize:1024
rollingFile name:'custom', file:'custom.log', maxFileSize:1024
}
root {
info 'infoLog','warnLog','errorLog','custom', stdout
error()
additivity = true
}
}
```
the infoLog,warnLog and errorLog was from the previous question ... they were working well.
now I add new RollingFile wit name "custom" ...
I tried to log from my controller and service using log.info("something .... ${obj}");
but it seems that message was not inserted into custom.log, do I need to add something to the configuration ?
thank you !! | just got answer from the grails' mailing list:
i just need to add
debug "grails.app"
bellow warn "org.mortbay.log"
case closed ! :) | I have exact the same jetty/tomcat env's. Spent hours to figure it out. The trick is to define the file location (a relative path in my case) as a global variable inside Config.groovy, customized it in the environment blocks, and use the variable location inside log4j closure. Sample code is at: <http://denistek.blogspot.com/2010/02/grails-environment-specific-logging-to.html> | log4j in grails : how to log into file? | [
"",
"java",
"grails",
"groovy",
"log4j",
"dsl",
""
] |
While, compiling a package, written in C++ on RHEL 5.0. I am getting the following error.
**> error: `nocreate` is not a member of `std::ios`**
The source-code corresponds to:
> ifstream tempStr(`argv[4]`,`ios::in`|`ios::nocreate`);
---
I have tried
> #g++ -O -Wno-deprecated <file.cpp> -o <file>
as well as:
> #g++ -O -o <file>
**Please suggest a solution.** | `ios::nocreate` is not part of standard C++ - what are you expecting it to do?
Edit: From a Google, it seems like it was intended to prevent the file being created if it doesn't already exist. This is the default for ifstreams anyway, so you can just say:
```
ifstream f( filename );
if ( ! f.is_open() ) {
// open failed - probably because infput file does not exist
}
``` | Opening a file in read mode (`ios::in`) won't create it if it doesn't exist. You can just leave off the non-standard `nocreate`. And since `in` is the default for `ifstream`:
```
ifstream tempStr (argv[4]);
``` | ios::nocreate error while compiling a C++ code | [
"",
"c++",
"linux",
"g++",
"iostream",
""
] |
I'm trying to do some simple string manipulation with the href attribute of a hyperlink extracted using [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/):
```
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup('<a href="http://www.some-site.com/">Some Hyperlink</a>')
href = soup.find("a")["href"]
print href
print href[href.indexOf('/'):]
```
All I get is:
```
Traceback (most recent call last):
File "test.py", line 5, in <module>
print href[href.indexOf('/'):]
AttributeError: 'unicode' object has no attribute 'indexOf'
```
How should I convert whatever `href` is into a normal string? | Python strings do not have an `indexOf` method.
Use `href.index('/')`
`href.find('/')` is similar. But `find` returns `-1` if the string is not found, while `index` raises a `ValueError`.
So the correct thing is to use `index` (since '...'[-1] will return the last character of the string). | href is a unicode string. If you need the regular string, then use
```
regular_string = str(href)
``` | Simple python / Beautiful Soup type question | [
"",
"python",
"string",
"beautifulsoup",
""
] |
I'm working on a project that is implementing a number Java web applications (and associated JAR files) using Seam.
What is considered best practice with regard to including version information in deployments? What I need to understand is how web applications should contain and publish their versions and how the same can be done for JAR files.
Thanks | [there are sun specifications](http://java.sun.com/javase/6/docs/technotes/guides/versioning/spec/versioning2.html#wp89936) and [tutorials](http://java.sun.com/docs/books/tutorial/deployment/jar/packageman.html). | You've got a couple of options when it comes to including the version number:
1. add it to the JAR's [MANIFEST.INF](http://java.sun.com/developer/Books/javaprogramming/JAR/basics/manifest.html).
2. include the version of the JAR in the filename.
It's quite common to do both. | Best practice for including version info in Java web apps and libraries? | [
"",
"java",
"versioning",
"seam",
""
] |
For example, I have a string :
```
/div1/div2[/div3[/div4]]/div5/div6[/div7]
```
Now I want to split the content by "`/`" and ignore the content in the "`[ ]`".
The result should be:
1. `div1`
2. `div2[/div3[/div4]]`
3. `div5`
4. `div6[/div7]`
How can I get the result using regular expression? My programming language is JavaScript. | This works...
```
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string testCase = "/div1/div2[/div3[/div4]]/div5/div6[/div7]";
//string pattern = "(?<Match>/div\\d(?:\\[(?>\\[(?<null>)|\\](?<-null>)|.?)*(?(null)(?!))\\])?)";
string pattern = "(?<Match>div\\d(?:\\[(?>\\[(?<null>)|\\](?<-null>)|.?)*(?(null)(?!))\\])?)";
Regex rx = new Regex(pattern);
MatchCollection matches = rx.Matches(testCase);
foreach (Match match in matches)
Console.WriteLine(match.Value);
Console.ReadLine();
}
}
```
Courtesy of...
<http://retkomma.wordpress.com/2007/10/30/nested-regular-expressions-explained/> | You can't do this with regular expressions because it's recursive. (That answers your question, now to see if I can solve the problem elegantly...)
Edit: aem tipped me off! :D
Works as long as every `[` is followed by `/`. It *does not* verify that the string is in the correct format.
```
string temp = text.Replace("[/", "[");
string[] elements = temp.Split('/').Select(element => element.Replace("[", "[/")).ToArray();
``` | How to write a regular expression for this scenario? | [
"",
"javascript",
"regex",
""
] |
I am working on maintaining someone else's code that is using multithreading, via two methods:
```
1: ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf ReadData), objUpdateItem)
2: Dim aThread As New Thread(AddressOf LoadCache)
aThread.Start()
```
However, on a dual core machine, I am only getting 50% CPU utlilization, and on a dual core with hyperthreadin enabled machine, I am only getting 25% CPU utilization.
Obviously threading is extremely complicated, but this behaviour would seem to indicate that I am not understanding some simple fundamental fact?
## UPDATE
The code is too horribly complex to post here unfortunately, but for reference purposes, here is roughly what happens....I have approx 500 Accounts whose data is loaded from the database into an in memory cache...each account is loaded individually, and that process first calls a long running stored procedure, followed by manipulation and caching of the returned data. So, the point of threading in this situation is that there is indeed a bottleneck hitting the database (ie: the thread will be idled for up to 30 seconds waiting for the query to return), so we thread to allow others to begin processing the data they have received from Oracle.
So, the main thread executes:
```
ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf ReadData), objUpdateItem)
```
Then, the ReadData() then proceeds to execute (exactly once):
```
Dim aThread As New Thread(AddressOf LoadCache)
aThread.Start()
```
And this is occurring in a recursive function, so the QueueUserWorkItem can be executing multiple times, which in turn then executes *exactly one* new thread via the aThread.Start
Hopefully that gives a decent idea of how things are happening.
So, under this scenario, should this not theoretically pin *both* cores, rather than maxing out at 100% on one core, while the other core is essentially idle? | That code starts one thread that will go an do something. To get more than one core working you need to start more than one thread and get them both busy. Starting a thread to do some work, and then having your main thread wait for it won't get the task done any quicker. It is common to start a long running task on a background thread so that the UI remains responsive, which may be what this code was intended to do, but it won't make the task get done any quicker.
@Judah Himango - I had assumed that those two lines of code were samples of how multi-threading were being achieved in two different places in the program. Maybe the OP can clarify if this is the case or if these two lines really are in the one method. If they are part of one method then we will need to see what the two methods are actually doing.
Update:
That does sound like it should max out both cores. What do you mean by recursivly calling ReadData()? If each new thread is only calling ReadData at or near its end to start the next thread then that could explain the behaviour you are seeing.
I am not sure that this is actaully a good idea. If the stored proc takes 30 seconds to get the data then presumably it is placing a fair load on the database server. Running it 500 times in parallel is just going to make things worse. Obviously I don't know your database or data, but I would look at improving the performance of the stored proc.
If multi threading does look like the way forward, then I would have a loop on the main thread that calls ThreadPool.QueueUserWorkItem once for each account that needs loading. I would also remove the explicit thread creation and only use the thread pool. That way you are less likely to starve the local machine by creating too many threads. | How many threads are you spinning up? It may seem primitive (wait a few years, and you won't need to do this anymore), but your code has got to figure out an optimal number of threads to start, and spin up that many. Simply running a single thread won't make things any faster, and won't pin a physical processor, though it may be good for other reasons (a worker thread to keep your UI responsive, for instance).
In many cases, you'll want to be running a number of threads equal to the number of logical cores available to you (available from Environment.ProcessorCount, I believe), but it may have some other basis. I've spun up a few dozen threads, talking to different hosts, when I've been bound by remote process latency, for instance. | Multithreading on a multi core machines not maxing CPU | [
"",
"c#",
".net",
"vb.net",
"multithreading",
""
] |
My aim is to get a json array like this one:
```
var args = [{ name: 'test', value: 1 }, { key: 'test2', value: 2}];
```
How can I get the below code to build up an array like the above one?
```
this.dependentProperties = []; //array
function addDependentProperty(depName, depValue) {
dependentProperties.push(new Array(depName, depValue));
}
```
By using the push method I end up having a json notation like this one:
```
args:{[["test1",1],["test2",2]]}
``` | ```
dependentProperties.push({name: depName, value: depValue});
``` | ```
var args = [{ name: 'test', value: 1 }, { key: 'test2', value: 2}];
```
...this is an array where each element is a associated-array (=hash, =object).
```
dependentProperties.push(new Array(depName, depValue));
```
...you are pushing a (sub-)Array into the parent array. That's not the same as an associative array. You now have a heterogeneous array.
```
dependentProperties.push({name: depName, value: depValue});
```
...This is pushing an associated-array into your top-level array. This is what you want. Luca is correct. | json array: How to create new array elements? | [
"",
"javascript",
"ajax",
"json",
""
] |
I'm parsing human-readable scientific text that is mostly in the field of chemistry. What I'm interested in is breaking the text into a list of words, scientific terms (more on that below), and punctuation marks.
So for example, I expect the text "hello, world." to break into 4 tokens: 1) "hello"; 2) comma; 3) "world" and 4) period. Note that spaces don't require specialized tokens.
The problem is related to the "scientific terms": these are names of chemical formulas such as "1-methyl-4-phenylpyridinium". Anyone who has ever learned chemistry knows these formulas can get quite long and may contain numbers, dashes and commas, and sometimes even parentheses, but I think it's safe to assume these lovely expressions can't contain spaces. Also, I believe these expressions must start with a number. I would like each such expression to come out as a single token.
Today I use manual parsing to find "chunks" of text that begin with a number and end with either a space, a line break, or a punctuation mark followed by either a space or line break.
I wondered if there's a smart solution (regex or other) I can use to tokenize the text according to the above specifications. I'm working in Python but this may be language agnostic.
An example input (obviously disregard the content...):
"Hello. 1-methyl-4-phenylpyridinium is ultra-bad. However, 1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine is worse."
Example output (each token in its own line):
```
Hello
.
1-methyl-4-phenylpyridinium
is
ultra
-
bad
.
However
,
1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine
is
worse
.
``` | This will solve your current example. It can be tweaked for a larger data set.
```
import re
splitterForIndexing = re.compile(r"(?:[a-zA-Z0-9\-,]+[a-zA-Z0-9\-])|(?:[,.])")
source = "Hello. 1-methyl-4-phenylpyridinium is ultra-bad. However, 1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine is worse."
print "\n".join( splitterForIndexing.findall(source))
```
The result is:
```
"""
Hello
.
1-methyl-4-phenylpyridinium
is
ultra-bad
.
However
,
1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine
is
worse
.
"""
```
Sorry didn't see ultra-bad. If it's necessary for those words to be split..
```
import re
splitterForIndexing = re.compile(r"(?:[a-zA-Z]+)|(?:[a-zA-Z0-9][a-zA-Z0-9\-(),]+[a-zA-Z0-9\-()])|(?:[,.-])")
source = "Hello. 1-methyl-4-phenylpyridinium is ultra-bad. However, 1-methyl-4-phenyl-1,(2,3),6-tetrahydropyridine is worse."
print "\n".join( splitterForIndexing.findall(source))
```
Gives:
```
"""
Hello
.
1-methyl-4-phenylpyridinium
is
ultra
-
bad
.
However
,
1-methyl-4-phenyl-1,(2,3),6-tetrahydropyridine
is
worse
.
"""
``` | I agree with Sebastiaan Megens that a regex solution may be possible, but probably not very readable or maintainable, especially if you are not already good with regular expressions. I would recommend the [pyparsing module](http://pyparsing.wikispaces.com/), if you're sticking with Python (which I think is a good choice).
Extra maintainability will come in very handy if your parsing needs should grow or change. (And I'm sure plenty of folks would say "when" rather than "if"! For example, someone already commented that you may need a more sophisticated notion of what needs to be allowed as a chemical name. Maybe your requirements are already changing before you've even chosen your tool!) | Python: question about parsing human-readable text | [
"",
"python",
"parsing",
""
] |
I'm trying to add custom properties to a workbook I have created programmatically. I have a method in place for getting and setting properties, but the problem is the workbook is returning null for the CustomDocumentProperties property. I cannot figure out how to initialize this property so that I can add and retrieve properties from the workbook. Microsoft.Office.Core.DocumentProperties is an interface, so I cant go and do the following
```
if(workbook.CustomDocumentProperties == null)
workbook.CustomDocumentProperties = new DocumentProperties;
```
Here is the code I have to get and set the properties:
```
private object GetDocumentProperty(string propertyName, MsoDocProperties type)
{
object returnVal = null;
Microsoft.Office.Core.DocumentProperties properties;
properties = (Microsoft.Office.Core.DocumentProperties)workBk.CustomDocumentProperties;
foreach (Microsoft.Office.Core.DocumentProperty property in properties)
{
if (property.Name == propertyName && property.Type == type)
{
returnVal = property.Value;
}
DisposeComObject(property);
}
DisposeComObject(properties);
return returnVal;
}
protected void SetDocumentProperty(string propertyName, string propertyValue)
{
DocumentProperties properties;
properties = workBk.CustomDocumentProperties as DocumentProperties;
bool propertyExists = false;
foreach (DocumentProperty prop in properties)
{
if (prop.Name == propertyName)
{
prop.Value = propertyValue;
propertyExists = true;
}
DisposeComObject(prop);
if(propertyExists) break;
}
if (!propertyExists)
{
properties.Add(propertyName, false, MsoDocProperties.msoPropertyTypeString, propertyValue, Type.Missing);
}
DisposeComObject(propertyExists);
}
```
The line
properties = workBk.CustomDocumentProperties as DocumentProperties;
always set properties to null.
This is using Microsoft.Office.Core v12.0.0.0 and Microsoft.Office.Interop.Excell v12.0.0.0 (Office 2007) | I looked at my own code and can see that I access the properties using late binding. I can't remember why, but I'll post some code in case it helps.
```
object properties = workBk.GetType().InvokeMember("CustomDocumentProperties", BindingFlags.Default | BindingFlags.GetProperty, null, workBk, null);
object property = properties.GetType().InvokeMember("Item", BindingFlags.Default | BindingFlags.GetProperty, null, properties, new object[] { propertyIndex });
object propertyValue = property.GetType().InvokeMember("Value", BindingFlags.Default | BindingFlags.GetProperty, null, propertyWrapper.Object, null);
```
**EDIT**: ah, now I remember [why](http://support.microsoft.com/default.aspx?scid=303296). :-)
**EDIT 2**: Jimbojones' answer - to use the dynamic keyword - is a better solution (if you value ease-of-use over the performance overhead of using `dynamic`). | If you are targetting .NET 4.0, you can use the `dynamic` key word for late binding
```
Document doc = GetActiveDocument();
if ( doc != null )
{
dynamic properties = doc.CustomDocumentProperties;
foreach (dynamic p in properties)
{
Console.WriteLine( p.Name + " " + p.Value);
}
}
``` | Accessing Excel Custom Document Properties programmatically | [
"",
"c#",
"excel",
"automation",
""
] |
There are many libraries that manage the wiimote but I am looking for the "best" one, or at least that has the following features:
* open-source
* portable (at least **Win32 and Linux**)
* written and usable in **c or c++**
* good coverage of wiimote devices
I rely on people that already used such library. Google is good source of information but it doesn't know which one is best library. | if you will use multiple wiimotes, don't use wiiuse library. i am working on a stereo system with two wiimotes using wiiuse library but wiiuse made me crazy( it gives delayed ir tracking data ) and i decided to change my library wiiuse from wiiyourself | Some friends of mine have had good luck with [wiiuse](https://github.com/MJL85/wiiuse/). It's in C, for both Windows and Linux. | What is the best library to manage a wiimote? | [
"",
"c++",
"c",
"wiimote",
""
] |
Is it possible to use some kind of attribute to throw an exception. This is what I mean. Instead of doing this:
```
public int Age
{
get
{
return this.age;
}
set
{
this.age = value;
NotifyPropertyChanged("Age");
if (value < 18)
{
throw new Exception("age < 18");
}
}
}
```
Do something like this:
```
[Range(18,100, ErrorMessage="Must be older than 18")]
public int Age
{
get
{
return this.age;
}
set
{
this.age = value;
NotifyPropertyChanged("Age");
}
}
```
Any help would be greatly appreciated!
Best Regards,
Kiril | You're looking for an AOP (Aspect Oriented Programming) library, which can do this quite easily. I would recommend giving [PostSharp](http://www.postsharp.org/) a try. The example on the home page should give an indication how you might use it on a property/method. | No, that's not possible. You will have to do the validation yourself in the setter - just like NotifyPropertyChanged.
Btw - this is called "Aspect Oriented Programming". | Using an attribute to throw an exception in .NET | [
"",
"c#",
".net",
"silverlight",
""
] |
```
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
try
{
var pageTracker = _gat._getTracker("UA-XXXXXXX-1");
pageTracker._trackPageview();
}
catch(err) {}
```
Would it be possible to call this script from an external JS file? I wanted to to something like:
```
<script type="text/javascript" src="googleanalytics.js" ></script>
```
and put one of these on each of my HTML pages.
The code I have above will be inside googleanalytics.js
Google's instructions was to put the code in each page. The problem with that is it makes it harder to change the tracking code. (We use different tracking codes for our DEV and PROD pages).
I've tried it out and it doesn't seem to be working.
Is there something wrong with doing that? Or is there something else causing the problem?
**Important FYI**
Please note that we are using IE6 and 8 browsers (yes, I know, no need to tell me) | Yes this is possible. If it is not working then there is something else going on.
Just a thought, Google Analytics is usually about a day behind in reporting so when you make changes it will take some time before you know it is working. What I like to do is hit a page that does not get traffic very often to assure me that I have my tracking set up correctly.
Also, you might try making the link an absolute link in your `<script` tag. It might just be looking in the wrong place for the analytics code. | i got an easy way to do this...
Since analytic js is asynchronous it won't give any problem...
include below code in any js file
(Please Note: The code i used is new analytics code provided by google analytics)
```
var imported = document.createElement('script');
imported.src = 'https://www.googletagmanager.com/gtag/js?id=UA-12xxxxxxx-1';
document.head.appendChild(imported);
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-12xxxxxxx-1');
``` | Is it possible to put Google Analytics code in an external JS file? | [
"",
"javascript",
"google-analytics",
""
] |
I have a google-maps mashup that worked fairly well with "small" test files - every file I generated, even for a 60 mile trip, was less than 16k.
Then, yesterday, a user sent me a KML file they were having problems with - it's over 360k in size and, while it uploads okay, and when I call GGeoXML(), it appears to load into Google Maps okay, but no map appears and the error "Script error. (main.js,0)" appears in the log. This happens both in my own application and if I try to feed the kml file to Google's "Code Playground" - but the file loads fine in Google Earth. If I re-save the file from Google Earth into kmz format, that also works - but since the file is no longer XML, I lose some of the "added value" features of my mashup.
I've scanned the Google documentation, but I could not find any reference to a maximum file size for kml files.
Any suggestions?
Here's a code fragment that causes the problem in the Code Playground:
```
var map;
function zoomToGeoXML(geoXml) {
var center = geoXml.getDefaultCenter();
var span = geoXml.getDefaultSpan();
var sw = new GLatLng(center.lat() - span.lat() / 2,
center.lng() - span.lng() / 2);
var ne = new GLatLng(center.lat() + span.lat() / 2,
center.lng() + span.lng() / 2);
var bounds = new GLatLngBounds(sw, ne);
map.setCenter(center);
map.setZoom(map.getBoundsZoomLevel(bounds));
}
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
var geoXml = new GGeoXml("http://(my base url)/files/gps/expr.kml",
function() { zoomToGeoXML(geoXml); });
map.addOverlay(geoXml);
}
}
``` | If you rearrange a few lines from Mike's example, you get rid of the "side-effect that the map will initially be of the entire globe before zooming into the area defined by the kml file."
```
var map;
function loadMapAndZoomToGeoXML(geoXml) {
center = geoXml.getDefaultCenter();
var span = geoXml.getDefaultSpan();
var sw = new GLatLng(center.lat() - span.lat() / 2, center.lng() - span.lng() / 2);
var ne = new GLatLng(center.lat() + span.lat() / 2, center.lng() + span.lng() / 2);
var bounds = new GLatLngBounds(sw, ne);
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(center);
map.setZoom(KmlMap.getBoundsZoomLevel(bounds));
map.addOverlay(geoXml);
map.enableScrollWheelZoom();
map.setUIToDefault();
map.addControl(new GLargeMapControl());
}
function initialize() {
if (GBrowserIsCompatible()) {
var geoXml = new GGeoXml("http://(my base url)/files/gps/expr.kml", function() { loadMapAndZoomToGeoXML(geoXml); });
}
}
```
Unfortunately it ties up the business of loading the map with zooming it and centering it, but that can be refactored further. I wanted to stick to the example Mike gave as much as possible. | It turns out that the real problem isn't the file size, it's the fragment
```
map = new GMap2(document.getElementById("map_canvas"));
var geoXml = new GGeoXml("http://(my base url)/files/gps/expr.kml",
function() { zoomToGeoXML(geoXml); });
map.addOverlay(geoXml);
```
According to the Google Map docs, you must call setCenter() immediately after constructing a new map. I didn't do that because zoomToGeoXML() does.
Unfortunately, that apparently sets up a race condition in the google map code. Changing the code to read:
```
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(0,0));
var geoXml = new GGeoXml("http://(my base url)/files/gps/expr.kml",
function() { zoomToGeoXML(geoXml); });
map.addOverlay(geoXml);
```
apparently solves the problem correctly. However, it has the side-effect that the map will initially be of the entire globe before zooming into the area defined by the kml file. | KML file loads but doesn't display - why not? | [
"",
"javascript",
"google-maps",
""
] |
I have a few TextBox on the WinForm. I would like the focus to move to the next control when Enter key is pressed? Whenever a textbox gains control, it will also select the text, so that any editing will replace the current one.
What is the best way to do this? | Tab as Enter: create a user control which inherits textbox, override the `KeyPress` method. If the user presses enter you can either call `SendKeys.Send("{TAB}")` or `System.Windows.Forms.Control.SelectNextControl()`. Note you can achieve the same using the `KeyPress` event.
Focus Entire text: Again, via override or events, target the `GotFocus` event and then call `TextBox.Select` method. | A couple of code examples in C# using **SelectNextControl**.
The first moves to the next control when ***ENTER*** is pressed.
```
private void Control_KeyUp( object sender, KeyEventArgs e )
{
if( (e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return) )
{
this.SelectNextControl( (Control)sender, true, true, true, true );
}
}
```
The second uses the ***UP*** and ***DOWN*** arrows to move through the controls.
```
private void Control_KeyUp( object sender, KeyEventArgs e )
{
if( e.KeyCode == Keys.Up )
{
this.SelectNextControl( (Control)sender, false, true, true, true );
}
else if( e.KeyCode == Keys.Down )
{
this.SelectNextControl( (Control)sender, true, true, true, true );
}
}
```
See MSDN [SelectNextControl Method](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.selectnextcontrol.aspx) | Press Enter to move to next control | [
"",
"c#",
"winforms",
""
] |
Currently, I'm looking for any experiences or advices about test tools on Service Oriented Architecture (SOA) Java developments.
Which the bestpratices and best tools for this job ?
Thanks for your time | I find SoapUI fairly handy for exploratory testing; they've recently added REST support, although I haven't played with that in detail. It's also useful for testing performed by QA staff who aren't ready to write tests in a programming language.
That said, for my own needs, I'd use JUnit and a web-service-invoking client library of some kind for consistency. That client library could be your own, or a simply just a library that knows how to invoke on that kind of web service. | My advice would be separate the functionality from the transport (the webservice in your case) and test just the functionality.
As you're unlikely to be rolling your own transport layer I think it's safe enough (these days) to assume that will work as intended but make sure you do integration tests as the potential for interop issues still exist. | Tests frameworks and tools for SOA Java developments | [
"",
"java",
"web-services",
"unit-testing",
"soa",
""
] |
I have a class with a field that needs to be initialized when the object is initialized, such as a list that needs to be created before objects can be added/removed from it.
```
public class MyClass1
{
private List<MyOtherClass> _otherClassList;
public MyClass1()
{
this._otherClasslist = new List<MyOtherClass>();
}
}
public class MyClass2
{
private List<MyOtherClass> = new List<MyOtherClass>();
public MyClass2()
{
}
}
```
What is the difference between these two classes, and why would you choose one method over the other?
I usually set the field in the constructor, as in MyClass1, because I find it easier to be able to look in one place to see all the stuff that happens when the object is being instantiated, but is there any case where it is better to initialize a field directly like in MyClass2? | The ILs emitted by C# compiler (VS2008 sp1) will be almost equivalent for both cases (even in Debug and Release builds).
However, if you ***need to add parameterized constructors that take*** **`List<MyOtherClass>`** ***as an argument***, it will be different (especially, when you will create a significantly large number of objects with such constructors).
See the following examples to see the differences (you can copy&past to VS and build it to see ILs with [Reflector](http://www.red-gate.com/products/reflector/) or [ILDASM](http://msdn.microsoft.com/en-us/library/f7dy01k1.aspx)).
```
using System;
using System.Collections.Generic;
namespace Ctors
{
//Tested with VS2008 SP1
class A
{
//This will be executed before entering any constructor bodies...
private List<string> myList = new List<string>();
public A() { }
//This will create an unused temp List<string> object
//in both Debug and Release build
public A(List<string> list)
{
myList = list;
}
}
class B
{
private List<string> myList;
//ILs emitted by C# compiler are identicial to
//those of public A() in both Debug and Release build
public B()
{
myList = new List<string>();
}
//No garbage here
public B(List<string> list)
{
myList = list;
}
}
class C
{
private List<string> myList = null;
//In Release build, this is identical to B(),
//In Debug build, ILs to initialize myList to null is inserted.
//So more ILs than B() in Debug build.
public C()
{
myList = new List<string>();
}
//This is identical to B(List<string> list)
//in both Debug and Release build.
public C(List<string> list)
{
myList = list;
}
}
class D
{
//This will be executed before entering a try/catch block
//in the default constructor
private E myE = new E();
public D()
{
try
{ }
catch (NotImplementedException e)
{
//Cannot catch NotImplementedException thrown by E().
Console.WriteLine("Can I catch here???");
}
}
}
public class E
{
public E()
{
throw new NotImplementedException();
}
}
class Program
{
static void Main(string[] args)
{
//This will result in an unhandled exception.
//You may want to use try/catch block when constructing D objects.
D myD = new D();
}
}
}
```
**Note:** I did not change any optimization flag when switching to Release build. | There is one difference:
> Fields are initialized immediately
> before the constructor for the object
> instance is called, so if the
> constructor assigns the value of a
> field, it will overwrite any value
> given during field declaration. [From
> MSDN](http://msdn.microsoft.com/en-us/library/ms173118(VS.80).aspx): | Initializing Class Fields at the Field Definition or in Class Constructor | [
"",
"c#",
"constructor",
"initialization",
"field",
""
] |
I have just started learning Javascript and I am absolutely overwhelmed with the number of technologies available especially on the browser side. Earlier I thought that just Javascript should suffice but now it appears that I need to understand JQuery, GWT, YUI and another dozen acronyms I do not even know the expansion for. Can somebody please tell me which are the most essential technologies one needs to be fluent with in this domain? | I usually go with [standard JavaScript](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference) unless I need to modify the [DOM](http://quirksmode.org/dom/w3c_html.html) or [attach events](http://quirksmode.org/js/events_advanced.html). In those cases, [each browser has its own way of doing things](http://quirksmode.org/compatibility.html) and then it's much simpler to use a well-tested framework.
Right now, I've found that [jQuery](http://jquery.com/) is the most light-weight and intuitive choice if all you want is the ability to control the DOM. For everything else, I write my own code.
Just don't use more than one framework or it'll get messy. | I strongly recommend learning [JQuery](http://jquery.com/), it is a very powerful javascript framework giving you a nice little abstraction over the typical DOM (document object model) manipulations.
I would also give a look to [JQuery UI](http://jqueryui.com/), which helps you add smooth animation and effects to you page while giving you the possibility to use nifty features such as tabs and modal dialog boxes. | DHTML newbie question | [
"",
"javascript",
"jquery",
""
] |
I have a function that detects all files started by a string and it returns an array filled with the correspondent files, but it is starting to get slow, because I have arround 20000 files in a particular directory.
I need to optimize this function, but I just can't see how. This is the function:
```
function DetectPrefix ($filePath, $prefix)
{
$dh = opendir($filePath);
while (false !== ($filename = readdir($dh)))
{
$posIni = strpos( $filename, $prefix);
if ($posIni===0):
$files[] = $filename;
endif;
}
if (count($files)>0){
return $files;
} else {
return null;
}
}
```
What more can I do?
Thanks | <http://php.net/glob>
```
$files = glob('/file/path/prefix*');
```
Wikipedia breaks uploads up by the first couple letters of their filenames, so `excelfile.xls` would go in a directory like `/uploads/e/x` while `textfile.txt` would go in `/uploads/t/e`.
Not only does this reduce the number of files `glob` (or any other approach) has to sort through, but it avoids the maximum files in a directory issue others have mentioned. | You could use [scandir()](https://www.php.net/manual/en/function.scandir.php) to list the files in the directory, instead of iterating through them one-by-one using `readdir()`. scandir() returns an array of the files.
However, it'd be better if you could change your file system organization - do you really need to store 20000+ files in a single directory? | Optimize PHP function | [
"",
"php",
"optimization",
""
] |
I'm completely new to loading in libraries like this, but here's where I stand:
I have a homemade DLL file it's about as simple as it gets, the class itself and a method. In the home program that loads this library, I have:
```
Assembly testDLL = Assembly.LoadFile("C:\\dll\\test.dll");
```
From here, I'm kind of stuck. As far as I know, it's loading it correctly because it gives me errors when I change the name.
What do I do from here? How exactly do I load the class & methods within it?
Thanks. | Use `Assembly.GetTypes()` to get a collection of all the types, or `Assembly.GetType(name)` to get a particular type.
You can then create an instance of the type with a parameterless constructor using `Activator.CreateInstance(type)` or get the constructors using `Type.GetConstructors` and invoke them to create instances.
Likewise you can get methods with `Type.GetMethods()` etc.
Basically, once you've got a type there are loads of things you can do - look at the [member list](http://msdn.microsoft.com/en-us/library/system.type_members.aspx) for more information. If you get stuck trying to perform a particular task (generics can be tricky) just ask a specific question an I'm sure we'll be able to help. | This is how you can get the classes if you know the type.
```
Assembly assembly = Assembly.LoadFrom("C:\\dll\\test.dll");
// Load the object
string fullTypeName = "MyNamespace.YourType";
YourType myType = assembly.CreateInstance(fullTypeName);
```
The full type name is important. Since you aren't adding the .dll you can't do a Using because it is not in your project.
If you want all I would just Jon Skeet answer. | Load a .DLL file and access methods from class within? | [
"",
"c#",
"dll",
""
] |
## Performance consideration: Spread rows in multiple tables vs concentrate all rows in one table.
Hi.
I need to log information about about every step that goes on in the application in an SQL DB.
There are certain tables, I want the log should be related to:
Product - should log when a product has been created changed etc.
Order - same as above
Shipping - same
etc. etc. etc.
The data will be need to be retrieved often.
I have few ideas on how to do it:
1. Have a log table that will contain columns for all these tables, then when I wanna represent data in the UI for a certain Product will do select \* from Log where LogId = Product.ProductId.
I know that this might be funny to have many cols, but I have this feeling that performance will be better. In the other hand there will be a huge amount of rows in this table.
2. Have many log tables for each log type (ProductLogs, OrderLogs etc.) I really don't like this idea since it's not consistent and have many tables with same structure doesn't make sense, but (?) it might be quicker when searching in a table that has a lower amount of rows (m i wrong?).
3. According to statement no. 1, I could do a second many-to-one table that will have LogId, TableNameId and RowId cols, and will reference a log row to many table rows in the DB, than will have a UDF to retrieve data (e.g. log id 234 belongs to table Customer at CustomerId 345 and to Product table where productId = RowId); I think this is the nicest way to do it, but again, there might be a huge amount of rows, will it slow down the search? or this is how it should be done, whatcha say?...
Example of No. 3 in the above list:
```
CREATE TABLE [dbo].[Log](
[LogId] [int] IDENTITY(1,1) NOT NULL,
[UserId] [int] NULL,
[Description] [varchar](1024) NOT NULL,
CONSTRAINT [PK_Log] PRIMARY KEY CLUSTERED
(
[LogId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Log] WITH CHECK ADD CONSTRAINT [FK_Log_Table] FOREIGN KEY([UserId])
REFERENCES [dbo].[Table] ([TableId])
GO
ALTER TABLE [dbo].[Log] CHECK CONSTRAINT [FK_Log_Table]
---------------------------------------------------------------------
CREATE TABLE [dbo].[LogReference](
[LogId] [int] NOT NULL,
[TableName] [varchar](32) NOT NULL,
[RowId] [int] NOT NULL,
CONSTRAINT [PK_LogReference] PRIMARY KEY CLUSTERED
(
[LogId] ASC,
[TableName] ASC,
[RowId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[LogReference] WITH CHECK ADD CONSTRAINT [FK_LogReference_Log] FOREIGN KEY([LogId])
REFERENCES [dbo].[Log] ([LogId])
GO
ALTER TABLE [dbo].[LogReference] CHECK CONSTRAINT [FK_LogReference_Log]
---------------------------------------------------------------------
CREATE FUNCTION GetLog
(
@TableName varchar(32),
@RowId int
)
RETURNS
@Log TABLE
(
LogId int not null,
UserId int not null,
Description varchar(1024) not null
)
AS
BEGIN
INSERT INTO @Log
SELECT [Log].LogId, [Log].UserId, [Log].Description
FROM [Log] INNER JOIN
LogReference ON [Log].LogId = LogReference.LogId
WHERE (LogReference.TableName = @TableName) AND (LogReference.RowId = @RowId)
RETURN
END
GO
``` | I would definitely go for option 3, for several reasons:
Data should be in the fields of a table, not as a table name (option 2) or a field name (option 1). That way the database gets easier to work with and easier to maintain.
Narrower tables genrally perform better. The number of rows has less impact on the performance than the number of fields.
If you have a field for each table (option 1), you are likely to get a lot of empty fields when only a few of the tables are affected by an operation. | Be careful with preoptimizing databases. Most databases are reasonably fast and somewhat complicated. You want to run a test for efficiency first.
Second putting everything in one table makes it more likely that the results you want are in the cache which will speed up performance immensely. Unfortunately it also makes it much more likely that you will have to search a gigantic table to find what you are looking for. This can be partly solved with an index, but indexes don't come free (they make writing more expensive, for one).
My advice would be to make a test to see if the performance really matter and then test the different scenarios to see which is the fastest. | Performance consideration: Spread rows in multiple tables vs concentrate all rows in one table | [
"",
"sql",
"sql-server",
"performance",
"data-storage",
""
] |
(The title for this question isn't the best, but I'm unsure how else to word it!)
I'm working on a search form which contains a checklist of values. Basically, a checked item means 'include this type in the search'. Something like this:
```
Search for item: __________
Search in:
[ ] Fresh Foods
[ ] Frozen Foods
[ ] Beverages
[ ] Deli Counter
```
I have an object to represent this search:
```
class FoodSearchCriteria{
public string SearchString {get;set;}
public bool SearchFreshFoods {get;set;}
public bool SearchFrozenFoods {get;set;}
public bool SearchBeverages {get;set;}
public bool SearchDeliCounter {get;set;}
}
```
The only way I can think of doing this atm is like this:
```
public IList<FoodItem> FindFoodItems(FoodSearchCriteria criteria)
// in reality, this is a fuzzy search not an exact match
var matches = _DB.FoodItems.Where(x => x.FoodTitle == SearchString);
var inCategories = new List<FoodItem>();
if (criteria.SearchFreshFoods)
inCategories.Add(matches.Where(x => x.Type == 'Fresh Foods'));
if (criteria.SearchFrozenFoods)
inCategories.Add(matches.Where(x => x.Type == 'Frozen Foods'));
//etc etc
return inCategories;
}
```
This feels like a code smell to me, what would be a better way to approach it? | Have you tried:
```
List<string> types = new List<string>();
if (criteria.SearchFreshFoods) { types.Add("Fresh Foods"); }
if (criteria.SearchFrozenFoods) { types.Add("Frozen Foods"); }
if (criteria.SearchBeverages) { types.Add("Beverages"); }
if (criteria.SearchDeliCounter) { types.Add("Deli Counter"); }
return _DB.FoodItems.Where(x => x.FoodTitle == SearchString &&
types.Contains(x.Type));
```
That means just one SQL query, which is handy.
You could certainly refactor the FoodSearchCriteria type to make it easier to build the list though... | Take a look at [PredicateBuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx)
```
PredicateBuilder predicate = PredicateBuilder.False<FoodItem>();
if (criteria.SearchFreshFoods)
{
predicate = predicate.Or(x => x.Type == 'Fresh Foods');
}
if (criteria.SearchFrozenFoods)
{
predicate = predicate.Or(x => x.Type == 'Frozen Foods'));
}
...
_DB.FoodItems.Where(predicate);
``` | Building up a LINQ query based on bools | [
"",
"c#",
".net",
"linq",
""
] |
Is there a ready-to-use API (C / C++) in Windows Mobile ecosystem that I could use to generate a GUID? I am looking for simple one-shot API to do this. If there is a need to write a whole algorithm or use some extra 3rd-party modules, I will do away without this.
**Background**. To display notification to the user I use SHNotificationAdd, which requires a GUID for it. Examples in MSDN and other sources show that GUID is hard-coded. However, I want to wrap the SHNotification\* within a class that blends well within the overall design of my application. MSDN is very shy on details on what SHNOTIFICATIONDATA->clsid represents. The "class" mentioned raise more questions than it answers. | You don't need to generate a GUID for SHNOTIFICATIONDATA.
You only set the clsid if you want WM to notify a COM object that implements IshellNotificationCallback interface.
Quote from [MSDN](http://msdn.microsoft.com/en-us/library/aa458065.aspx):
> When loading up the SHNOTIFICATIONDATA
> structure, you can specify either the
> notification class (clsid), the window
> to receive command choices (hwndSink),
> or both. If you specify the clsid,
> your COM component must implement
> IshellNotificationCallback. If you
> specify the clsid and an hwndSink,
> both COM and Window Message-style
> callbacks will be generated.
I've never personally used the COM callback, I always use the windows message callback. It's a lot easier to setup and use and you don't need to generate a GUID. | Use [CoCreateGUID()](http://msdn.microsoft.com/en-us/library/ms886229.aspx) for Windows Mobile... | How do I generate GUID under Windows Mobile? | [
"",
"c++",
"windows-mobile",
"guid",
""
] |
I am looking at code that toggles displaying and hiding a table column.
I am assuming this creates an array:
```
var States = { };
```
Why no need for the [new operator](http://www.w3schools.com/js/tryit.asp?filename=tryjs_array)?
Does this line set the States col element .isOpen property to true?
```
States[col] = {isOpen : true};
```
I am figuring out how to modify this function so I can save the state of this column with a cookie. i.e. - when page is rendered, column is set to none by default. However, if the last operation was show column and the page is re-rendered I would like the column to still be open, not go back to default.
The code:
```
/**************************************************************************
*
* Function: toggleVis
*
* Description: Following Function hides and expands the main column.
*
*
***************************************************************************/
// Set the default "show" mode to that specified by W3C DOM
// compliant browsers
var showMode = 'table-cell';
// However, IE5 at least does not render table cells correctly
// using the style 'table-cell', but does when the style 'block'
// is used, so handle this
if (document.all) showMode='block';
// This is the function that actually does the manipulation
var States = { };
function toggleVis(col){
if (!States[col] || States[col].IsOpen == null)
{
States[col] = {isOpen : true}; // This assumes the cell is already shown
//States[col] = {isOpen : false}; // This assumes the cell is already hidden
}
//mode = States[col].IsOpen ? showMode : 'none';
mode = States[col].IsOpen ? 'none' : showMode; //starts from closed, next click need open
cells = document.getElementsByName(col);
for(j = 0; j < cells.length; j++) cells[j].style.display = mode;
States[col].IsOpen = !States[col].IsOpen;
}
``` | ```
var States = {}
```
This creates a new object - arrays and objects are quite similar in javascript, but some subtle differences are there.
```
States[col] = {isOpen : true}
```
creates a new object and puts it into the next index of the States object. You can now access this value using States.col1.isOpen for example.
I notice you have two different ways of typing: IsOpen en isOpen, this is probably causing a problem for you.
Next you have to set the cookie with the information you want - take a peek at this URL:
<http://www.w3schools.com/JS/js_cookies.asp>
Hope this helps! | Ok, Maybe this is way off base but I think you are doing this entirely the wrong way.
1. Download jQuery and install it (it's
about 17kb, a tiny bit of overhead).
2. When you generate your page give each td in a given column a common class such as class='col2'.
3. Use your scripting library to remove hide all the cells.
$('.col2).hide()
To show the column you use the show function:
```
$('.col2').show()
```
You are done.
Things like this are so much easier with the correct libraries it's painful to see it done other ways. | Javascript syntax used in hiding html column | [
"",
"javascript",
"html",
"dom",
""
] |
I am maintaining a large asp.net app.
My objective is to identify the lines added in response to particular tickets. While it is possible using our SVN, I want to put it in the code. because these changes would look just odd to a first time reader of the code.
So which outlining method is more suitable for this purpose
```
{
//response to ticket #xxxxx
...
...
..
}
```
OR
```
#region response to ticket xxxxx
..
...
..
#endregion
```
Or is there any other method more suited for this | Between the two, definitely use comments - they are very flexible. Regions are no good for this sort of thing - what if multiple tickets require code changes which overlap? That's easily explained in a longer comment.
However, I'd argue against putting this kind of info in the comments anyway. No one is actually going to stumble onto code written a year ago and go look up the ticket. Code should be self-explanatory, and in the *very odd* case where it is not, comments should describe what the code *actually does*, not why. To address your specific concern of new readers - your colleagues do not need justification for why code is the way it is. They will assume it is that way for a reason, and when making additional changes will always try to maintain the existing functionality. That's basic professional behavior.
Your changeset should be associated with the ticket # in case anyone needs historical information. There's a list of justifications for why things are they way they are stored on each file. That is stored external to your codebase - either in your source control or some other repository.
In my experience, putting ticket numbers in the code is usually a symptom of bad practices. It denotes a deviation from the design instead of fixing the design. A ticket number says "this is how the code *was*, and this is how it is *now*." Codebases should not reflect their own history - all that matters is how they work *right now*. | Response to Option 1: Adding comments for tickets would decrease the readability of code. I think (and this is encouraged at my company) that when you check in a ticket-fix, you should also document that section of code more appropriately, but again, adding a ticket number might just be confusing.
Response to Option 2: Regions are for grouping functions with similar purpose together, so I would not recommend this option either.
Proposed Option: Use the /// standard of commenting functions and add a This is what was changed. element. This way fixes don't disrupt the normal readability, but it's simple to see functions that were involved with tickets. As an added bonus, this mechanism is self-documenting, so these would automatically get put into your generated documents. Note: You might want to check that custom tags are supported. | C# outlining. braces or regions | [
"",
"c#",
"code-formatting",
""
] |
I know I must be missing something here, but I cannot seem to get this to work.
I have assigned a background color to the body of an html document using the style tags inside the head section of the document, but when I try to read it via JavaScript, I get nothing:
```
<html>
<head>
<style>
body { background-color: #ff0; }
</style>
</head>
<body>
<a href="#" onclick='alert(document.body.style.backgroundColor)'>Click Here</a>
</body>
</html>
```
.. however, if I assign the style inline, it works:
```
<html>
<head></head>
<body style='background-color: #ff0;'>
<a href="#" onclick='alert(document.body.style.backgroundColor)'>Click Here</a>
</body>
</html>
```
I know I am missing something basic, but my mind is not in the zone today -- can anyone tell me why my first scenario is not working?
Thanks | The `style` property of a DOM element refers only to the element's *inline* styles.
Depending on the browser, you can get the actual style of an element using [DOM CSS](http://www.quirksmode.org/dom/w3c_css.html)
In firefox, for example:
```
var body = document.getElementsByTagName("body")[0];
var bg = window.getComputedStyle(body, null).backgroundColor;
```
Or in IE:
```
var body = document.getElementsByTagName("body")[0];
var bg = body.currentStyle.backgroundColor;
``` | In this case, you'll want the [`computedStyle`](http://www.java2s.com/Tutorial/JavaScript/0440__Style/GetComputedStyle.htm) on the Element as the `style` attribute hasn't been set yet. In IE, you'll need to check the Element's `currentStyle` property, via [something like this](http://erik.eae.net/archives/2007/07/27/18.54.15/). | Reading non-inline CSS style info from Javascript | [
"",
"javascript",
"css",
""
] |
In [Oracle SQL Developer](http://www.oracle.com/technology/products/database/sql_developer/index.html), if I'm viewing the information on a table, I can view the constraints, which let me see the foreign keys (and thus which tables are referenced by this table), and I can view the dependencies to see what packages and such reference the table. But I'm not sure how to find which tables reference the table.
For example, say I'm looking at the `emp` table. There is another table `emp_dept` which captures which employees work in which departments, which references the `emp` table through `emp_id`, the primary key of the `emp` table. Is there a way (through some UI element in the program, not through SQL) to find that the `emp_dept` table references the `emp` table, without me having to know that the `emp_dept` table exists? | No. There is no such option available from Oracle SQL Developer.
You have to execute a query by hand or use other tool (For instance [PLSQL Developer](http://www.allroundautomations.com/plsqldev.html) has such option). The following SQL is that one used by PLSQL Developer:
```
select table_name, constraint_name, status, owner
from all_constraints
where r_owner = :r_owner
and constraint_type = 'R'
and r_constraint_name in
(
select constraint_name from all_constraints
where constraint_type in ('P', 'U')
and table_name = :r_table_name
and owner = :r_owner
)
order by table_name, constraint_name
```
Where `r_owner` is the schema, and `r_table_name` is the table for which you are looking for references. The names are case sensitive
---
Be careful because on the reports tab of Oracle SQL Developer there is the option "All tables / Dependencies" this is from [ALL\_DEPENDENCIES](http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_1041.htm#i1576452) which refers to "*dependencies between procedures, packages, functions, package bodies, and triggers accessible to the current user, including dependencies on views created without any database links."*. Then, this report have no value for your question. | To add this to SQL Developer as an extension do the following:
1. Save the below code into an xml file (e.g. fk\_ref.xml):
```
<items>
<item type="editor" node="TableNode" vertical="true">
<title><![CDATA[FK References]]></title>
<query>
<sql>
<![CDATA[select a.owner,
a.table_name,
a.constraint_name,
a.status
from all_constraints a
where a.constraint_type = 'R'
and exists(
select 1
from all_constraints
where constraint_name=a.r_constraint_name
and constraint_type in ('P', 'U')
and table_name = :OBJECT_NAME
and owner = :OBJECT_OWNER)
order by table_name, constraint_name]]>
</sql>
</query>
</item>
</items>
```
2. Add the extension to SQL Developer:
* Tools > Preferences
* Database > User Defined Extensions
* Click "Add Row" button
* In Type choose "EDITOR", Location is where you saved the xml file above
* Click "Ok" then restart SQL Developer
3. Navigate to any table and you should now see an additional tab next to SQL one, labelled FK References, which displays the new FK information.
4. Reference
* <http://www.oracle.com/technetwork/issue-archive/2007/07-jul/o47sql-086233.html> | How can I find which tables reference a given table in Oracle SQL Developer? | [
"",
"sql",
"oracle",
"foreign-keys",
"oracle-sqldeveloper",
""
] |
I am reading through the examples on the Qt page and am wondering why they add references to already existing classes in their code [example](http://doc.trolltech.com/4.1/network-http-httpwindow-h.html):
```
#ifndef HTTPWINDOW_H
#define HTTPWINDOW_H
#include <QDialog>
class QFile;
class QHttp;
class QHttpResponseHeader;
class QLabel;
class QLineEdit;
class QProgressDialog;
class QPushButton;
class HttpWindow : public QDialog
{
...
``` | Those are forward declarations. Using them can (in some cases) obviate the need to #include the relevant header files, thus speeding up compilation. The Standard C++ library does something similar with the `<iosfwd>` header. | This is called [Forward Declaration](http://en.wikipedia.org/wiki/Forward_declaration)
You can refer to [this question here](https://stackoverflow.com/questions/553682/when-to-use-forward-declaration) to have a detailed idea of when to use Forward Declaration | Why does Qt include empty class definitions of existing classes in the header files? | [
"",
"c++",
"qt",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.