Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm puzzling with where to place some code. I have a listbox and the listitems are stored in the database. The thing is, where should I place the code that retrieves the data from the database? I do already have a database class with a method ExecuteSelectQuery(). Shall I create Utility class with a method public DataTable GetGroupData() ? /\* group is the listbox \*/ This method then calls the method ExecuteSelectQuery() from the database class.
What should I do? | You could simply abstract the database code into a utility class, as you suggest, and this wouldn't be a terrible solution. (You probably can't get much better with WebForms.) Yet if the system is going to end up quite complicated, then you might want to pick a more formal architecture...
Probably the best option for ASP.NET is the [ASP.NET MVC Framework](http://www.asp.net/mvc/), which fully replaces WebForms. It's built around the [Model-View-Controller](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) architecture pattern, which is designed specifically to clearly separate code for the user interface and backened logic, which seems to be exactly what you want. (Indeed, it makes the design of websites a lot more structured in many ways.)
Also, if you want to create a more structured model for your database system, consider using an ORM such as the [ADO.NET Entity Framework](http://msdn.microsoft.com/en-us/library/bb399572.aspx). However, this may be overkill if your database isn't very complicated. Using the MVC pattern is probably going to make a lot more difference. | There are many data access patterns you could look at implementing. A [Repository pattern](http://martinfowler.com/eaaCatalog/repository.html) might get you where you need to go.
The idea is to have a GroupRepository class that fetches Group data. It doesn't have to be overly complicated. A simple method like GetAllGroups could return a collection you can use for your ListBox items. | C# Where to place code that retrieves GUI data? | [
"",
"c#",
"database",
"user-interface",
"webforms",
""
] |
I am working on dynamically creating some JavaScript that will be inserted into a web page as it's being constructed.
The JavaScript will be used to populate a `listbox` based on the selection in another `listbox`. When the selection of one `listbox` is changed it will call a method name based on the selected value of the `listbox`.
For example:
`Listbox1` contains:
* `Colours`
* `Shapes`
If `Colours` is selected then it will call a `populate_Colours` method that populates another `listbox`.
To clarify my question: How do I make that `populate_Colours` call in JavaScript? | Assuming the `populate_Colours` method is in the global namespace, you may use the following code, which exploits both that all object properties may be accessed as though the object were an associative array, and that all global objects are actually properties of the `window` host object.
```
var method_name = "Colours";
var method_prefix = "populate_";
// Call function:
window[method_prefix + method_name](arg1, arg2);
``` | I would recommend **NOT** to use `global` / `window` / `eval` for this purpose.
Instead, do it this way:
define all methods as properties of Handler:
```
var Handler={};
Handler.application_run = function (name) {
console.log(name)
}
```
Now call it like this
```
var somefunc = "application_run";
Handler[somefunc]('jerry');
```
**Output:** jerry
---
Case when importing functions from different files
```
import { func1, func2 } from "../utility";
const Handler= {
func1,
func2
};
Handler["func1"]("sic mundus");
Handler["func2"]("creatus est");
``` | How do I call a dynamically-named method in Javascript? | [
"",
"javascript",
"dynamic",
"methods",
""
] |
I am trying to create an object from an Active Directory base on a simple login. The problem is that some of the login information is valid.
How could I just use a try-catch so that if an exception is thrown, just skip to the next login?
Here is the code:
```
foreach (var PharosUserItem in ListRef)
{
ADUser User;
try
{
User = new ADUser(PharosUserItem.UserLoginPharos);
}
catch (ByTel.DirectoryServices.Exceptions.UserNotFoundException ex)
{
break;
}
}
```
The break gets me out of the `foreach`, which is not what I want. Any ideas? | You are looking for *continue*
```
foreach (var PharosUserItem in ListRef)
{
ADUser User;
try
{
User = new ADUser(PharosUserItem.UserLoginPharos);
}
catch (ByTel.DirectoryServices.Exceptions.UserNotFoundException ex)
{
continue;
}
}
``` | Use the [`continue`](http://msdn.microsoft.com/en-us/library/aa664757.aspx) statement instead:
```
foreach (var pharosUserItem in ListRef)
{
ADUser user;
try
{
user = new ADUser(pharosUserItem.UserLoginPharos);
}
catch (UserNotFoundException)
{
continue;
}
// Use "user" here
}
```
(I've made a few changes in terms of variable casing, avoiding using a massively long fully-qualified name for the exception, and providing a variable for the exception which you then ignore.)
Note that if there's any reasonable way that you could get a list of valid users and check it, that would be nicer than using the exception for flow control as you're doing here. It may not be feasible, but it's worth checking :) | How to skip a record in a Foreach | [
"",
"c#",
".net",
"foreach",
"try-catch",
""
] |
I have a mysql database that stores some timestamps. Let's assume that all there is in the table is the ID and the timestamp. The timestamps might be duplicated.
I want to find the average time difference between consecutive rows that are not duplicates (timewise). Is there a way to do it in SQL? | If your table is t, and your timestamp column is ts, and you want the answer in seconds:
```
SELECT TIMESTAMPDIFF(SECOND, MIN(ts), MAX(ts) )
/
(COUNT(DISTINCT(ts)) -1)
FROM t
```
This will be miles quicker for large tables as it has no n-squared JOIN
This uses a cute mathematical trick which helps with this problem. Ignore the problem of duplicates for the moment. The average time difference between consecutive rows is the difference between the first timestamp and the last timestamp, divided by the number of rows -1.
Proof: The average distance between consecutive rows is the sum of the distance between consective rows, divided by the number of consecutive rows. But the sum of the difference between consecutive rows is just the distance between the first row and last row (assuming they are sorted by timestamp). And the number of consecutive rows is the total number of rows -1.
Then we just condition the timestamps to be distinct. | Are the ID's contiguous ?
You could do something like,
```
SELECT
a.ID
, b.ID
, a.Timestamp
, b.Timestamp
, b.timestamp - a.timestamp as Difference
FROM
MyTable a
JOIN MyTable b
ON a.ID = b.ID + 1 AND a.Timestamp <> b.Timestamp
```
That'll give you a list of time differences on each consecutive row pair...
Then you could wrap that up in an AVG grouping... | How to find the average time difference between rows in a table? | [
"",
"sql",
"mysql",
""
] |
I found something about this issue for ASP, but it didn't help me much ...
What I'd like to do is the following: I want to create a user control that has a collection as property and buttons to navigate through this collection. I want to be able to bind this user control to a collection and display different controls on it (containing data from that collection).
Like what you had in MS Access on the lower edge of a form ...
to be more precise:
When I actually use the control in my application (after I created it), I want to be able to add multiple controls to it (textboxes, labels etc) between the `<myControly>` and `</mycontrol>`
If I do that now, the controls on my user control disappear. | Here is an example of one way to do what you want:
First, the code - UserControl1.xaml.cs
```
public partial class UserControl1 : UserControl
{
public static readonly DependencyProperty MyContentProperty =
DependencyProperty.Register("MyContent", typeof(object), typeof(UserControl1));
public UserControl1()
{
InitializeComponent();
}
public object MyContent
{
get { return GetValue(MyContentProperty); }
set { SetValue(MyContentProperty, value); }
}
}
```
And the user control's XAML - UserControl1.xaml
```
<UserControl x:Class="InCtrl.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300" Name="MyCtrl">
<StackPanel>
<Button Content="Up"/>
<ContentPresenter Content="{Binding ElementName=MyCtrl, Path=MyContent}"/>
<Button Content="Down"/>
</StackPanel>
</UserControl>
```
And finally, the xaml to use our wonderful new control:
```
<Window x:Class="InCtrl.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:me="clr-namespace:InCtrl"
Title="Window1" Height="300" Width="300">
<Grid>
<me:UserControl1>
<me:UserControl1.MyContent>
<Button Content="Middle"/>
</me:UserControl1.MyContent>
</me:UserControl1>
</Grid>
</Window>
``` | I'm having a hard time understanding your question, but I think what you're describing is an [`ItemsControl`](http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.aspx) using [`DataTemplates`](http://msdn.microsoft.com/en-us/library/ms742521.aspx) to display the contents of (presumably) an [ObservableCollection(T)](http://msdn.microsoft.com/en-us/library/ms668604.aspx). | C# User Control that can contain other Controls (when using it) | [
"",
"c#",
"wpf",
"user-controls",
""
] |
I have a web based email application that logs me out after 10 minutes of inactivity ("For security reasons"). I would like to write something that either a) imitates a keystroke b) pings an ip or c) some other option every 9 minutes so that I stay logged in. I am on my personal laptop in an office with a door, so I'm not too worried about needing to be logged out.
I have written a small python script to ping an ip and then sleep for 9 minutes, and this works dandy, but I would like something that I could include in my startup applications. I don't know if this means I need to compile something into an exe, or can I add this python script to startup apps? | You can also use the **Scheduled Tasks** feature (on the Control Panel) to run it at startup, or you can change your script to ping the IP and exit, and scheduled it to run every 9 minutes. You have nice settings there, for example, you can stop running it at night, so you'll still log out.
You might still need the bat file though, I don't know about Python.
In fact, if you need just a simple ping you can scheduled ping.exe. | Assuming you use Windows, you can add a bat file containing the python run command in the Startup folder.
Example keeploggedin.bat
```
C:\Steve\Projects\Python> python pytest.py
``` | automatic keystroke to stay logged in | [
"",
"python",
"authentication",
""
] |
I am sure this has been discussed repeatedly, but I am stumped. I am using jQuery to make an AJAX call to an ASP.NET Web service which returns some HTML. That part is working fine.
I want to do some calculations on the height of the HTML returned, but when the the call happens for the first time I am getting a height of 0. I know my calculation are just happening before the AJAX call is complete, because on the second attempt it works. If I clear cache then it returns 0 again.
I need to fire an event after the html is rendered. I have tried both global and local events like `ajaxComplete`.
```
$.ajax({
type: "POST",
url: "Webservices/Service.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#OverlayContent").html(msg.d);
}
complete: function(msg) {
alert($("#OverlayContent").height());
}
});
```
I appreciate any help. | Sounds like your height calculation is running before the html is inserted and rendered in the DOM. Make sure to stagger it with a setTimeout call or an interval. For example:
```
$.ajax({
type: "POST",
url: "Webservices/Service.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#OverlayContent").html(msg.d);
setTimeout(function(){ getHeight();},100);
}
});
function getHeight(){
// If our height is 0, set a new timeout and we'll check again
if($("#OverlayContent").height() === 0){
setTimeout(function(){ getHeight() }, 100);
}
else{
alert("The height is: " + $("#OverlayContent").height());
}
}
```
You need to poll on the html being inserted into the DOM and rendered. | In all likelihood the complete event is firing simultaneously if not *before* the success event, since complete fires as soon as the AJAX data is finished being received. The success event is fired once it receives return data *with* the 200 OK status code.
You could use a delay, but personally I think using jQuery's queue() method would be better:
```
success: function(msg) {
$("#OverlayContent").html(msg.d).queue(function(){
alert($("#OverlayContent").height());
$(this).dequeue();
})
}
```
The dequeue() at the end there is important to restore the normal flow of things.
At that point you just get rid of the complete callback entirely. | Why am I unable to retrieve the calculated height of content inserted in response to a jQuery AJAX request? | [
"",
"javascript",
"jquery",
"ajax",
"dom",
""
] |
When I'm using e.g. PuTTY and my connection gets lost (or when I do a manual `ipconfig /release` on Windows), it responds directly and notifies my connection was lost.
I want to create a Java program which monitors my Internet connection (to some reliable server), to log the date/times when my internet fails.
I tried use the `Socket.isConnected()` method but that will just forever return "true". How can I do this in Java? | Well, the best way to tell if your connection is interrupted is to try to read/write from the socket. If the operation fails, then you have lost your connection sometime.
So, all you need to do is to try reading at some interval, and if the read fails try reconnecting.
The important events for you will be when a read fails - you lost connection, and when a new socket is connected - you regained connection.
That way you can keep track of up time and down time. | Even though TCP/IP is "connection oriented" protocol, normally no data is sent over an idle connection. You can have a socket open for a year without a single bit sent over it by the IP stack. In order to notice that a connection is lost, you have to send some data on the application level.(\*) You can try this out by unplugging the phone cable from your ADSL modem. All connections in your PC should stay up, unless the applications have some kind of application level keepalive mechanism.
So the only way to notice lost connection is to open TCP connection to some server and read some data from it. Maybe the most simple way could be to connect to some FTP server and fetch a small file - or directory listing - once in a while. I have never seen a generic server which was really meant to be used for this case, and owners of the FTP server may not like clients doing this.
(\*) There is also a mechanism called TCP keepalive but in many OS's you have to activate it for all applications, and it is not really practical to use if you want to notice loss of connection quickly | Java detect lost connection | [
"",
"java",
"tcp",
"connection",
""
] |
I have an object that has a list of 'observers'. These observers get notified of things, and they might respond to this change by adding or removing themselves or other observers from the object.
I want a robust, and not unnecessarily slow, way to support this.
```
class Thing {
public:
class Observer {
public:
virtual void on_change(Thing* thing) = 0;
};
void add_observer(Observer* observer);
void remove_observer(Observer* observer);
void notify_observers();
private:
typedef std::vector<Observer*> Observers;
Observers observers;
};
void Thing::notify_observers() {
/* going backwards through a vector allows the current item to be removed in
the callback, but it can't cope with not-yet-called observers being removed */
for(int i=observers.size()-1; i>=0; i--)
observers[i]->on_change(this);
// OR is there another way using something more iterator-like?
for(Observers::iterator i=...;...;...) {
(*i)->on_change(this); //<-- what if the Observer implementation calls add_ or remove_ during its execution?
}
}
```
I could perhaps have a flag, set by add\_ and remove\_, to reset my iterator if it gets invalidated, and then perhaps a 'generation' counter in each observer so I know if I've already called it? | The sane way to manage this chaos is to have a flag so the remove code knows whether it's iterating the observers.
In the remove, if the code is in an iteration, then the pointer is set to null rather than removed. The flag is set to a third state to indicate that this has happened.
The observers must be iterated with [] operator in case an add is called during iteration, and the array is reallocated. Null values in the array are ignored.
After iteration, if the flag is set to indicate that observers were removed in the iteration, the array can be compacted. | Maybe you could use a better(?) design. For example instead of having the Observers remove themselves, you could have the notify function remove them (or do any other operation) based on their return value. | Adding and removing items without invalidating iterators | [
"",
"c++",
"iterator",
"std",
""
] |
Is there any difference between `Server.MapPath()` and `HostingEnvironment.MapPath()`? Does `Server.MapPath()` have any advantages over `HostingEnvironment.MapPath()`?
My original problem was mapping the file path on a server when the `HttpContext` is not present and I cannot pass a `Server` variable from `Global.asax` to my method.
I used `HostingEnvironment.MapPath()` instead since it doesn't need `HttpContext`. Are there any situations when these two methods will give different results? | `Server.MapPath()` eventually calls `HostingEnvironment.MapPath()`, but it creates a `VirtualPath` object with specific options:
> The `VirtualPath` object passed to `HostingEnvironment.MapPath()` is constructed like this:
>
> ```
> VirtualPath.Create(path, VirtualPathOptions.AllowAllPath|VirtualPathOptions.AllowNull);
> ```
***Edit***: in reality, the only difference is that you are allowed to pass null to `Server.MapPath()`, but not to `HostingEnvironment.MapPath()` | `Server.MapPath()` requires an `HttpContext`. `HostingEnvironment.MapPath` does not. | What is the difference between Server.MapPath and HostingEnvironment.MapPath? | [
"",
"c#",
"asp.net",
""
] |
Is it possible to view an array in the Visual Studio debugger? QuickWatch only shows the first element of the array. | You can try this nice little trick for C++. Take the expression which gives you the array and then append a comma and the number of elements you want to see. Expanding that value will show you elements 0-(N-1) where N is the number you add after the comma.
For example if `pArray` is the array, type `pArray,10` in the watch window. | If you have a large array and only want to see a subsection of the array you can type this into the watch window;
```
ptr+100,10
```
to show a list of the 10 elements starting at ptr[100]. Beware that the displayed array subscripts will start at [0], so you will have to remember that ptr[0] is really ptr[100] and ptr[1] is ptr[101] etc. | View array in Visual Studio debugger? | [
"",
"c++",
"visual-studio",
"arrays",
"view",
"debugging",
""
] |
please have a look at the following code. When the value of i == 0 the alert 1 prints variable values as per logic. But if I try to print values (alert 2), it just says "undefined, undefined". My question is what changes I'll have to make to get the values printed in second alert (Alert 2) same as per alert 1?
```
var testPoint = [];
function load() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(52.5271463402545, -1.50573921491311), 8, G_HYBRID_MAP);
GDownloadUrl("controllers/gmap_genxml2.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
if(i == 0) {
testPoint["lat"] = parseFloat(markers[i].getAttribute("lat"));
testPoint["lng"] = parseFloat(markers[i].getAttribute("lng"));
/********* ALERT 1 ***********/
alert(testPoint["lat"]+" "+testPoint["lng"]);
/********* ALERT 1 End ***********/
}
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, name, address, type);
map.addOverlay(marker);
}
});
/********* ALERT 2 ******************/
alert(testPoint["lat"]+" "+testPoint["lng"]);
/********* ALERT 2 Start ***********/
}
}
```
Thank you for your help.
DeeJay | ```
testPoint = [];
// This global var is introduced to mark that testPoint values are not yet loaded.
var isLoaded = false;
function load() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(52.5271463402545, -1.50573921491311), 8, G_HYBRID_MAP);
GDownloadUrl("controllers/gmap_genxml2.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
if(i == 0) {
testPoint["lat"] = parseFloat(markers[i].getAttribute("lat"));
testPoint["lng"] = parseFloat(markers[i].getAttribute("lng"));
/********* ALERT 1 ***********/
alert(testPoint["lat"]+" "+testPoint["lng"]);
/********* ALERT 1 End ***********/
// Set it to true to indicate that testPoint array is already loaded.
isLoaded = true;
}
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, name, address, type);
map.addOverlay(marker);
}
});
/********* ALERT 2 ******************/
// Try to alert testPoint each 0.5 sec until we can successfully do it.
function alert2() {
// if testPoint is loaded - then alert it, if not then try in 0.5 sec.
if (isLoaded) {
alert(testPoint["lat"]+" "+testPoint["lng"])
} else {
setTimeout(alert2, 500);
}
};
alert2();
/********* ALERT 2 Start ***********/
}
}
``` | You have to realize that a lot of JavaScript is event based. Here is what is happening:
`GDownloadUrl` takes a callback. The second argument is a function that will be called *when the request is complete*. It **will not** be called right away. This is important. After you close the call to `GDownloadUrl`, Javascript keeps on going. It doesn't wait for the request to complete. As a matter of fact, if you leave both alerts in you will see that the alert 2 will fire before alert 1. As such, if you want to do a particular thing with these variables once they are fetched, you should move that code to a function and call it from within the `GDownloadUrl` callback. This is just the way JavaScript works and you'll get used to it. | How to set javascript variable from the inside of a function? | [
"",
"javascript",
"variables",
""
] |
I created a table and set the collation to **utf8** in order to be able to add a unique index to a field. Now I need to do case insensitive searches, but when I performed some queries with the collate keyword and I got:
```
mysql> select * from page where pageTitle="Something" Collate utf8_general_ci;
```
> ERROR 1253 (42000): COLLATION 'utf8\_general\_ci' is not valid for
> CHARACTER SET 'latin1'
```
mysql> select * from page where pageTitle="Something" Collate latin1_general_ci;
```
> ERROR 1267 (HY000): Illegal mix of collations (utf8\_bin,IMPLICIT) and
> (latin1\_general\_ci,EXPLICIT) for operation '='
I am pretty new to SQL, so I was wondering if anyone could help. | A string in MySQL has a [character set and a collation](http://dev.mysql.com/doc/refman/5.0/en/charset.html). Utf8 is the character set, and utf8\_bin is one of its collations. To compare your string literal to an utf8 column, convert it to utf8 by prefixing it with the \_charset notation:
```
_utf8 'Something'
```
Now a collation is only valid for some character sets. The case-*sensitive* collation for utf8 appears to be utf8\_bin, which you can specify like:
```
_utf8 'Something' collate utf8_bin
```
With these conversions, the query should work:
```
select * from page where pageTitle = _utf8 'Something' collate utf8_bin
```
The \_charset prefix works with string literals. To change the character set of a field, there is CONVERT ... USING. This is useful when you'd like to convert the pageTitle field to another character set, as in:
```
select * from page
where convert(pageTitle using latin1) collate latin1_general_cs = 'Something'
```
To see the character and collation for a column named 'col' in a table called 'TAB', try:
```
select distinct collation(col), charset(col) from TAB
```
A list of all character sets and collations can be found with:
```
show character set
show collation
```
And all valid collations for utf8 can be found with:
```
show collation where charset = 'utf8'
``` | Also please note that in case of using "Collate utf8\_general\_ci" or "Collate latin1\_general\_ci", i.e. "force" collate - such a converting will prevent from usage of existing indexes! This could be a bottleneck in future for performance. | MYSQL case sensitive search for utf8_bin field | [
"",
"mysql",
"sql",
"character-encoding",
"case-sensitive",
"mysql-error-1267",
""
] |
This may sound crazy, and i didnt believe it until i saw it for myself.
The vertical scroll bar does not scroll when you click in the space between the scroller or the arrows. You have to drag the bar to get it to scroll. This only happens in the ugly default theme (not windows classic).
The scroll bar has some heavy javascript behind it that drive scrolling of another DIV on the page.
Has anyone even encountered this before? Why the heck does the theme influence IE's rendering?! Only IE!
**edit**:
this problem happens when you are in "non-classic" XP theme (the default ugly one). switching themes does not cause this, but it does fix it if you switch to classic from the default. | Does it help when you add
```
<!--[if IE]><meta http-equiv="MSThemeCompatible" content="no"><![endif]-->
```
to your page source? It worked well to work around glitches in IE when a non-classic theme is enabled for me. Note that the conditional comments are there so that firefox does not parse the tag (because it will screw up scrollbars in firefox sometimes). | I just had the same problem with vertical scrollbar in IE7 within the XP theme. After many experiments, I finally found the solution to it. I don't know this solution fits your case.
The container (div#scroll in the example below) with the rendered scrollbars must be larger than 18px. Any number below that will cause the vertical bar disabled.
```
<div id="scroll">
<div id="fill">
</div>
</div>
```
The stylesheet, for example:
```
#fill{
width: 1px;
height: 1000px;
}
#scroll {
width: 18px; /* This has to be larger than or equal to 18. */
height: 50px;
overflow-y: scroll;
}
```
Thanks,
Grace | vertical scroll bar not working when using window xp theme (not classic) | [
"",
"javascript",
"internet-explorer",
"scrollbar",
"windows-themes",
""
] |
I want to generate a list of color specifications in the form of (r, g, b) tuples, that span the entire color spectrum with as many entries as I want. So for 5 entries I would want something like:
* (0, 0, 1)
* (0, 1, 0)
* (1, 0, 0)
* (1, 0.5, 1)
* (0, 0, 0.5)
Of course, if there are more entries than combination of 0 and 1 it should turn to use fractions, etc. What would be the best way to do this? | Use the HSV/HSB/HSL color space (three names for more or less the same thing). Generate N tuples equally spread in hue space, then just convert them to RGB.
Sample code:
```
import colorsys
N = 5
HSV_tuples = [(x*1.0/N, 0.5, 0.5) for x in range(N)]
RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples)
``` | Color palettes are interesting. Did you know that the same brightness of, say, green, is perceived more intensely than, say, red? Have a look at <http://poynton.ca/PDFs/ColorFAQ.pdf>. If you would like to use preconfigured palettes, have a look at [seaborn's palettes](https://seaborn.pydata.org/tutorial/color_palettes.html):
```
import seaborn as sns
palette = sns.color_palette(None, 3)
```
Generates 3 colors from the current palette. | Generating color ranges in Python | [
"",
"python",
"colors",
""
] |
What are some applications for Python that **relative amateur programmers** can get into?
For example, Ruby has Rails for building web applications. What are some cool applications of Python?
Thanks. | Google App Engine has excellent support for developing -- and especially for deploying -- web applications in Python (with several possible frameworks, of which Django may be the most suitable one for "relative amateurs"). Apart from web apps, Blender lets you use Python for 3D graphics, Poser for apps involving moving human-like figures, SPSS for statistics, scipy and many other tools included in Enthought's distribution support Python use in scientific programming and advanced visualization, etc, etc -- the sky's the limit. | You can build web applications in Python. See the [Django framework](http://www.djangoproject.com/).
Besides that, [here's](http://www.python.org/about/apps/) a nice list.
Not particularly relevant, but interesting, is the fact that NASA uses Python. | Applications of Python | [
"",
"python",
""
] |
In a script , I want to run a .exe with some command line parameters as "-a",and then
redirect the standard output of the program to a file?
How can I implement that? | You can redirect directly to a file using subprocess.
```
import subprocess
with open('output.txt', 'w') as output_f:
p = subprocess.Popen('Text/to/execute with-arg',
stdout=output_f,
stderr=output_f)
``` | Easiest is `os.system("the.exe -a >thefile.txt")`, but there are many other ways, for example with the `subprocess` module in the standard library. | How to redirect the output of .exe to a file in python? | [
"",
"python",
"redirect",
"io",
""
] |
Let me reformulate, as the answer <https://stackoverflow.com/questions/951907/where-are-my-visitors-going> was absolutely correct, but my question not precise enough ;)
How does one track with Java Script where the visitors are going? (From a technical standpoint.)
Is the idea to execute a code every time a link is pressed? If yes, does this have to be specified in the `<a>`-tag itself, i.e., `<a href="..." onmousedown="return mycode(this)">`, or can this be done globally without having to mention it for every link?
I don't want the specifics of any code (as there is GoogleAnalytics etc.), I just want to know generally how it could work.
Btw, you guys are really quick! | You can write an event that records visitor activity per anchor tag or you can write a script that scans the document and does it for you (which is what Google Analytics does). If you choose to use a script, make sure you put it at the end of the document so that your web page is as responsive as possible.
You can easily iterate through anchor tags as follows (untested):
```
var tags = document.getElementsByTagName("a");
for (var i = 0; i < tags.length; i++) {
tags[i].onclick = function() {...};
}
``` | This link may give you some idea - <http://blog.ndrix.com/2007/07/how-google-analytics-works.html>
* A visitor loads a page on your website
* In the process, her browser loads and runs some Javascript from Google
* That Javascript collects information about the visitor
* The information is sent to Google by requesting a URI and passing the details as CGI parameters | How does one track with JS where the visitors are going? | [
"",
"javascript",
"html",
"statistics",
""
] |
Where the heck do I get org.hibernate.tool.ant.HibernateToolTask ? I can't seem to find a .jar file that contains it. | Download Hibernate Tools - it's in hibernate-tools.jar located in plugins\org.hibernate.eclipse\_3.2.4.CR2-R200901280154\lib\tools | I got the latest (hibernate 4) version of `hibernate-tools.jar` (`hibernate-tools-4.3.1.Final.jar`) like this:
* Get the jar for Hibernate tools v. 4.3.1:
+ Dowload JBossTools 4.3.0
+ from <http://tools.jboss.org/downloads/jbosstools/mars/4.3.0.Final.html#zips>
+ choose "Update site" download from the "Artifacts" tab
+ the jar is in `jbosstools-4.3.0.Final-updatesite-core\plugins\org.jboss.tools.hibernate.runtime.v_4_3_5.0.0.Final-v20150924-2221-B39.jar\lib`in the unpacked zip | where the heck is org.hibernate.tool.ant.HibernateToolTask? | [
"",
"java",
"hibernate",
"ant",
"task",
""
] |
I'm currently getting the total thread CPU time using JMX in the following manner:
```
private long calculateTotalThreadCpuTime(ThreadMXBean thread) {
long totalTime = 0l;
for (ThreadInfo threadInfo : thread.dumpAllThreads(false, false))
totalTime += thread.getThreadCpuTime(threadInfo.getThreadId());
return totalTime;
}
```
As the ThreadMXBean is actually a remote proxy, performance is *dreadful*, in the order of magnitude of seconds for this actual method call.
Is there a faster way of doing this?
---
**Update**: I'm using this for performance monitoring. The measurements were both 'wall clock' time and JProfiler, which showed about 85% of my time spent in this method. I do have some other MXBean calls ( Runtime, Memory, GC ), but they are much cheaper. Most likely because every call to `thread.getThreadCpuTime` is a remote one.
**Update 2**: JProfiler screenshot showing the performance problems.
 | Optimisations:
* invoke getThreadCPUTime inside a thread pool, since it seems to be network-bound;
* whenever a thread is found to be in `Thread.STATE.TERMINATED`, keep its name in a Map and skip querying the next time. | If you are willing to use non-standard APIs, you can cast `OperatingSystemMXBean` to `com.sun.management.OperatingSystemMXBean` and invoke `getProcessCpuTime()`, as described in [Using a Sun internal class to get JVM CPU time](http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking#UsingaSuninternalclasstogetJVMCPUtime) on David Robert Nadeau's blog. | Efficient way of getting thread CPU time using JMX | [
"",
"java",
"jmx",
""
] |
Okay, so a while ahead I posted how to read other config files of other programs (here is the link [Previous Post](https://stackoverflow.com/questions/938585/open-other-programs-configuration-files). I managed to do it. But now there is another problem. The scenario is like this, I have two programs. Program **A** reads its configuration from a config file and program **B** is only used to modify the contents of the config file which **A** reads. The name of the config file is *email.config*. It is in the same directory in which program **A** & **B** resides.
The problem is that I get path of a file for attachment using open file dialog. If the path points to a file in the same directory, the program works perfect! But if it points to a file outside the directory it throws an exception of type *System.NullReferenceException*.
Here is the code
```
private void saveBtn_Click(object sender, EventArgs e)
{
try
{
// save everything and close
string attachment = attachTxtBox.Text;
var configMap = new ExeConfigurationFileMap { ExeConfigFilename = configFileName };
// it throws exception here when
// the path points to a file outside the exes directory
Configuration externalConfig = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
externalConfig.AppSettings.Settings["ServerAddress"].Value = serverAddr;
externalConfig.AppSettings.Settings["Port"].Value = port;
externalConfig.AppSettings.Settings["SSL"].Value = ssl.ToString();
externalConfig.AppSettings.Settings["Sender"].Value = senderAddr;
externalConfig.AppSettings.Settings["SenderPassword"].Value = password;
externalConfig.AppSettings.Settings["Subject"].Value = subject;
externalConfig.AppSettings.Settings["AttachmentPath"].Value = attachment;
externalConfig.AppSettings.Settings["Body"].Value = messageBody;
// Save values in config
externalConfig.Save(ConfigurationSaveMode.Full);
Application.Exit();
}
catch (System.Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
Application.Exit();
}
}
```
The content of *email.config* is:
```
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings file="">
<clear />
<add key="ServerAddress" value="" />
<add key="Port" value="" />
<add key="Sender" value="" />
<add key="SenderPassword" value="" />
<add key="Subject" value="" />
<add key="AttachmentPath" value="" />
<add key="Body" value="" />
</appSettings>
</configuration>
```
What am I doing wrong here?
**EDIT:** The value of *configFileName* is *"email.config"* | Well, I figured it out myself after debugging for almost 5 hours, Damn!
The problem was when I used OpenFileDialog to get the file path, it changed the current directory to the one which is selected in the dialog, so the program couldn't find the config file. All I did was to set the RestoreDirectory property of OpenFileDialog to true and *poof* it worked
Thanks everyone, ChrisF, Eoin Campbell and pablito. | Are you accessing the file by its full path or just the file name?
If the latter then this will work when the file is in the same folder as the executable, but not otherwise.
**UPDATE**
It looks as though things are more complicated than I first thought and this doesn't seem to be the issue here - see the comments. The line that's raising the exception is:
```
externalConfig.AppSettings.Settings["ServerAddress"].Value = serverAddr;
```
So that means that there's a null reference somewhere along the chain. If you can identify which it is then that should give you a pointer to the problem. | C# Configuration Files | [
"",
"c#",
".net",
"file",
"config",
""
] |
My system successfully passes objects from a client to servlet. However it is primitive as it was built to cater for Java 1.1. The message object it passes consists of an int (representing one of about seventy types) and a String of tokens which need to be parsed (the tokens may contain a list, a list of objects, etc). Not good!
So, I'm looking to refactor this to Java 1.5. Using an enum instead of an int is certainly an improvement, but I'm unsure how to send the rest of the message. Creating seventy different classes to represent each type surely isn't the correct way to go.
Any pointers on how I should refactor this? | There is no need to create a different class to represent each type of message. You create one message class with the properties that you need. Something like this:
```
public class Message implements Serializable{
private Long id;
private String msgText;
//other necessary properties
public Message(){
this(0, "default message");
}
public Message(Long id, String msgText){
setId(id);
setMsgText(msgText);
//etc
}
//getters and setters
}
```
And you then create objects as needed. For example:
```
Message m1 = new Message(9, "The Eagle has landed");
//serialize m1 to server
Message m2 = new Message(27, "The Wren has landed");
//serialize m2 to the server
```
and so on. | You may want to use serialized objects.
They are meant to be easily passed along the network.
In your situation you will just need a serialized 'message' class. Then you can read and write it to a stream.
[Here](http://java.sun.com/developer/technicalArticles/Programming/serialization/) is a tutorial on using serialized objects. There are lots out there. | Java: appropriate way to pass messages between client and servlet? | [
"",
"java",
"communication",
"message-passing",
""
] |
I'm developing a class that will be used to generate a tree structure. Each Node of the tree needs to know both who it's parent is and who it's children are. The fields used to track each Nodes parent and children are not accessible outside the base Node class.
Right now I have methods for AddChild, and Remove child. Which consequently also set the parent fields of the instances being related.
So what I'm wondering now is if it would be any better or worse to switch this and setup methods where the user of the class has to call Node.SetParent(Node parentNode) and Node.ClearParent(Node oldParentNode) methods instead.
If you are tracking both parent and child relationships, why would you choose to set the child relationships over the parents or vise versa, or does it even matter? | In either case, when you are attaching a node to the tree you will need a reference to both the parent and the child node in question, so I don't see how it would make a difference, as either way will be equally possible in all situations.
I'd suggest figuring out which direction your logic will make the most sense (i.e. is it easier to think about building the tree from the leaves up or the root down) and go with that. | Decisions like these typically depend on how the class will be used. If a typical scenerio is for a tree to be build from the parent node down, then using an AddChild method is often best, if your users build them from the other way around, give the a SetParent method. If there is a need for both, implement both, so long as the appropriate book keeping is done internal to the class.
(side note: I usually build trees from the parent down) | Children or Parent based Tree Structure | [
"",
"c#",
"data-structures",
"tree",
""
] |
There is a project written in PHP that is just simply all procedural ... step by step calling DB functions, processing, and printing out the output. And then it is changed to totally object oriented -- there is a singleton for the App object, and various functions are invoked through the App object.
Someone claims that the memory usage or footprint on the server will be less. Would that be the case? I thought procedural often just uses the bare minimal, while Object oriented programming with various design patterns usually instantiates more things than needed, or simply have objects around while procedural usually just have the bare minimal.
So will changing all code to object oriented actually make the memory usage on the server smaller? | It will probably make it more, but there's really no way to tell. If your code actually improves by doing it in an OOP way, then it may be less. There is no direct correlation between memory used and the presence of object oriented ness. Maybe in general, object oriented takes more memory, but only if both sets of code are written equally well, and that's almost never the case.
Is there a reason this application is being upgraded to be objected oriented? You know it's not one or the other, you can mix and match pieces... OOP is not a silver bullet. | Unfortunately, I've done my tests too. I did test speed, and it's about the same, but when testing for memory usage getting memory\_get\_usage() in PHP, I saw an overwhelmingly larger number on the OOP side.
116,576 bytes for OOP to 18,856 bytes for procedural. I know "Hardware is cheap", but come on! 1,000% increase in usage? Sorry, that's not optimal. And having so many users hitting your website at once, I'm sure your RAM would just burn, or run out. Am I wrong?
Basically, what I'm hearing from all my OOP fans is that... You will use more resources, it will be just as fast as well written procedural function calls, but it will be better for large projects and multi-developer environment. A balance needs to be found.
**More devs (sloppy devs) and larger site**
Con: More RAM used for your app.
Pro: Easier to maintain the code among many across the whole app.
**One dev with a simple site**
Con: If your site grows, or starts to include many developers, development might be a bit slower if your procedural code sucks.
Pro: Low RAM, slightly faster speed. If your code is written properly (and only good developers can do this - haha), your code will be just as easy to maintain.
In the RAM wars, Procedural wins. In the maintainability wars, good code wins. ;)
OOP fans say that OOP is cleaner. I've seen some really messy OOP code, and then I've seen some REALLY CLEAN procedural code, written by developers who could write great code in any language or style. Code that made it a pleasure to work with. The bottom line is that if you have sloppy developers, it won't matter which style you use, you're gonna have sloppy code.
Because of my very own personal benchmarks, I opt out of memory hog OOP, mainly because I do write really clean procedural, and I'm usually the only dev on any of my projects.
Cheers! | will changing all code to object oriented make memory usage bigger or smaller? | [
"",
"php",
"oop",
""
] |
Is there a way to determine which classes are loaded from which JARs at runtime?
I'm sure we've all been in JAR hell before. I've run across this problem a lot troubleshooting `ClassNotFoundException`s and `NoClassDefFoundError`s on projects. I'd like to avoid finding all instances of a class in JARs and using process of elimination on the code causing a CNFE to find the culprit.
Will any profiling or management tools give you this kind of information?
This problem is super annoying purely because we should have this information at the time the class gets loaded. There has to be a way to get to it, or record it and find it, yet I know of nothing that will do this, do you?
I know OSGi and versioned bundles/modules aim to make this a non issue... but it doesn't seem to be going away any time soon.
Note: I found this [question](https://stackoverflow.com/questions/139534/classloader-issues-how-to-determine-which-library-versions-jar-files-are-load) is a subset of my question related to classes loaded from versioned jars.
Somewhat related, this post explains a strategy to search for a class within JARs (either under the current directory) or in your M2\_REPO: [JarScan, scan all JAR files in all subfolders for specific class](https://stackoverflow.com/questions/759923/jarscan-scan-all-jar-files-in-all-subfolders-for-specific-class)
Also somewhat related, [JBoss Tattletale](http://docs.jboss.org/tattletale/developerguide/en/html_single/) | Passing the `-verbose:class` switch to the `java` command will print each class loaded and where it was loaded from.
[Joops](http://code.google.com/p/joops/) is also a nice tool for finding missing classes ahead of time. | From code you can call:
```
myObject.getClass().getProtectionDomain().getCodeSource()
```
(Note, `getProtectionDomain` may unfortunately return `null` (bad design), so "proper code" would check for that.) | How to explore which classes are loaded from which JARs? | [
"",
"java",
"profiling",
"classloader",
"jar",
""
] |
How can I do the following in JavaScript?
1. Concatenate "1", "2", "3" into "123"
2. Convert "123" into 123
3. Add 123 + 100 = 223
4. Covert 223 into "223" | You want to become familiar with [`parseInt()`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt) and [`toString()`](https://developer.mozilla.org/en-US/docs/toString).
And useful in your toolkit will be to look at a variable to find out what type it is—[`typeof`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/typeof):
```
<script type="text/javascript">
/**
* print out the value and the type of the variable passed in
*/
function printWithType(val) {
document.write('<pre>');
document.write(val);
document.write(' ');
document.writeln(typeof val);
document.write('</pre>');
}
var a = "1", b = "2", c = "3", result;
// Step (1) Concatenate "1", "2", "3" into "123"
// - concatenation operator is just "+", as long
// as all the items are strings, this works
result = a + b + c;
printWithType(result); //123 string
// - If they were not strings you could do
result = a.toString() + b.toString() + c.toString();
printWithType(result); // 123 string
// Step (2) Convert "123" into 123
result = parseInt(result,10);
printWithType(result); // 123 number
// Step (3) Add 123 + 100 = 223
result = result + 100;
printWithType(result); // 223 number
// Step (4) Convert 223 into "223"
result = result.toString(); //
printWithType(result); // 223 string
// If you concatenate a number with a
// blank string, you get a string
result = result + "";
printWithType(result); //223 string
</script>
``` | ### Step (1) Concatenate "1", "2", "3" into "123"
```
"1" + "2" + "3"
```
*or*
```
["1", "2", "3"].join("")
```
*The [join](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) method concatenates the items of an array into a string, putting the specified delimiter between items. In this case, the "delimiter" is an empty string (`""`).*
### Step (2) Convert "123" into 123
```
parseInt("123")
```
*Prior to [ECMAScript 5](https://kangax.github.io/compat-table/es5/), it was necessary to pass the radix for base 10: `parseInt("123", 10)`*
### Step (3) Add 123 + 100 = 223
```
123 + 100
```
### Step (4) Covert 223 into "223"
```
(223).toString()
```
*or*
```
String(223)
```
### Put It All Togther
```
(parseInt("1" + "2" + "3") + 100).toString()
```
*or*
```
(parseInt(["1", "2", "3"].join("")) + 100).toString()
``` | JavaScript string and number conversion | [
"",
"javascript",
"string",
"numbers",
""
] |
I'm writing a plug-in for a program where I can attribute objects in the program by appending "User Strings" to each object that have a key string and a value string. However, in some cases I need to store an array of a primitive type rather then just a single value. So what is the easiest way to convert an array of values into a string, and then later take that same string and convert it back into the original array of values. | You could create a couple of extension methods to convert your collections to/from delimited strings, passing in a custom delegate to perform the conversion of each item:
```
public static string ToDelimitedString<T>
(this IEnumerable<T> source, Func<T, string> converter, string separator)
{
return string.Join(separator, source.Select(converter).ToArray());
}
public static IEnumerable<T> FromDelimitedString<T>
(this string source, Func<string, T> converter, params string[] separator)
{
return source.Split(separator, StringSplitOptions.None).Select(converter);
}
```
And here are a few examples of usage:
```
int[] source1 = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
string txt1 = source1.ToDelimitedString(x => x.ToString(), "|");
Console.WriteLine(txt1); // "1|2|3|4|5|6|7|8|9|10"
int[] dest1 = txt1.FromDelimitedString(x => int.Parse(x), "|").ToArray();
Console.WriteLine(source1.SequenceEqual(dest1)); // "True"
// ...
string[] source2 = new[] { "Fish & Chips", "Salt & Pepper", "Gin & Tonic" };
string txt2 = source2.ToDelimitedString(x => HttpUtility.UrlEncode(x), "&");
Console.WriteLine(txt2); // "Fish+%26+Chips&Salt+%26+Pepper&Gin+%26+Tonic"
var dest2 = txt2.FromDelimitedString(x => HttpUtility.UrlDecode(x), "&");
Console.WriteLine(source2.SequenceEqual(dest2)); // "True"
``` | You must use split and join:
Here is a good article about it:
<http://www.csharp-station.com/HowTo/StringJoinSplit.aspx> | Converting an Array of primatives to and from a single string | [
"",
"c#",
""
] |
What is a fast and efficient way to implement the server-side component for an autocomplete feature in an html input box?
I am writing a service to autocomplete user queries in our web interface's main search box, and the completions are displayed in an ajax-powered dropdown. The data we are running queries against is simply a large table of concepts our system knows about, which matches roughly with the set of wikipedia page titles. For this service obviously speed is of utmost importance, as responsiveness of the web page is important to the user experience.
The current implementation simply loads all concepts into memory in a sorted set, and performs a simple log(n) lookup on a user keystroke. The tailset is then used to provide additional matches beyond the closest match. The problem with this solution is that it does not scale. It currently is running up against the VM heap space limit (I've set -Xmx2g, which is about the most we can push on our 32 bit machines), and this prevents us from expanding our concept table or adding more functionality. Switching to 64-bit VMs on machines with more memory isn't an immediate option.
I've been hesitant to start working on a disk-based solution as I am concerned that disk seek time will kill performance. Are there possible solutions that will let me scale better, either entirely in memory or with some fast disk-backed implementations?
Edits:
@Gandalf: For our use case it is important the the autocompletion is comprehensive and isn't just extra help for the user. As for what we are completing, it is a list of concept-type pairs. For example, possible entries are [("Microsoft", "Software Company"), ("Jeff Atwood", "Programmer"), ("StackOverflow.com", "Website")]. We are using Lucene for the full search once a user selects an item from the autocomplete list, but I am not yet sure Lucene would work well for the autocomplete itself.
@Glen: No databases are being used here. When I'm talking about a table I just mean the structured representation of my data.
@Jason Day: My original implementation to this problem was to use a [Trie](http://en.wikipedia.org/wiki/Trie), but the memory bloat with that was actually worse than the sorted set due to needing a large number of object references. I'll read on the ternary search trees to see if it could be of use. | With a set that large I would try something like a Lucene index to find the terms you want, and set a timer task that gets reset after every key stroke, with a .5 second delay. This way if a user types multiple characters fast it doesn't query the index every stroke, only when the user pauses for a second. Useability testing will let you know how long that pause should be.
```
Timer findQuery = new Timer();
...
public void keyStrokeDetected(..) {
findQuery.cancel();
findQuery = new Timer();
String text = widget.getEnteredText();
final TimerTask task = new TimerTask() {
public void run() {
...query Lucene Index for matches
}
};
findQuery.schedule(task, 350); //350 ms delay
}
```
Some pseduocode there, but that's the idea. Also if the query terms are set the Lucene Index can be pre-created and optimized. | I had a similar requirement.
I used relational database with a single well-indexed synthetic table (avoiding joins and views to speed up lookups), and in-memory cache (Ehcache) to store most used entries.
By using MRU cache you'll be able to have instant response times for most of the lookups, and there is probably nothing that can beat relational database in accessing indexed column in a big table stored on disk.
This is solution for big datasets you can't store on the client and it works pretty fast (non-cached lookup was always retrieved under 0.5 seconds in my case). It's also horizontally scalable - you can always add additional servers and database servers.
You could also play with caching of only the most used results on the client, especially if you've already implemented it. In my case, server-side solution is fast enough, and client load times are slow enough as it is, so it's not warranted.
P.S. Having client query only when user pauses for a certain amount of time to avoid repeated lookups as suggested is a good solution. On my client, I query database only after first three characters are entered, since less than that returns too many results in all instances. | Autocomplete server-side implementation | [
"",
"java",
"memory",
"autocomplete",
"performance",
""
] |
Can I change creation date of some file using Python in Linux? | Linux and Unix file system stores :
> File access, change and modification time (remember UNIX or Linux never stores file creation time, this is favorite question asked in UNIX/Linux sys admin job interview)
[Understanding UNIX / Linux file systems](http://www.cyberciti.biz/tips/understanding-unixlinux-filesystem-inodes.html) | You can use [os.utime](http://docs.python.org/library/os.html#os.utime) to change access and modify time but not the creation date. | Change file creation date | [
"",
"python",
"linux",
"file",
"date",
""
] |
In our application, we are allowing users to open files and directories.
Java 6 provides us with...
```
java.awt.Desktop.getDesktop().open(file);
```
which works great. However, since we need to ensure Java 5 compatibility, we also implement a method of opening files by calling the `start` command in `cmd.exe`...
```
String command = "cmd.exe start ...";
Runtime.getRuntime().exec(command);
```
This is where the problem shows up. It seems that the `start` command can only handle [8.3](http://en.wikipedia.org/wiki/8.3_filename) file names, which means that any non-short (8.3) file/directory names cause the `start` command to fail.
Is there an easy way to generate these short names? Or any other workarounds? | Try something like this
```
import java.io.IOException;
class StartExcel {
public static void main(String args[])
throws IOException
{
String fileName = "c:\\temp\\xls\\test2.xls";
String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",fileName};
Runtime.getRuntime().exec(commands);
}
}
```
It's important to pass a dummy title to the Windows start command where there is a possibility that the filename contains a space. It's a feature. | Try this: <http://dolf.trieschnigg.nl/eightpointthree/eightpointthree.html> | Is there a way to generate the 8.3 or 'short' (Windows) version of a file name in Java? | [
"",
"java",
"windows",
"runtime.exec",
""
] |
I have many math types like Point3, and I am running into the dilemma of implementing operators, instance and static methods for arithmetic.
So say the type is `Point3`. Where a, b, c is a `Point3`, I sure wanna be able to say:
```
c = a + b;
```
But should I also implement:
```
c = Point3.Add (a, b);
```
And this:
```
c = a.Add (b);
```
To me #3 is useless and less readable than #1. And #2 seems like pointless unless you have an interface for Add, Subtract, Multiply, Divide, etc.
What do you recommend? Is there any problem or drawback with just having the operators (+, -, \*, /)? Would this impede the generics arithmetic (I know it doesn't support it directly, but maybe having static methods would be useful in a workaround)?
Would a guidelines for this matter whether it's a class or a struct?
EDIT: Also for #3, I forgot to mention that this is for an immutable type, so returns a new Point3, instead of changing a. | In general, I think Microsoft seems to have kind of done A+B in most of their classes similar to this.
For samples, see the entire System.Windows.Media.Media3D namespace, as well as the XNA math classes. Both have point/vector/quaternion/matrices/etc, and use Class.Operator(a,b), and occasionally do c = a + b;
Personally, I would do the first where it makes sense and is clear, and always do the second option. I usually implement the first using the second option (the operator is implemented using the static method). | Use operator overloads to meet your needs. To honor .NET languages that do not support overloaded operators, include static methods that wrap the operators (or the other way around).
The third option is only viable if you are using reference types and want to avoid instantiating new ones. | Arithmetic Operators vs Methods in Class Design Guidelines | [
"",
"c#",
".net",
"class",
""
] |
I have a linked list with a c-style `ctor` and `dtor`.
I just got too frustrated when this if statement decided not to test true, putting me in
an infinite loop. I dont understand why it will never test true.
I am trying to delete a node (the address of a class object) from my `LinkedList`.
Maybe someone could help me out?
```
Node *Current = first_; // I want this to be my only Node Ptr Varaible Declaration.
if ( NULL == first_ )
std::cout << "Cannot delete from an empty list: \n";
while ( Current != NULL )
{
if ( first_->data_ == node->data_ )
{
//check to see if we are deleteing the head.
first_ = first_->next_;
--listLen_;
delete Current;
std::cout << "Head Deleted!\n";
}
if ( Current->data_ == node->data_ ) // FOR SOME REASON this is never true?
{
--listLen_;
node->data_ = NULL;
Current = Current->next_;
node->data_ = Current;
}
else // we must not of found it. // else should match previous i
{
Current->prev_ = Current;// since we are not deleting the first node we are OK here.
Current = first_->next_;
if ( Current->next_ == NULL ) // see if we are at the end of the list.
{
first_ = NULL;
last_ = Current->prev_;
}
}
}
return;
``` | Keep your loops small, it easier to figure out what went wrong. Assuming your data compare makes sense, look at this the following:
```
curr = first_;
while( curr && (curr->data_ != node->data_) ) {
curr = curr->next_;
}
if (!curr) return // didnt find it, nothing to remove
if ( curr == first_ )
first_ = curr->next_
else
curr->prev_->next_ = curr->next_
curr->next_->prev_ = curr->prev_ // always fix next's prev
delete curr
``` | This should really be rewritten, since it has too many problems...also why not use a STL container? I assume this is a homework question.
The answer to the infinite loop is the else case that increments to the next node:
```
Current = first_->next_;
```
This will make you loop forever if the data is not found in in the first two nodes...since you will set the next test to the first's next node always and it will never set the current to NULL provided there are more than 2 nodes in the list. | Delete a node from the middle of a C++ queue | [
"",
"c++",
"linked-list",
""
] |
Is there a quick way to get a list in JavaScript of the available Active X plugins?
I need to do a test to see if a plugin has been installed before I actually try to run it.
In effect I want to create a page that says 'Plugin Installed and properly Working' or have it fail gracefully.
I'm not sure how to have it fail gracefully if the plugin is not available. | Just `try` it.
```
try {
var plugin = new ActiveXObject('SomeActiveX');
} catch (e) {
alert("Error"); // Or some other error code
}
``` | The [object](http://www.w3schools.com/TAGS/tag_object.asp) tag will display whatever is inside it if the object cannot be instantiated:
```
<object ...>
<p>
So sorry, you need to install the object. Get it <a href="...">here</a>.
</p>
</object>
```
So, graceful failure is built-in and you don't need to use script at all. | Javascript way to list available plugins for IE | [
"",
"javascript",
"internet-explorer",
"browser",
""
] |
I've grown disillusioned with Groovy based alternatives to Ant. AntBuilder doesn't work from within Eclipse, the Groovy plugin for Eclipse is disappointing, and Gradle just isn't ready yet.
The Ant documentation has a section titled "Using Ant Tasks Outside of Ant" which gives a teaser for how to use the Ant libraries from Java code. There's another example here:
<http://www.mail-archive.com/dev@ant.apache.org/msg16310.html>
In theory it seems simple enough to replace build.xml with Build.java. The Ant documentation hints at some undocumented dependencies that I'll have to discover (undocumented from the point of view of using Ant from within Java).
Given the level of disappointment with Ant scripting, I wonder why this hasn't been done before. Perhaps it has and isn't a good build system.
Has anyone tried writing build files in Java using the Ant libraries? | Our build system is primarily based upon exactly what you describe, and it works very well indeed. We use the Ant tasks (especially the file-manipulation tasks) from custom java programs which assemble the application using auto-discovery of convention-based application module layout.
You *may* need some glue Ant XML, to do things like compile the build scripts themselves, and to actually invoke the java to perform the build, but it's minor.
Not only is java more readable than Ant, especially when it comes to conditional execution, but it's vastly quicker. Our Ant-based build used to take a minute or so to assemble an EAR, now the java based version takes about 5 seconds. | Given that Java is compiled, this is kind of a chicken and egg problem. You need to build your Build.java to build your project.
Ant currently supports inline scripting using BeanShell, Groovy and a bunch of others, that can really help reduce the need for that.
EDIT: In response to Dean's multiple comments, if your build consists strictly of a long proceedure, then indeed you don't need ant's build script. However, the power of the build script is that it ensures that dependencies are only executed once while allowing for mulitiple entry points, something that is far from trivial if you roll your own.
If you don't like the XML format, you are not alone, the author of ANT agrees with you. However, if your view of the build process is something that can be launched from your IDE as its only launch point, I would say that your build needs are quite simple.
EDIT2: I upvoted skaffman's answer because it speaks directly to the question. In the comments we seem to agree that the approach is fine for a procedural build, but would not work for a declarative one, and that you need at least a little ANT xml to get the ball rolling with your Build.java to avoid the chicken and egg problem. That seems to get to the crux of the matter. | Replacing build.xml with Build.java - using Java and the Ant libraries as a build system | [
"",
"java",
"ant",
"build-automation",
"build-tools",
""
] |
I have a similar question to [this one](https://stackoverflow.com/questions/222752/sorting-a-tuple-that-contains-tuples) but instead my tuple contains lists, as follows:
```
mytuple = (
["tomato", 3],
["say", 2],
["say", 5],
["I", 4],
["you", 1],
["tomato", 6],
)
```
What's the most efficient way of sorting this? | You can get a sorted tuple easy enough:
```
>>> sorted(mytuple)
[['I', 4], ['say', 2], ['say', 5], ['tomato', 3], ['tomato', 6], ['you', 1]]
```
This will sort based on the items in the list. If the first two match, it compares the second, etc.
If you have a different criteria, you can provide a comparison function.
**Updated:** As a commenter noted, this returns a list. You can get another tuple like so:
```
>>> tuple(sorted(mytuple))
(['I', 4], ['say', 2], ['say', 5], ['tomato', 3], ['tomato', 6], ['you', 1])
``` | You cannot sort a tuple.
What you can do is use [sorted()](http://docs.python.org/library/functions.html?highlight=sorted#sorted) which will not sort the tuple, but will create a sorted list from your tuple. If you really need a sorted tuple, you can then cast the return from sorted as a tuple:
```
mytuple = tuple(sorted(mytuple, key=lambda row: row[1]))
```
This can be a waste of memory since you are creating a list and then discarding it (and also discarding the original tuple). Chances are you don't need a tuple. Much more efficient would be to start with a list and sort that. | Sorting a tuple that contains lists | [
"",
"python",
"list",
"sorting",
"tuples",
""
] |
I'm attempting to write an application to extract properties and code from proprietary IDE design files. The file format looks something like this:
```
HEADING
{
SUBHEADING1
{
PropName1 = PropVal1;
PropName2 = PropVal2;
}
SUBHEADING2
{
{ 1 ; PropVal1 ; PropValue2 }
{ 2 ; PropVal1 ; PropValue2 ; OnEvent1=BEGIN
MESSAGE('Hello, World!');
{ block comments are between braces }
//inline comments are after double-slashes
END;
PropVal3 }
{ 1 ; PropVal1 ; PropVal2; PropVal3 }
}
}
```
What I am trying to do is extract the contents under the subheading blocks. In the case of SUBHEADING2, I would also separate each token as delimited by the semicolons. I had reasonably good success with just counting the brackets and keeping track of what subheading I'm currently under. The main issue I encountered involves dealing with the code comments.
This language happens to use {} for block comments, which interferes with the brackets in the file format. To make it even more interesting, it also needs to take into account double-slash inline comments and ignore everything up to the end of the line.
What is the best approach to tackling this? I looked at some of the compiler libraries discussed in another article (ANTLR, Doxygen, etc.) but they seem like overkill for solving this specific parsing issue. | You should be able to put something together in a few hours, using regular expressions in combination with some code that uses the results.
Something like this should work:
- Initialize the process by loading the file into a string.
* Pull each top-level block from the string, using regex tags to separately identify the block keyword and contents.
* If a block is found,
+ Make a decision based on the keyword
+ Pass the content to this process recursively.
Following this, you would process HEADING, then the first SUBHEADING, then the second SUBHEADING, then each sub-block. For the sub-block containing the block comment, you would presumably know based on the block's lack of a keyword that any sub-block is a comment, so there is no need to process the sub-blocks. | I'd suggest writing a tokenizer and parser; this will give you more flexibility. The tokenizer basically does a simple text-wise breakdown of the sourcecode and puts it into more usable data structure; the parser figures out what to do with it, often leveraging recursion.
Terms to google: tokenizer, parser, compiler design, grammars
Math expression evaluator: <http://www.codeproject.com/KB/vb/math_expression_evaluator.aspx>
(you might be able to take an example like this and hack it apart into what you want)
More info about parsing: <http://www.codeproject.com/KB/recipes/TinyPG.aspx>
You won't have to go nearly as far as those articles go, but, you're going to want to study a bit on this one first. | Design strategy for a simple code parser | [
"",
"c#",
"parsing",
"compiler-construction",
""
] |
I have huge class that I need to build stub for.
To give you picture it is Messages class of the GWT. Often this is class with dozens of methods that return String.
With JMock I can do stubbing, but I will end with allowing each method... This is not something that I would like to see.
Is there something that will automatically build the stubs for each method? I need this methods to return something predefined, like empty string, but I will be happy with any suggestions. | In JMock you can allow the methods you care about with explicit results and then allow any other method of the messages object with an allowing statement that does not include a method. E.g.:
```
allowing(m).getBlah("something");
will(returnValue("foo"));
allowing(m); // matches anything else, will return some default value if called
```
But...
If you are just stubbing a bunch of getter methods, a mock object framework is the wrong tool to use. Mock objects are used for testing that the object under test sends the correct commands to neighbouring objects to effect change in its environment.
It's often easier to create a stub class if the interface that only contains getters. Or you can use [Usurper](http://www.org-libs.org/org-lib-usurper/) to generate stubs automatically. | Glad to see you found an answer. Just for further info, jMock allows quite flexible specifications of how you match methods, see <http://www.jmock.org/match-object-or-method.html>. For example, you can do this sort of thing:
```
allowing (any(Object.class)).method("get.*").withNoArguments();
```
to match any getter.
S | Automatic stubbing in java word. What to use? | [
"",
"java",
"mocking",
"stubbing",
""
] |
Let me rephrase my question, I have a mysql database that is holding emails to be sent, on a shared host. I would like to run a cron job that will read the database and sent out any messages in the database every 10 minutes or so.
Now my question is, what is the best way with php to read my database and send out the emails in small batched so that I don't overwhelm the shared host. | Well I came up with this solution similar to the PDO one. Are there any unforeseen problems with running this as a cron job?
```
<?php
$con = mysql_connect("localhost","root","123456");
$throttle = 0;
$batch = 50;
$pause = 10; // seconds
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("maildb", $con);
// Message Table
$MSGresult = mysql_query("SELECT * FROM msgs");
// User Table
$USERresult = mysql_query("SELECT * FROM members");
while($MSGrow = mysql_fetch_array($MSGresult))
{
while($USERrow = mysql_fetch_array($USERresult))
{
mail($USERrow['email'],$MSGrow['subject'],$MSGrow['body']);
$throttle += 1;
if ($throttle > $batch ) { sleep($pause); $throttle = 0;}
}
mysql_data_seek($USERresult,0);
}
mysql_close($con);
?>
``` | Assuming the use of PDO, and making some accommodation for not knowing your schema, it might look something like this:
```
$dbh = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'dbuser', 'dbpass');
$msgh = $dbh->prepare('SELECT subject, body from message where listname = :listname');
$msgh->bindParam(':listname', $listname, PDO::PARAM_STR);
$msgh->execute();
$msg = $msgh->fetch(PDO::FETCH_ASSOC);
$usrh = $dbh->prepare('SELECT recipient from userlist where is_subscribed_to = :listname');
$usrh->bindParam(':listname', $listname, PDO::PARAM_STR);
$usrh->execute();
while ($recipient = $usrh->fetch(PDO::FETCH_ASSOC)) {
mail($recipient, $msg['subject'], $msg['body']);
if ($over_throttle) {
sleep(THROTTLE_SLEEP_SECONDS);
$over_throttle = 0;
}
++$over_throttle;
}
```
As for 'prewritten', you might take a look at [phplist](http://www.phplist.com/). | PHP, Email and Cron | [
"",
"php",
"email",
"cron",
""
] |
I am trying to insert a variable passed to my function into the output of my .innerHTML = code but do not know how to properly insert it into the HTML output.
```
function playsong(song)
{
parent.document.getElementById('player').innerHTML = '<object width="199" height="26"><param name="movie" value="audio_player_black.swf"><embed src="audio_player_black.swf?audio_file=upload/'[song]'&color=00000" width="199" height="26"></embed></object>';
}
```
I just get [song] in my HTML output rather than the value of [song]
Not sure how I need to do this properly | easy:
```
parent.document.getElementById('player').innerHTML = '<object width="199" height="26"><param name="movie" value="audio_player_black.swf"><embed src="audio_player_black.swf?audio_file=upload/'+song+'&color=00`000" width="199" height="26"></embed></object>';
```
just like concatenating any 2 + strings | Instead of:
```
[song]
```
use:
```
+song+
``` | inserting javascript variable into html output of .innerHTML = | [
"",
"javascript",
"html",
""
] |
I came across a very strange behavior in asp.net's `ObjectDataSource`, the description to reproduce is somewhat long, so bear with me while I set the scene.
So, imagine a trivial ObjectDataSource/GridView combo in a User Control. The ObjectDataSource calls a method which returns a `List` of objects, and the GridView shows these objects in tabular form:
```
<div runat="server" ID="ControlWrapper">
<asp:GridView ID="GridView1" AutoGenerateColumns="true" DataSourceID="ObjDataSource1" OnRowDataBound="GridView1_RowBound" runat="server">
</asp:GridView>
</div>
<asp:ObjectDataSource ID="ObjDataSource1" runat="server" SelectMethod="GetBundle" OnSelecting="FixDataSource_Selecting" OnSelected="FixDataSource_Selected"
TypeName="West.VitalSigns.Contracts.ProdFixController">
</asp:ObjectDataSource>
```
This approach will work with pretty much nothing in the code-behind. But let's say that we want to create n number of `GridView`-s depending on the contents of the database. So we comment out the GridView in the markup...
```
<div runat="server" ID="ControlWrapper">
<!--
<asp:GridView ID="GridView1" AutoGenerateColumns="true" DataSourceID="ObjDataSource1" OnRowDataBound="GridView1_RowBound" runat="server">
</asp:GridView>
-->
</div>
```
...and add something like this to the ObjectDataSource's `Selected` event handler:
```
protected void FixDataSource_Selected(object sender, ObjectDataSourceStatusEventArgs args)
{
HashSet<string> components = new HashSet<string<()
foreach (ProdFix fix in (List<ProdFix>)args.ReturnValue)
{
if (!components.Contains(fix.Component))
{
GridView v = new GridView();
v.ID=fix.Component.Replace(" " ,"").Replace("-","");
v.AutoGenerateColumns = true;
v.DataSource = args.ReturnValue;
v.RowDataBound +=new GridViewRowEventHandler(BundleGrid_RowBound);
ControlWrapper.Controls.Add(v);
components.Add(fix.Component);
}
}
}
```
This code works (or at least the un-simplified version works on my machine), so you decide to remove the commented-out section from the markup (don't want that cruft hanging around, after all!)
```
<div runat="server" ID="ControlWrapper">
</div>
```
When you do this, however, **the code no longer works!** The ObjectDataSource won't fire, which means that the `Selected` event will never happen, which means you won't get your `GridView`-s. It looks like ObjectDataSource is reacting to commented-out markup in the aspx file?
So, is this:
* A bug in ASP.NET?
* A non-standard way of dynamically creating GridViews?
* A WTF that I shouldn't have tried anyway?
* All of the above? | Your gridview control in the markup is not hidden, even with the comments. HTML comments do not apply to server-side tags. Use server side comments instead:
```
<% /* %> <% */ %>
```
or
```
<%-– and -–%>
``` | 24hrs later, I noticed that this approach to getting N number of grid-views was pretty silly. Instead of using an `ObjectDataSource` I refactored my code to just call the `GetBundle` method directly from Page\_Load() and create the GridViews programatically.
cdonner has the answer correct about the server-side comments. I didn't realize that there was a difference. | ObjectDataSource reacts to commented-out GridView? | [
"",
"c#",
"asp.net",
"gridview",
""
] |
I have a computer on a small network, so my ip is 192.168.2.100.
I am trying to get my real ip. I download the no-ip client but that just seems like a lot of trouble for such a simple thing.
I created this php script that got <http://www.ip-adress.com/> page and retrieved the ip it gave me.
Is there a simpler way? Either using C, WSH or something. Or if there is an easier way in php please tell me.
When I get the ip I'll uploaded it to my ftp site so that I can see the ip from work. | No, there's not really an easier way. Your computer really doesn't know the public IP it's behind -- there could any number of layers of NAT between it and the public internet. All it knows is that it receives messages at 192.168.2.100, and sends outgoing messages through the gateway at 192.168.2.1. It has no idea what happens after the packet hits the gateway. | Do note reinvent the wheel, there is a [standard protocol, STUN](https://stackoverflow.com/questions/905406/obtaining-own-external-ip-address-in-posix-c/910909#910909) (with already existing implementations), just for that. See also [Discovering public IP programatically](https://stackoverflow.com/questions/613471/discovering-public-ip-programatically/628180). | Getting my ip address | [
"",
"php",
"c",
"networking",
"ip-address",
"wsh",
""
] |
In C# can I cast a variable of type `object` to a variable of type `T` where `T` is defined in a `Type` variable? | Here is an example of a cast and a convert:
```
using System;
public T CastObject<T>(object input) {
return (T) input;
}
public T ConvertObject<T>(object input) {
return (T) Convert.ChangeType(input, typeof(T));
}
```
**Edit:**
Some people in the comments say that this answer doesn't answer the question. But the line `(T) Convert.ChangeType(input, typeof(T))` provides the solution. The `Convert.ChangeType` method tries to convert any Object to the Type provided as the second argument.
For example:
```
Type intType = typeof(Int32);
object value1 = 1000.1;
// Variable value2 is now an int with a value of 1000, the compiler
// knows the exact type, it is safe to use and you will have autocomplete
int value2 = Convert.ChangeType(value1, intType);
// Variable value3 is now an int with a value of 1000, the compiler
// doesn't know the exact type so it will allow you to call any
// property or method on it, but will crash if it doesn't exist
dynamic value3 = Convert.ChangeType(value1, intType);
```
I've written the answer with generics, because I think it is a very likely sign of code smell when you want to cast `a something` to `a something else` without handling an actual type. With proper interfaces that shouldn't be necessary 99.9% of the times. There are perhaps a few edge cases when it comes to reflection that it might make sense, but I would recommend to avoid those cases.
**Edit 2:**
Few extra tips:
* Try to keep your code as type-safe as possible. If the compiler doesn't know the type, then it can't check if your code is correct and things like autocomplete won't work. Simply said: *if you can't predict the type(s) at compile time, then how would the compiler be able to*?
* If the classes that you are working with [implement a common interface](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/), you can cast the value to that interface. Otherwise consider creating your own interface and have the classes implement that interface.
* If you are working with external libraries that you are dynamically importing, then also check for a common interface. Otherwise consider creating small wrapper classes that implement the interface.
* If you want to make calls on the object, but don't care about the type, then store the value in an `object` or [`dynamic`](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic) variable.
* [Generics](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/) can be a great way to create reusable code that applies to a lot of different types, without having to know the exact types involved.
* If you are stuck then consider a different approach or code refactor. Does your code really have to be that dynamic? Does it have to account for any type there is? | Other answers do not mention "dynamic" type. So to add one more answer, you can use "dynamic" type to store your resulting object without having to cast converted object with a static type.
```
dynamic changedObj = Convert.ChangeType(obj, typeVar);
changedObj.Method();
```
Keep in mind that with the use of "dynamic" the compiler is bypassing static type checking which could introduce possible runtime errors if you are not careful.
Also, it is assumed that the obj is an instance of Type typeVar or is convertible to that type. | Casting a variable using a Type variable | [
"",
"c#",
"reflection",
"types",
""
] |
I am working on a small ap that uses vbscript to write to a ms access db everytime i use it (really for personal use only so i don't need to worry about sql injection). When i run it i keep getting a "syntax error in INSERT INTO statement". The connection string is correct because the db locks when its run. table name is ors. What am I doing wrong?
```
sql1="INSERT INTO ors VALUES (,,'B223234','12/22/08')"
constring="Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\Documents and Settings\me\My Documents\tracker.mdb;
User Id=admin;Password=;"
set con=createobject("adodb.connection")
con.open constring
con.execute sql1
con.close
``` | You need NULL for the "blank" values. You also need to use # surrounding a date instead of the single quotes for date fields.
If you don't want to specify all values, you could specify only the fields you want to set.
(Assuming date field, not text for date value)
This:
`INSERT INTO ors VALUES (NULL,NULL,'B223234',#12/22/08#)`
Or This:
`INSERT INTO ors (Field3, Field4) VALUES ('B223234',#12/22/08#)` | If I remember correctly I think dates in MS Access require # surrounding them instead of single quotes. Try changing your insert to
```
INSERT INTO ors VALUES (,,'B223234',#12/22/08#)
```
in addition you may have to specify blanks for the missing parameters
```
INSERT INTO ors VALUES (NULL,NULL,'B223234',#12/22/08#)
```
my MS Access knowledge is a bit rusty but give that a shot. | vbscript insert into ms access | [
"",
"sql",
"ms-access",
"vbscript",
""
] |
How to I get the SCHEMA when doing a select on sysobjects?
I am modifing a stored procedure called **SearchObjectsForText** which returns only the Name but I would also like to include the SCHEMA.
Right now it is doing something similar to this:
```
SELECT DISTINCT name
FROM sysobjects
```
I would like to know what tables need to be joined to return the SCHEME for each 'name'. | If you mean SQL Server 2005 or higher, use sys.objects instead of sysobjects:
```
SELECT sys.objects.name, sys.schemas.name AS schema_name
FROM sys.objects
INNER JOIN sys.schemas ON sys.objects.schema_id = sys.schemas.schema_id
```
2005 introduced schemas. up to 2000, users equaled schemas. The same query for SQL Server 2000:
```
SELECT sysusers.name AS OwnerName, sysobjects.name
FROM sysobjects
INNER JOIN sysusers ON sysobjects.uid = sysusers.uid
``` | On Sql Server 2005 (and above) you can use the sys.objects view:
```
select
name as ObjectName,
schema_Name(schema_id) as SchemaName
from
sys.objects
```
In Sql Server 2000 (and below), "schema" had a different conceptual meaning. Note from MSDN:
*In earlier releases of SQL Server, databases could contain an entity called a "schema", but that entity was effectively a database user. SQL Server 2005 is the first release of SQL Server in which a schema is both a container and a namespace.* | SQL Server - Return SCHEMA for sysobjects | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
```
site_id | start_date | end_date
1 | oct 1, 08 | oct 2, 08
1 | oct 2, 08 | oct 3, 08
...
1 | oct 30, 08 | oct 31, 08
2 | oct 1, 08 | oct 2, 08
2 | oct 2, 08 | oct 3, 08
...
2 | oct 30, 08 | oct 31, 08
```
I have a table that contains 1 record per site per day of the month (per month of the year). I need to be able to determine if a site for a given month has at least 15 contiguous records, and I need to know the start and end date of that series of contiguous days. I can do this in a stored procedure, but I was hoping this could be accomplished in a single query. I am dealing with a fairly large dataset, at least 30 million records per month.
Example Results:
```
site_id | contiguous_start_date | contiguous_end_date
1 | oct 5, 2008 | oct 20, 2008
2 | oct 10 | oct 30, 2008
3 | oct 1 | oct 31, 2008
```
thanks for your help! | Here is an example of how to do such a query:
```
SQL> create table t (site_id,start_date,end_date)
2 as
3 select 1, date '2008-10-01', date '2008-10-02' from dual union all
4 select 1, date '2008-10-02', date '2008-10-03' from dual union all
5 select 1, date '2008-10-03', date '2008-10-30' from dual union all
6 select 1, date '2008-10-30', date '2008-10-31' from dual union all
7 select 2, date '2008-10-01', date '2008-10-02' from dual union all
8 select 2, date '2008-10-02', date '2008-10-03' from dual union all
9 select 2, date '2008-10-03', date '2008-10-04' from dual union all
10 select 2, date '2008-10-04', date '2008-10-05' from dual union all
11 select 2, date '2008-10-05', date '2008-10-06' from dual union all
12 select 2, date '2008-10-06', date '2008-10-07' from dual union all
13 select 2, date '2008-10-07', date '2008-10-08' from dual union all
14 select 2, date '2008-10-08', date '2008-10-09' from dual union all
15 select 2, date '2008-10-09', date '2008-10-10' from dual union all
16 select 2, date '2008-10-10', date '2008-10-11' from dual union all
17 select 2, date '2008-10-11', date '2008-10-12' from dual union all
18 select 2, date '2008-10-12', date '2008-10-13' from dual union all
19 select 2, date '2008-10-13', date '2008-10-14' from dual union all
20 select 2, date '2008-10-14', date '2008-10-15' from dual union all
21 select 2, date '2008-10-15', date '2008-10-16' from dual union all
22 select 2, date '2008-10-16', date '2008-10-17' from dual union all
23 select 2, date '2008-10-17', date '2008-10-18' from dual union all
24 select 2, date '2008-10-18', date '2008-10-19' from dual union all
25 select 2, date '2008-10-19', date '2008-10-20' from dual union all
26 select 3, date '2008-10-01', date '2008-10-02' from dual union all
27 select 3, date '2008-10-02', date '2008-10-03' from dual union all
28 select 3, date '2008-10-03', date '2008-10-04' from dual union all
29 select 3, date '2008-10-04', date '2008-10-05' from dual union all
30 select 3, date '2008-10-05', date '2008-10-06' from dual union all
31 select 3, date '2008-10-06', date '2008-10-07' from dual union all
32 select 3, date '2008-10-07', date '2008-10-08' from dual union all
33 select 3, date '2008-10-08', date '2008-10-09' from dual union all
34 select 3, date '2008-10-09', date '2008-10-10' from dual union all
35 select 3, date '2008-10-30', date '2008-10-31' from dual
36 /
Tabel is aangemaakt.
```
And then the query:
```
SQL> select site_id
2 , min(start_date) contiguous_start_date
3 , max(end_date) contiguous_end_date
4 , count(*) number_of_contiguous_records
5 from ( select site_id
6 , start_date
7 , end_date
8 , max(rn) over (partition by site_id order by start_date) maxrn
9 from ( select site_id
10 , start_date
11 , end_date
12 , case lag(end_date) over (partition by site_id order by start_date)
13 when start_date then null
14 else rownum
15 end rn
16 from t
17 )
18 )
19 group by site_id
20 , maxrn
21 order by site_id
22 , contiguous_start_date
23 /
```
And the results:
```
SITE_ID CONTIGUOUS_START_DA CONTIGUOUS_END_DATE NUMBER_OF_CONTIGUOUS_RECORDS
---------- ------------------- ------------------- ----------------------------
1 01-10-2008 00:00:00 31-10-2008 00:00:00 4
2 01-10-2008 00:00:00 20-10-2008 00:00:00 19
3 01-10-2008 00:00:00 10-10-2008 00:00:00 9
3 30-10-2008 00:00:00 31-10-2008 00:00:00 1
4 rijen zijn geselecteerd.
```
Regards,
Rob. | This is definitely very possible. I solved a similar problem in SQL Server a couple of months ago. I know nothing of Oracle syntax, so I'm afraid I can't convert if for you, but if you're solid with Oracle, [this](http://thehobt.blogspot.com/2009/04/calculating-elapsed-time-based-upon.html) should be enough to get you there. | How can I efficiently query for contiguous sets of dates in my data set? | [
"",
"sql",
"oracle",
""
] |
I have some code that is really slow. I knew it would be and now it is. Basically, I am reading files from a bunch of directories. The file names change but the data does not. To determine if I have read the file, I am hashing it's bytes and comparing that to a list of hashes of already processed files. There are about 1000 files in each directory, and figuring out what's new in each directory takes a good minute or so (and then the processing starts). Here's the basic code:
```
public static class ProgramExtensions
{
public static byte[] ToSHA256Hash(this FileInfo file)
{
using (FileStream fs = new FileStream(file.FullName, FileMode.Open))
{
using (SHA256 hasher = new SHA256Managed())
{
return hasher.ComputeHash(fs);
}
}
}
public static string ToHexString(this byte[] p)
{
char[] c = new char[p.Length * 2 + 2];
byte b;
c[0] = '0'; c[1] = 'x';
for (int y = 0, x = 2; y < p.Length; ++y, ++x)
{
b = ((byte)(p[y] >> 4));
c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
b = ((byte)(p[y] & 0xF));
c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
}
return new string(c);
}
}
class Program
{
static void Main(string[] args)
{
var allFiles = new DirectoryInfo("c:\\temp").GetFiles("*.*");
List<string> readFileHashes = GetReadFileHashes();
List<FileInfo> filesToRead = new List<FileInfo>();
foreach (var file in allFiles)
{
if (readFileHashes.Contains(file.ToSHA256Hash().ToHexString()))
filesToRead.Add(file);
}
//read new files
}
}
```
Is there anyway I can speed this up? | I believe you can archive the most significant performance improvement by simply first checking the filesize, if the filesize does not match, you can skip the entire file and don't even open it.
Instead of just saving a list of known hashes, you would also keep a list of known filesizes and only do a content comparison when filesizes match. When filesize doesn't match, you can save yourself from even looking at the file content.
Depending on the general size your files generally have, a further improvement can be worthwhile:
* Either doing a binary compare with early abort when the first byte is different (saves reading the entire file which can be a very significant improvement if your files generally are large, any hash algorithm would read the entire file. Detecting that the first byte is different saves you from reading the rest of the file). If your lookup file list likely contains many files of the same size so you'd likely have to do a binary comparison against several files instead consider:
* hashing in blocks of say 1MB each. First check the first block only against the precalculated 1st block hash in your lookup. Only compare 2nd block if 1st block is the same, saves reading beyond 1st block in most cases for different files. Both those options are only really worth the effort when your files are large.
I doubt that changing the hashing algorithm itself (e.g first check doing a CRC as suggested) would make any significant difference. Your bottleneck is likely disk IO, not CPU so avoiding disk IO is what will give you the most improvement. But as always in performance, **do** measure.
Then, if this is still not enough (and only then), experiment with asynchronous IO (remember though that sequential reads are generally faster than random access, so too much random asynchronous reading can hurt your performance) | * Create a file list
* Sort the list by filesize
* Eliminate files with unique sizes from the list
* Now do hashing (a fast hash first might improve performance as well) | What is the fastest way to find if an array of byte arrays contains another byte array? | [
"",
"c#",
"comparison",
"reference-type",
"arrays",
""
] |
I'm trying to get log4j application (webapp) logging working in a Tomcat 6 app. I have log4j-1.2.15.jar in my WEB-INF directory, log4j.dtd and log4j.xml in WEB-INF/classes.
My log4j.xml looks like:
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
<appender name="massAppender" class="org.apache.log4j.RollingFileAppender">
<param name="maxFileSize" value="100KB" />
<param name="maxBackupIndex" value="2" />
<param name="File" value="${catalina.home}/logs/mass.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} %5p %c{1}: %m%n " />
</layout>
</appender>
<category name="com.company.mass">
<priority value="DEBUG"/>
<appender-ref ref="massAppender"/>
</category>
<root>
<appender-ref ref="massAppender" />
</root>
</log4j:configuration>
```
My servlet is in the package:
```
package com.company.mass;
```
where the logger is declared as:
```
private static Logger logger = Logger.getLogger(Handler.class);
```
and at the top of my doGet(...) method there is:
```
logger.error("foo");
```
When I deploy the app in Tomcat and go to the servlet, it works correctly. I even get a mass.log file, but nothing gets put in it. It doesn't show up in any other logs either, and there are no obvious errors. Any idea what's going on? | Are you sure that log4j is actually using your `log4j.xml` for it's configuration, and not another file on the classpath?
Enable the system property `-Dlog4j.debug` to have log4j print out information about exactly which configuration file it is using. | Not sure if you need a priority in your root logger. Try this config
```
<category name="com.company.mass">
<priority value="DEBUG"/>
<!-- no need to specify appender again here -->
</category>
<root>
<priority value="INFO"/>
<appender-ref ref="massAppender" />
</root>
``` | Tomcat 6 and log4j application logging produce no output | [
"",
"java",
"tomcat",
"logging",
"log4j",
"tomcat6",
""
] |
Is it possible to call the JVM's built-in native code, i.e. the code that various class in java.lang and java.io call? In other words, can you bypass the built-in java API to access various system-level calls such as file-system access? I know I could do this by building my own native code library and calling that via JNI, but it would be elegant to not need an extra native library for functionality already built into the JVM. | No you can't. It's designed that way on purpose; you would override the API contracts if you could.
In any event, the standard library wrapper code is *very* slight and with JIT compilers you shouldn't notice any speed impact.
Furthermore, the *implementation* of those methods are not part of the API spec. What is "native" for one implementation of Java doesn't have to be for another. | You can, of course, use reflection to call the methods providing the code is trusted. However, the non-public APIs are liable to change between updates and implementations, so pretty much pointless and absolutely non-elegant. | Calling built-in java native methods | [
"",
"java",
"jvm",
"java-native-interface",
"native",
""
] |
Is there anything in the Python standard library that will properly parse/unparse strings for using in shell commands? I'm looking for the python analog to perl's `String::ShellQuote::shell_quote`:
```
$ print String::ShellQuote::shell_quote("hello", "stack", "overflow's", "quite", "cool")
hello stack 'overflow'\''s' quite cool
```
And, even more importantly, something which will work in the reverse direction (take a string and decompose it into a list). | `pipes.quote` is now `shlex.quote` in python 3.
It is easy enough to use that piece of code.
<https://github.com/python/cpython/blob/master/Lib/shlex.py#L281>
That version handles zero-length argument correctly. | Looks like
```
try: # py3
from shlex import quote
except ImportError: # py2
from pipes import quote
quote("hello stack overflow's quite cool")
>>> '"hello stack overflow\'s quite cool"'
```
gets me far enough. | Python module to shellquote/unshellquote? | [
"",
"python",
"shell",
"quoting",
""
] |
So I'm writing a Java app, and I've got an ESRI Shapefile which contains the borders of all the U.S. states. What I need is to be able to determine whether any given lat/lon point is within a specified distance from ANY state border line - i.e., I will *not* be specifying a particular border line, just need to see whether the point is close to *any* of them.
The solution does NOT have to be very precise at all; e.g. I don't need to be dealing with measuring perpendicular to the border, or whatever. Just checking to see if going X meters north, south, east or west would result in crossing a border would be more than sufficient. The solution DOES have to be computationally efficient, as I'll be performing a huge number of these calculations.
I'm planning to use the GeoTools library (though if there's a simpler option, I'm all for it) with the Shapefile plugin. What I don't really understand is: Once I've got the shapefile loaded into memory, how do I check to see whether I'm near a border?
Thanks!
-Dan | Assuming [JTS](http://www.vividsolutions.com/jts/jtshome.htm) for Geometry which is what is included in GeoTools:
```
public boolean pointIsClose( File file, Point targetPoint,double distance) {
boolean ret = false;
Map connect = new HashMap();
connect.put("url", file.toURL());
DataStore dataStore = DataStoreFinder.getDataStore(connect);
FeatureSource featureSource = dataStore.getFeatureSource(typeName);
FeatureCollection collection = featureSource.getFeatures();
FeatureIterator iterator = collection.features();
try {
while (iterator.hasNext()) {
Feature feature = iterator.next();
Geometry sourceGeometry = feature.getDefaultGeometry();
ret= sourceGeometry.isWithinDistance(targetPoint, distance );
}
} finally {
iterator.close();
}
return ret;
}
```
The double number will have to come from the [CRS](http://docs.codehaus.org/display/GEOTDOC/01+CRS+Helper+Class) which will define the units in which the calculation will be performed.
These are the geotools imports:
```
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.feature.Feature;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.geometry.jts.JTS;
import org.geotools.referencing.CRS;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
``` | If you just want to know if point A is within X meters of a state border and X is constant and you don't care which border it is, you can precompute the negative space as a series of boxes. Then all you have to do is a contains check for each of those boxes against the point. If none of them match, you're not in the negative space. | Determining whether geographic point is within X meters of a state border (using shapefile for border data) | [
"",
"java",
"maps",
"geospatial",
"geography",
"geotools",
""
] |
Here are the problems I am having with the control from the factory:
* no easy way to get the first visible date (yeah I could use day render, but at that point in the page cycle, I can't do what I need to, which is manipulate a collection in viewstate)
* changing the visibledate property in my code does not raise the visiblemonthchanged event. That just doesn't make any sense to me.
Can someone suggest a free, improved calendar control? | **jQuery** [datepicker](http://docs.jquery.com/UI/Datepicker):
example:
```
<input id='datepicker' class='datepicker' />
$(function(){
$(".datepicker").datepicker({
buttonImage: "/Content/img/calendar.gif",
buttonImageOnly: true });
});
``` | Greetings,
You could try the calender control from [http://www.eworldui.net](http://www.eworldui.net/). I have used them without any issues and they are free to use. | Any Free Alternative to the ASP.net Calendar Control? | [
"",
"c#",
".net",
"asp.net",
"calendar",
""
] |
I am trying to create a class as such:
```
class CLASS
{
public:
//stuff
private:
int x, y;
char array[x][y];
};
```
Of course, it doesn't work until I change `int x, y;` to
```
const static int x = 10, y = 10;
```
Which is impractical, because I am trying to read the values of x and y from a file. So is there any way to initialize an array with non-contant values, or declare an array and declare its size on different statements? And I know this would probably require the creation of an array class, but I'm not sure where to start on this, and I don't want to create a 2D dynamic list when the array itself is not dynamic, just the size is not known at compile-time. | The compiler need to have the exact size of the class when compiling, you will have to use the new operator to dynamically allocate memory.
Switch char array[x][y]; to char\*\* array; and initialize your array in the constructor, and don't forget to delete your array in the destructor.
```
class MyClass
{
public:
MyClass() {
x = 10; //read from file
y = 10; //read from file
allocate(x, y);
}
MyClass( const MyClass& otherClass ) {
x = otherClass.x;
y = otherClass.y;
allocate(x, y);
// This can be replace by a memcopy
for( int i=0 ; i<x ; ++i )
for( int j=0 ; j<x ; ++j )
array[i][j] = otherClass.array[i][j];
}
~MyClass(){
deleteMe();
}
void allocate( int x, int y){
array = new char*[x];
for( int i = 0; i < y; i++ )
array[i] = new char[y];
}
void deleteMe(){
for (int i = 0; i < y; i++)
delete[] array[i];
delete[] array;
}
MyClass& operator= (const MyClass& otherClass)
{
if( this != &otherClass )
{
deleteMe();
x = otherClass.x;
y = otherClass.y;
allocate(x, y);
for( int i=0 ; i<x ; ++i )
for( int j=0 ; j<y ; ++j )
array[i][j] = otherClass.array[i][j];
}
return *this;
}
private:
int x, y;
char** array;
};
```
\*EDIT:
I've had the copy constructor
and the assignment operator | use vector.
```
#include <vector>
class YourClass
{
public:
YourClass()
: x(read_x_from_file()), y(read_y_from_file())
{
my_array.resize(x);
for(int ix = 0; ix < x; ++ix)
my_array[ix].resize(y);
}
//stuff
private:
int x, y;
std::vector<std::vector<char> > my_array;
};
``` | Is there a way to initialize an array with non-constant variables? (C++) | [
"",
"c++",
"arrays",
""
] |
All of the `Func<T>` delegates return a value. What are the .NET delegates that can be used with methods that return `void`? | All Func delegates return something; all the Action delegates return void.
`Func<TResult>` takes no arguments and returns TResult:
```
public delegate TResult Func<TResult>()
```
`Action<T>` takes one argument and does not return a value:
```
public delegate void Action<T>(T obj)
```
`Action` is the simplest, 'bare' delegate:
```
public delegate void Action()
```
There's also `Func<TArg1, TResult>` and `Action<TArg1, TArg2>` (and others up to 16 arguments). All of these (except for `Action<T>`) are new to .NET 3.5 (defined in System.Core). | > ... takes no arguments and has a void return type?
I believe `Action` is a solution to this. | Func delegate with no return type | [
"",
"c#",
".net",
"types",
"parameters",
"delegates",
""
] |
I'm re-reading *[CLR via C#](https://rads.stackoverflow.com/amzn/click/com/0735621632)* right now and have some questions about garbage collection in .NET. In the book, after Generation 0 is filled, garbage collection starts and moves all outstanding object references to the Generation 1.
The same happens when the Generation 1 is filled. But what happens when second generation is filled? There are no other generations to move references. Is the size of Generation 2 expanded by the CLR? | Yes, it will expand the size of Generation 2 if it can. If there is no more space available you will get an `OutOfMemoryException`. | The different generations of garbage collection are not about having a particular size but about how old the garbage is. None of the generations have size limitations that I know of. | What happens during Garbage Collection if Generation 2 is filled? | [
"",
"c#",
".net",
"garbage-collection",
""
] |
I know there is a way to make enum work for string types with conversions galore - the code doesn't look pretty.
Does anyone know of any way to have something like this:
```
public SOMESTRUCTURE SessionKeys : string
{
value1 = "value1key",
value2 = "value2key",
name = "name"
}
```
so later in my code I could refer to it as:
```
SessionKeys.value1
``` | This is about the best I've come up with. (I haven't compiled it, so the syntax may be off.)
```
public static class SessionKeys
{
public const string Value1 = "Value1";
public const string Value2 = "Value2";
...
}
``` | Using C# 2.0 - I believe the best option is to use a static class with constants for your values, as suggested by [John Fisher](https://stackoverflow.com/questions/958606/storing-string-values-as-constants-in-the-same-manner-as-enum/958610#958610).
If you can use C# 3.0, you could use a standard enum, and a simple extension method to handle the conversion in a less objectionable manner. | Storing string values as constants in the same manner as Enum | [
"",
"c#",
".net",
".net-2.0",
"enums",
"constants",
""
] |
Most SQL dialects accept both the following queries:
```
SELECT a.foo, b.foo
FROM a, b
WHERE a.x = b.x
SELECT a.foo, b.foo
FROM a
LEFT JOIN b ON a.x = b.x
```
Now obviously when you need an outer join, the second syntax is required. But when doing an inner join why should I prefer the second syntax to the first (or vice versa)? | The old syntax, with just listing the tables, and using the `WHERE` clause to specify the join criteria, is being deprecated in most modern databases.
It's not just for show, the old syntax has the possibility of being ambiguous when you use both INNER and OUTER joins in the same query.
Let me give you an example.
Let's suppose you have 3 tables in your system:
```
Company
Department
Employee
```
Each table contain numerous rows, linked together. You got multiple companies, and each company can have multiple departments, and each department can have multiple employees.
Ok, so now you want to do the following:
> List all the companies, and include all their departments, and all their employees. Note that some companies don't have any departments yet, but make sure you include them as well. Make sure you only retrieve departments that have employees, but always list all companies.
So you do this:
```
SELECT * -- for simplicity
FROM Company, Department, Employee
WHERE Company.ID *= Department.CompanyID
AND Department.ID = Employee.DepartmentID
```
Note that the last one there is an inner join, in order to fulfill the criteria that you only want departments with people.
Ok, so what happens now. Well, the problem is, it depends on the database engine, the query optimizer, indexes, and table statistics. Let me explain.
If the query optimizer determines that the way to do this is to first take a company, then find the departments, and then do an inner join with employees, you're not going to get any companies that don't have departments.
The reason for this is that the `WHERE` clause determines which *rows* end up in the final result, not individual parts of the rows.
And in this case, due to the left join, the Department.ID column will be NULL, and thus when it comes to the INNER JOIN to Employee, there's no way to fulfill that constraint for the Employee row, and so it won't appear.
On the other hand, if the query optimizer decides to tackle the department-employee join first, and then do a left join with the companies, you will see them.
So the old syntax is ambiguous. There's no way to specify what you want, without dealing with query hints, and some databases have no way at all.
Enter the new syntax, with this you can choose.
For instance, if you want all companies, as the problem description stated, this is what you would write:
```
SELECT *
FROM Company
LEFT JOIN (
Department INNER JOIN Employee ON Department.ID = Employee.DepartmentID
) ON Company.ID = Department.CompanyID
```
Here you specify that you want the department-employee join to be done as one join, and then left join the results of that with the companies.
Additionally, let's say you only want departments that contains the letter X in their name. Again, with old style joins, you risk losing the company as well, if it doesn't have any departments with an X in its name, but with the new syntax, you can do this:
```
SELECT *
FROM Company
LEFT JOIN (
Department INNER JOIN Employee ON Department.ID = Employee.DepartmentID
) ON Company.ID = Department.CompanyID AND Department.Name LIKE '%X%'
```
This extra clause is used for the joining, but is not a filter for the entire row. So the row might appear with company information, but might have NULLs in all the department and employee columns for that row, because there is no department with an X in its name for that company. This is hard with the old syntax.
This is why, amongst other vendors, Microsoft has deprecated the old outer join syntax, but not the old inner join syntax, since SQL Server 2005 and upwards. The only way to talk to a database running on Microsoft SQL Server 2005 or 2008, using the old style outer join syntax, is to set that database in 8.0 compatibility mode (aka SQL Server 2000).
Additionally, the old way, by throwing a bunch of tables at the query optimizer, with a bunch of WHERE clauses, was akin to saying "here you are, do the best you can". With the new syntax, the query optimizer has less work to do in order to figure out what parts goes together.
So there you have it.
LEFT and INNER JOIN is the wave of the future. | The JOIN syntax keeps conditions near the table they apply to. This is especially useful when you join a large amount of tables.
By the way, you can do an outer join with the first syntax too:
```
WHERE a.x = b.x(+)
```
Or
```
WHERE a.x *= b.x
```
Or
```
WHERE a.x = b.x or a.x not in (select x from b)
``` | SQL left join vs multiple tables on FROM line? | [
"",
"sql",
"syntax",
"join",
""
] |
I have a base page class that inherits from Page. We'll call it SpiffyPage.
I also have a user control called SpiffyControl.
I then have an aspx page, ViewSpiffyStuff.aspx, that inherits from SpiffyPage.
On page load, the SpiffyPage class is supposed to inject a SpiffyControl into the aspx page.
The problem is that SpiffyControl is a user control, and to instantiate that in the code behind one has to access the ASP namespace, sort of like:
```
ASP.controls_spiffycontrol_aspx MyControl;
```
But SpiffyPage isn't an aspx page, it's just a base page, and as such I can't access the ASP namespace, and I therefore can't instantiate a SpiffyControl in order to inject it.
How can I achieve my goal?
Edit:
One important point is that I must have a reference to the actual control type so I can assign values to certain custom Properties. That's why a function like LoadControl, which returns type Control, won't work in this case. | Add a baseclass to your SpiffyControl, like:
```
public class SpiffyBase : UserControl
{
public void DoIt()
{
Response.Write("DoIt");
}
}
```
and then you make your SpiffyControl inherit that baseclass, like:
```
public partial class SpiffyControl : SpiffyBase
```
then you should be able to do this from a Basepage class:
```
public class BasePage : Page
{
protected override void OnLoad(EventArgs e)
{
var c = Page.LoadControl("SpiffyControl.ascx") as SpiffyBase;
Page.Controls.Add(c);
c.DoIt();
}
}
``` | I would implement SpiffyControl in a separate ASP.NET Server Control project, and reference that project from the web application. That way the control will not reside in the ASP namespace, but in the namespace of your choice and behave like any other server control.
Update: a nice side effect of putting the user controls into a separate project is that they become more decoupled from the web application as such, which in turn tends to make them more reusable and, depending on their design, also more testable. | Using a user control in a base page class | [
"",
"c#",
".net",
"asp.net",
"vb.net",
""
] |
I am trying to do something similar to this sample code from Phil Haack to VB, and LINQ Orderby is giving me problems - and I can't figure out how to do this. Entire method posted for completenes.
This is the C# version:
```
public ActionResult DynamicGridData(string sidx, string sord, int page, int rows)
{
var context = new HaackOverflowDataContext();
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = context.Questions.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var questions = context.Questions.OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (
from question in questions
select new
{
i = question.Id,
cell = new string[] { question.Id.ToString(), question.Votes.ToString(), question.Title }
}).ToArray()
};
return Json(jsonData);
}
```
My problem is with this line...:
```
var questions = context.Questions.OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);
```
In VB.Net OrderBy does not accept a string as value - and it seems to do that in C# (or I am missing something).
(Please not the use of VAR is not the issue here, I have that covered. :) )
**Edit:**
This is the error I get (I simply cannot compile):
Overload resolution failed because no accessible 'OrderBy' can be called with these arguments...
Screenshot of complete error message: [](https://i.stack.imgur.com/5JBsa.png)
**Edit2:**
More information, as requested.
sidx contains the name of a column to sort by
sord contains asc or desc
The VB-code:
```
Function MemberData(ByVal sidx As String, ByVal sord As String, ByVal page As Integer, ByVal rows As Integer) As JsonResult
Dim allRecords As IQueryable(Of Models.Member) = Me.MemberRepository.FindAllMembers
Dim currentPageRecords As IQueryable(Of Models.Member)
Dim pageIndex As Integer = page - 1
Dim pageSize As Integer = rows
Dim totalRecords As Integer = allRecords.Count
Dim totalPages As Integer = CInt(Math.Ceiling(totalRecords / pageSize))
Dim orderBy As String = sidx + " " + sord
currentPageRecords = allRecords.OrderBy(Function(m) orderBy).Skip(pageIndex * pageSize).Take(pageSize)
Dim jsonData = New With { _
.total = totalPages, _
.page = page, _
.records = totalRecords, _
.rows = New ArrayList _
}
For Each member As Models.Member In currentPageRecords
jsonData.rows.Add(New With {.id = member.MemberId, .cell = GenerateCellData(member)})
Next
Return Json(jsonData)
End Function
``` | Is it possible he's using [Dynamic Linq?](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx) With dynamic linq you can pass string to the OrderBy methods as well as many other of the IEnumerable extension methods. | I tried to do the same as Kjensen, but i had a lot of problems (including the fact that the original C# sample has some bugs: revisitig the pages some results are ommited). So, i decided to modify the sample of Phil Haack (<http://haacked.com/archive/2009/04/14/using-jquery-grid-with-asp.net-mvc.aspx>) using stored procedures (i never trust in a ORM-thing generating SQL Code, the stored procedure isn't the best but neither the code from Linq) and vb. net (i haven't clean the code and some comments are in spanish)
SQL Code
```
Create procedure getDataPage1
(@tableName as varchar(100),
@columns as varchar(200),
@columnOrder as varchar(100),
@columnOrderDirection as varchar(20),
@currentPage as int,
@pageSize as int,
@filter as varchar(2000) = '')
AS
BEGIN
-- No se debe referenciar a otras columnas Identity (para esos casos se debe hacer un conversion previa antes de hacer el INSERT INTO)
-- Version válida para Sql server 2000, usar funcion ROW_NUMBER para SQL server 2005 o posterior
-- Ejemplos de uso:
-- exec getDataPage1 'DataTarjetasProcesada', 'linea = cast(linea as varchar(100)), Tarjeta, Bloqueo, Saldo', 'Tarjeta', 'desc', 6, 800
-- exec getDataPage1 'Question', 'Id, Votes, Title', 'Title', 'desc', 2, 10
set nocount on
declare @query as nvarchar(1000)
-- Paso 1: se numera el listado
set @query = 'Select Identifier = Identity(int, 1, 1), ' + @columns +
' into #temp ' +
' from ' + @tableName +
case when @filter = '' then '' else ' where ' + @filter end +
' Order By ' + @columnOrder + ' ' + @columnOrderDirection
-- Paso 2: se toma la página de consulta
+
' select ' + @columns + ' from #temp '+
' where Identifier between ' + cast( @pageSize * (@currentPage -1) + 1 as varchar(15)) +
' and '+ cast (@pageSize*( @currentPage ) as varchar (15))
EXECUTE sp_executesql @query
set nocount off
END
```
Vb .net Code
```
Function DynamicGridData(ByVal sidx As String, ByVal sord As String, ByVal page As Integer, ByVal rows As Integer) As ActionResult
Dim context As New MvcTestApplication.modelDataContext
Dim pageIndex As Integer = Convert.ToInt32(page) - 1
Dim pageSize As Integer = rows
Dim totalRecords As Integer = context.Questions.Count()
Dim totalPages As Integer = Math.Ceiling(CDec(totalRecords) / CDec(pageSize))
' Establecemos la función de ordenación dependiendo del valor del
' parámetro "sidx", que es el campo de orden actual
' Establecemos si se trata de orden ascendente o descendente, en
' función del parámetro "sord", que puede valer "asc" o "desc"
Dim results As IMultipleResults = context.getDataPage1("Question", "Id, Votes, Title", sidx, sord, page, pageSize)
Dim questions = results.GetResult(Of Question)()
Dim jsonData = New With { _
.total = totalPages, _
.page = page, _
.records = totalRecords, _
.rows = (From question In questions _
Select New With _
{ _
.i = question.Id, _
.cell = New String() {question.Id.ToString(), question.Votes.ToString(), question.Title} _
} _
).ToArray() _
}
Return Json(jsonData)
End Function
``` | LINQ - Dynamic OrderBy in VB.Net | [
"",
"c#",
".net",
"vb.net",
"linq",
""
] |
Is there a straight forward way to decode a base64 string using ONLY THE JAVA 1.5 LIBRARIES?
I have to use Java 1.5 due to cross platform compatibility issues between Windows and Mac OS X (only Mac 10.5 supports Java 1.6, everything lower than 10.5 has Java 1.5 as default).
The object "sun.misc.Base64Decoder" exists in Java 6, but not in Java 5. | No, it's not possible based on just using JDK 5.0.
You'll need to roll your own implementation (it isn't that hard) or preferably use one of the open source implementations. There are lots including Commons Codec which provides Base64 <http://commons.apache.org/codec/api-release/org/apache/commons/codec/binary/Base64.html>
JavaMail also provides Base64 encoding/decoding via MimeUtility which also does quoted printable encoding etc...
<http://java.sun.com/products/javamail/javadocs/javax/mail/internet/MimeUtility.html> | [Apache Commons Codec](http://commons.apache.org/codec/userguide.html)
FYI, you should be using this even in Java 6. [Don't use classes in sun.\*](http://java.sun.com/products/jdk/faq/faq-sun-packages.html) | Decode base64 String Java 5 | [
"",
"java",
"base64",
"decode",
""
] |
> **Possible Duplicate:**
> [How Random is System.Guid.NewGuid()?](https://stackoverflow.com/questions/467271/how-random-is-system-guid-newguid)
Based on [this question](https://stackoverflow.com/questions/292254/vb6-how-do-i-make-a-random-string-of-0-9-and-a-z-of-x-characters/) I would like to know if using a GUID to generate a random string of characters and numbers has any flaws in it?
So, for example, if I wanted a random string of characters and numbers of 32 or fewer characters I could use the following C# code:
```
string s = Guid.NewGuid().ToString().Replace("-", "");
```
If the length needed to be shorter than 32 I would truncate the string and if it needed to be longer I would add multiple GUID's together.
What are the flaws in this approach?
After I wrote this I realized that one flaw would be that it would only ever have the letters a through f so I will modify the question:
Is this a truly random sequence of 6 characters and 10 digits? | A GUID doesn't make guarantees about randomness, it makes guarantees around uniqueness. If you want randomness, use Random to generate a string. | It's not actually intended to be random, but instead to be (relatively) unique. If you really want randomness, I recommend using something like a hash of a value from System.Random.
[Here's](http://msdn.microsoft.com/en-us/library/system.random.aspx) a link to the MSDN documentation for the .NET "System.Random", as well as the same for their [Hashing package](http://msdn.microsoft.com/en-us/library/system.security.policy.hash.generatehash.aspx). | Is using a GUID a valid way to generate a random string of characters and numbers? | [
"",
"c#",
".net",
"random",
""
] |
if so how? | To select by a primary key you should use one of:
* `DataTable.Rows.Find(Object)` in case your PK is one column
* `DataTable.Rows.Find(Object[])` in case you have more then 1 column as a primary key
In case of a typed DataSet, the method `MyDataTable.Rows.Find(...)` will be generated for you with the proper signature. Basically it is a method on DataRowCollection class | 'Contains' does not seem to be a member of the DataRow class (maybe this is a typed data set?)
In any case, you can always use (DataTable.Select(....).Length > 0) as a substitute | Can you use DataTable.Contains(object key) if your datatable's primary key is two columns? | [
"",
"c#",
"visual-studio",
"ado.net",
"datatable",
"datarow",
""
] |
I am writing an unmanaged DLL in C++. Is using float as a function parameter in a Windows DLL a good idea?
I'd like my DLL to be usable from as many languages as possible (VB6, .NET, etc). To this end, I've used STDCALL and avoided C++ types.
Will most languages handle float correctly? If not, what should I use? | The `float` type used in most compilers is even standardized in some IEEE format, so go ahead. | All Microsoft languages, such as VB and C# will be just fine with it. In fact, you should be fine using any type that [VARIANT](http://msdn.microsoft.com/en-us/library/ms221627.aspx)s support. | Using floats in Windows DLL function parameters | [
"",
"c++",
"windows",
"dll",
""
] |
I'm working with WCF (VS2005, .Net 3.0) and want to test out a service by directly calling it via a web browser instead of from code.
I have one method decorated with the OperationContract attribute call GetTest(). I have the service behind a .svc file that I can access; however, when I go .../Test.svc/GetTest, only a blank screen comes up.
Here is the web.config:
```
<system.serviceModel>
<services>
<service name="TestService" behaviorConfiguration="TestBehavior">
<endpoint
address=""
binding="basicHttpBinding"
contract="TestService.ITestService"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="TestBehavior">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
```
Whenever I try to set a breakpoint in the service, it does not get hit as well. Any ideas on where I'm going wrong here? I'm used to ASMX services where I get a response when I access the methods via a browser; however, I can only get the "You've created a Service" page when I access the service but nothing from the methods. | WCF does not offer the "call it from the web" options that ASMX services used to do. Why? It's a huge security hole, and not the best way to test a web service.
One option is to do as @Yossi suggested, and use the Wcf Service Test Tool.
Or better yet, write your own client to consume your web service. This will help you deal with the same issues those who will consume your service will deal with, and believe me, WCF can have quite a few of those hangups.
Don't get me wrong, WCF is frikkin awesome! But there's a lot to juggle, and if you're new odds are you're going to get it wrong. Even early adopters still don't know all the ins and outs of WCF. | Consider using the [Wcf Service Test Tool](http://msdn.microsoft.com/en-us/library/bb552364.aspx) for initial testing of your service (but really- unit testing is your friend :-)) (and yeah - you will need a mex endpoint, at least initially)
As for debugging - are you attached to the correct process hosting the service? are you compiled with debug symbols? if the service is published to IIS - is the published code the same as the code in visual studio? | Unable to call a WCF service directly (.NET 3.0) | [
"",
"c#",
"wcf",
".net-3.0",
""
] |
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*Edit 2\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
I figured out the problem... But I don't like the implications. I was testing our iPhone targeted mobile application earlier and using a plugin to mask Firefox's User Agent String as an iPhone.
.Net was infact NOT generating the required code for post backs based on that piece of information alone.
I do not like this however, because since the iPhone and other multimedia devices can interpret javascript, ASP.net is breaking any application that relies on server generated javascript to run.
So, if the community will allow it... I'd like to change my official question to... Why will ASP.net not generate javascript for specific browsers and how can I turn this "feature" off.
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* End Edit 2 \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
I've got a weird problem. I copied some working code from my remote host to my computer at work. When I try to use the page I'm getting a javascript error
```
__doPostBack is not defined
javascript:__doPostBack('ctl00$ContentPlaceHolder1$login','')()()
```
When I few the output page source, sure enough there is no server side generated javascript.
I tried creating a simple page:
```
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="jsTest.aspx.vb" Inherits="_jsTest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="tbTest" runat="server"></asp:TextBox><br />
<asp:LinkButton ID="linkTest" runat="server">LinkButton</asp:LinkButton>
</form>
</body>
</html>
```
Codebehind:
```
Partial Class _jsTest
Inherits System.Web.UI.Page
Protected Sub linkTest_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles linkTest.Click
Response.Write(tbTest.Text)
End Sub
End Class
```
Getting the same error.
I've tried rebooting (hey, it works half the time), cleared out everything from App\_Code, global.asax and web.config, added a textbox with autopostback=true... I'm out of ideas.
Can anyone shed some light on what's happening here?
\*\*\*\*\*\*\*\*\*\*\*\*\*\*More Information\*\*\*\*\*\*\*\*\*\*\*\*\*\*
I just tried everything again in IE and it works as expected, the page source shows:
```
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTkxNTA2MDE2NWRkxhZMwlMVwJprcVsvQLJLrTcgaSM=" />
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwK20LZAAuzRsusGAsz0+6YPxxO+Ewv1XsD5QKJiiprrGp+9a3Q=" />
</div>
```
While the source in Firefox only shows:
```
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTkxNTA2MDE2NWRkxhZMwlMVwJprcVsvQLJLrTcgaSM=" />
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwK20LZAAuzRsusGAsz0+6YPxxO+Ewv1XsD5QKJiiprrGp+9a3Q=" />
```
Saving the web pages to the desktop and opening in notepad reveals the same thing... | The problem is the default way ASP.net treats unknown browsers... such as the iPhone. Even though it would be nice to assume unknown browsers could use javascript... you can specify what capabilities that a browser has in the section of web.config or machine.config.
Check out <http://slingfive.com/pages/code/browserCaps/> for an updated browsercaps config file for asp.net
Here is an example of a case to match GECKO Based Browsers (Netscape 6+, Mozilla/Firefox, ...)
```
<case match="^Mozilla/5\.0 \([^)]*\) (Gecko/[-\d]+)(?'VendorProductToken' (?'type'[^/\d]*)([\d]*)/(?'version'(?'major'\d+)(?'minor'\.\d+)(?'letters'\w*)))?">
browser=Gecko
<filter>
<case match="(Gecko/[-\d]+)(?'VendorProductToken' (?'type'[^/\d]*)([\d]*)/(?'version'(?'major'\d+)(?'minor'\.\d+)(?'letters'\w*)))">
type=${type}
</case>
<case> <!-- plain Mozilla if no VendorProductToken found -->
type=Mozilla
</case>
</filter>
frames=true
tables=true
cookies=true
javascript=true
javaapplets=true
ecmascriptversion=1.5
w3cdomversion=1.0
css1=true
css2=true
xml=true
tagwriter=System.Web.UI.HtmlTextWriter
<case match="rv:(?'version'(?'major'\d+)(?'minor'\.\d+)(?'letters'\w*))">
version=${version}
majorversion=0${major}
minorversion=0${minor}
<case match="^b" with="${letters}">
beta=true
</case>
</case>
</case>
``` | Before you reinstall Firefox, run it in debug mode (I think it's called debug mode). It turns off all plugins and that can help you narrow it down a bit. What about other browsers like Chrome or Safari? | ASP.net not generating javascript for some User Agents | [
"",
"asp.net",
"javascript",
"user-agent",
"auto-generate",
""
] |
I needed to come up with a SQL query that returns rows that satisfy multiple conditions. This article describes what I needed to do and the solution:
<http://thenoyes.com/littlenoise/?p=58>
Basically it uses a bit operation to figure out if a provided string is found.. but I'm having hard time following how it works.
```
SET @q = 'A,B';
SELECT studentName
FROM quizAnswers
GROUP BY studentName
HAVING
BIT_OR(1 << FIND_IN_SET(question, @q) - 1)
=
(1 << LENGTH(@q) - LENGTH(REPLACE(@q, ',', '')) + 1) - 1; -- This is 2^numValues - 1
+-------------+
| studentName |
+-------------+
| seekwill |
+-------------+
```
I tested it and it works as expected. Can someone explain how this works?
Thanks,
Amie | I am not going to explain what BIT\_OR is doing.
**Alternative solution:**
If it is possible, I usually prefer *pure* SQL solutions that do not depend on the vendor-specific features. If what you need is similar to the example in the article you refer to, then this SQL statement should run pretty much on any RDBMS and produce the desired result:
```
-- //return those students that have correctly answered not less then 3 questions among A,B,C
select studentName, COUNT(DISTINCT question) AS CNT
from quizAnswers
where question in ('A', 'B', 'C')
GROUP BY studentName
HAVING COUNT(DISTINCT question) >= 3
```
and by playing with `HAVING COUNT...` you are even more flexible:
```
-- //return those students that have correctly answered at least 1 question among A,B (either A or B)
select studentName, COUNT(DISTINCT question) AS CNT
from quizAnswers
where question in ('A', 'B',)
GROUP BY studentName
HAVING COUNT(DISTINCT question) >= 1
```
Basically you just need to fill `...` in part `where question in (...)` and set the value of the COUNT(...), which by default would be the number of answers to check for a Complete Set. | If there is a match for one of the values in the list, a bit is set and left-shifted as many times as the position of the matching item in the list. The group-by does an xor operation on all the individual bitmaps per student, resulting in a single value that contains the same information (one bit set for each matching value that existed).
This method is obviously limited by the number of bits that the return type can hold. | Complete set in SQL | [
"",
"sql",
"mysql",
""
] |
I would like to know how to retrieve all results from each `<p>` tag.
```
import re
htmlText = '<p data="5" size="4">item1</p><p size="4">item2</p><p size="4">item3</p>'
print re.match('<p[^>]*size="[0-9]">(.*?)</p>', htmlText).groups()
```
result:
```
('item1', )
```
what I need:
```
('item1', 'item2', 'item3')
``` | The regex answer is extremely fragile. Here's proof (and a working BeautifulSoup example).
```
from BeautifulSoup import BeautifulSoup
# Here's your HTML
html = '<p data="5" size="4">item1</p><p size="4">item2</p><p size="4">item3</p>'
# Here's some simple HTML that breaks your accepted
# answer, but doesn't break BeautifulSoup.
# For each example, the regex will ignore the first <p> tag.
html2 = '<p size="4" data="5">item1</p><p size="4">item2</p><p size="4">item3</p>'
html3 = '<p data="5" size="4" >item1</p><p size="4">item2</p><p size="4">item3</p>'
html4 = '<p data="5" size="12">item1</p><p size="4">item2</p><p size="4">item3</p>'
# This BeautifulSoup code works for all the examples.
paragraphs = BeautifulSoup(html).findAll('p')
items = [''.join(p.findAll(text=True)) for p in paragraphs]
```
Use BeautifulSoup. | For this type of problem, it is recommended to use a DOM parser, not regex.
I've seen [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) frequently recommended for Python | Python regular expression for multiple tags | [
"",
"python",
"html",
"regex",
""
] |
Let's say I have an event. Let's call it DoStuff. Before DoStuff happens, I'm trying to use another event, PreviewDoStuff, to check if I need to prevent DoStuff from being called. The problem I'm facing with this is that I'm unable to get any kind of value back from the PreviewDoStuff, like a return code or anything due to how events are written. And event args aren't passed back to the caller, so I can't get the event args "handled" property. I'm sure there has to be a way to do it, but I'm not sure how. Any ideas?
Thanks! | Declare the event as `EventHandler<CancelEventArgs>`. Then the listener can set Cancel to true, and you can use that value to determine whether to raise the "real" event or not.
Mandatory code sample:
```
public event EventHandler<CancelEventArgs> PreviewDoStuff;
public event EventHandler DoStuff;
private void RaiseDoStuff()
{
CancelEventArgs args = new CancelEventArgs();
OnPreviewDoStuff(args);
if (!args.Cancel)
{
OnDoStuff(EventArgs.Empty);
}
}
protected void OnPreviewDoStuff(CancelEventArgs e)
{
EventHandler<CancelEventArgs> previewDoStuff = PreviewDoStuff;
if (previewDoStuff != null)
{
previewDoStuff(this, e);
}
}
protected void OnDoStuff(EventArgs e)
{
EventHandler doStuff = DoStuff;
if (doStuff != null)
{
doStuff(this, e);
}
}
```
For an example of this in real-life use, check the [FormClosing](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx) event, which uses a FormClosingEventArgs class, which in turn inherits from CancelEventArgs. | Have your PreviewDoStuff set an internal flag which DoStuff checks when it fires. Even better, have the code that raises DoStuff check the flag before it raises the event. | How to write a "Preview"-type event that can cancel a main event? | [
"",
"c#",
"events",
"event-handling",
""
] |
I have implemented the IEquatable interface in a class with the following code.
```
public bool Equals(ClauseBE other)
{
if (this._id == other._id)
{
return true;
}
return false;
}
public override bool Equals(Object obj)
{
if (obj == null)
{
return base.Equals(obj);
}
if (!(obj is ClauseBE))
{
throw new InvalidCastException("The 'obj' argument is not a ClauseBE object.");
}
return Equals(obj as ClauseBE);
}
public override int GetHashCode()
{
return this._id.GetHashCode();
}
public static bool operator ==(ClauseBE a, ClauseBE b)
{
// cast to object so we call the overloaded Equals function which appropriately checks when b is null.
return a.Equals(b as object);
}
public static bool operator !=(ClauseBE a, ClauseBE b)
{
// cast to object so we call the overloaded Equals function which appropriately checks when b is null.
return !a.Equals(b as object);
}
```
This code work very well for most all cases. However, the following check throws an exception in the equality operator overload method because a is null and therefore does not have a Equals method.
```
if(this.Clause != null)
{
}
```
What is the standard way to solve this issue?
## EDIT
I have gone to this, but it seems pretty cumbersome. I was hoping there was a more elegant way to accomplish this.
```
public static bool operator ==(ClauseBE a, ClauseBE b)
{
if (a as object == null && b as object == null)
{
return true;
}
if ((a as object == null && b as object != null)
|| (b as object == null && a as object != null))
{
return false;
}
// cast to object so we call the overloaded Equals function which appropriately checks when b is null.
return a.Equals(b as object);
}
public static bool operator !=(ClauseBE a, ClauseBE b)
{
if (a as object == null && b as object == null)
{
return false;
}
if((a as object == null && b as object != null)
|| (b as object == null && a as object != null))
{
return true;
}
// cast to object so we call the overloaded Equals function which appropriately checks when b is null.
return !a.Equals(b as object);
}
```
## Solution
Thanks all. I got a lot of good tips from everyone, I really appreciate it. This is what I finally settled on, it's a lot more elegant than what I had started with. All code is the same except operator overloads.
```
public static bool operator ==(ClauseBE a, ClauseBE b)
{
if (ReferenceEquals(a, null) && ReferenceEquals(b, null))
{
return true;
}
if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
{
return false;
}
return a.Equals(b);
}
public static bool operator !=(ClauseBE a, ClauseBE b)
{
return !(a == b);
}
``` | I've always found it easier to write the static operator with null handling, and have the Equals override call the overloaded operator with "this" as one of the parameters.
From [Guidelines for Overloading Equals() and Operator == (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/ms173147.aspx)
```
//add this code to class ThreeDPoint as defined previously
//
public static bool operator ==(ThreeDPoint a, ThreeDPoint b)
{
// If both are null, or both are same instance, return true.
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
// If one is null, but not both, return false.
if (((object)a == null) || ((object)b == null))
{
return false;
}
// Return true if the fields match:
return a.x == b.x && a.y == b.y && a.z == b.z;
}
public static bool operator !=(ThreeDPoint a, ThreeDPoint b)
{
return !(a == b);
}
``` | This is how ReSharper creates equality operators and implements `IEquatable<T>`, which I trust blindly, of course ;-)
```
public class ClauseBE : IEquatable<ClauseBE>
{
private int _id;
public bool Equals(ClauseBE other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return other._id == this._id;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != typeof(ClauseBE))
return false;
return Equals((ClauseBE)obj);
}
public override int GetHashCode()
{
return this._id.GetHashCode();
}
public static bool operator ==(ClauseBE left, ClauseBE right)
{
return Equals(left, right);
}
public static bool operator !=(ClauseBE left, ClauseBE right)
{
return !Equals(left, right);
}
}
``` | IEquatable Interface what to do when checking for null | [
"",
"c#",
"iequatable",
""
] |
A Django autofield when displayed using a formset is hidden by default. What would be the best way to show it?
At the moment, the model is declared as,
```
class MyModel:
locid = models.AutoField(primary_key=True)
...
```
When this is rendered using Django formsets,
```
class MyModelForm(ModelForm):
class Meta:
model = MyModel
fields = ('locid', 'name')
```
it shows up on the page as,
```
<input id="id_form-0-locid" type="hidden" value="707" name="form-0-locid"/>
```
Thanks.
---
**Edit**
I create the formset like this -
```
LocFormSet = modelformset_factory(MyModel)
pformset = LocFormSet(request.POST, request.FILES, queryset=MyModel.objects.order_by('name'))
```
---
**Second Edit**
Looks like I'm not using the custom form class I defined there, so the question needs slight modification..
*How would I create a formset from a custom form (which will show a hidden field), as well as use a custom queryset?*
At the moment, I can either inherit from a BaseModelFormSet class and use a custom query set, or I can use the ModelForm class to add a custom field to a **form**. Is there a way to do both with a formset?
---
**Third Edit**
I'm now using,
```
class MyModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
locid = forms.IntegerField(min_value = 1, required=True)
self.fields['locid'].widget.attrs["type"] = 'visible'
self.queryset = MyModel.objects.order_by('name')
class Meta:
model = MyModel
fields = ('locid', 'name')
LocFormSet = modelformset_factory(MyModel, form = MyModelForm)
pformset = LocFormSet()
```
But this still doesn't
* Show locid
* Use the custom query that was specified. | Okay, none of the approaches above worked for me. I solved this issue from the template side, finally.
* There is a ticket filed (<http://code.djangoproject.com/ticket/10427>), which adds a "value" option to a template variable for a form. For instance, it allows,
{{form.locid.value}}
to be shown. This is available as a patch, which can be installed in the SVN version of django using "patch -p0 file.patch"
* Remember, the {{form.locid.value}} variable will be used **in conjunction** with the invisible form - otherwise, the submit and save operations for the formset will crash.
* This is *Not* the same as {{form.locid.data}} - as is explained in the ticket referred to above. | Try changing the default field type:
```
from django import forms
class MyModelForm(ModelForm):
locid = forms.IntegerField(min_value=1, required=True)
class Meta:
model = MyModel
fields = ('locid', 'name')
```
**EDIT:** Tested and works... | How to show hidden autofield in django formset | [
"",
"python",
"django",
"formset",
""
] |
My company creates web surveys and once in a while I get asked if we can do an exit survey on a website. So when a visitor is about to leave the site a "popup" appears asking if they'd take a quick survey. By "popup" I'm referring to a floating CSS div, not a child window (although sometimes clients don't realise this).
Is it technically possible to code a genuine exit survey?
I don't think so but am I missing something? The **onbeforeunload** event is close to the functionality required but the message and buttons aren't fully customiseable to make it usable.
The current trend for implementing an exit survey is to popup an invite at the start of the visit, and if the user says ok then a child window is opened and focus set back to the main window. At the end of the visit the users sees the child window. I swear I've never seen a "popup on exit" survey (unless by coincidence). | Surely they 'exit' the site by closing the window/tab? You're asking for a way to prevent them closing the tab? Or popup a window triggered by the close action? That sounds like it would be prevented by the browser for good reason, and if you found a workaround it would be likely to be fixed in future versions. | ```
var exitmessage = 'Please dont go!'; //custome message
DisplayExit = function() {
return exitmessage;
};
window.onbeforeunload = DisplayExit;
``` | How to popup when a visitor exits from a website | [
"",
"javascript",
"html",
"ajax",
""
] |
I'm using the Maven 2 assembly plug-in to build a jar-with-dependencies and make an executable JAR file. My assembly includes Spring, and the CXF library.
CXF includes copies of META-INF files spring.schemas and spring.handlers which end up clobbering the similar files from the spring-2.5.4 jar.
By hand, I can update those two files within the jar-with-dependencies.
What I'm looking for is some way in the Maven POM to direct the assembly plug-in to get the correct version of those two files.
The assembly plug-in documentation talks about file filtering, but doesn't seem to have configuration for or parameters, without going to the trouble of creating a custom assembly descriptor.
Is making a custom assembly descriptor my only hope in this instance? | For some reason the solution that Mojo and the others are suggesting still doesn't work for me. I've created my custom `spring.handlers` and `spring.schemas` files and put them under `src/main/resources/META-INF`. However, when using the `unpackOptions` my files are not included as well. When I don't use the `unpackOptions` my files aren't the ones in the jar.
What I ended up doing is to reference the files directly. This finally put my files into the JAR.
```
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<!-- TODO: a jarjar format would be better -->
<id>jar-with-dependencies</id>
<formats>
<format>jar</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<dependencySets>
<dependencySet>
<outputDirectory>/</outputDirectory>
<unpack>true</unpack>
<unpackOptions>
<excludes>
<exclude>META-INF/spring.handlers</exclude>
<exclude>META-INF/spring.schemas</exclude>
</excludes>
</unpackOptions>
<scope>runtime</scope>
</dependencySet>
</dependencySets>
<files>
<file>
<source>${project.basedir}/src/main/resources/META-INF/spring.handlers</source>
<outputDirectory>META-INF</outputDirectory>
</file>
<file>
<source>${project.basedir}/src/main/resources/META-INF/spring.schemas</source>
<outputDirectory>META-INF</outputDirectory>
</file>
</files>
</assembly>
``` | I would suggest using the maven-shade-plugin instead. If you look at the pom for the cxf-bundle (<https://github.com/apache/cxf/blob/master/pom.xml>) you can see how you can use the shade transformers to merge the spring.schemas and other necessary files. | Maven 2 assembly plugin clobbers some META-INF files | [
"",
"java",
"spring",
"maven-2",
""
] |
I want to give a certain linked list to a class I am making. I want the class to write into that list (eg by .addLast()).
Should I use the `ref` keyword for that?
I am somewhat puzzled on where to use the `ref` and `out` keywords in C#, as all *classes* are allocated dynamically on the heap and we actually use pointers for most operations.
Of course, `out` and `ref` keywords make sense for primitives and structs.
Also, if I don't send the list directly, but send a class containing the list? (it's `internal` and needed), do I still need to use `ref`? or if I pass it between functions, ex:
```
void A(ref LinkedList<int> list){
B(list);
}
void B(ref LinkedList<int> list){
_myList = list;
}
``` | For what you're doing you don't need to use ref. If you did pass the list using ref, you would be allowing the caller to change which list you're referencing, rather than just changing the contents of the list. | This is a common misconception of the use of `ref` keyword in C#. Its purpose is to pass either a value or a reference type by reference, and you only need it in specific circumstances where you need a direct reference to the actual argument, rather than a copy of the argument (be it a value or reference itself). It is imperative not to confuse *reference types* with *passing by reference* in any case.
Jon Skeet has written [an excellent article](https://jonskeet.uk/csharp/parameters.html) about parameter passing in C#, which compares and contrasts value types, reference types, passing by value, passing by reference (`ref`), and output parameters (`out`). I recommend you take some time to read through this in full and your understanding should become much clearer.
To quote the most important parts from that page:
**Value parameters:**
> By default, parameters are value
> parameters. This means that a new
> storage location is created for the
> variable in the function member
> declaration, and it starts off with
> the value that you specify in the
> function member invocation. If you
> change that value, that doesn't alter
> any variables involved in the
> invocation
**Reference parameters:**
> Reference parameters don't pass the
> values of the variables used in the
> function member invocation - they use
> the variables themselves. Rather than
> creating a new storage location for
> the variable in the function member
> declaration, the same storage location
> is used, so the value of the variable
> in the function member and the value
> of the reference parameter will always
> be the same. Reference parameters need
> the ref modifier as part of both the
> declaration and the invocation - that
> means it's always clear when you're
> passing something by reference. Let's
> look at our previous examples, just
> changing the parameter to be a
> reference parameter:
To conclude: having read my reply and Jon Skeet's article, I hope that you will then see that there is *no need whatsoever* for using the `ref` keyword in the context of your question. | using ref with class C# | [
"",
"c#",
"pointers",
"reference",
"keyword",
""
] |
Just a quick one here.
What are the benefits of using `java.io.Console` as opposed to using a `BufferedReader` wrapping an `InputStreamReader` for `System.in`?
Why would I use it?
Thanks for any advice! | You can use `java.io.Console` to present an interactive command-line to the user. You could do all that with `System.in` yourself, but you would have to implement things like noticing when the input was done, or `readPassword`, etc. | Because it's code that is already written for you...no need to re-invent the wheel. Chances are, you're not going to get it any better than it already is. | Why Use java.io.Console? | [
"",
"java",
"input",
"console",
""
] |
I'm trying to figure out why this JavaScript doesn't stop the form from being submitted:
```
<form action="http://www.example.com" id="form">
<input type="text" />
<input type="submit" />
</form>
<script>
var code = function () {
return false;
};
var element = window.document.getElementById("form");
if (element.addEventListener) {
element.addEventListener("submit", code, false);
}
</script>
```
Unless I add the following onsubmit attribute to the form element:
```
<form action="http://www.example.com" id="form" onsubmit="return false">
<input type="text" />
<input type="submit" />
</form>
<script>
var code = function () {
return false;
};
var element = window.document.getElementById("form");
if (element.addEventListener) {
element.addEventListener("submit", code, false);
}
</script>
```
Seems like the addEventListener method alone should do the trick. Any thoughts? I'm on a Mac and I'm experiencing the same result on Safari, Firefox and Opera. Thanks. | Combined the information from the two very helpful answers into a solution that works on both Mac and PC:
```
<script>
var code = function (eventObject) {
if (eventObject.preventDefault) {
eventObject.preventDefault();
} else if (window.event) /* for ie */ {
window.event.returnValue = false;
}
return true;
};
var element = window.document.getElementById("form");
if (element.addEventListener) {
element.addEventListener("submit", code, false);
} else if (element.attachEvent) {
element.attachEvent("onsubmit", code);
}
</script>
``` | Looks like if you change your function to
```
var code = function(e) {
e.preventDefault();
}
```
It should do what you're looking for.
[source](http://www.drunkenfist.com/304/2009/04/02/a-javascript-curiosity-regarding-addeventlistener/) | Form is still submitted even though listener function returns false | [
"",
"javascript",
"forms",
"addeventlistener",
"onsubmit",
""
] |
I'm working on a project where we are doing a lot of custom javascript and especially jquery, on an mvc style project.
The only problem is that I keep adding more and more global functions/variables and they are piling up. I've got a few files but I'm unsure how to split some of the stuff up into separate files.
I've thought about composing some of these function and global variables into objects, but the object syntax in javascript seems a little awkward to me (because of the absence of classic classes). Though if I had a good example to follow maybe I could come around.
How do you deal with a project where the global javascript functions and variables start piling up like this? | A very simple way to pile a bunch of global variables and functions into a single global object:
```
// Awful pile of globally-scoped names
var foo = 1
var bar = 2
function go = function(){
console.log('Yeehaw!');
}
// Instead, just dump everything into a global-level object
var MyApp = {
foo: 1,
bar: 2,
go: function(){
console.log('Yeehaw!');
}
}
// Now access stuff like this
console.log(MyApp.foo);
console.log(MyApp.bar);
MyApp.go();
```
For "simple" top-level variables and functions, I can recommend this. There are plenty of improvements that can be made to this, but they'll probably fall under the category of premature optimizations; this is a great first step. | The Crockford Videos on YUI theater are a good example of how to set up JavaScript namespaces among other things. | What's a good way to refactor a growing number of javascript/jquery functions? | [
"",
"javascript",
"jquery",
"refactoring",
"object",
"global-variables",
""
] |
I have a [jQuery UI Sortable](http://docs.jquery.com/UI/Sortable) list. The sortable items also have a click event attached. Is there a way to prevent the click event from firing after I drag an item?
```
$().ready( function () {
$('#my_sortable').sortable({
update: function() { console.log('update') },
delay: 30
});
$('#my_sortable li').click(function () {
console.log('click');
});
});
```
```
#my_sortable li {
border: 1px solid black;
display: block;
width: 100px;
height: 100px;
background-color: gray;
}
```
```
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script>
<ul id="my_sortable">
<li id="item_1">A</li>
<li id="item_2">B</li>
<li id="item_3">C</li>
</ul>
``` | I had the same problem and since my sortable items contained three or four clickable items (and the number was variable) binding/unbinding them on the fly didn't really seem an option. However, by incident I specified the
```
helper : 'clone'
```
option, which behaved identically to the original sortable in terms of interface but apparently does not fire click events on the dragged item and thus solves the problem. It's as much a hack as anything else, but at least it's short and easy.. | If you have a reference to the click event for your li, you can unbind it in the sortable update method then use Event/one to rebind it. The event propagation can be stopped before you rebind, preventing your original click handler from firing.
```
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script>
<script type="text/javascript" charset="utf-8">
var myClick = function () {
console.log('click');
};
$().ready( function () {
$('#my_sortable').sortable({
update: function(event, ui) {
ui.item.unbind("click");
ui.item.one("click", function (event) {
console.log("one-time-click");
event.stopImmediatePropagation();
$(this).click(myClick);
});
console.log('update') },
delay: 30
});
$('#my_sortable li').click(myClick);
});
</script>
<style type="text/css" media="screen">
#my_sortable li {
border: 1px solid black;
display: block;
width: 100px;
height: 100px;
background-color: gray;
}
</style>
</head>
<body>
<ul id="my_sortable">
<li id="item_1">A</li>
<li id="item_2">B</li>
<li id="item_3">C</li>
</ul>
</body>
</html>
``` | jQuery UI Sortable -- How can I cancel the click event on an item that's dragged/sorted? | [
"",
"javascript",
"jquery",
"jquery-ui",
""
] |
I'm developing sites using progressive enhancement implemented completely in jQuery.
For instance, I'm adding onclick event handlers dynamically to anchor tags to play linked MP3 files "inline" using SoundManager and popping up Youtube players for Youtube links, through $(document).ready(function()).
However, if the user clicks on them while the page is loading, they still get the non-enhanced version.
I've thought about hiding the relevant stuff (via display: none, or something like that) and showing it when loaded, or putting a modal "loading" dialog, but both sound like hacks.
Any better ideas? I feel I'm missing something completely obvious here.
Regards,
Alex | I haven't tested this, but you could try [`live`](http://docs.jquery.com/Events/live). The thinking is that you could put your click handlers outside of document.ready so they get executed right away. Since `live` uses [event delegation](http://www.sitepoint.com/blogs/2008/07/23/javascript-event-delegation-is-easier-than-you-think/) to achieve it's functionality, you don't really need to wait for the DOM to be ready, and any clicks that are made while the page is loading should still be captured by the event handler.
If that doesn't work, you could try putting the Javascript script tags directly underneath whatever they need to bind. It's not pretty, but it will pretty much eliminate the problem. | Assuming you have used good judgement and people are falling for the non-enhanced version just because the delay is too long then I would use **CSS to disable the controls**. The CSS will load almost right away. Then using Javascript I would toggle the CSS so the controls are re-enabled.
However, my first reaction is that if the user can click it while the page is loading, then your page or connection is too slow. However, if this is seldom the case--less than 1% of the time--then you can shrug it off as long as the user can achieve his goal, that is listen to his music. I say this because once the users realizes that a better experience awaits half a second later, he will usually wait for Javascript to render and then click. | Progressive enhancement, behavior when pages are not fully loaded yet | [
"",
"javascript",
"jquery",
"html",
"progressive-enhancement",
""
] |
I'm building a web app that attempts to install/upgrade the database on App\_Start.
Part of the installation procedure is to ensure that the database has the asp.net features installed. For this I am using the System.Web.Management.SqlServices object.
My intention is to do all the database work within an SQL transaction and if any of it fails, roll back the transaction and leave the database untouched.
the SqlServices object has a method "Install" that takes a ConnectionString but not a transaction. So instead I use SqlServices.GenerateApplicationServicesScripts like so:
```
string script = SqlServices.GenerateApplicationServicesScripts(true, SqlFeatures.All, _connection.Database);
SqlHelper.ExecuteNonQuery(transaction, CommandType.Text, script, ...);
```
and then I use the SqlHelper from the Enterprise Library.
but this throws an Exception with a butt-load of errors, a few are below
```
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near the keyword 'USE'.
Incorrect syntax near the keyword 'CREATE'.
Incorrect syntax near 'GO'.
The variable name '@cmd' has already been declared. Variable names must be unique within a query batch or stored procedure.
```
I'm presuming it's some issue with using the GO statement within an SQL Transaction.
How can I get this generated script to work when executed in this way. | GO is not a SQL keyword.
It's a batch separator used by client tools (like SSMS) to break the entire script up into batches
You'll have to break up the script into batches yourself or use something like [sqlcmd](http://msdn.microsoft.com/en-us/library/ms162773.aspx) with "-c GO" or osql to deal with "GO" | I just want to add that if you name your transaction, you can include multiple GO sections within in and they will all roll back as a unit. Such as:
```
BEGIN TRANSACTION TransactionWithGos;
GO
SET XACT_ABORT ON; -- Roll back everything if error occurs in script
GO
-- do stuff
GO
COMMIT TRANSACTION TransactionWithGos;
GO
``` | Using "GO" within a transaction | [
"",
".net",
"sql",
"sql-server",
"t-sql",
"transactions",
""
] |
I use XNA, and one of the things i do a lot is pass around data as Vector2s. Now, a lot of the objects in XNA (such as a graphics device and such), inste3ad of containing a Vector2 that tells you the size of the viewport, they offer separate Width and Height methods. Is there some way to add a Vector2 property to them so i can get that data without manually building a new vector2 everytime i need it? i guess what i want is something like "extension properties"... | You can use Michael's approach, but that does in fact build a new Vector2 every time. If you really only want the Vector2 to be created once, you can wrap the class you want, and provide your own Vector2 property:
```
public class GraphicsDeviceWrapper
{
private Vector2 vector;
public GraphicsDeviceWrapper(GraphicsDevice device)
{
this.vector = new Vector2(device.Viewport.Width, device.Viewport.Height);
this.Device = device;
}
public Vector2 Vector
{
get{return this.vector;}
}
public GraphicsDevice Device
{
get; private set
}
}
``` | Vector2 is a value type ... honestly, you don't really have to worry too much about creating new instances because they're created on the stack. Every time you can the .Vector property it's going to make a new instance anyways.
you don't have to worry about it though because value types do not invoke the garbage collector. Thus, the biggest reason to try to instantiate once is nullified (ie. the GC).
that being said, for larger structs such as a Matrix, you may want to consider passing them byref to avoid new allocations on the stack. | XNA Width and Height to Vector2 | [
"",
"c#",
"xna",
""
] |
What is the best way to find a file "upwardly" in Python? (Ideally it would work on Windows too). E.g.,
```
>>> os.makedirs('/tmp/foo/bar/baz/qux')
>>> open('/tmp/foo/findme.txt', 'w').close()
>>> os.chdir('/tmp/foo/bar/baz/qux')
>>> findup('findme.txt')
'/tmp/foo/findme.txt'
```
As far as I can tell, there isn't anything in the Python standard library (although I'd love to be proven wrong). Also, googling around didn't turn up much that's definitive; I'm wondering if there's something out there that "everyone" uses. | ```
import os
def findup(filename):
drive, thisdir = os.path.splitdrive(os.getcwd())
while True:
fullpath = os.path.join(drive, thisdir, filename)
if os.path.isfile(fullpath):
return fullpath
if thisdir == os.path.sep: #root dir
raise LookupError('file not found: %r' % filename)
thisdir = os.path.dirname(thisdir)
os.makedirs('/tmp/foo/bar/baz/qux')
open('/tmp/foo/findme.txt', 'w').close()
os.chdir('/tmp/foo/bar/baz/qux')
print findup('findme.txt')
```
Prints:
```
/tmp/foo/findme.txt
```
Also works on Windows. Probably will work on any platform. | The module os.path has what you need, in particular: abspath() (if the path is not absolute), dirname(), isfile(), and join().
```
dir = os.path.curdir()
filename = None
while True:
filename = os.path.join(dir, 'filename')
if os.path.isfile(filename):
break
updir = os.path.dirname(dir)
if updir == dir:
filename = None
break
dir = updir
```
Edit: change posixpath to os.path so that this works on Windows.
Edit x2: add code. | How to find a file upwardly in Python? | [
"",
"python",
""
] |
I have a pretty new code base written in C++. Already I'm starting to see some bad practices creeping into the project (class file with 1000+ lines of code, functions with a lot of parameters, ...).
I would like to stop on these right away with some automated tools which can hook into the build and check for poor coding practices. What suggestions do you have for such tools? I'm interested in metrics but really more interested in a stylistic sort of lint which would highlight functions with 37 parameters. | As with the others I'm not sure of a tool that will judge style. But [CCCC](http://freshmeat.net/projects/cccc/) will produce numerous metrics that can help you find the trouble spots. Metrics like cyclomatic complexity will give you quantitative evidence where the problem spots are. The downside is that you will have to incorporate these metrics with a style guide that you adopt or create on your own. | I'm sorry I can't help you with respect to style, but a great metrics tool which supports C++ and is [free: SourceMonitor](http://www.campwoodsw.com/sourcemonitor.html).
In particular, you will get good info like Cyclomatic Complexity (which I find of more value for bad programming practice than number of parameters), as well as lines of code, percentage of comments, longest function, etc.
Give it a try -- and it is very fast as well. | Code metrics and warnings for C++ | [
"",
"c++",
"code-metrics",
""
] |
How to do intersection and union for sets of the type tr1::unordered\_set in c++? I can't find much reference about it.
Any reference and code will be highly appreciated. Thank you very much.
Update: I just guessed the tr1::unordered\_set should provide the function for intersection, union, difference.. Since that's the basic operation of sets.
Of course I can write a function by myself, but I just wonder if there are built in function from tr1.
Thank you very much. | I see that `set_intersection()` et al. from the `algorithm` header won't work as they explicitly require their inputs to be sorted -- guess you ruled them out already.
It occurs to me that the "naive" approach of iterating through hash A and looking up every element in hash B should actually give you near-optimal performance, since successive lookups in hash B will be going to the same hash bucket (assuming that both hashes are using the same hash function). That should give you decent memory locality, even though these buckets are almost certainly implemented as linked lists.
Here's some code for `unordered_set_difference()`, you can tweak it to make the versions for set union and set difference:
```
template <typename InIt1, typename InIt2, typename OutIt>
OutIt unordered_set_intersection(InIt1 b1, InIt1 e1, InIt2 b2, InIt2 e2, OutIt out) {
while (!(b1 == e1)) {
if (!(std::find(b2, e2, *b1) == e2)) {
*out = *b1;
++out;
}
++b1;
}
return out;
}
```
Assuming you have two `unordered_set`s, `x` and `y`, you can put their intersection in `z` using:
```
unordered_set_intersection(
x.begin(), x.end(),
y.begin(), y.end(),
inserter(z, z.begin())
);
```
Unlike [bdonlan's answer](https://stackoverflow.com/questions/896155/c-tr1unorderedset-union-and-intersection/896398#896398), **this will actually work for any key types, and any combination of container types** (although using `set_intersection()` will of course be faster if the source containers are sorted).
NOTE: If bucket occupancies are high, it's probably faster to copy each hash into a `vector`, sort them and `set_intersection()` them there, since searching within a bucket containing n elements is O(n). | There's nothing much to it - for intersect, just go through every element of one and ensure it's in the other. For union, add all items from both input sets.
For example:
```
void us_isect(std::tr1::unordered_set<int> &out,
const std::tr1::unordered_set<int> &in1,
const std::tr1::unordered_set<int> &in2)
{
out.clear();
if (in2.size() < in1.size()) {
us_isect(out, in2, in1);
return;
}
for (std::tr1::unordered_set<int>::const_iterator it = in1.begin(); it != in1.end(); it++)
{
if (in2.find(*it) != in2.end())
out.insert(*it);
}
}
void us_union(std::tr1::unordered_set<int> &out,
const std::tr1::unordered_set<int> &in1,
const std::tr1::unordered_set<int> &in2)
{
out.clear();
out.insert(in1.begin(), in1.end());
out.insert(in2.begin(), in2.end());
}
``` | tr1::unordered_set union and intersection | [
"",
"c++",
"set",
"tr1",
""
] |
I'm building a tiny webapplication in which our customers can update some details about their company. The customers currently don't have a login/password and we don't want to validate their registration, so we want to give them a automaticly generated password/key to login to the website.
Our plan to encrypt their customerId and give that to the customer so that he can enter that key on the webapp to allow us to decrypt the key into his ID.
There are about 10K customers and they don't all have an email, so some will receive a letter with the URL and the code. This means that the customer has to type the code in, so the code can't be more than 8 characters (preferably 6).
Here's an empty template:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int passwordLength = 6;
int customerId = 12345;
string encrypted = Crypter.Encrypt(customerId, "secretKey", passwordLength);
if (customerId == Crypter.Decrypt(encrypted, "secretKey"))
{
Console.WriteLine("It worked! Well done!");
}
}
}
public static class Crypter
{
public static string Encrypt(int input, string key, int passwordLength)
{
string encryptedString = "";
//do encrypt stuffz here
return encryptedString;
}
public static int Decrypt(string encryoted, string key)
{
int decrypted = 0;
//do decrypt stuffz here
return decrypted;
}
}
}
```
**=> Can anyone link me to more information on how to do this?**
I'm not looking for a "plz send me teh codez" but if anyone has already made something like this, feel free to share.
Thanks in advance for any information. | Firstly, I'm not sure if your idea is a very good one. However, putting that aside for a moment, I'm not sure you really need to encrypt/decrypt anything.
What you're saying is that you'll take some internal customer ID and turn it into some other ID (in your case, and encrypted version of the internal customer ID). Why not just create 2 keys - an internal customer ID (the one you keep in your database and use as the primary key) and external customer ID.(another 8 digit unique key that is used as an alternative). You store both in your database and when they "login" you lookup based upon the later.
I would as you you this though: What stops someone guessing your 6 or 8 digit keys. Regardless of whether they're encrypted IDs of just some random set of characters, with only 6 or 8 digits it won't take long for someone to run an attack on your site and guess someones key. The very fact that you're going to format these keys into exactly 6 or 8 digits makes the attacker's job easier.
I think you'd be better of sending out this 8 digit key, getting the user to enter some info that you already know (their name, e-mail address, company name etc) and then getting them to define a userid/login of their choice. | Don't base your secret code on user ID. Instead, generate a random 6 character string for each customer and store it in the database. It's not vulnerable to finding the actual algorithm. | 2-way encryption from int into a short string | [
"",
"c#",
".net",
"asp.net",
"cryptography",
"passwords",
""
] |
using Ruby or Python, does someone know how to draw on the screen, covering up any other window? Kind of like, press a key, and the program will show current weather or stock quote on the screen (using the whole screen as the canvas), and then press the key again, and everything restores to the same as before? (like Mac OS X's dash board). | You could use the systems dashboard (desktop widgets, or whatever it's called) API. In order to do that you need bindings to it for Python or Ruby.
Alternatively you could use some generic gui toolkit or application framework and just create a frameless window with transparent background. Then you need to be sure that the chosen toolkit supports 'always-on-top' options on your desired platform(s). | If you are on windows you can directly draw to desktop dc(device context) using win32api
e.g. just for fun try this :)
```
>>> import win32ui
>>> import win32gui
>>> hdc = win32ui.CreateDCFromHandle( win32gui.GetDC( 0 ) )
>>> hdc.DrawText("Wow it works", (100, 100, 200, 200))
>>> hdc.LineTo(500,500)
```
but that won't be very useful ,as not erasable
best bet would be to use a transparent window or window with a cutout region (atleast on windows that is possible)
or even if you can't draw transparent on some system you can grab the current screen and display it as background of you window that would give a transparent effect | does someone know how to show content on screen (covering up any window) using Ruby or Python? | [
"",
"python",
"ruby",
"user-interface",
""
] |
i'm struggling a bit with repositories. I'm using C# and NHibernate. The question i have is : how much should my repository do before it calls a save or a get?
For example i have a user class which is an aggregate root. I want to call a method called "register" which will add the user and set some default values based on business rules and create some other entities which are also sub parts of the "user" root (ie address, groups, etc) . Should i call
```
userRepo.Register(newUser);
```
which would be(ignoring the obvious issues):
```
Regsiter(User newUser){
newUser.SomeProp = "Default Data";
Group g= new Group;
g.SomeProp2 = "Default Data";
newUser.Groups.Add(g);
Session.Save(g);
Session.Save(newUser);
}
```
or should i have put register in a business layer and have it do:
```
Regsiter(User newUser){
newUser.SomeProp = "Default Data";
Group g= new Group;
g.SomeProp2 = "Default Data";
newUser.Groups.Add(g);
userRepo.Register(newUser, g);// this does session.save on both objects.
}
```
Both seems slightly wrong.
What's the correct approach?
edit -------------------------------
thanks for all the responses. I can't decide who is the most right and therefore which answer to accept.
Generally everyone is saying put the business rules in another layer. that makes sense but i'm unsure about the data calls for groups - since groups aren't an aggregate root they shouldn't have their own repository so how do i go about adding and saving them? In my project adding a group to the user's group collection doesn't automatically create the group in the db; i also need to call session.save on the object. so do i put that into the user repo as userRepo.SaveGroup(g)?
If i have a createGroup() in the other layer then it'll either need to use it's own repo or the users. or am i being thick? | Determine where you want your Register method, maybe in a UserServices class. You can delegate object creation to a UserFactory. In a CreateNewUser() method, set up your defaults for the user and the Groups collection. Then call UserRepository.Save(newUser) to persist the data.
```
// UserServices class
public void Register(User newUser)
{
// add custom registration stuff.
_userRepository.Save(newUser);
}
// Application code
User user = UserFactory.CreateNewUser();
_userServices.Register(user);
// UserFactory
public User CreateNewUser()
{
// all new user, group creation
}
``` | Personally, I keep the repository pattern as a substitute for sprocs. So my repository would have methods like `getById(int id)`, `save()`, `add(DomainObject obj)` etc.
In a business tier, I'd have userManager.registerUser(string username, /\* params, etc \*/). This would create the domain object. This method would just call the `add()` method in the data tier.
In short, the business tier is business-y, and the data tier is data-y. | How much logic should i put my repository methods when using repository pattern? | [
"",
"c#",
"nhibernate",
"domain-driven-design",
"repository-pattern",
"repository",
""
] |
Is there any way to execute perl code without having to use Runtime.getRuntime.exec("..."); (parse in java app)? | I've been looking into this myself recently. The most promising thing I've found thus far is the [Inline::Java](http://search.cpan.org/perldoc?Inline::Java) module on CPAN. It allows calling Java from Perl but also (via some included Java classes) calling Perl from Java. | [this](http://www.perlmonks.org/index.pl?node_id=373839) looks like what you're asking for | Include Perl in Java | [
"",
"java",
"perl",
"include",
""
] |
I know this has been asked before but there is really not a clear answer. My problem is I built a file upload script for GAE and only found out after, that you can only store files up to aprox. 1MB in the data store. I can stop you right here if you can tell me that if I enable billing the 1MB limit is history but I doubt it.
I need to be able to upload up to 20mb per file so I thought maybe I can use Amazon's S3. Any ideas on how to accomplish this?
I was told to use a combination of GAE + Ec2 and S3 but I have no idea how this would work.
Thanks,
Max | From the [Amazon S3 documentation](http://docs.amazonwebservices.com/AmazonS3/2006-03-01/UsingHTTPPOST.html):
1. The user opens a web browser and accesses your web page.
2. Your web page contains an HTTP form that contains all the information necessary for the user to upload content to Amazon S3.
3. The user uploads content directly to Amazon S3.
GAE prepares and serves the web page, a speedy operation. You user uploads to S3, a lengthy operation, but that is between your user's browser and Amazon; GAE is not involved.
Part of the S3 protocol is a *success\_action\_redirect*, that lets you tell S3 where to aim the browser in the event of a successful upload. That redirect can be to GAE. | Google App Engine and EC2 are competitors. They do the same thing, although GAE provides an environment for your app to run in with strict language restrictions, while EC2 provides you a virtual machine ( think VMWare ) on which to host your application.
S3 on the other hand is a raw storage api. You can use a SOAP or REST api to access it. If you want to stick with GAE, you can simply use the [Amazon S3 Python Library](http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134) to make REST calls from Python to S3.
You will, of course, have to pay for usage on S3. Its amazing how granular their billing is. When getting started I was literally charged 4 cents one month. | Google App Engine and Amazon S3 File Uploads | [
"",
"python",
"google-app-engine",
"amazon-s3",
"amazon-ec2",
""
] |
I am new to programming, I was wondering if there is a way to find the java classes I need for a particular thing other than asking people for them on forums? I have seen the APIs on sun website but there is no good search option to find the class that will work for me. | If you're new to Java (or programming), it's going to be important to learn how to read and understand the documentation in order to become self-reliant -- it's the first step to getting less dependent from other people, and in most cases, will improve your learning and programming speed.
The following are some tips and suggestions:
**Get to know the [Java API Specification](http://java.sun.com/javase/6/docs/api/).**
At first, the Javadoc format of the API Specification seem a little bit underpowered without any search ability, but I've found that to be that being able to browse the documentation with a browser to be very powerful.
Since the Javadocs are just HTML files, they can be easily viewed and navigated in a browser, and bookmarking pages are easy as well. Also, [the API Specification is available for download](http://java.sun.com/javase/downloads/index.jsp), so it not necessary to always go to the web to get information.
As the documentation is just web pages, using the Find feature of the browser can find information quickly in a page, and if that fails, using Google or your favorite search engine to find documentation is very fast and easy.
**Google (or your favorite search engine) is your friend.**
Need information on the `StringBuilder` class? Try the following query:
[`stringbuilder java 6`](http://www.google.com/#hl=en&q=stringbuilder+java+6)
The first result will be the Java API Specification page for the [`StringBuilder`](http://java.sun.com/javase/6/docs/api/java/lang/StringBuilder.html) class. The tip is to append the string "`java 6`" at the end of the query and that seems to bring the API Specification to the top most of the time.
**Get comfortable with the structure of the API Specification.**
The presentation structure of the [Javadoc](http://java.sun.com/j2se/javadoc/) tool is very nice and logical:
```
+-----------+-------------------+
| | |
| Packages | |
| | |
+-----------+ Details |
| | |
| Classes | |
| | |
+-----------+-------------------+
```
The Javadoc is partitioned into three frames.
* Top-left frame: Listing of all the packages of the Java platform API.
* Bottom-left frame: Listing of all the classes in the selected package.
* Right frame: Details of the currently selected package or class.
Generally, looking for a class starts from selecting a package from the top-left hand frame, then looking for the class in the bottom-left frame, and finally browsing through the details on the right hand frame. The idea is:
```
Package -> Class -> Details
```
The details in the right hand frame for the classes and packages are also very structured. For classes, the structure are as follows:
* Class name
* Inheritance hierarchy
* Implemented interfaces
* Related classes
* Information on and description of the class; usage examples.
* Field summary
* Constructor summary
* Method summary
* Field/Constructor/Method details.
When I'm looking for information on a method, I will scroll down to the Method Summary, find the method I want, and click on that method name which will jump to the Method Details.
Also, everything about the class is documented in one page -- it may seem like it is too much information for one page, but it does make it easy to get all the information you need about the class from one location. In other documentation formats, it may be necessary to flip between multiple pages to get information about several methods in the same class. With the Javadoc format, it's all in one page.
**Learn the Java Platform API**
The next step is to learn the important packages of the Java Platform API. This will aid in quickly finding classes from the huge collection of classes in the platform API.
**Don't worry, take it slow -- you don't need to learn everything at once!**
Some packages of interest are:
* **`java.lang`** -- Contains the classes such as `String`, `System`, `Integer`, and other that are automatically imported in every Java program.
* **`java.util`** -- Contains the Java collections (such as `List`, `Set`, `Map` and their implementations), `Date`, `Random` and other utilitarian classes. This is probably the first package to go to in order to find classes that will be useful in performing common operations.
* **`java.io`** -- Classes concerning with input and output, such as `File`, `Reader`s and `Writer`s and the various `Stream`s.
* **`java.awt`** and **`javax.swing`** -- For graphical user interfaces, Java uses Abstract Window Toolkit or Swing, and those two packages are used to deal with GUIs in Java.
Knowing where classes are and starting to get a feel of where to look in the vast amount of documentation will make it easier to find information. It will probably take a while to get used to it, but once you get a hang of it, it should be much easier, and you'll be able to find the information on your own.
Good luck! | Most of the times if it is in the core of the language ( that is not a 3rd party library ) I use the following link:
<http://java.sun.com/javase/6/docs/api/allclasses-frame.html>
Which list all the classes in Java SE.
To know if the class may work or not I try by pressing Ctrl-F and guess what class would be the appropiate.
Eventually with time, when you get used to the classes there are, the search will be easier.
For instance, let's say you want to use an array:
Ctrl+F Array yields:
```
Array
Array
ArrayBlockingQueue
ArrayDeque
ArrayIndexOutOfBoundsException
ArrayList
Arrays
ArrayStoreException
ArrayType
ArrayType
```
I click on each one and see the documentation. Some of them make no sense, some of them are exactly what I need.
Sometimes it may not work very straight forward. Lets way how to create a Window:
Ctrl+F don't show JFrame which is the correct answer, but it is just matter of tunning your sense :)
I hope this helps. | how to find java classes? | [
"",
"java",
"class-library",
""
] |
This code illustrates something that I think should be treated as bad practice, and elicit warnings from a compiler about redefining or masking a variable:
```
#include <iostream>
int *a;
int* f()
{
int *a = new int;
return a;
}
int main()
{
std::cout << a << std::endl << f() << std::endl;
return 0;
}
```
Its output (compiled with g++):
```
0
0x602010
```
I've looked at a couple references (Stroustrup and The Complete C++ Reference) and can't find anything about when and why this is allowed. I know that it's not within a single local scope, though.
When and why is this allowed? Is there a good use for this construct? How can I get g++ to warn me about it? Do other compilers squawk about it? | It's allowed so that you can safely ignore global identifier overriding. Essentially, you only have to be concerned with global names you actually use.
Suppose, in your example, `f()` had been defined first. Then some other developer added the global declaration. By adding a name, `f()` which used to work, still works. If overriding was an error, then the function would suddenly stop working, even though it doesn't do anything at all with the newly added global variable. | As to why this is allowed: this is perfectly valid.
When you are within your f() function, you're defining a local scope. Local scopes override the global scope, so defining your "a" variable there "hides" the global `int *a;` | In C++, when can two variables of the same name be visible in the same scope? | [
"",
"c++",
"standards",
"warnings",
"compiler-warnings",
""
] |
Basically what I want to do is, depending on the some variable, to cast a void pointer into a different datatype. For example (the 'cast' variable is just something in order to get my point across):
```
void* ptr = some data;
int temp = some data;
int i = 0;
...
if(temp == 32) cast = (uint32*)
else if(temp == 16) cast = (uint16*)
else cast = (uint8*)
i = someArray[*((cast)ptr)];
```
Is there anything in C++ that can do something like this (since you can't actually assign a variable to be just (uint32\*) or something similar)? I apologize if this isn't clear, any help would be greatly appreciated. | The "correct" way:
```
union MyUnion
{
uint32 asUint32;
uint16 asUint16;
uint8 asUint8;
}
uint32 to_index(int size, MyUnion* ptr)
{
if (size== 32) return ptr->asUint32;
if (size== 16) return ptr->asUint16;
if (size== 8) return ptr->asUint8;
}
i = someArray[to_index(temp,ptr)]
```
[update: fixed dumb typo] | Clearly, [`boost::variant`](http://www.boost.org/doc/libs/1_39_0/doc/html/variant.html) is the way to go. It *already* stores a type-tag that makes it impossible for you to cast to the wrong type, ensuring this using the help of the compiler. Here is how it works
```
typedef boost::variant<uint32_t*, uint16_t*, uint8_t*> v_type;
// this will get a 32bit value, regardless of what is contained. Never overflows
struct PromotingVisitor : boost::static_visitor<uint32_t> {
template<typename T> uint32_t operator()(T* t) const { return *t; }
};
v_type v(some_ptr); // may be either of the three pointers
// automatically figures out what pointer is stored, calls operator() with
// the correct type, and returns the result as an uint32_t.
int i = someArray[boost::apply_visitor(PromotingVisitor(), v)];
``` | Casting void pointers, depending on data (C++) | [
"",
"c++",
"casting",
"void-pointers",
""
] |
This was a hard question for me to summarize so we may need to edit this a bit.
## Background
About four years ago, we had to translate our asp.net application for our clients in Mexico. Extensibility and scalability were not that much of a concern at the time (oh yes, I just said those dreadful words) because we only have U.S. and Mexican customers.
Rather than use resource files, we replaced every single piece of static text in our application with some type of server control (asp.net label for example). We store each and every English word in a SQL database. We have added the ability to translate the English text into another language and also can add cultural overrides. For example, **hello** can be translated to **¡hola!** in one language and overridden to **¡bueno!** in a different culture. The business has full control over these translations because will built management utilities for them to control everything. The translation kicks in when we detect that the user has a browser culture other than en-us. Every form descends from a base form that iterates through each server control and executes a translation (translation data is stored as a datatable in an application variable for a culture). I'm still amazed at how fast the control iteration is.
## The problem
The business is very happy with how the translations work. In addition to the static content that I mentioned above, the business now wants to have certain data translated as well. System notes are a good example of a translation they want. Example "*Sent Letter #XXXX* to Customer" - the business wants the "Sent Letter to Customer" text translated based on their browser culture.
I have read a couple of other posts on SO that talk about localization but they don't address my problem. How do you translate a phrase that is dynamically generated? I could easily read the English text and translate "Sent", "Letter", "to" and "Customer", but I guarantee that it will look stupid to the end user because it's a phrase. The dynamic part of the system-generated note would screw up any look-ups that we perform on the phrase if we stored the phrase in English, less the dynamic text.
One thought I had... We don't have a table of system generated note types. I suppose we could create one that had placeholders for dynamic data and the translation engine would ignore the placeholder markers. The problem with this approach is that our SQL server database is a replication of an old pick database and we don't really know all the types of system generated phrases (They are deep in the pic code base, in subroutines, control files, etc.). Things like notes, ticklers, and payment rejection reasons are all stored differently. Trying to normalize this data has proven difficult. It would be a huge effort to go back and identify and change every pick program that generated a message.
[This question](https://stackoverflow.com/questions/359870/localizing-system-generated-status-messages) is very close; but I'm not dealing with just system-generated status messages but rather an infinite number of phrases and types of phrases with no central generation mechanism.
Any ideas? | The lack of a "bottleneck" -- what you identify as the (missing) "central generation mechanism" -- is the architectural problem in this situation. Ideally, rearchitecting to put such a bottleneck in place (so you can keep using your general approach with a database of culture-appropriate renditions of messages, just with "placeholders" for e.g. the #XXXX in your example) would be best.
If that's just unfeasible, you can place the "bottleneck" at the other end of the pipe -- when a message is about to be emitted. At that point, or few points, you need to try and match the (English) string that's about to be emitted with a series of well-crafted regular expressions (with "placeholders" typically like `(.*?)`...) and thereby identify the appropriate key for the DB lookup. Yes, that **still** is a lot of work, but at least it should be feasible without the issues you mention wrt old translated pick code. | In a pinch I suppose you could try something like [foisting the job off onto Google](http://code.google.com/p/google-api-translate-java/) if you don't have a translation on hand for a particular phrase, and stashing the translation for later.
Stashing the translations for later provides both a data collection point for building a message catalog and a rough (if sometimes [laughably](http://tvtropes.org/pmwiki/pmwiki.php/Main/TheVodkaIsGoodButTheMeatIsRotten) [wonky](http://catb.org/~esr/jargon/html/W/wonky.html)) dynamically built starter set of translations. Once you begin the process, track which translations have been reviewed and how frequently each have been hit. Frequently hit machine translations can then be reviewed and refined. | Localizing data that is generated dynamically | [
"",
"c#",
"asp.net",
"sql-server",
"localization",
""
] |
I'm using a simple PHP library to add documents to a SOLR index, via HTTP.
There are 3 servers involved, currently:
1. The PHP box running the indexing job
2. A database box holding the data being indexed
3. The solr box.
At 80 documents/sec (out of 1 million docs), I'm noticing an unusually high interrupt rate on the network interfaces on the PHP and solr boxes (2000/sec; what's more, the graphs are nearly identical -- when the interrupt rate on the PHP box spikes, it also spikes on the Solr box), but much less so on the database box (300/sec). I imagine this is simply because I open and reuse a single connection to the database server, but every single Solr request is currently opening a new HTTP connection via cURL, thanks to the way the Solr client library is written.
So, my question is:
1. Can cURL be made to open a keepalive session?
2. What does it take to reuse a connection? -- is it as simple as reusing the cURL handle resource?
3. Do I need to set any special cURL options? (e.g. force HTTP 1.1?)
4. Are there any gotchas with cURL keepalive connections? This script runs for hours at a time; will I be able to use a single connection, or will I need to periodically reconnect? | cURL PHP documentation ([curl\_setopt](http://www.php.net/manual/en/function.curl-setopt.php)) says:
> `CURLOPT_FORBID_REUSE` - `TRUE` to force
> the connection to explicitly close
> when it has finished processing, and
> not be pooled for reuse.
So:
1. Yes, actually it should re-use connections by default, as long as you re-use the cURL handle.
2. by default, cURL handles persistent connections by itself; should you need some special headers, check CURLOPT\_HTTPHEADER
3. the server may send a keep-alive timeout (with default Apache install, it is 15 seconds or 100 requests, whichever comes first) - but cURL will just open another connection when that happens. | Curl sends the keep-alive header by default, but:
1. create a context using `curl_init()` without any parameters.
2. store the context in a scope where it will survive (not a local var)
3. use `CURLOPT_URL` option to pass the url to the context
4. execute the request using `curl_exec()`
5. don't close the connection with `curl_close()`
very basic example:
```
function get($url) {
global $context;
curl_setopt($context, CURLOPT_URL, $url);
return curl_exec($context);
}
$context = curl_init();
//multiple calls to get() here
curl_close($context);
``` | Persistent/keepalive HTTP with the PHP Curl library? | [
"",
"php",
"http",
"curl",
"libcurl",
"keep-alive",
""
] |
I have an array or a list from linq. I want to show it as a string in console! What should I do? | The most generic answer that I can give to you is to loop through each element and use the `ToString()` method on each element.
Alternatively, you can serialize the Array/List to Xml. | ```
String.Join(delimiter, array);
```
You could represent it as:
```
Console.WriteLine("{" + String.Join(", ", array) + "}");
```
Of course, I think this only works with strings. | Represent array in C# | [
"",
"c#",
"arrays",
""
] |
I was reading the Essential C# 3.0 book and am wondering if this is a good way to check delegates for null?:
```
class Thermostat
{
public delegate void TemperatureChangeHandler ( float newTemperature );
public TemperatureChangeHandler OnTemperatureChange { get; set; }
float currentTemperature;
public float CurrentTemperature
{
get { return this.currentTemperature; }
set
{
if ( currentTemperature != value )
{
currentTemperature = value;
TemperatureChangeHandler handler = OnTemperatureChange;
if ( handler != null )
{
handler ( value );
}
}
}
}
}
```
Does the solution changes if the type is immutable? I figured maybe with immutability you wouldn't run into this threading problem. | ## Original (somewhat inaccurate) Response:
There has been much discussion on this.
In short: you can't guarantee that the handler will be valid even by doing this copy/check for null/ execute step.
The problem is, if OnTemperatureChange is unregistered between the time you copy it, and the time you execute the copy, then it's probably true that you don't want the listener to be executed anyway.
You may as well just do:
```
if (OnTemperatureChange != null )
{
OnTemperatureChange ( value );
}
```
And handle a null reference exception.
I sometimes add a default handler that does nothing, just to prevent the null reference exception, but that adds performance impact quite seriously, especially in the case where there is no other handler registered.
## Update 2014-07-10:
I defer to [Eric Lippert](https://web.archive.org/web/20161214085852/https://blogs.msdn.microsoft.com/ericlippert/2009/04/29/events-and-races/).
My original response did allude to using default handlers, but I didn't recommend using a temp variable, which I now agree as good practice also, per the article. | Use a question mark for a conditional access:
```
OnTemperatureChange?.Invoke();
```
> The null-conditional operators are short-circuiting. That is, if one
> operation in a chain of conditional member or element access
> operations returns null, the rest of the chain doesn't execute. | Checking delegates for null | [
"",
"c#",
".net",
"delegates",
""
] |
I'm looking at creating a helper method to set an exception's message, automatically setting String.Format, adding in inner exceptions, setting commandline exit codes, etc; something like:
```
public static void MyExceptionHelper(ExitCode code, string message) {}
public static void MyExceptionHelper(ExitCode code, Exception e) {}
public static void MyExceptionHelper(ExitCode code, Exception e, String message) {}
public static void MyExceptionHelper(ExitCode code, Exception e, String message, params object[] args) {}
// etc...
```
The BCL has got a few static classes around that does that sort of thing (eg System.ThrowHelper in mscorlib).
Where is the best place to put these? As overloaded constructors on the exception, in a separate static class (like the BCL), as static methods on the exception itself, or somewhere else? | For methods like this, I prefer overloaded constructors. You're clearly using it to create a new object, and that's what a constructor is for.
Once you get into the world of static methods, it's not always clear where they should end up. You'll need to analyze who will use them and how they will be used, then examine the pros and cons of each potential location. Then, you will know where to put them. | I'd recommend the Exception application block in [EnterpriseLibrary](http://msdn.microsoft.com/en-us/library/cc467894.aspx), it has a very elegant design for dealing with exceptions and if you don't want all of EntLib I'd recommend copying their interface. | How to create exception helpers? | [
"",
"c#",
".net",
"exception",
""
] |
I'm trying to think of a regular expression for this but not having any luck..
Let's say you have a security question on you website so the person can recover a password. People often forget exactly how they entered information. For example, given the question "What company do you work for?", a user might answer "Microsoft Corp.". But a month later when they are prompted to answer this question, they might type in "Microsoft", which wouldn't match their original answer even though they clearly answered correctly.
"Microsoft Corp." or "Microsoft Inc." or "Microsoft Co." would match "Microsoft", and "questar gas" would match "Questar Gas Co.". "Bank Corp. of America" would NOT match "Bank of America" because the word "Corp." is not at the end of the string.
What is the best way to accomplish this? | I wouldn't worry too much about people changing their answers. People are remarkably consistant in how they answer these kinds of questions. If I know your first job was at Microsoft, the fact that I type it slightly differently may suggest that I'm an attacker.
Avoid placing plaintext answers in your database. This is similar to storing plaintext passwords, which is definately a bad idea. If your database, or a backup of the database, gets out of your control, then you have a leak of your client's private information. Maybe it won't fall into the wrong hands, but think of the email you'll have to send to your users. "Change all the sites where you answered this question the same way."
Instead, take the salted hash of the answer, and store that in the database. When the user answers the question later, use the same algorithm to hash their answer, and compare to the stored value.
You can use some normalization to minimize the effect of typos. You could convert to lowercase, and remove spaces and punctuation. For example, "Microsoft Corp." would become "microsoftcorp". That way, if a user decides to leave off the period or add another space, it would still match. | Regex matching is probably not the best way. I say you probably want to use a "string distance" algorithm, like [Levenshtein](http://en.wikipedia.org/wiki/Levenshtein_distance) or [Jaro-Winkler](http://en.wikipedia.org/wiki/Jaro-Winkler_distance) to decide how close the user's input is to the expected one.
Though, to address Victor's point about not being too *flexible*, make sure to require a very high matching threshold. | Matching partial strings for password recovering | [
"",
"java",
"regex",
""
] |
One of the [tips for `jslint` tool](http://www.jslint.com/lint.html) is:
> **`++` and `--`**
> The `++` (increment) and `--` (decrement)
> operators have been known to contribute to bad code by
> encouraging excessive trickiness. They
> are second only to faulty architecture
> in enabling to viruses and other
> security menaces. There is a plusplus
> option that prohibits the use of these
> operators.
I know that PHP constructs like `$foo[$bar++]` may easily result in off-by-one errors, but I couldn't figure out a better way to control the loop than a:
```
while( a < 10 ) do { /* foo */ a++; }
```
or
```
for (var i=0; i<10; i++) { /* foo */ }
```
Is the `jslint` highlighting them because there are some similar languages that lack the "`++`" and "`--`" syntax or handle it differently, or are there other rationales for avoiding "`++`" and "`--`" that I might be missing? | My view is to always use ++ and -- by themselves on a single line, as in:
```
i++;
array[i] = foo;
```
instead of
```
array[++i] = foo;
```
Anything beyond that can be confusing to some programmers and is just not worth it in my view. For loops are an exception, as the use of the increment operator is idiomatic and thus always clear. | There is a history in C of doing things like:
```
while (*a++ = *b++);
```
to copy a string, perhaps this is the source of the excessive trickery he is referring to.
And there's always the question of what
```
++i = i++;
```
or
```
i = i++ + ++i;
```
actually do. It's defined in some languages, and in other's there's no guarantee what will happen.
Those examples aside, I don't think there's anything more idiomatic than a for loop that uses `++` to increment. In some cases you could get away with a foreach loop, or a while loop that checked a different condtion. But contorting your code to try and avoid using incrementing is ridiculous. | Why avoid increment ("++") and decrement ("--") operators in JavaScript? | [
"",
"javascript",
"syntax",
"jslint",
"postfix-operator",
"prefix-operator",
""
] |
One problem in large C++ projects can be build times. There is some class high up in your dependency tree which you would need to work on, but usually you avoid doing so because every build takes a very long time. You don't necessarily want to change its public interface, but maybe you want to change its private members (add a cache-variable, extract a private method, ...). The problem you are facing is that in C++, even private members are declared in the public header file, so your build system needs to recompile everything.
What do you do in this situation?
I have sketched two solutions which I know of, but they both have their downsides, and maybe there is a better one I have not yet thought of. | The pimpl pattern:
In your header file, only declare the public methods and a private pointer (the pimpl-pointer or delegate) to a forward declared implementation class.
In your source, declare the implementation class, forward every public method of your public class to the delegate, and construct an instance of your pimpl class in every constructor of your public class.
Plus:
* Allows you to change the implementation of your class without having to recompile everything.
* Inheritance works well, only the syntax becomes a little different.
Minus:
* Lots and lots of stupid method bodies to write to do the delegation.
* Kind of awkward to debug since you have tons of delegates to step through.
* An extra pointer in your base class, which might be an issue if you have lots of small objects. | John Lakos' [Large Scale C++ Software Design](https://rads.stackoverflow.com/amzn/click/com/0201633620) is an excellent book that addresses the challenges involved in building large C++ projects. The problems and solutions are all grounded in reality, and certainly the above problem is discussed at length. Highly recommended. | What patterns do you use to decouple interfaces and implementation in C++? | [
"",
"c++",
"delegation",
"pimpl-idiom",
""
] |
What classes should I use in C# in order to get information about a certain computer in my network? (Like who is logged on that computer, what Operating System is running on that computer, what ports are opened etc) | WMI Library and here is a [VB.net example](http://www.siccolo.com/Articles/CodeProject/Build_Local_Network_Browser/Build_Local_Network_Browser.html). It shouldn't be difficult to convert it to C# | Checkout [System.Management](http://msdn.microsoft.com/en-us/library/system.management(loband).aspx) and [System.Management.ManagementClass](http://msdn.microsoft.com/en-us/library/system.management.managementclass.aspx). Both are used for accessing WMI, which is how to get the information in question.
**Edit:** Updated with sample to access WMI from remote computer:
```
ConnectionOptions options;
options = new ConnectionOptions();
options.Username = userID;
options.Password = password;
options.EnablePrivileges = true;
options.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope scope;
scope = new ManagementScope("\\\\" + ipAddress + "\\root\\cimv2", options);
scope.Connect();
String queryString = "SELECT PercentProcessorTime, PercentInterruptTime, InterruptsPersec FROM Win32_PerfFormattedData_PerfOS_Processor";
ObjectQuery query;
query = new ObjectQuery(queryString);
ManagementObjectSearcher objOS = new ManagementObjectSearcher(scope, query);
DataTable dt = new DataTable();
dt.Columns.Add("PercentProcessorTime");
dt.Columns.Add("PercentInterruptTime");
dt.Columns.Add("InterruptsPersec");
foreach (ManagementObject MO in objOS.Get())
{
DataRow dr = dt.NewRow();
dr["PercentProcessorTime"] = MO["PercentProcessorTime"];
dr["PercentInterruptTime"] = MO["PercentInterruptTime"];
dr["InterruptsPersec"] = MO["InterruptsPersec"];
dt.Rows.Add(dr);
}
```
*Note: userID, password, and ipAddress must all be defined to match your environment.* | C#: get information about computer in domain | [
"",
"c#",
".net",
"network-programming",
""
] |
I tried to assign a new value into the hidden input and checkbox of an input form. It's working fine in Firefox but not in IE (I'm using IE 7). Does anyone know what is wrong with my code?
HTML:
```
<input type="hidden" id="msg" name="msg" value="" style="display:none"/>
<input type="checkbox" name="sp" value="100" id="sp_100">
```
Javascript:
```
var Msg="abc";
document.getElementById('msg').value = Msg;
document.getElementById('sp_100').checked = true;
``` | Have a look at [jQuery](http://www.jquery.com/), a cross-browser library that will make your life a lot easier.
```
var msg = 'abc';
$('#msg').val(msg);
$('#sp_100').attr('checked', 'checked');
``` | For non-grouped elements, name and id should be same. In this case you gave name as 'sp' and id as 'sp\_100'. Don't do that, do it like this:
HTML:
```
<input type="hidden" id="msg" name="msg" value="" style="display:none"/>
<input type="checkbox" name="sp" value="100" id="sp">
```
Javascript:
```
var Msg="abc";
document.getElementById('msg').value = Msg;
document.getElementById('sp').checked = true;
```
For more details
please visit : <http://www.impressivewebs.com/avoiding-problems-with-javascript-getelementbyid-method-in-internet-explorer-7/> | document.getElementById().value and document.getElementById().checked not working for IE | [
"",
"javascript",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.