Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm using parallel linq, and I'm trying to download many urls concurrently using essentily code like this:
```
int threads = 10;
Dictionary<string, string> results = urls.AsParallel( threads ).ToDictionary( url => url, url => GetPage( url );
```
Since downloading web pages is Network bound rather than CPU bound, using more threads than my number of processors/cores is very benificial, since most of the time in each thread is spent waiting for the network to catch up. However, judging form the fact that running the above with threads = 2 has the same performance as threads = 10 on my dual core machine, I'm thinking that the treads sent to AsParallel is limited to the number of cores.
Is there any way to override this behavior? Is there a similar library available that doesn't have this limitation?
(I've found such a library for python, but need something that works in .Net) | Do the URLs refer to the same server? If so, it could be that you are hitting the HTTP connection limit instead of the threading limit. There's an easy way to tell - change your code to:
```
int threads = 10;
Dictionary<string, string> results = urls.AsParallel(threads)
.ToDictionary(url => url,
url => {
Console.WriteLine("On thread {0}",
Thread.CurrentThread.ManagedThreadId);
return GetPage(url);
});
```
EDIT: Hmm. I can't get `ToDictionary()` to parallelise *at all* with a bit of sample code. It works fine for `Select(url => GetPage(url))` but not `ToDictionary`. Will search around a bit.
EDIT: Okay, I still can't get `ToDictionary` to parallelise, but you can work around that. Here's a short but complete program:
```
using System;
using System.Collections.Generic;
using System.Threading;
using System.Linq;
using System.Linq.Parallel;
public class Test
{
static void Main()
{
var urls = Enumerable.Range(0, 100).Select(i => i.ToString());
int threads = 10;
Dictionary<string, string> results = urls.AsParallel(threads)
.Select(url => new { Url=url, Page=GetPage(url) })
.ToDictionary(x => x.Url, x => x.Page);
}
static string GetPage(string x)
{
Console.WriteLine("On thread {0} getting {1}",
Thread.CurrentThread.ManagedThreadId, x);
Thread.Sleep(2000);
return x;
}
}
```
So, how many threads does this use? 5. Why? Goodness knows. I've got 2 processors, so that's not it - and we've specified 10 threads, so that's not it. It still uses 5 even if I change `GetPage` to hammer the CPU.
If you only need to use this for one particular task - and you don't mind slightly smelly code - you might be best off implementing it yourself, to be honest. | By default, .Net has limit of 2 concurrent connections to an end service point (IP:port). Thats why you would not see a difference if all urls are to one and the same server.
It can be controlled using [ServicePointManager.DefaultPersistentConnectionLimit](http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.defaultpersistentconnectionlimit.aspx) property. | Parallel Linq - Use more threads than processors (for non-CPU bound tasks) | [
"",
"c#",
"linq",
"multithreading",
""
] |
I should have paid more attention in relational databases class, so I need some help.
I have a table structured like so (there's more, but I'm only posting relevant info):
```
+------------------+-------------+------+-----+-------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------+-------------+------+-----+-------------------+-------+
| session_id | char(32) | NO | | NULL | |
| file | varchar(30) | NO | | NULL | |
| access_time | timestamp | NO | | CURRENT_TIMESTAMP | |
+------------------+-------------+------+-----+-------------------+-------+`
```
I want to select the `file` field of the record with the greatest `access_time` for each `session_id`. So pretty much the last page visited in each session.
I've tried countless combinations of DISTINCT and the GROUP BY clause, but I can't seem to wrap my head around it for some reason. I'm using MySQL. Help please. | I know this will work in SQL Server, and it should port to MySQL.
```
select session_id, timestamp, file
from table t1
join (select session_id, max(timestamp) as timestamp)
from table group by session_id) as t2
on t1.session_id = t2.session_id
and t1.timestamp = t2.timestamp
``` | ```
select * from my_table t1
where t1.access_time = (
select max(t2.access_time)
from my_table t2
where t2.session_id = t1.session_id
)
``` | Select newest record matching session_id | [
"",
"sql",
"mysql",
""
] |
I'm trying to use [CruiseControl 2.7.3](http://cruisecontrol.sourceforge.net/index.html), (the original), to build a Java project that is in an SVN repository.
My cruise configuration is using the [svn plugin](http://cruisecontrol.sourceforge.net/main/configxml.html#svn) for the modification set. When a modification is detected, a build is scheduled using Ant. That Ant build file then uses the svnant Ant Task to do a complete checkout of the project. For a while, we had this set to just checkout "HEAD", but we've had cases where the build won't fire for a check in or two because the checkin occurred after the modification set check, but before the ant call to svn checkout. As a result, we are trying to change the ant build file to use the revision number that the modification check retrieves.
The CruiseControl Configuration Reference page claims that a property, [svnrevision](http://cruisecontrol.sourceforge.net/main/configxml.html#svn), is set and passed to the builders, just like the label property is by the [labelincrementers](http://cruisecontrol.sourceforge.net/main/configxml.html#labelincrementer). It appears to not be set when I press the **force build** button.
Is there something I need to do to make this go? | Looking at the code for the SVN source control it seems that svnrevision should be passed along to the builder, and thus along to your Ant invocation. Have you tried using the property from your Ant script?
In response to the question in the comment:
That's because in the force build case there was no modification, so there's no modification revision number. In that case the svnlabelincrementer will pass the latest revision number for what you have locally, which will also be the latest. | Can you use the quietperiod setting? After a commit, CruiseControl can wait for some amount of time (say, 30 seconds) before kicking off a build.
It won't fire off individual builds for each commit. Rather, commits around the same time will kick off a single build. | Using SVN with CruiseControl? | [
"",
"java",
"svn",
"continuous-integration",
"cruisecontrol",
""
] |
So I'm receiving data over a socket using a buffer (byte[]) of size 1024, and I want to combine the reads together to form the entire packet in the event that they're bigger than 1024 bytes. I chose a List to store the entire packet, and what I want to do is add each buffer read to it as it comes in. I'd want to do:
```
List.AddRange(Buffer);
```
But in the event that the buffer isn't full a bunch of empty bytes would get padded to the end. So naturally what I would want to do is add only a certain range of bytes to the List, but there is no such method. I could always create a temporary byte array of exactly the number of bytes that were received and then use AddRange() and get the result I want, but it just seems stupid to me. Not to mention it would be creating then throwing away an array on each read of data, which wouldn't be good for performance on a scalable multiuser server.
Is there a way to do this with a List? Or is there some other data structure I can use? | If you're using C# 3.5 (LINQ)
```
list.AddRange(buffer.Take(count));
``` | Do you *actually* need the result to be a `List<byte>`? What are you going to do with it afterwards? If you *really* only need an `IEnumerable<byte>` I'd suggest creating something like this:
```
using System;
using System.Collections;
using System.Collections.Generic;
public class ArraySegmentConcatenator<T> : IEnumerable<T>
{
private readonly List<ArraySegment<T>> segments =
new List<ArraySegment<T>>();
public IEnumerator<T> GetEnumerator()
{
foreach (ArraySegment<T> segment in segments)
{
for (int i=0; i < segment.Count; i++)
{
yield return segment.Array[i+segment.Offset];
}
}
}
public void Add(ArraySegment<T> segment)
{
segments.Add(segment);
}
public void Add(T[] array)
{
segments.Add(new ArraySegment<T>(array));
}
public void Add(T[] array, int count)
{
segments.Add(new ArraySegment<T>(array, 0, count));
}
public void Add(T[] array, int offset, int count)
{
segments.Add(new ArraySegment<T>(array, offset, count));
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
```
Then you can just add the relevant segments each time. Of course, you could end up with a lot of wasted memory, and you'd have to be careful to create a new buffer each time (instead of reading over the original again) but it would be efficient in other ways. | How can I compound byte[] buffers into a List<byte>? | [
"",
"c#",
".net",
"networking",
""
] |
I have two tables with a 1:n relationship: "content" and "versioned-content-data" (for example, an article entity and all the versions created of that article). I would like to create a view that displays the top version of each "content".
I use this query (with a simple subquery):
```
SELECT
t1.id,
t1.title,
t1.contenttext,
t1.fk_idothertable
t1.version
FROM mytable as t1
WHERE (version = (
SELECT MAX(version) AS topversion
FROM mytable
WHERE (fk_idothertable = t1.fk_idothertable)))
```
The subquery is to the same table that extracts the highest version of a specific item. The versioned items will have the same fk\_idothertable.
In SQL Server I tried to create an indexed view of this query but subqueries are not allowed in indexed views.
What is a way to convert this query to one with JOINs?
It seems like indexed views cannot contain:
* subqueries
* common table expressions
* derived tables
* HAVING clauses | This probably won't help if table is already in production but the right way to model this is to make version = 0 the permanent version and always increment the version of OLDER material. So when you insert a new version you would say:
```
UPDATE thetable SET version = version + 1 WHERE id = :id
INSERT INTO thetable (id, version, title, ...) VALUES (:id, 0, :title, ...)
```
Then this query would just be
```
SELECT id, title, ... FROM thetable WHERE version = 0
```
No subqueries, no MAX aggregation. You always know what the current version is. You never have to select max(version) in order to insert the new record. | Maybe something like this?
```
SELECT
t2.id,
t2.title,
t2.contenttext,
t2.fk_idothertable,
t2.version
FROM mytable t1, mytable t2
WHERE t1.fk_idothertable == t2.fk_idothertable
GROUP BY t2.fk_idothertable, t2.version
HAVING t2.version=MAX(t1.version)
```
Just a wild guess... | How to convert a SQL subquery to a join | [
"",
"sql",
"sql-server",
"join",
"subquery",
""
] |
I have a ComboBox that doesn't seem to update the SelectedItem/SelectedValue.
The ComboBox ItemsSource is bound to a property on a ViewModel class that lists a bunch of RAS phonebook entries as a CollectionView. Then I've bound (at separate times) both the `SelectedItem` or `SelectedValue` to another property of the ViewModel. I have added a MessageBox into the save command to debug the values set by the databinding, but the `SelectedItem`/`SelectedValue` binding is not being set.
The ViewModel class looks something like this:
```
public ConnectionViewModel
{
private readonly CollectionView _phonebookEntries;
private string _phonebookeEntry;
public CollectionView PhonebookEntries
{
get { return _phonebookEntries; }
}
public string PhonebookEntry
{
get { return _phonebookEntry; }
set
{
if (_phonebookEntry == value) return;
_phonebookEntry = value;
OnPropertyChanged("PhonebookEntry");
}
}
}
```
The \_phonebookEntries collection is being initialised in the constructor from a business object. The ComboBox XAML looks something like this:
```
<ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedValue="{Binding Path=PhonebookEntry}" />
```
I am only interested in the actual string value displayed in the ComboBox, not any other properties of the object as this is the value I need to pass across to RAS when I want to make the VPN connection, hence `DisplayMemberPath` and `SelectedValuePath` are both the Name property of the ConnectionViewModel. The ComboBox is in a `DataTemplate` applied to an `ItemsControl` on a Window whose DataContext has been set to a ViewModel instance.
The ComboBox displays the list of items correctly, and I can select one in the UI with no problem. However when I display the message box from the command, the PhonebookEntry property still has the initial value in it, not the selected value from the ComboBox. Other TextBox instances are updating fine and displaying in the MessageBox.
What am I missing with databinding the ComboBox? I've done a lot of searching and can't seem to find anything that I'm doing wrong.
---
This is the behaviour I'm seeing, however it's not working for some reason in my particular context.
I have a MainWindowViewModel which has a `CollectionView` of ConnectionViewModels. In the MainWindowView.xaml file code-behind, I set the DataContext to the MainWindowViewModel. The MainWindowView.xaml has an `ItemsControl` bound to the collection of ConnectionViewModels. I have a DataTemplate that holds the ComboBox as well as some other TextBoxes. The TextBoxes are bound directly to properties of the ConnectionViewModel using `Text="{Binding Path=ConnectionName}"`.
```
public class ConnectionViewModel : ViewModelBase
{
public string Name { get; set; }
public string Password { get; set; }
}
public class MainWindowViewModel : ViewModelBase
{
// List<ConnectionViewModel>...
public CollectionView Connections { get; set; }
}
```
The XAML code-behind:
```
public partial class Window1
{
public Window1()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
}
```
**Then XAML:**
```
<DataTemplate x:Key="listTemplate">
<Grid>
<ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedValue="{Binding Path=PhonebookEntry}" />
<TextBox Text="{Binding Path=Password}" />
</Grid>
</DataTemplate>
<ItemsControl ItemsSource="{Binding Path=Connections}"
ItemTemplate="{StaticResource listTemplate}" />
```
The TextBoxes all bind correctly, and data moves between them and the ViewModel with no trouble. It's only the ComboBox that isn't working.
You are correct in your assumption regarding the PhonebookEntry class.
The assumption I am making is that the DataContext used by my DataTemplate is automatically set through the binding hierarchy, so that I don't have to explicitly set it for each item in the `ItemsControl`. That would seem a bit silly to me.
---
Here is a test implementation that demonstrates the problem, based on the example above.
**XAML:**
```
<Window x:Class="WpfApplication7.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<DataTemplate x:Key="itemTemplate">
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Path=Name}" Width="50" />
<ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedValue="{Binding Path=PhonebookEntry}"
Width="200"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ItemsControl ItemsSource="{Binding Path=Connections}"
ItemTemplate="{StaticResource itemTemplate}" />
</Grid>
</Window>
```
The **code-behind**:
```
namespace WpfApplication7
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
}
public class PhoneBookEntry
{
public string Name { get; set; }
public PhoneBookEntry(string name)
{
Name = name;
}
}
public class ConnectionViewModel : INotifyPropertyChanged
{
private string _name;
public ConnectionViewModel(string name)
{
_name = name;
IList<PhoneBookEntry> list = new List<PhoneBookEntry>
{
new PhoneBookEntry("test"),
new PhoneBookEntry("test2")
};
_phonebookEntries = new CollectionView(list);
}
private readonly CollectionView _phonebookEntries;
private string _phonebookEntry;
public CollectionView PhonebookEntries
{
get { return _phonebookEntries; }
}
public string PhonebookEntry
{
get { return _phonebookEntry; }
set
{
if (_phonebookEntry == value) return;
_phonebookEntry = value;
OnPropertyChanged("PhonebookEntry");
}
}
public string Name
{
get { return _name; }
set
{
if (_name == value) return;
_name = value;
OnPropertyChanged("Name");
}
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class MainWindowViewModel
{
private readonly CollectionView _connections;
public MainWindowViewModel()
{
IList<ConnectionViewModel> connections = new List<ConnectionViewModel>
{
new ConnectionViewModel("First"),
new ConnectionViewModel("Second"),
new ConnectionViewModel("Third")
};
_connections = new CollectionView(connections);
}
public CollectionView Connections
{
get { return _connections; }
}
}
}
```
If you run that example, you will get the behaviour I'm talking about. The TextBox updates its binding fine when you edit it, but the ComboBox does not. Very confusing seeing as really the only thing I've done is introduce a parent ViewModel.
I am currently labouring under the impression that an item bound to the child of a DataContext has that child as its DataContext. I can't find any documentation that clears this up one way or the other.
I.e.,
Window -> DataContext = MainWindowViewModel
..Items -> Bound to DataContext.PhonebookEntries
....Item -> DataContext = PhonebookEntry (implicitly associated)
I don't know if that explains my assumption any better(?).
---
To confirm my assumption, change the binding of the TextBox to be
```
<TextBox Text="{Binding Mode=OneWay}" Width="50" />
```
And this will show the TextBox binding root (which I'm comparing to the DataContext) is the ConnectionViewModel instance. | You set the DisplayMemberPath and the SelectedValuePath to "Name", so I assume that you have a class PhoneBookEntry with a public property Name.
Have you set the DataContext to your ConnectionViewModel object?
I copied you code and made some minor modifications, and it seems to work fine.
I can set the viewmodels PhoneBookEntry property and the selected item in the combobox changes, and I can change the selected item in the combobox and the view models PhoneBookEntry property is set correctly.
Here is my XAML content:
```
<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<StackPanel>
<Button Click="Button_Click">asdf</Button>
<ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedValue="{Binding Path=PhonebookEntry}" />
</StackPanel>
</Grid>
</Window>
```
And here is my code-behind:
```
namespace WpfApplication6
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
ConnectionViewModel vm = new ConnectionViewModel();
DataContext = vm;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
((ConnectionViewModel)DataContext).PhonebookEntry = "test";
}
}
public class PhoneBookEntry
{
public string Name { get; set; }
public PhoneBookEntry(string name)
{
Name = name;
}
public override string ToString()
{
return Name;
}
}
public class ConnectionViewModel : INotifyPropertyChanged
{
public ConnectionViewModel()
{
IList<PhoneBookEntry> list = new List<PhoneBookEntry>();
list.Add(new PhoneBookEntry("test"));
list.Add(new PhoneBookEntry("test2"));
_phonebookEntries = new CollectionView(list);
}
private readonly CollectionView _phonebookEntries;
private string _phonebookEntry;
public CollectionView PhonebookEntries
{
get { return _phonebookEntries; }
}
public string PhonebookEntry
{
get { return _phonebookEntry; }
set
{
if (_phonebookEntry == value) return;
_phonebookEntry = value;
OnPropertyChanged("PhonebookEntry");
}
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
```
**Edit:** Geoffs second example does not seem to work, which seems a bit odd to me. If I **change the PhonebookEntries property on the ConnectionViewModel to be of type ReadOnlyCollection**, the TwoWay binding of the SelectedValue property on the combobox works fine.
Maybe there is an issue with the CollectionView? I noticed a warning in the output console:
> System.Windows.Data Warning: 50 : Using CollectionView directly is not fully supported. The basic features work, although with some inefficiencies, but advanced features may encounter known bugs. Consider using a derived class to avoid these problems.
**Edit2 (.NET 4.5):** The content of the DropDownList can be based on ToString() and not of DisplayMemberPath, while DisplayMemberPath specifies the member for the selected and displayed item only. | To bind the data to ComboBox
```
List<ComboData> ListData = new List<ComboData>();
ListData.Add(new ComboData { Id = "1", Value = "One" });
ListData.Add(new ComboData { Id = "2", Value = "Two" });
ListData.Add(new ComboData { Id = "3", Value = "Three" });
ListData.Add(new ComboData { Id = "4", Value = "Four" });
ListData.Add(new ComboData { Id = "5", Value = "Five" });
cbotest.ItemsSource = ListData;
cbotest.DisplayMemberPath = "Value";
cbotest.SelectedValuePath = "Id";
cbotest.SelectedValue = "2";
```
`ComboData` looks like:
```
public class ComboData
{
public int Id { get; set; }
public string Value { get; set; }
}
```
(note that `Id` and `Value` have to be properties, not class fields) | Binding a WPF ComboBox to a custom list | [
"",
"c#",
"wpf",
"data-binding",
"mvvm",
"combobox",
""
] |
Zend Framework makes development a lot easier; for instance there is a getPost function from the Zend\_Http that handles POST parameters.
Is there anything similar to handle file uploads? I can access $\_FILES directly, but I would rather use a built in function to keep things consistent. | you can use Zend\_Form\_Element\_File, it has very similar functionality as Zend\_File\_Transfer and it works without any problems.
<http://framework.zend.com/manual/en/zend.form.standardElements.html#zend.form.standardElements.file> | You can do file uploads with Zend\_Form. Tutorial [here](http://akrabat.com/2008/04/07/simple-zend_form-file-upload-example/). | Is there a function in Zend Framework to handle file uploads? | [
"",
"php",
"zend-framework",
"file-upload",
""
] |
I want to take two times (in seconds since epoch) and show the difference between the two in formats like:
* 2 minutes
* 1 hour, 15 minutes
* 3 hours, 9 minutes
* 1 minute ago
* 1 hour, 2 minutes ago
How can I accomplish this?? | *Since everyone shouts "YOODAA!!!" but noone posts a concrete example, here's my contribution.*
You could also do this with [Joda-Time](http://www.joda.org/joda-time/). Use [`Period`](http://www.joda.org/joda-time/apidocs/org/joda/time/Period.html) to represent a period. To format the period in the desired human representation, use [`PeriodFormatter`](http://www.joda.org/joda-time/apidocs/org/joda/time/format/PeriodFormatter.html) which you can build by [`PeriodFormatterBuilder`](http://www.joda.org/joda-time/apidocs/org/joda/time/format/PeriodFormatterBuilder.html).
Here's a kickoff example:
```
DateTime myBirthDate = new DateTime(1978, 3, 26, 12, 35, 0, 0);
DateTime now = new DateTime();
Period period = new Period(myBirthDate, now);
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendYears().appendSuffix(" year, ", " years, ")
.appendMonths().appendSuffix(" month, ", " months, ")
.appendWeeks().appendSuffix(" week, ", " weeks, ")
.appendDays().appendSuffix(" day, ", " days, ")
.appendHours().appendSuffix(" hour, ", " hours, ")
.appendMinutes().appendSuffix(" minute, ", " minutes, ")
.appendSeconds().appendSuffix(" second", " seconds")
.printZeroNever()
.toFormatter();
String elapsed = formatter.print(period);
System.out.println(elapsed + " ago");
```
Much more clear and concise, isn't it?
This prints by now
```
32 years, 1 month, 1 week, 5 days, 6 hours, 56 minutes, 24 seconds ago
```
(Cough, old, cough) | ```
Date start = new Date(1167627600000L); // JANUARY_1_2007
Date end = new Date(1175400000000L); // APRIL_1_2007
long diffInSeconds = (end.getTime() - start.getTime()) / 1000;
long diff[] = new long[] { 0, 0, 0, 0 };
/* sec */diff[3] = (diffInSeconds >= 60 ? diffInSeconds % 60 : diffInSeconds);
/* min */diff[2] = (diffInSeconds = (diffInSeconds / 60)) >= 60 ? diffInSeconds % 60 : diffInSeconds;
/* hours */diff[1] = (diffInSeconds = (diffInSeconds / 60)) >= 24 ? diffInSeconds % 24 : diffInSeconds;
/* days */diff[0] = (diffInSeconds = (diffInSeconds / 24));
System.out.println(String.format(
"%d day%s, %d hour%s, %d minute%s, %d second%s ago",
diff[0],
diff[0] > 1 ? "s" : "",
diff[1],
diff[1] > 1 ? "s" : "",
diff[2],
diff[2] > 1 ? "s" : "",
diff[3],
diff[3] > 1 ? "s" : ""));
``` | How can I calculate a time span in Java and format the output? | [
"",
"java",
"date",
"time",
"formatting",
""
] |
Am I correct in thinking the following snippet does not work (the array items are not modified) *because* the array is of integer which is value type.
```
class Program
{
public static void Main()
{
int[] ints = new int[] { 1,2 };
Array.ForEach(ints, new Action<int>(AddTen));
// ints is not modified
}
static void AddTen(int i)
{
i+=10;
}
}
```
The same would apply if the example used an array of string, presumably because string is immutable.
The question I have is:-
Is there a way around this? I can't change the signature of the callback method - for instance by adding the ref keyword and I don't want to wrap the value type with a class - which would work...
(Of course, I could simply write an old fashioned foreach loop to do this!) | You are simply changing the local variable - not the item in the list. To do this, you want `ConvertAll`, which creates a new list/array:
```
int[] ints = new int[] { 1,2 };
int[] newArr = Array.ConvertAll<int,int>(ints, AddTen);
```
with:
```
static int AddTen(int i)
{
return i+10;
}
```
This can also be written with an anonymous method:
```
int[] newArr = Array.ConvertAll<int,int>(ints,
delegate (int i) { return i+ 10;});
```
Or in C# 3.0 as a lambda:
```
int[] newArr = Array.ConvertAll(ints, i=>i+10);
```
Other than that... a `for` loop:
```
for(int i = 0 ; i < arr.Length ; i++) {
arr[i] = AddTen(arr[i]); // or more directly...
}
```
But one way or another, you are going to have to get a value *out* of your method. Unless you change the signature, you can't. | The Array.ForEach() method won't let you practically modify it's members. You can modify it by using LINQ such as this
```
ints = ints.Select(x => x +10 ).ToArray();
``` | c# using Array.ForEach Action Predicate with array of value type or string | [
"",
"c#",
"foreach",
"action",
""
] |
I am using a javascript called 'Facelift 1.2' in one of my websites and while the script works in Safari 3, 4b and Opera, OmniWeb and Firefox it does not in any IE version.
But even in the working browser i get the following error I cannot decipher.
Maybe in due time—with more experience in things Javascript—I will be able to but for now I thought I would ask some of you, here at SO.
The following is the error popup i get in IETester testing the page for Interet Explorer 6,7 and 8:
[](https://i.stack.imgur.com/GVlu8.png)
The following is from the Firebug console in Firefox 3.0.6:
[](https://i.stack.imgur.com/Qof6U.png)
The website is: <http://www.457cc.co.nz/index.php> In case it helps you see the problem mentioned in action.
I have also looked up what line 620 corresponds to which is:
*"line 76" is:*
```
this.isCraptastic = (typeof document.body.style.maxHeight=='undefined');
```
which is part of this block of code (taken from the flir.js):
```
// either (options Object, fstyle FLIRStyle Object) or (fstyle FLIRStyle Object)
,init: function(options, fstyle) { // or options for flir style
if(this.isFStyle(options)) { // (fstyle FLIRStyle Object)
this.defaultStyle = options;
}else { // [options Object, fstyle FLIRStyle Object]
if(typeof options != 'undefined')
this.loadOptions(options);
if(typeof fstyle == 'undefined') {
this.defaultStyle = new FLIRStyle();
}else {
if(this.isFStyle(fstyle))
this.defaultStyle = fstyle;
else
this.defaultStyle = new FLIRStyle(fstyle);
}
}
this.calcDPI();
if(this.options.findEmbededFonts)
this.discoverEmbededFonts();
this.isIE = (navigator.userAgent.toLowerCase().indexOf('msie')>-1 && navigator.userAgent.toLowerCase().indexOf('opera')<0);
this.isCraptastic = (typeof document.body.style.maxHeight=='undefined');
if(this.isIE) {
this.flirIERepObj = [];
this.flirIEHovEls = [];
this.flirIEHovStyles = [];
}
}
```
The whole script is also available on my server: <http://www.457cc.co.nz/facelift-1.2/flir.js>
I just don't know where to start looking for the error, especially since it only affects IE but works in the rest. Maybe you guys have an idea. I would love to hear them.
Thanks for reading.
Jannis
PS: This is what Opera's error console reports:
```
JavaScript - http://www.457cc.co.nz/index.php
Inline script thread
Error:
name: TypeError
message: Statement on line 620: Cannot convert undefined or null to Object
Backtrace:
Line 620 of linked script http://www.457cc.co.nz/facelift-1.2/flir.js
document.body.appendChild(test);
Line 70 of linked script http://www.457cc.co.nz/facelift-1.2/flir.js
this.calcDPI();
Line 2 of inline#1 script in http://www.457cc.co.nz/index.php
FLIR.init();
stacktrace: n/a; see 'opera:config#UserPrefs|Exceptions Have Stacktrace'
``` | I agree with tvanfosson - the reason you're getting that error is quite likely because you're calling `init()` before the page is done loading, so `document.body` is not yet defined.
In the page you linked, you should move the following code to the bottom of the page (just before the closing html tag:
```
<script type="text/javascript">
FLIR.init({ path: 'http://www.457cc.co.nz/facelift-1.2/' });
FLIR.auto();
</script>
```
Even better, you should attach the initialization to the document's `ready` event. If you do it this way, there is no need to even move your javascript to the bottom of the file. Using jquery:
```
$(document).ready( function(){
FLIR.init({ path: 'http://www.457cc.co.nz/facelift-1.2/' });
FLIR.auto();
});
```
[More on jquery's document.ready event »](http://docs.jquery.com/Tutorials:Introducing_%24%28document%29.ready%28%29) | **Edit** Answer left for context. See @Triptych's (accepted) answer for the correct resolution.
My suggestion is to move the inclusion of the javascript to the end of your mark up. I think what is happening is that the code is executing before the DOM is completely loaded and thus the document.body is null when you try to reference it in determining the maxHeight style property. Moving the inclusion of the javascript to the end of your markup should be enough to guarantee that the body of the document is loaded at least and avoid this particular error.
```
... rest of html....
<script type='text/javascript'
src='http://www.457cc.co.nz/facelift/flir.js'>
</script>
</body>
</html>
``` | Javascript: Error 'Object Required'. I can't decipher it. Can you? | [
"",
"javascript",
"debugging",
"flir",
""
] |
I didn't see any questions that asked this previously so here goes:
Once you made (or had) the decision to start using LINQ to SQL how long did it take you to learn it's ins and outs?
We're looking at using it at my organization but my superiors are concerned with the initial time cost (learning it). Hours would be the most useful of answers but any insight would be appreciated.
Bonus question: how much time has LINQ saved you since you started using it? | You can learn LINQ to SQL in the subway coming back from work :). Seriously, it really doesn't take any time learning it (1-2 days max), and it's gonna save you a lot of your time! | I don't have any specific metric, but I can say for sure that on the first project I used it, it saved me on the first 2 week sprint more than I spent learning.
Ps. you will find a gotcha as with any approach you use, just stay away of tables with no keys :) | How long did it take you to learn LINQ to SQL? | [
"",
"sql",
"linq-to-sql",
""
] |
I have a struct containing song data:
```
public struct uLib
{
public string Path;
public string Artist;
public string Title;
public string Album;
public string Length;
}
```
My library consists of an array of this `uLib`. How would I sort this array by say Artist? Is there a native sort function I can call on this type of array, or will I have to "roll my own"? | First of all, that should not be a struct. It's larger than 16 bytes, so you don't get the performance benefits of having a struct. Also, it doesn't represent a single value, so it doesn't make sense semantically to make it a struct. Just make it a class instead.
The `Array` class has a `Sort` method that you can use:
```
Array.Sort(theArray, (x,y) => string.Compare(x.Artist,y.Artist));
```
If you don't have C# 3 you use a delegate instead of the lambda expression:
```
Array.Sort(theArray, delegate(uLib x, uLib y) { return string.Compare(x.Artist,y.Artist) } );
```
Edit:
Here's an example of what your data could look like as a class:
```
public class ULib {
private string _path, _artist, _title, _album, _length;
public string Path { get { return _path; } set { _path = value; } }
public string Artist { get { return _artist; } set { _artist = value; } }
public string Title { get { return _title; } set { _title = value; } }
public string Album { get { return _album; } set { _album = value; } }
public string Length { get { return _length; } set { _length = value; } }
public ULib() {}
public ULib(string path, string artist, string title, string album, string length) {
Path = path;
Artist = artist;
Title = title;
Album = album;
Length = length;
}
}
```
In C# there there is a short form for a property. Instead of writing code for a private variable and a setter and getter to access it, this creates that automatically:
```
public string Path { get; set; }
``` | from u in ULibArray order by u.Artist select u; | How would I sort through an array of structs? | [
"",
"c#",
".net",
"arrays",
"sorting",
""
] |
Why (for example web2py) do you return data from a controller in a dictionary instead of variables (see Rails)?
For example:
```
return dict(sape=4139, guido=4127, jack=4098)
```
instead of (that's the way Rails does it)
```
@var1 = "jello"
@var2 = "hihi"
```
Is there any advantage using dictionaries over plain variables (speed-wise/code-wise)?
Update: The above way is actually a correct way for creating a dictionary (at least in Python 2.6.1). The other way (that many people say it's the correct one)
```
return {"var1": "jello", "var2": "hihi"}
```
is not used a lot by python frameworks.
From [Python's documentation](http://docs.python.org/tutorial/datastructures.html):
"When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:"
```
dict(sape=4139, guido=4127, jack=4098)
``` | The main advantage is that this is the only way in python to return a) more than a single value **and** b) give that value a name. Other options would be to use a class (extra code), return a tuple (no names, so you'd have to use indexes to access the values) or allow to return only a single value which would probably mean that everyone would return a dictionary since that's the most simple solution.
It also allows to wrap several methods and join/merge their results. Lastly, it allows to return different sets of value/name pairs for each call easily, for example, omit optional values or return additional hints. | You can use local variables if you'd like:
```
def hello():
var1 = "whatever you like"
var2 = "another value"
return locals() # or vars()
```
`hello.html`:
```
<html><body>
<p>var1 {{=var1}}</p>
<p>var2 {{=var2}}</p>
</body></html>
```
[from PHP to web2py](http://mdp.cti.depaul.edu/AlterEgo/default/show/106):
> In web2py an HTTP request for
> "/app/c/f" is mapped into a call to
> the function f() in file (controller)
> c.py in the application "app". The
> file c.py is written in Python. The
> output of the function f() can be a
> string (in this case it is returned),
> or a set of variables (implemented as
> a python dictionary). In the latter
> case the variables are rendered into
> HTML by a file c/f.html, called a
> view. | Why do Python's frameworks return dictionaries from controllers? | [
"",
"python",
"ruby-on-rails",
"web2py",
""
] |
I'm looking for quick/simple method for matching a given IP4 dotted quad IP to a CIDR notation mask.
I have a bunch of IPs I need to see if they match a range of IPs.
example:
```
$ips = array('10.2.1.100', '10.2.1.101', '10.5.1.100', '1.2.3.4');
foreach ($ips as $IP) {
if (cidr_match($IP, '10.2.0.0/16') == true) {
print "you're in the 10.2 subnet\n";
}
}
```
What would `cidr_match()` look like?
It doesn't really have to be simple, but fast would be good. Anything that uses only built-in/common functions is a bonus (as I'm likely to get one person to show me something in pear that does this, but I can't depend on pear or that package being installed where my code is deployed). | If only using IPv4:
* use `ip2long()` to convert the IPs and the subnet range into long integers
* convert the /xx into a subnet mask
* do a bitwise 'and' (i.e. ip & mask)' and check that that 'result = subnet'
something like this should work:
```
function cidr_match($ip, $range)
{
list ($subnet, $bits) = explode('/', $range);
if ($bits === null) {
$bits = 32;
}
$ip = ip2long($ip);
$subnet = ip2long($subnet);
$mask = -1 << (32 - $bits);
$subnet &= $mask; # nb: in case the supplied subnet wasn't correctly aligned
return ($ip & $mask) == $subnet;
}
``` | In a similar situation, I ended up using symfony/http-foundation.
When using this package, your code would look like:
```
$ips = array('10.2.1.100', '10.2.1.101', '10.5.1.100', '1.2.3.4');
foreach($ips as $IP) {
if (\Symfony\Component\HttpFoundation\IpUtils::checkIp($IP, '10.2.0.0/16')) {
print "you're in the 10.2 subnet\n";
}
}
```
It also handles IPv6.
Link: <https://packagist.org/packages/symfony/http-foundation> | Check whether or not a CIDR subnet contains an IP address | [
"",
"php",
"ip-address",
"cidr",
""
] |
What would be the closest resemblance? | You could also try [EasyMock](http://www.easymock.org/). RhinoMocks was built off the EasyMock.NET engine, so there are a lot of similarities. | I know [JMock](http://www.jmock.org/) is very similar to RhinoMocks. | Is there anything like RhinoMocks in Java? | [
"",
"java",
"mocking",
"rhino-mocks",
""
] |
Saludos a todos en stackoverflow.com!!
So... I'm a C++ newbie currently taking the subject of Data Structures, and I want to consult something with you guys:
Since I started studying Systems Engineering, I've been using the last version of Dev-C++ for all my programming projects. It has done it's job well so far, but it has a FATAL flaw... trying to debug your code in it it's just... awfully painful!! Everytime you activate the debug mode you have to cross your fingers and hope it doesn't crash in your face just before the variable you are watching even changes.
Then, I though about using Visual-C++ from Microsoft, as it is free too; however, I asked my teacher and told me not to use it in the course, as it is not standard (compiled programs in it will only work for Windows); we are required to make code that can be compiled both in a Windows and Linux environment, and once compiled in any, being able to use the application on both environments.
So people, I want you to please give me advice: Which C++ compiling software out there has a strong and/or stable debugging mode, implements the standard compiler (is it called g++, by the way??), and it's hopefully free???
Thanks for your attention. Gracias y hasta luego ^\_^ (BTW, happy first post!!! ^o^) | [Code::Blocks](http://www.codeblocks.org/) - it's free, it's cross-platform, it's pretty good. You can download a package consisting of the CB IDE, the MinGW C++ compiler and the gdb debugger. Installation is very straightforward. | There is an implementation of g++ and GDB ( the Gnu Debugger ) for windows called Mingw that works very well. Though since I'm guessing you're also looking for a graphical IDE / debugger, I'd point you at Eclipse. The C Development Tools for eclipse include an excellent interface to the Mingw build tools and GDB. Also, on your comment about a compiled program being used on both Windows and \*nix, this is not possible as far as I know. | Which is the best, standard (and hopefully free) C++ compiler? | [
"",
"c++",
"debugging",
"compiler-construction",
"standards",
""
] |
I have an Address object that has properties AddressLine1, AddressLine2, Suburb, State, ZipCode. (there are more but this is enough for the example). Also, each of these properties are strings. And I'm using C# 3.0.
I'm wanting to represent it as a string but as I'm doing that I'm finding that I'm creating a method with a high cyclomatic complexity due to all the if-statements...
Assuming the string assigned to each property is the same as the name of the property (ie AddressLine1 = "AddressLine1")...I want the address to be represented as follows:
"AddressLine1 AddressLine2 Suburb State ZipCode".
Now, the original way I had done this was by a simple String.Format()
```
String.Format("{0} {1} {2} {3} {4}", address.AddressLine1,
address.AddressLine2, address.Suburb, address.State, address.ZipCode);
```
This is all well and good until I've found that some of these fields can be empty...in particular AddressLine2. The result is additional unneeded spaces...which are particularly annoying when you get several in a row.
To get around this issue, and the only solution I can think of, I've had to build the string manually and only add the address properties to the string if they are not null or empty.
ie
```
string addressAsString = String.Empty;
if (!String.IsNullOrEmpty(address.AddressLine1))
{
addressAsString += String.Format("{0}", address.AddressLine1);
}
if(!String.IsNullOrEmpty(address.AddressLine2))
{
addressAsString += String.Format(" {0}", address.AddressLine2);
}
etc....
```
Is there a more elegant and/or concise way to achieve this that I'm not thinking about? My solution just *feels* messy and bloated...but I can't think of a better way to do it...
For all I know, this is my only option given what I want to do...but I just thought I'd throw this out there to see if someone with more experience than me knows of a better way. If theres no better option then oh well...but if there is, then I'll get to learn something I didn't know before.
Thanks in advance! | This possibly isn't the most efficient way, but it is concise. You could put the items you want into an array and filter out the ones without a significant value, then join them.
```
var items = new[] { line1, line2, suburb, state, ... };
var values = items.Where(s => !string.IsNullOrEmpty(s));
var addr = string.Join(" ", values.ToArray());
```
Probably more efficient, but somewhat harder to read, would be to aggregate the values into a `StringBuilder`, e.g.
```
var items = new[] { line1, line2, suburb, state, ... };
var values = items.Where(s => !string.IsNullOrEmpty(s));
var builder = new StringBuilder(128);
values.Aggregate(builder, (b, s) => b.Append(s).Append(" "));
var addr = builder.ToString(0, builder.Length - 1);
```
I'd probably lean towards something like the first implementation as it's much simpler and more maintainable code, and then if the performance is a problem consider something more like the second one (if it does turn out to be faster...).
(Note this requires C# 3.0, but you don't mention your language version, so I'm assuming this is OK). | When putting strings together I recommend you use the StringBuilder class. Reason for this is that a System.String is immutable, so every change you make to a string simply returns a new string.
If you want to represent an object in text, it might be a good idea to override the ToString() method and put your implementation in there.
Last but not least, with Linq in C# 3.5 you can join those together like Greg Beech just did here, but instead of using string.Join() use:
```
StringBuilder sb = new StringBuilder();
foreach (var item in values) {
sb.Append(item);
sb.Append(" ");
}
```
Hope this helps. | What is the best way to convert an Address object to a String? | [
"",
"c#",
"string",
"c#-3.0",
"object",
""
] |
to describe it some more, if i have an image map of a region that when clicked, a query is performed to get more information about that region.
my client wants me to display an approximate number of search results while hovering over that region image map.
my problem is how do i cache? or get that number without heavily exhausting my server's memory resources?
btw im using php and mysql if that's a necessary info. | You could periodically execute the query and then store the results (e.g., in a different table).
The results would not be absolutely up-to-date, but would be a good approximation and would reduce the load on the server. | MySQL can give you the approximate number of rows that would be returned by your query, without actually running the query. This is what EXPLAIN syntax is for.
You run the query with 'EXPLAIN' before the 'SELECT', and then multiply all the results in the rows column.
The accuracy is highly variable. It may work with some types of queries, but be useless on others. It makes use of statistics about your data that MySQL's optimizer keeps.
Note: using ANALYZE TABLE on the table periodically (ie once a month) may help improve the accuracy of these estimates. | what is the best way to get an approximate number of search results from a query? | [
"",
"php",
"mysql",
"search",
"approximation",
""
] |
I am relatively new to C#/.Net. I'm developing a desktop application that requires multi threading. I came up with the following pattern below as a base. I was wondering if anyone could point out how to make it better in terms of coding, being thread safe, and being efficient.
Hopefully this makes some sense.
---
```
public abstract class ThreadManagerBase
{
// static class variables
private static ThreadManagerBase instance = null;
private static BackgroundWorker thread = null;
private static ProgressBarUIForm progress = null;
/// <summary>
/// Create a new instance of this class. The internals are left to the derived class to figure out.
/// Only one instance of this can run at any time. There should only be the main thread and this thread.
/// </summary>
public abstract static ThreadManagerBase NewInstance();
/// <summary>
/// Clears the instance.
/// </summary>
public static void ClearInstance()
{
instance = null;
}
/// <summary>
/// Initializes the background worker with some presets.
/// Displays progress bar.
/// </summary>
private abstract static void InitializeThread()
{
thread = new BackgroundWorker();
thread.WorkerReportsProgress = true;
thread.WorkerSupportsCancellation = true;
thread.DoWork += new DoWorkEventHandler(thread_DoWork);
thread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(thread_RunWorkerCompleted);
thread.ProgressChanged += new ProgressChangedEventHandler(thread_ProgressChanged);
thread.RunWorkerAsync();
progress = new ProgressBarUIForm();
progress.EnableCancelButton = true;
progress.UserCanceled += new EventHandlerCancelClicked(progress_UserCanceled);
progress.ShowDialog();
thread.Dispose();
thread = null;
}
private static void progress_UserCanceled(bool userCanceled)
{
thread.CancelAsync();
}
private static void thread_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progress.SetProgressLevel = e.ProgressPercentage;
progress.SetProgressMessage = e.UserState.ToString();
}
private static void thread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progress.Close();
progress = null;
}
private static void thread_DoWork(object sender, DoWorkEventArgs e)
{
ProcessWork();
}
private abstract static void ProcessWork()
{
// do actuall stuff here.
// the derived classes will take care of the plumbing.
}
}
``` | You don't need a BackgroundWorker unless you want to be spoonfed, normal threads are perfectly acceptable, as long as you follow the rules. | Have you looked into the [Microsoft Parallel Extensions to .NET Framework 3.5](http://www.microsoft.com/downloads/details.aspx?FamilyId=348F73FD-593D-4B3C-B055-694C50D2B0F3&displaylang=en)? It's a pretty good library that takes a lot of the work out of threading.
There are also a lot of articles on MSDN about threading patterns that you should research too. Threading can get really complicated really fast. It's nice to have someone else to have though of all the important stuff that can go wrong, and simplify it down to a library or a pattern. Of course, there's danger in that too if you don't understand the gotchas of any particular solution. So, make sure you research well whatever solution you choose. | C# Multi Thread Design Example | [
"",
"c#",
"multithreading",
"design-patterns",
""
] |
Hope I can explain this somewhat decently, as it's blowing a fuse in my brain today. I'm learning TDD in C#, so I'm still trying to rewire my brain to fit it.
Let's say I have a **User** class, that previously had a static method to retrieve a User object (simplified below).
```
public static User GetUser(string username)
{
User user = GetUserFromCache(username);
if(user == null)
{
user = GetUserFromDatabase(username);
StoreObjectInCache(user);
}
return user;
}
```
So I'm trying to rewrite this to use dependency injection so I can fake out the "GetUserFromDatabase" method if it needs to go there. That means I have to make the function not static. Whereas the data access layer would construct the user object from the database, mapping the returned columns to the object properties, a retrieval from cache would return a true-blue **User** object. However, in a non-static method, I can't just say
```
this = GetUserFromCache(username);
```
Because it just doesn't work that way. Though I'm by no means the world expert in how to dance around this with OO, it looks like I'd almost have to grab the User object from cache and write another mapping function that would store the returned User object properties into the new User instance.
What's the solution here? Any OO magic I'm missing? Is the only solution to refactor everything to use factories instead of having the instantiation logic in the object itself? Or have I been staring at this too long and missing something completely obvious? | I don't think you're missing any magic and I think refactoring to remove the persistence code from your business objects and into your persistence layer is the right way to go both from a unit testing and a design perspective. You may want to think about having the cache sit between your business layer and the persistence layer, mediating the retrieval/update of your business objects to simplify things. You should be able to mock/fake your cache and persistence layer if you separate things out this way. | [Unit testing code that does date processing based on today's date](https://stackoverflow.com/questions/565289/unit-testing-code-that-does-date-processing-based-on-todays-date/565315#565315)
Before
* There is some code that uses the database to fetch a User and place it into the cache.
After
* There is some code that uses the database to fetch a User
* There is some code that places the User in the cache.
These two sets of code should not be dependent on each other.
```
public static Func<string, UserName> Loader {get;set;}
public static Constructor()
{
Loader = GetFromDataBase;
}
public static User GetUser(string userName)
{
User user = GetUserFromCache()
if (user == null)
{
user = Loader(userName);
StoreUserInCache(user);
}
return user;
}
public void Test1()
{
UserGetter.Loader = Mock.GetUser;
UserGetter.GetUser("Bob");
}
```
Classically, an interface would be used instead of a Func. If more than one method is involved, an interface is an obvious choice over the Func. If the methods implementations themselves are static, Func is a way to do abstraction over them. | TDD: Static methods, dependency injection, caching, and you! | [
"",
"c#",
"oop",
"tdd",
""
] |
I am using C++ `ofstream` to write out a file. I want to set the permissions to be only accessible by the user: 700. In unix; I suppose I can just issue a `system("chmod 700 file.txt");` but I need this code to work on Windows as well. I can use some Windows api; but what is the best c++ cross platform way to do this? | Ironically, I have just run into this very same need earlier today.
In my case, the answer came down to what level of permission granularity I need on Windows, versus Linux. In my case, I only care about User, Group, and Other permission on Linux. On Windows, the basic Read/Write All permission leftover from DOS is good enough for me, i.e. I don't need to deal with ACL on Windows.
Generally speaking, Windows has two privilege models: the basic DOS model and the newer access control model. Under the DOS model there is one type of privilege: write privilege. All files can be read, so there is no way to turn off read permission (because it doesn't exist). There is also no concept of execute permission. If a file can be read (answer is yes) and it is binary, then it can be executed; otherwise it can't.
The basic DOS model is sufficient for most Windows environments, i.e. environments where the system is used by a single user in a physical location that can be considered relatively secure. The access control model is more complex by several orders of magnitude.
The access control model uses access control lists (ACL) to grant privileges. Privileges can only be granted by a process with the necessary privileges. This model not only allows the control of User, Group, and Other with Read, Write, and Execute permission, but it also allows control of files over the network and between Windows domains. (You can also get this level of insanity on Unix systems with PAM.)
*Note: The Access Control model is only available on NTFS partitions, if you are using FAT partitions you are SOL.*
Using ACL is a big pain in the ass. It is not a trivial undertaking and it will require you to learn not just ACL but also all about Security Descriptors, Access Tokens, and a whole lot of other advanced Windows security concepts.
Fortunately for me, for my current needs, I don't need the true security that the access control model provides. I can get by with basically pretending to set permissions on Windows, as long as I really set permissions on Linux.
Windows supports what they call an "ISO C++ conformant" version of chmod(2). This API is called \_chmod, and it is similar to chmod(2), but more limited and not type or name compatible (of course). Windows also has a deprecated chmod, so you can't simply add chmod to Windows and use the straight chmod(2) on Linux.
I wrote the following:
```
#include <sys/stat.h>
#include <sys/types.h>
#ifdef _WIN32
# include <io.h>
typedef int mode_t;
/// @Note If STRICT_UGO_PERMISSIONS is not defined, then setting Read for any
/// of User, Group, or Other will set Read for User and setting Write
/// will set Write for User. Otherwise, Read and Write for Group and
/// Other are ignored.
///
/// @Note For the POSIX modes that do not have a Windows equivalent, the modes
/// defined here use the POSIX values left shifted 16 bits.
static const mode_t S_ISUID = 0x08000000; ///< does nothing
static const mode_t S_ISGID = 0x04000000; ///< does nothing
static const mode_t S_ISVTX = 0x02000000; ///< does nothing
static const mode_t S_IRUSR = mode_t(_S_IREAD); ///< read by user
static const mode_t S_IWUSR = mode_t(_S_IWRITE); ///< write by user
static const mode_t S_IXUSR = 0x00400000; ///< does nothing
# ifndef STRICT_UGO_PERMISSIONS
static const mode_t S_IRGRP = mode_t(_S_IREAD); ///< read by *USER*
static const mode_t S_IWGRP = mode_t(_S_IWRITE); ///< write by *USER*
static const mode_t S_IXGRP = 0x00080000; ///< does nothing
static const mode_t S_IROTH = mode_t(_S_IREAD); ///< read by *USER*
static const mode_t S_IWOTH = mode_t(_S_IWRITE); ///< write by *USER*
static const mode_t S_IXOTH = 0x00010000; ///< does nothing
# else
static const mode_t S_IRGRP = 0x00200000; ///< does nothing
static const mode_t S_IWGRP = 0x00100000; ///< does nothing
static const mode_t S_IXGRP = 0x00080000; ///< does nothing
static const mode_t S_IROTH = 0x00040000; ///< does nothing
static const mode_t S_IWOTH = 0x00020000; ///< does nothing
static const mode_t S_IXOTH = 0x00010000; ///< does nothing
# endif
static const mode_t MS_MODE_MASK = 0x0000ffff; ///< low word
static inline int my_chmod(const char * path, mode_t mode)
{
int result = _chmod(path, (mode & MS_MODE_MASK));
if (result != 0)
{
result = errno;
}
return (result);
}
#else
static inline int my_chmod(const char * path, mode_t mode)
{
int result = chmod(path, mode);
if (result != 0)
{
result = errno;
}
return (result);
}
#endif
```
It's important to remember that my solution only provides DOS type security. This is also known as no security, but it is the amount of security that most apps give you on Windows.
Also, under my solution, if you don't define STRICT\_UGO\_PERMISSIONS, when you give a permission to group or other (or remove it for that matter), you are really changing the owner. If you didn't want to do that, but you still didn't need full Windows ACL permissions, just define STRICT\_UGO\_PERMISSIONS. | There is no cross-platform way to do this. Windows does not support Unix-style file permissions. In order to do what you want, you'll have to look into creating an access control list for that file, which will let you explicitly define access permissions for users and groups.
An alternative might be to create the file in a directory whose security settings have already been set to exclude everyone but the user. | How to set file permissions (cross platform) in C++? | [
"",
"c++",
"windows",
"unix",
""
] |
I've just installed resharper and it's letting me know the namespaces i'm not actually using in each of my classes.
which lead me to the question - is there actually any overhead in leaving these, unused, using declarations in?
is it just a matter of tight code, or is there a performance hit in invoking these namespaces when i don't need to? | From [The C# Team's answers to frequently asked questions](http://blogs.msdn.com/csharpfaq/archive/2004/10/20/245411.aspx):
> When you add assembly references or
> make use of the 'using' keyword,
> **csc.exe will ignore any assembly which
> you have not actually made use of in
> your code** ... Don't [waste] your time stripping out
> unused '`using`' statements or assembly
> references from your application. **The
> C# compiler will do so for you
> automatically.**
You can verify that this is actually the case by calling `Assembly.GetReferencedAssemblies()`; you'll see that anything that isn't used won't actually be included in the list.
The main utility in stripping out unused ones is
* It is easier to see what your code is actually using
* It will keep your Intellisense from being polluted with things that you aren't actually going to use. | There are some performance reasons to strip down `using` statements:
* VS's IntelliSense runs faster when there is less data to look through
However, note all these reasons are compile-time specific. The compiler strips unused `using`s automatically. | overhead to unused "using" declarations? | [
"",
"c#",
"performance",
"using",
""
] |
I am using SVN to manage a copy of my web site. The site runs a typo3 installation, which uses PHP to create the backend.
The problem is, all the stupid .SVN folders show up in the directory listing of PHP. I DO NOT mean the build in apache listing. I mean a directoy listing created by the PHP backend.
So, is there any way to hide special directories from PHP?
[NOTE]
Changing the PHP source code is not an option. Typo3 is too big, and each extensions uses its own code. Would be much more effort than an SVN export script.
Chris
PS: I do not want to setup a svn export --> web\_root just to get rid of the files. And I know that I can prevent apache from serving the .SVN directories, I did that. But they still show up in the backend, when browsing the directory tree (which is created by PHP). And they are very annoying... | This is difficult, since you will have to change behavior of something somewhere between the filesystem and Typo3. You have:
> Filesystem → Operating System → PHP → Typo3
The files must stay in the filesystem and must stay visible by the operating system, so you can use SVN. Changing Typo3 is not an option for you, and changing PHP has many other major undesirable consequences that you should avoid. So, what you have left is to insert something in between OS→PHP or PHP→Typo3.
The first case is actually possible, depending on what operating system you use, and if you have administrator (root) access. **[FUSE](http://fuse.sourceforge.net/)** is part of the Linux kernel, and is also [available for many other operating systems](http://apps.sourceforge.net/mediawiki/fuse/index.php?title=OperatingSystems). Then, with fuse, you may install a filter like [rofs-filtered](http://ebixio.com/rofs-filtered), that allows you to filter which files and directories are visible in a mounted volume. You use it to create a filesystem that mirrors your SVN checkout directory, filtering the `.svn` directories. | > So, is there any way to hide special directories from PHP?
No.
As long as the user PHP is run under has read access to the directory it will always produce all the files/directories in that directory. There is no way to hide files from certain processes, were this possible writing a root kit to hide from ls and other file system tools would be a lot easier.
The option you would want/need is a way to define files that Typo3 ignores, and have it be system wide and thus used by the extensions as well. You have specified however that you do not want to change the source code, and do not want to do svn export.
You are thus stuck with the .svn directories. | How can I hide .SVN directories from PHP | [
"",
"php",
"svn",
"configuration",
""
] |
In my application, I have the following recurring pattern where I get the feeling that this is an incomplete or warped version of some common pattern that I'm not aware of. In my implementation, I can't seem to find a good way to implement a particular operation, as described below.
A collection of objects, let's call them "sources", produces data if you call a method on them. An instance of [ScheduledThreadPoolExecutor](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html) (from `java.util.concurrent`) is used to periodically do readings on the sources and put the data on a common outbound queue:
```
--o
method calls +-----+
--o <-- | o | ---> |||||||||||
--> | o o |
--o data +-----+
sources thread pool outbound queue
```
The sources, the thread pool and the queue are members of a class that provides methods to add sources and to retrieve the head of the queue.
Below is the code to add a new source. I'm wondering what happens if I remove a source from the collection.
```
public void vAddSource(ISource src)
{
this._rgSources.add(src);
final ISource srcT = src;
// q is the outbound queue, which is a private member in the class
// defining this method. Name is abbreviated for readability
Runnable cmd = new Runnable() { public void run() { q.add(srcT.sRead()); } }
// tpx is the thread pool
this._tpx.scheduleAtFixedRate(cmd, 0L, 1000L, TimeUnit.MILLISECONDS);
}
```
Now, the way Java works - if I got that correctly -, src etc. are object identifiers that get passed around by value, so in the above code there is only one ISource object and an identifier for it gets added to the collection as well as passed into the thread pool. If I remove the identifier from the collection, the object is still there, hence the thread pool will continue to read from it as if nothing happened.
Am I understanding this correctly? And what would be a typical approach if you wanted the thread pool to take note of the removal and also discard the source? | `ThreadPoolExecutor` (and hence `ScheduledThreadPoolExecutor`) has a `remove(Runnable)` method. You might also be interested in `FutureTask` which can be cancelled (although that wont take it out of the work queue).
ETA (by Hanno Fietz, from pgras' answer): This also requires to map the Runnables to a source so that the removeSource method could call ThreadPoolExecutor.remove with the right one. | One solution would be to keep a mapping between sources and Runnables so you could implement a removeSource method.
Another way would be to keep a WeakReference to the source instead of a hard one and to let the Runnable terminate itself if the source was garbage collected. | Design Pattern for Java: Does this look familiar to anyone? | [
"",
"java",
"design-patterns",
""
] |
Is there a difference between this:
```
var onClick = function() {
var image = .....
$.post("/..../...", null, function(data) { myCallback(data, image); } );
}
```
and
```
var onClick = function() {
this.image = .....
$.post("/..../...", null, function(data) { myCallback(data, this.image); } );
}
```
I am using the 'this' way, and for some reason any parameter I pass into myCallback is null??
If I output the variable before the $.post call using alert, I get a value so its not null? | At the time....
```
function(data) { myCallback(data, this.image); }
```
...will be executed (after the ajax call has completed), the execution context is changed. It will be inside a jQuery object context. So at that point, this === jQuery, which as you already saw, has no image property. Hence, the error.
By the way, google for JavaScript closures and try to understand them. It's exactly what your problem is all about. | Declaring the variable using 'var' will work thanks to the sol-called 'closure' you are creating. The 'this' keyword refers to the currently scoped object, which, depending on the situation, might refer to the function, the window object, or any other object. This scope will most definitively be different once the callback method fires and thus is not reliable. | Declaring variables using the keyword this in js | [
"",
"javascript",
"jquery",
""
] |
I'm currently working on a simple game in Java with several different modes. I've extended a main Game class to put the main logic within the other classes. Despite this, the main game class is still pretty hefty.
After taking a quick look at my code the majority of it was Getters and Setters (60%) compared to the rest that is truly needed for the logic of the game.
A couple of Google searches have claimed that Getters and Setters are evil, whilst others have claimed that they are necessary for good OO practice and great programs.
So what should I do? Which should it be? Should I be changing my Getters and Setters for my private variables, or should I stick with them? | There is also the point of view that most of the time, using setters still breaks encapsulation by allowing you to set values that are meaningless. As a very obvious example, if you have a score counter on the game that only ever goes up, instead of
```
// Game
private int score;
public void setScore(int score) { this.score = score; }
public int getScore() { return score; }
// Usage
game.setScore(game.getScore() + ENEMY_DESTROYED_SCORE);
```
it should be
```
// Game
private int score;
public int getScore() { return score; }
public void addScore(int delta) { score += delta; }
// Usage
game.addScore(ENEMY_DESTROYED_SCORE);
```
This is perhaps a bit of a facile example. What I'm trying to say is that discussing getter/setters vs public fields often obscures bigger problems with objects manipulating each others' internal state in an intimate manner and hence being too closely coupled.
The idea is to make methods that directly do things you want to do. An example would be how to set enemies' "alive" status. You might be tempted to have a setAlive(boolean alive) method. Instead you should have:
```
private boolean alive = true;
public boolean isAlive() { return alive; }
public void kill() { alive = false; }
```
The reason for this is that if you change the implementation that things no longer have an "alive" boolean but rather a "hit points" value, you can change that around without breaking the contract of the two methods you wrote earlier:
```
private int hp; // Set in constructor.
public boolean isAlive() { return hp > 0; } // Same method signature.
public void kill() { hp = 0; } // Same method signature.
public void damage(int damage) { hp -= damage; }
``` | * Very evil: public fields.
* Somewhat evil: Getters and setters where they're not required.
* Good: Getters and setters only where they're really required - make the type expose "larger" behaviour which happens to *use* its state, rather than just treating the type as a repository of state to be manipulated by other types.
It really depends on the situation though - sometimes you really *do* just want a dumb data object. | Are getters and setters poor design? Contradictory advice seen | [
"",
"java",
"oop",
"setter",
"getter",
"accessor",
""
] |
In **C++**, is there any difference between:
```
struct Foo { ... };
```
and:
```
typedef struct { ... } Foo;
``` | In C++, there is only a subtle difference. It's a holdover from C, in which it makes a difference.
The C language standard ([C89 §3.1.2.3](http://port70.net/~nsz/c/c89/c89-draft.txt), [C99 §6.2.3](http://port70.net/~nsz/c/c99/n1256.html#6.2.3), and [C11 §6.2.3](http://port70.net/~nsz/c/c11/n1570.html#6.2.3)) mandates separate namespaces for different categories of identifiers, including *tag identifiers* (for `struct`/`union`/`enum`) and *ordinary identifiers* (for `typedef` and other identifiers).
If you just said:
```
struct Foo { ... };
Foo x;
```
you would get a compiler error, because `Foo` is only defined in the tag namespace.
You'd have to declare it as:
```
struct Foo x;
```
Any time you want to refer to a `Foo`, you'd always have to call it a `struct Foo`. This gets annoying fast, so you can add a `typedef`:
```
struct Foo { ... };
typedef struct Foo Foo;
```
Now `struct Foo` (in the tag namespace) and just plain `Foo` (in the ordinary identifier namespace) both refer to the same thing, and you can freely declare objects of type `Foo` without the `struct` keyword.
---
The construct:
```
typedef struct Foo { ... } Foo;
```
is just an abbreviation for the declaration and `typedef`.
---
Finally,
```
typedef struct { ... } Foo;
```
declares an anonymous structure and creates a `typedef` for it. Thus, with this construct, it doesn't have a name in the tag namespace, only a name in the typedef namespace. This means it also cannot be forward-declared. *If you want to make a forward declaration, you have to give it a name in the tag namespace*.
---
In C++, all `struct`/`union`/`enum`/`class` declarations act like they are implicitly `typedef`'ed, as long as the name is not hidden by another declaration with the same name. See [Michael Burr's answer](https://stackoverflow.com/questions/612328/difference-between-struct-and-typedef-struct-in-c/612476#612476) for the full details. | In [this DDJ article](http://drdobbs.com/article/print?articleId=184403396), Dan Saks explains one small area where bugs can creep through if you do not typedef your structs (and classes!):
> If you want, you can imagine that C++
> generates a typedef for every tag
> name, such as
>
> ```
> typedef class string string;
> ```
>
> Unfortunately, this is not entirely
> accurate. I wish it were that simple,
> but it's not. C++ can't generate such
> typedefs for structs, unions, or enums
> without introducing incompatibilities
> with C.
>
> For example, suppose a C program
> declares both a function and a struct
> named status:
>
> ```
> int status(); struct status;
> ```
>
> Again, this may be bad practice, but
> it is C. In this program, status (by
> itself) refers to the function; struct
> status refers to the type.
>
> If C++ did automatically generate
> typedefs for tags, then when you
> compiled this program as C++, the
> compiler would generate:
>
> ```
> typedef struct status status;
> ```
>
> Unfortunately, this type name would
> conflict with the function name, and
> the program would not compile. That's
> why C++ can't simply generate a
> typedef for each tag.
>
> In C++, tags act just like typedef
> names, except that a program can
> declare an object, function, or
> enumerator with the same name and the
> same scope as a tag. In that case, the
> object, function, or enumerator name
> hides the tag name. The program can
> refer to the tag name only by using
> the keyword class, struct, union, or
> enum (as appropriate) in front of the
> tag name. A type name consisting of
> one of these keywords followed by a
> tag is an elaborated-type-specifier.
> For instance, struct status and enum
> month are elaborated-type-specifiers.
>
> Thus, a C program that contains both:
>
> ```
> int status(); struct status;
> ```
>
> behaves the same when compiled as C++.
> The name status alone refers to the
> function. The program can refer to the
> type only by using the
> elaborated-type-specifier struct
> status.
>
> So how does this allow bugs to creep
> into programs? Consider the program in
> [Listing 1](http://drdobbs.com/cpp/184403396?pgno=1). This program defines a
> class foo with a default constructor,
> and a conversion operator that
> converts a foo object to char const \*.
> The expression
>
> ```
> p = foo();
> ```
>
> in main should construct a foo object
> and apply the conversion operator. The
> subsequent output statement
>
> ```
> cout << p << '\n';
> ```
>
> should display class foo, but it
> doesn't. It displays function foo.
>
> This surprising result occurs because
> the program includes header lib.h
> shown in [Listing 2](http://drdobbs.com/cpp/184403396?pgno=2). This header
> defines a function also named foo. The
> function name foo hides the class name
> foo, so the reference to foo in main
> refers to the function, not the class.
> main can refer to the class only by
> using an elaborated-type-specifier, as
> in
>
> ```
> p = class foo();
> ```
>
> The way to avoid such confusion
> throughout the program is to add the
> following typedef for the class name
> foo:
>
> ```
> typedef class foo foo;
> ```
>
> immediately before or after the class
> definition. This typedef causes a
> conflict between the type name foo and
> the function name foo (from the
> library) that will trigger a
> compile-time error.
>
> I know of no one who actually writes
> these typedefs as a matter of course.
> It requires a lot of discipline. Since
> the incidence of errors such as the
> one in [Listing 1](http://drdobbs.com/cpp/184403396?pgno=1) is probably pretty
> small, you many never run afoul of
> this problem. But if an error in your
> software might cause bodily injury,
> then you should write the typedefs no
> matter how unlikely the error.
>
> I can't imagine why anyone would ever
> want to hide a class name with a
> function or object name in the same
> scope as the class. The hiding rules
> in C were a mistake, and they should
> not have been extended to classes in
> C++. Indeed, you can correct the
> mistake, but it requires extra
> programming discipline and effort that
> should not be necessary. | Difference between 'struct' and 'typedef struct' in C++? | [
"",
"c++",
"struct",
"typedef",
""
] |
When ASP.NET controls are rendered their ids sometimes change, like if they are in a naming container. `Button1` may actually have an id of `ctl00_ContentMain_Button1` when it is rendered, for example.
I know that you can write your JavaScript as strings in your .cs file, get the control's clientID and inject the script into your page using clientscript, but is there a way that you can reference a control directly from JavaScript using ASP.NET Ajax?
I have found that writing a function to parse the dom recursively and find a control that CONTAINS the id that I want is unreliable, so I was looking for a best practice rather than a work-around. | Oh, and I also found this, in case anyone else is having this problem.
Use a custom jQuery selector for asp.net controls:
<http://john-sheehan.com/blog/custom-jquery-selector-for-aspnet-webforms/> | This post by Dave Ward might have what you're looking for:
<http://encosia.com/2007/08/08/robust-aspnet-control-referencing-in-javascript/>
Excerpt from article:
> Indeed there is. The better solution
> is to use inline ASP.NET code to
> inject the control’s ClientID
> property:
>
> ```
> $get('<%= TextBox1.ClientID %>')
> ```
>
> Now the correct client element ID is
> referenced, regardless of the
> structure of the page and the nesting
> level of the control. In my opinion,
> the very slight performance cost of
> this method is well worth it to make
> your client scripting more resilient
> to change.
And some sample code by Dave from the comment thread of that post:
```
<script>
alert('TextBox1 has a value of: ' + $get('<%= TextBox1.ClientID %>').value);
</script>
```
The comment thread to the article I linked above has some good discussion as well. | Reference ASP.NET control by ID in JavaScript? | [
"",
"javascript",
"asp.net",
"ajax",
""
] |
Suppose I have two modules:
a.py:
```
import b
print __name__, __file__
```
b.py:
```
print __name__, __file__
```
I run the "a.py" file. This prints:
```
b C:\path\to\code\b.py
__main__ C:\path\to\code\a.py
```
**Question**: how do I obtain the path to the `__main__` module ("a.py" in this case) from within the "b.py" library? | ```
import __main__
print(__main__.__file__)
``` | Perhaps this will do the trick:
```
import sys
from os import path
print(path.abspath(str(sys.modules['__main__'].__file__)))
```
Note that, for safety, you should check whether the `__main__` module has a `__file__` attribute. If it's dynamically created, or is just being run in the interactive python console, it won't have a `__file__`:
```
python
>>> import sys
>>> print(str(sys.modules['__main__']))
<module '__main__' (built-in)>
>>> print(str(sys.modules['__main__'].__file__))
AttributeError: 'module' object has no attribute '__file__'
```
A simple hasattr() check will do the trick to guard against scenario 2 if that's a possibility in your app. | How to get filename of the __main__ module in Python? | [
"",
"python",
"python-module",
""
] |
I am not sure I am getting the correct definition for what API Usage is. I have a snippet of code that is used for a BulkInsert into SQL from c# application. It said the snippet shows the API usage. How do I translate that?
```
private void WriteToDatabase()
{
// get your connection string
string connString = "";
// connect to SQL
using (SqlConnection connection =
new SqlConnection(connString))
{
// make sure to enable triggers
// more on triggers in next post
SqlBulkCopy bulkCopy =
new SqlBulkCopy
(
connection,
SqlBulkCopyOptions.TableLock |
SqlBulkCopyOptions.FireTriggers |
SqlBulkCopyOptions.UseInternalTransaction,
null
);
// set the destination table name
bulkCopy.DestinationTableName = this.tableName;
connection.Open();
// write the data in the "dataTable"
bulkCopy.WriteToServer(dataTable);
connection.Close();
}
// reset
this.dataTable.Clear();
this.recordCount = 0;
}
``` | [An application programming interface (API) is a set of routines, data structures, object classes and/or protocols provided by libraries and/or operating system services in order to support the building of applications](http://en.wikipedia.org/wiki/API)
In simpler terms, an API consists of the bits of an assembly you can see and interact with from the outside. The Microsoft.NET framework has LOTS of stuff that you can't use because they are not part of the framework's API. These classes, methods, interfaces, etc are marked internal or private, and are intended for use by MS.
What you're looking at is just an example of using this code from the perspective of someone on the outside of the library looking in. In other words, you could have written this code yourself, as a consumer of the API. It doesn't detail all the possible ways to use the API, but it gives you a hint. | Do you mean something like "System Integration," where you are writing code that connects to an API for something? If not, you may have to elaborate a bit more in terms of context.
EDIT: It would appear to me that you are merely testing the API by giving it a simple case to process. This is using the API and I could see some cases where one wants to find all instances where a particular API call is used such as if one is changing the API. | What is API Usage? | [
"",
"c#",
".net",
"asp.net",
"sql-server",
""
] |
When I launch an SWT application (via an Eclipse launch profile), I receive the following stack trace:
```
Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/jface/resource/FontRegistry
at org.eclipse.jface.resource.JFaceResources.getFontRegistry(JFaceResources.java:338)
at org.eclipse.jface.window.Window.close(Window.java:313)
at org.eclipse.jface.dialogs.Dialog.close(Dialog.java:971)
at org.eclipse.jface.dialogs.ProgressMonitorDialog.close(ProgressMonitorDialog.java:348)
at org.eclipse.jface.dialogs.ProgressMonitorDialog.finishedRun(ProgressMonitorDialog.java:582)
at org.eclipse.jface.dialogs.ProgressMonitorDialog.run(ProgressMonitorDialog.java:498)
at com.blah.si.workflow.SWTApplication.main(SWTApplication.java:135)
```
Now, the things that make this odd:
1. When I change the project build path and replace jface.jar with the source project (same version - 3.3.1), the error goes away.
2. Other applications I have that use the same jar, and a copy of the same launch profile and project, all works fine.
3. This is **NOT** a `ClassNotFoundException`. The class is on the classpath. If I attach source to the jar, I can debug into the getFontRegistry method. The method will execute successfully several times before eventually throwing a `NoClassDefFoundError` on line 338. Line 337 is a "if variable == null" statement checking to see if a static variable has been initialized. Line 338 is initializing it if it is not already initialized. The first time through, the null check fails, and the initialization is performed. On subsequent passes through the method, the null check passes, and thus the already-initialized static value is returned. On the final pass (the one that fails,) the null check fails again (even though the static variable has already been initialized) and when it tries to re-initialize the static variable, the `NoClassDefFoundError` is thrown. Here is the relevant source (starting with line 336, note that fontRegistry is a private static variable that is set in no other place):
.
```
public static FontRegistry getFontRegistry() {
if (fontRegistry == null) {
fontRegistry = new FontRegistry(
"org.eclipse.jface.resource.jfacefonts");
}
return fontRegistry;
}
```
.
1. I have already gotten a fresh copy of the jar (to ensure it isn't corrupted,) deleted my .classpath and .project files and started a fresh project, and recreated the launch profile. No change.
Because of the peculiarities in #3 above, I'm suspecting some kind of wierd classloader behavior - it seems as if that final pass through the method is in another classloader?
Ideas?
**Update:** The answer provided by Pourquoi Litytestdata prompted me to pay attention to what happens in the try block just above line 458 of ProgressMonitorDialog. Indeed, that code was throwing an exception, which was being gobbled by the finally block. The root cause was ANOTHER missing class (the missing class was not JFontRegistry or any of its directly related classes, but another that was spider-web dependencied in an edge case.) I'm upvoting all answers pointing me to pay attention to the classpath, and accepting Pourquoi's, because it was the breakthrough. Thanks to all. | I think the stacktrace presented above is concealing the real problem here. Below is the code in the method `run` within
[org.eclipse.jface.dialogs.ProgressMonitorDialog](http://kickjava.com/src/org/eclipse/jface/dialogs/ProgressMonitorDialog.java.htm) (with a comment added by me):
```
public void run(boolean fork, boolean cancelable,
IRunnableWithProgress runnable) throws InvocationTargetException,
InterruptedException {
setCancelable(cancelable);
try {
aboutToRun();
// Let the progress monitor know if they need to update in UI Thread
progressMonitor.forked = fork;
ModalContext.run(runnable, fork, getProgressMonitor(), getShell()
.getDisplay());
} finally {
finishedRun(); // this is line 498
}
}
```
The second-from-bottom line in Jared's stacktrace is line 498 of this class, which is the call to `finishedRun()` within the `finally` block. I suspect that the real cause is an exception being thrown in the `try` block. Since the code in the `finally` block also throws an exception, the original exception is lost. | It sounds like you are missing a JAR file that holds a dependency, as mentioned in this blog entry from July 2006, written by [**Sanjiv JIVAN**](http://www.jroller.com/sjivan/):
[**Difference between ClassNotFoundException and NoClassDefFoundError**](http://www.jroller.com/sjivan/entry/difference_between_classnotfoundexception_and_noclassdeffounderror)
> A **`ClassNotFoundException`** is thrown when the reported class is not found by the ClassLoader.
> This typically means that the class is missing from the `CLASSPATH`.
> It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent `ClassLoader` and hence the class from the child `ClassLoader` is not visible.
> This is sometimes the case when working in more complex environments like an App Server (WebSphere is infamous for such `ClassLoader` issues).
>
> People often tend to confuse **`java.lang.NoClassDefFoundError`** with `java.lang.ClassNotFoundException`. However there's an important distinction.
>
> For example an exception (an error really since **`java.lang.NoClassDefFoundError`** is a subclass of **`java.lang.Error`**) like
```
java.lang.NoClassDefFoundError:
org/apache/activemq/ActiveMQConnectionFactory
```
> does not mean that the ActiveMQConnectionFactory class is not in the `CLASSPATH`.
>
> In fact, its quite the opposite.
>
> **It means that the class `ActiveMQConnectionFactory` was found by the `ClassLoader` however when trying to load the class, it ran into an error reading the class definition.**
>
> **This typically happens when the class in question has static blocks or members which use a Class that's not found by the `ClassLoader`.**
>
> So to find the culprit, view the source of the class in question (`ActiveMQConnectionFactory` in this case) and **look for code using static blocks or static members**.
> If you don't have access the the source, then simply decompile it using **[JAD](http://www.kpdus.com/jad.html)**.
>
> On examining the code, say you find a line of code like below, make sure that the class SomeClass in in your `CLASSPATH`.
```
private static SomeClass foo = new SomeClass();
```
> Tip : To find out which jar a class belongs to, you can use the web site **[jarFinder](http://www.jarfinder.com/)**. This allows you to specify a class name using wildcards and it searches for the class in its database of jars.
> [jarhoo](http://www.jarhoo.com/) allows you to do the same thing but its no longer free to use.
>
> If you would like to locate the which jar a class belongs to in a local path, you can use a utility like **[jarscan](http://www.inetfeedback.com/jarscan/)**. You just specify the class you'd like to locate and the root directory path where you'd like it to start searching for the class in jars and zip files. | NoClassDefFoundError on JFace FontRegistry | [
"",
"java",
"eclipse",
"swt",
""
] |
I'm calling a function in Python which I know may stall and force me to restart the script.
How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else? | You may use the [signal](http://docs.python.org/library/signal.html) package if you are running on UNIX:
```
In [1]: import signal
# Register an handler for the timeout
In [2]: def handler(signum, frame):
...: print("Forever is over!")
...: raise Exception("end of time")
...:
# This function *may* run for an indetermined time...
In [3]: def loop_forever():
...: import time
...: while 1:
...: print("sec")
...: time.sleep(1)
...:
...:
# Register the signal function handler
In [4]: signal.signal(signal.SIGALRM, handler)
Out[4]: 0
# Define a timeout for your function
In [5]: signal.alarm(10)
Out[5]: 0
In [6]: try:
...: loop_forever()
...: except Exception, exc:
...: print(exc)
....:
sec
sec
sec
sec
sec
sec
sec
sec
Forever is over!
end of time
# Cancel the timer if the function returned before timeout
# (ok, mine won't but yours maybe will :)
In [7]: signal.alarm(0)
Out[7]: 0
```
10 seconds after the call `signal.alarm(10)`, the handler is called. This raises an exception that you can intercept from the regular Python code.
This module doesn't play well with threads (but then, who does?)
**Note that** since we raise an exception when timeout happens, it may end up caught and ignored inside the function, for example of one such function:
```
def loop_forever():
while 1:
print('sec')
try:
time.sleep(10)
except:
continue
``` | You can use `multiprocessing.Process` to do exactly that.
**Code**
```
import multiprocessing
import time
# bar
def bar():
for i in range(100):
print "Tick"
time.sleep(1)
if __name__ == '__main__':
# Start bar as a process
p = multiprocessing.Process(target=bar)
p.start()
# Wait for 10 seconds or until process finishes
p.join(10)
# If thread is still active
if p.is_alive():
print "running... let's kill it..."
# Terminate - may not work if process is stuck for good
p.terminate()
# OR Kill - will work for sure, no chance for process to finish nicely however
# p.kill()
p.join()
``` | Timeout on a function call | [
"",
"python",
"multithreading",
"timeout",
"python-multithreading",
""
] |
I need to model some information about seasons, and need to track them based on start / end date in a year-agnostic way. I.e. I need to allow users to define summer as being between, say, May 15th and September 10th, and do that for all years.
I'll need to do a lot of checking of the type isThisDateInSeason). All the date manipulation functions (i.e. Date, Calendar) seem to only work with valid dates, i.e. including year information.
Are there any best practices around how to do this? I can think of a bunch of hacky ways of doing it (i.e. store month and day of the month or to store dates and just bring them to a baseline year so I can can compare), but it seems like there might be a better way.
I am writing this in Java or Groovy.
Would the [Joda-Time](http://www.joda.org/joda-time/) library help here? I don't have experience with it, but it looks to have much more flexibility.
I found [this question](https://stackoverflow.com/questions/189468/identifying-the-season-from-the-date-using-java) about how to identify a season from date, but that focuses on months, and I need more flexibility to include dates. | If each user owns their own data (i.e. they specify their seasons and then they enter their own information) then you could just store the data with the season as part of it, however I have a feeling the scenario you are after is for shared data across numerous users who define seasons differently.
You would have to be very careful to 'normalize' dates as the leap year may cause unexpected problems, i.e. trying to set Feb 29 on a non leap year will cause problems / exceptions.
I have put the below together, unforutnatly its c# but the concept will be the same. I havnt actually tested the code, but as a even as psudo code it may help.
```
public class SeasonChecker
{
public enum Season {Summer, Autumn, Winter, Spring};
private List<SeasonRange> _seasons = new List<SeasonRange>();
public void DefineSeason(Season season, DateTime starting, DateTime ending)
{
starting = starting.Date;
ending = ending.Date;
if(ending.Month < starting.Month)
{
// split into 2
DateTime tmp_ending = new DateTime(ending.Year, 12, 31);
DateTime tmp_starting = new DateTime(starting.Year, 1, 1);
SeasonRange r1 = new SeasonRange() { Season = season, Starting= tmp_starting, Ending = ending };
SeasonRange r2 = new SeasonRange() { Season = season, Starting= starting, Ending = tmp_ending };
this._seasons.Add(r1);
this._seasons.Add(r2);
}
else
{
SeasonRange r1 = new SeasonRange() { Season = season, Starting= starting, Ending = ending };
this._seasons.Add(r1);
}
}
public Season GetSeason(DateTime check)
{
foreach(SeasonRange range in _seasons)
{
if(range.InRange(check))
return range.Season;
}
throw new ArgumentOutOfRangeException("Does not fall into any season");
}
private class SeasonRange
{
public DateTime Starting;
public DateTime Ending;
public Season Season;
public bool InRange(DateTime test)
{
if(test.Month == Starting.Month)
{
if(test.Day >= Starting.Day)
{
return true;
}
}
else if(test.Month == Ending.Month)
{
if(test.Day <= Ending.Day)
{
return true;
}
}
else if(test.Month > Starting.Month && test.Month < Ending.Month)
{
return true;
}
return false;
}
}
}
```
Note the above code makes the assumption that the season will not start and end on the same month - a fairly safe one I think! | I think you'll have to roll your own DateRange class, although this is such a common problem you would hope there is already a clever util out there that does it. As a general point when dealing with seasons you also have to take account of geography, which will make life really hard. In Oz we're the reverse of the US, so Summer runs from November to February. | Best practice for ignoring year in date for date ranges | [
"",
"java",
"groovy",
"date",
"jodatime",
""
] |
Is there any significant advantages for converting a string to an integer value between int.Parse() and Convert.ToInt32() ?
```
string stringInt = "01234";
int iParse = int.Parse(stringInt);
int iConvert = Convert.ToInt32(stringInt);
```
I found a [question](https://stackoverflow.com/questions/104063/system-convert-toint-vs-int) asking about casting vs Convert but I think this is different, right? | When passed a string as a parameter, Convert.ToInt32 calls int.Parse internally. So the only difference is an additional null check.
Here's the code from .NET Reflector
```
public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}
return int.Parse(value, CultureInfo.CurrentCulture);
}
``` | For what its worth:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int iterations = 1000000;
string val = "01234";
Console.Write("Run 1: int.Parse() ");
DateTime start = DateTime.Now;
DoParse(iterations, val);
TimeSpan duration = DateTime.Now - start;
Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms");
Console.Write("Run 1: Convert.ToInt32() ");
start = DateTime.Now;
DoConvert(iterations, val);
duration = DateTime.Now - start;
Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms");
Console.Write("Run 2: int.Parse() ");
start = DateTime.Now;
DoParse(iterations, val);
duration = DateTime.Now - start;
Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms");
Console.Write("Run 2: Convert.ToInt32() ");
start = DateTime.Now;
DoConvert(iterations, val);
duration = DateTime.Now - start;
Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms");
Console.Write("Run 3: int.Parse() ");
start = DateTime.Now;
DoParse(iterations, val);
duration = DateTime.Now - start;
Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms");
Console.Write("Run 3: Convert.ToInt32() ");
start = DateTime.Now;
DoConvert(iterations, val);
duration = DateTime.Now - start;
Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms");
Console.ReadKey();
}
static void DoParse(int iterations, string val)
{
int x;
for (int i = 0; i < iterations; i++)
{
x = int.Parse(val);
}
}
static void DoConvert(int iterations, string val)
{
int x;
for (int i = 0; i < iterations; i++)
{
x = Convert.ToInt32(val);
}
}
}
}
```
Result of 1,000,000 iterations of each:
```
Run 1: int.Parse() Duration: 312.5ms
Run 1: Convert.ToInt32() Duration: 328.125ms
Run 2: int.Parse() Duration: 296.875ms
Run 2: Convert.ToInt32() Duration: 312.5ms
Run 3: int.Parse() Duration: 312.5ms
Run 3: Convert.ToInt32() Duration: 312.5ms
``` | Any performance difference between int.Parse() and Convert.Toint()? | [
"",
"c#",
"performance",
""
] |
I have next code:
```
#include <iostream>
#include <algorithm>
#include <map>
#include <iterator>
//namespace std
//{
std::ostream& operator << ( std::ostream& out,
const std::pair< size_t, size_t >& rhs )
{
out << rhs.first << ", " << rhs.second;
return out;
}
//}
int main()
{
std::map < size_t, size_t > some_map;
// fill some_map with random values
for ( size_t i = 0; i < 10; ++i )
{
some_map[ rand() % 10 ] = rand() % 100;
}
// now I want to output this map
std::copy(
some_map.begin(),
some_map.end(),
std::ostream_iterator<
std::pair< size_t, size_t > >( std::cout, "\n" ) );
return 0;
}
```
In this code I just want copy map to output stream. For do this I need define operator <<(..) - OK.
But according names finding rules compiler can't find my operator<<().
Because std::cout, std::pair and std::copy which called my operator<< - all from namespace std.
Quick solution - add my oerator<< to std namespace - but it is ugly, imho.
What solutions or workaround for this problem do you know? | I've founded one new elegant way to solve this problem.
I've got many interest ideas when read answers:
* wrap iterator, for transform std::pair to std::string;
* wrap std::pair, for have a chance to overload operator<<(...);
* use usual std::for\_each with printing functor;
* use std::for\_each with boost::labda - looks nice, except accessing to std::pair< >::first and std::pair< >::second members;
I think I will use all of this ideas in future for solve different other problems.
But for this case I've understaded that I can formulate my bproblem as "transform map's data to strings and write them to output stream" instead "copy map's data to ouput stream". My solution looks like:
```
namespace
{
std::string toString( const std::pair< size_t, size_t >& data)
{
std::ostringstream str;
str << data.first << ", " << data.second;
return str.str();
}
} // namespace anonymous
std::transform(
some_map.begin(),
some_map.end(),
std::ostream_iterator< std::string >( std::cout, "\n" ),
toString );
```
I think this method is most short and expressive than others. | There is no standard way to cout a `std::pair` because, well, how you want it printed is probably different from the way the next guy wants it. This is a good use case for a custom functor or a lambda function. You can then pass that as an argument to `std::for_each` to do the work.
```
typedef std::map<size_t, size_t> MyMap;
template <class T>
struct PrintMyMap : public std::unary_function<T, void>
{
std::ostream& os;
PrintMyMap(std::ostream& strm) : os(strm) {}
void operator()(const T& elem) const
{
os << elem.first << ", " << elem.second << "\n";
}
}
```
To call this functor from your code:
```
std::for_each(some_map.begin(),
some_map.end(),
PrintMyMap<MyMap::value_type>(std::cout));
``` | std::copy to std::cout for std::pair | [
"",
"c++",
"stl",
"namespaces",
"operator-overloading",
""
] |
I have been trying to figure out how to retrieve (quickly) the number of files on a given HFS+ drive with python.
I have been playing with os.statvfs and such, but can't quite get anything (that seems helpful to me).
Any ideas?
**Edit:** Let me be a bit more specific. =]
I am writing a timemachine-like wrapper around rsync for various reasons, and would like a very fast estimate (does not have to be perfect) of the number of files on the drive rsync is going to scan. This way I can watch the progress from rsync (if you call it like `rsync -ax --progress`, or with the `-P` option) as it builds its initial file list, and report a percentage and/or ETA back to the user.
This is completely separate from the actual backup, which is no problem tracking progress. But with the drives I am working on with several million files, it means the user is watching a counter of the number of files go up with no upper bound for a few minutes.
I have tried playing with os.statvfs with exactly the method described in one of the answers so far, but the results do not make sense to me.
```
>>> import os
>>> os.statvfs('/').f_files - os.statvfs('/').f_ffree
64171205L
```
The more portable way gives me around 1.1 million on this machine, which is the same as every other indicator I have seen on this machine, including rsync running its preparations:
```
>>> sum(len(filenames) for path, dirnames, filenames in os.walk("/"))
1084224
```
Note that the first method is instantaneous, while the second one made me come back 15 minutes later to update because it took just that long to run.
Does anyone know of a similar way to get this number, or what is wrong with how I am treating/interpreting the os.statvfs numbers? | You could use a number from a previous `rsync` run. It is quick, portable, and for `10**6` files and any reasonable backup strategy it will give you `1%` or better precision. | The right answer for your purpose is to live without a progress bar once, store the number rsync came up with and assume you have the same number of files as last time for each successive backup.
I didn't believe it, but this seems to work on Linux:
```
os.statvfs('/').f_files - os.statvfs('/').f_ffree
```
This computes the total number of file blocks minus the free file blocks. It seems to show results for the whole filesystem even if you point it at another directory. os.statvfs is implemented on Unix only.
OK, I admit, I didn't actually let the 'slow, correct' way finish before marveling at the fast method. Just a few drawbacks: I suspect `.f_files` would also count directories, and the result is probably totally wrong. It might work to count the files the slow way, once, and adjust the result from the 'fast' way?
The portable way:
```
import os
files = sum(len(filenames) for path, dirnames, filenames in os.walk("/"))
```
`os.walk` returns a 3-tuple (dirpath, dirnames, filenames) for each directory in the filesystem starting at the given path. This will probably take a long time for `"/"`, but you knew that already.
The easy way:
Let's face it, nobody knows or cares how many files they really have, it's a humdrum and nugatory statistic. You can add this cool 'number of files' feature to your program with this code:
```
import random
num_files = random.randint(69000, 4000000)
```
Let us know if any of these methods works for you.
See also [How do I prevent Python's os.walk from walking across mount points?](https://stackoverflow.com/questions/577761/how-do-i-prevent-pythons-os-walk-from-walking-across-mount-points) | How to determine number of files on a drive with Python? | [
"",
"python",
"macos",
"filesystems",
"hard-drive",
""
] |
I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). Is there a way to combine these actions?
Maybe a "save and run" command. | **Option 1:**
Write a function similar to this and place it in your startup settings:
```
function myex()
execute ':w'
execute ':!!'
endfunction
```
You could even map a key combination to it -- look at the documentation.
---
**Option 2 (better):**
Look at the documentation for remapping keystrokes - you may be able to accomplish it through a simple key remap. The following works, but has "filename.py" hardcoded. Perhaps you can dig in and figure out how to replace that with the current file?
```
:map <F2> <Esc>:w<CR>:!filename.py<CR>
```
After mapping that, you can just press `F2` in command mode.
imap, vmap, etc... are mappings in different modes. The above only applies to command mode. The following should work in insert mode also:
```
:imap <F2> <Esc>:w<CR>:!filename.py<CR>a
```
Section 40.1 of the Vim manual is very helpful. | Okay, the simplest form of what you're looking for is the pipe command. It allows you to run multiple cmdline commands on the same line. In your case, the two commands are write `w` and execute current file `! %:p`. If you have a specific command you run for you current file, the second command becomes, e.g. `!python %:p`. So, the simplest answer to you question becomes:
```
:w | ! %:p
^ ^ ^
| | |--Execute current file
| |--Chain two commands
|--Save current file
```
One last thing to note is that not all commands can be chained. According to the [Vim docs](http://vimdoc.sourceforge.net/htmldoc/cmdline.html#cmdline-lines), certain commands accept a pipe as an argument, and thus break the chain... | Save and run at the same time in Vim | [
"",
"python",
"vim",
""
] |
Can any one tell me the advantage of synchronized method over synchronized block with an example? | > *Can anyone tell me the advantage of the synchronized method over the synchronized block with an example? Thanks.*
There is not a clear advantage of using synchronized method over the block.
Perhaps the only one ( but I wouldn't call it an advantage ) is you don't need to include the object reference `this`.
Method:
```
public synchronized void method() { // blocks "this" from here....
...
...
...
} // to here
```
Block:
```
public void method() {
synchronized( this ) { // blocks "this" from here ....
....
....
....
} // to here...
}
```
See? No advantage at all.
Blocks **do** have advantages over methods though, mostly in flexibility because you can use another object as lock whereas syncing the method would lock the entire object.
Compare:
```
// locks the whole object
...
private synchronized void someInputRelatedWork() {
...
}
private synchronized void someOutputRelatedWork() {
...
}
```
vs.
```
// Using specific locks
Object inputLock = new Object();
Object outputLock = new Object();
private void someInputRelatedWork() {
synchronized(inputLock) {
...
}
}
private void someOutputRelatedWork() {
synchronized(outputLock) {
...
}
}
```
Also if the method grows you can still keep the synchronized section separated:
```
private void method() {
... code here
... code here
... code here
synchronized( lock ) {
... very few lines of code here
}
... code here
... code here
... code here
... code here
}
``` | The only real difference is that a synchronized block can choose which object it synchronizes on. A synchronized method can only use `'this'` (or the corresponding Class instance for a synchronized class method). For example, these are semantically equivalent:
```
synchronized void foo() {
...
}
void foo() {
synchronized (this) {
...
}
}
```
The latter is more flexible since it can compete for the associated lock of *any* object, often a member variable. It's also more granular because you could have concurrent code executing before and after the block but still within the method. Of course, you could just as easily use a synchronized method by refactoring the concurrent code into separate non-synchronized methods. Use whichever makes the code more comprehensible. | Is there an advantage to use a Synchronized Method instead of a Synchronized Block? | [
"",
"java",
"multithreading",
"concurrency",
"locking",
"synchronized",
""
] |
When I assign an array of data to be POSTed as a cURL option (via CURLOPT\_POSTFIELDS), do I need to urlencode that data first or will that be taken care of? | The C implementation of [`curl_setopt`](http://curl.haxx.se/) doesn't seem to URL-encode the text. However, in PHP5, the [`http_build_query`](https://www.php.net/http_build_query) function returns a query string representation of the array that *is* URL-encoded.
### Example Usage
```
$curl_parameters = array(
'param1' => $param1,
'param2' => $param2
);
$curl_options = array(
CURLOPT_URL => "http://localhost/service",
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query( $curl_parameters ),
CURLOPT_HTTP_VERSION => 1.0,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false
);
$curl = curl_init();
curl_setopt_array( $curl, $curl_options );
$result = curl_exec( $curl );
curl_close( $curl );
``` | You don't have to urlencode first. However, it is important to realize that passing an array will make cURL send it as `multipart/form-data`, which explains why it is does not need to get urlencoded (by neither you nor cURL), and you need to use an array if you want to upload files. If you `http_build_query()` first (and send it as a string) it will be treated as `application/x-www-form-urlencoded`. | How to send array with CURL? Should I `urlencode` it? | [
"",
"php",
"post",
"curl",
"urlencode",
""
] |
I have a table with a status column (initially with `progress`). I need to update this column's value to `success`.
Is this query what I want?
```
Update "tablename" set status='success' where status='progress'
```
The reason I am asking is that both the update and the where condition are checking the same column.
Is this correct? | That statement will change the value for each row where status was "progress" to "success". Is that really what you want? | That will work but it will modify **all** rows that have progress in that column.
I think you probably want to limit the update based on some other part of the record.
For example if it were the progress of installing a particular piece of software (say Ubuntu on machine number 7):
```
update tbl set status='success'
where status='progress'
and machine_id = 7
and software = 'Ubuntu'
```
From a conceptual point of view, it's gathering the list of records to change first (with the `where` clause), then applying the `update ... set` to all those records. | Updating a column | [
"",
"sql",
""
] |
I'm currently converting a Delphi method used for random binary file access into Java. The Delphi procedure uses:
```
TSingleArray = Array[0..MAXSIZE] of Single
...
procedure GetLinkValues(const LinkVar: Integer; const TimePeriod: Integer; var Value: PSingleArray);
...
BlockRead(Fout, Value^, Nlinks*SizeOf(Single));
```
To read an array of bytes into an array of Single. Is there an equivalent way of doing this in Java without iterating through the array?
I’m currently using
```
List<Float> l = new ArrayList<Float>();
…
for (int i = 0 ; i < nLinks ; i++ )
l.add( resultsFile.readFloat());
```
But I’m concerned about speed. Endianness is not a problem. | Have you profiled the code and actually found it to be a problem? *Something* is going to have to loop... are you really sure this is a bottleneck in your code?
Having said all that, you should be able to use a FloatBuffer which I suspect does what you want. Unfortunately Sun's JavaDoc is down, so I can't easily link to or check the documentation at the minute.
To use a FloatBuffer, you'd probably want to:
* Create a FileChannel associated with the file (e.g. with FileInputStream.getChannel)
* Create a ByteBuffer
* Create a FloatBuffer wrapping the ByteBuffer, with ByteBuffer.asFloatBuffer
* Read into the ByteBuffer with FileChannel.read(byteBuffer)
* Read from the FloatBuffer
I'm not particularly familiar/comfortable with java.nio, so I *hope* this is all correct - but it's likely to be pretty fiddly. Your current loop is almost certainly simpler, so I strongly suggest you check the performance of that first! You might want to wrap your current FileInputStream in a BufferedInputStream, btw. | Based on the help provided by Jon the final code looks like this:
```
byte[] bt = new byte[nLinks * 4];
List<Float> l = new ArrayList<Float>();
if (linkVar != 0 && timePeriod < nPeriods) {
long p1 = RECORDSIZE * (nNodes * NODEVARS + nLinks * LINKVARS);
long p2 = RECORDSIZE * (nNodes * NODEVARS + nLinks * (linkVar - 1));
long p3 = offset2 + (timePeriod * p1) + p2;
resultsFile.seek(p3);
resultsFile.read(bt, 0, nLinks * 4);
ByteBuffer bb = ByteBuffer.wrap(bt);
bb.rewind();
bb.asFloatBuffer().get(values);
}
``` | Converting an array of bytes to an array of floats | [
"",
"java",
"delphi",
"arrays",
""
] |
We are currently running a Java integration application on a Linux box. First an overview of the application.
The Java application is a standalone application (not deployed on any Java EE application server like OracleAS,WebLogic,JBOSS etc).
By Stand Alone I mean its NOT a DESKTOP application. However it is run from the command line from a Main class. The user does not directly interact with this application at all. Messages are dumped into the queue using an API which is then read out by my Application which is constantly running 24/7. I wouldn't qualify this as a desktop app since the user has no direct interaction with it.(Not sure if this is the correct reasoning to qualify as one).
It uses Spring and connects to WebSphere MQ and Oracle Database
We use a Spring Listener(Spring Message Driven POJOs) which listens to a queue on WebSphere MQ. Once there is a message in the queue, the application read the message from the MQ and dumps(insert/update) it into the database.
Now the question is:
1. How can we horizontally scale this application? I mean just putting more boxes and running multiple instances of this same application, is that a viable approach?
2. Should we consider moving from Spring MDPs to EJB MDBs? Thereby deploying it on the Application Server. Is there any added benefit by doing so?
3. There is a request to make the application High Available(HA)? What are the suggested methodologies or strategies that can be put in place to make a standalone application HA? | Does "standalone" == "desktop"?
How do users interact with the controller that owns the message-driven beans?
My opinions on your questions:
1. You can scale by adding more message listeners to the listener pool, since each one runs in its own thread. You should match the size of the database connection pool to message listeners, so that would have to increase as well. Do that before adding more servers. Make sure you have enough RAM on hand.
2. I don't see what EJB MDB buys you over Spring MDB. You keep referring to "app servers". Do you specifically mean Java EE app servers like WebLogic, WebSphere, JBOSS, Glassfish? Because if you're deploying Spring on Tomcat I'd consider Tomcat to be the "app server" in this conversation.
3. HA means load balancing and failover. You'll need to have databases that are either synchronized or hot redeployable. Same with queues. F5 is a great hardware solution for load balancing. I'd talk to your infrastructure folks if you have some. | Another option is [Terracotta](http://www.terracotta.org/web/display/enterprise/Home), a framework that does precisely what you want; running your app on several machines simultaneously and balancing the load among them. | Scalability and high availability of a Java standalone application | [
"",
"java",
"spring",
"scalability",
"high-availability",
""
] |
I've recently seen some information about avoiding coding to specific browsers an instead using feature/bug detection. It seems that John Resig, the creator of jQuery is a big fan of feature/bug detection (he has an excellent talk that includes a discussion of this on [YUI Theater](http://video.yahoo.com/watch/4403981/11812238)). I'm curious if people are finding that this approach makes sense in practice? What if the bug no longer exists in the current version of the browser (It's an IE6 problem but not 7 or 8)? | Object detection's greatest strength is that you only use the objects and features that are available to you by the client's browser. In other words given the following code:
```
if (document.getFoo) {
// always put getFoo in here
} else {
// browsers who don't support getFoo go here
}
```
allows you to cleanly separate out the browsers without naming names. The reason this is cool is because as long as a browser supports `getFoo` you don't have to worry which one it is. This means that you may actually support browsers you have never heard of. If you target user agent strings find the browser then you only can support the browsers you know.
Also if a browser that previously did not support `getFoo` gets with the program and releases a new version that does, you don't have to change your code at all to allow the new browser to take advantage of the better code. | > What if the bug no longer exists in the current version of the browser (It's an IE6 problem but not 7 or 8)?
That's the whole point of feature/bug detection. If the browser updates its features or fixes a bug, then the feature/bug detecting code is already up to date. If you're doing browser sniffing on the other hand, you have to change your code every time the capabilities of a browser changes. | Browser Version or Bug Detection | [
"",
"javascript",
""
] |
In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name? | **Django 1.8+**
Per the [1.8 docs](https://docs.djangoproject.com/en/1.8/ref/applications/#configuring-applications) (and [current docs](https://docs.djangoproject.com/en/dev/ref/applications/#configuring-applications)),
> New applications should avoid `default_app_config`. Instead they should require the dotted path to the appropriate `AppConfig` subclass to be configured explicitly in `INSTALLED_APPS`.
Example:
```
INSTALLED_APPS = [
# ...snip...
'yourapp.apps.YourAppConfig',
]
```
Then alter your `AppConfig` as listed below.
**Django 1.7**
As stated by rhunwicks' comment to OP, this is now possible out of the box since Django 1.7
Taken from the [docs](https://docs.djangoproject.com/en/1.7/ref/applications/#for-application-authors):
```
# in yourapp/apps.py
from django.apps import AppConfig
class YourAppConfig(AppConfig):
name = 'yourapp'
verbose_name = 'Fancy Title'
```
then set the `default_app_config` variable to `YourAppConfig`
```
# in yourapp/__init__.py
default_app_config = 'yourapp.apps.YourAppConfig'
```
**Prior to Django 1.7**
You can give your application a custom name by defining app\_label in your model definition. But as django builds the admin page it will hash models by their app\_label, so if you want them to appear in one application, you have to define this name in all models of your application.
```
class MyModel(models.Model):
pass
class Meta:
app_label = 'My APP name'
``` | As stated by rhunwicks' comment to OP, this is now possible out of the box since Django 1.7
Taken from the [docs](https://docs.djangoproject.com/en/1.7/ref/applications/#for-application-authors):
```
# in yourapp/apps.py
from django.apps import AppConfig
class YourAppConfig(AppConfig):
name = 'yourapp'
verbose_name = 'Fancy Title'
```
then set the `default_app_config` variable to `YourAppConfig`
```
# in yourapp/__init__.py
default_app_config = 'yourapp.apps.YourAppConfig'
``` | Can you give a Django app a verbose name for use throughout the admin? | [
"",
"python",
"django",
""
] |
In C++, I have a class which contains an anonymous bitfield struct. I want to initialize it to zero without having to manually write out all fields.
I can imagine putting the initialization in three places:
1. Create a constructor in the bitfield
2. Zero out in the initializer list of the constructor for the containing class
3. Zero out in the body of the constructor for the containing class
This bitfield has many fields, and I'd rather not list them all.
For example see the following code:
```
class Big {
public:
Big();
// Bitfield struct
struct bflag_struct {
unsigned int field1 : 1;
unsigned int field2 : 2;
unsigned int field3 : 1;
// ...
unsigned int field20 : 1;
// bflag_struct(); <--- Here?
} bflag;
unsigned int integer_member;
Big *pointer_member;
}
Big::Big()
: bflag(), // <--- Can I zero bflag here?
integer_member(0),
pointer_member(NULL)
{
// Or here?
}
```
Is one of these preferable? Or is there something else I'm missing?
Edit: Based on the accepted answer below (by Ferruccio) I settled on this solution:
```
class Big {
// ...
struct bflag_struct {
unsigned int field 1 : 1;
// ...
bflag_struct() { memset(this, 0, sizeof *this); };
}
// ...
}
``` | You could always do this in your constructor:
```
memset(&bflag, 0, sizeof bflag);
``` | Union the bitfield struct with something easier to initialize to 0. | What is the best way to initialize a bitfield struct in C++? | [
"",
"c++",
"constructor",
"struct",
"initialization",
"bit-fields",
""
] |
I was recently reading [this document](http://www.kegel.com/c10k.html) which lists a number of strategies that could be employed to implement a socket server. Namely, they are:
1. Serve many clients with each thread, and use nonblocking I/O and level-triggered readiness notification
2. Serve many clients with each thread, and use nonblocking I/O and readiness change notification
3. Serve many clients with each server thread, and use asynchronous I/O
4. serve one client with each server thread, and use blocking I/O
5. Build the server code into the kernel
Now, I would appreciate a hint on which should be used **in CPython**, which we know has some good points, and some bad points. I am mostly interested in performance under high concurrency, and yes a number of the current implementations are too slow.
So if I may start with the easy one, "5" is out, as I am not going to be hacking anything into the kernel.
"4" Also looks like it must be out because of the GIL. Of course, you could use multiprocessing in place of threads here, and that does give a significant boost. Blocking IO also has the advantage of being easier to understand.
And here my knowledge wanes a bit:
"1" is traditional select or poll which could be trivially combined with multiprocessing.
"2" is the readiness-change notification, used by the newer epoll and kqueue
"3" I am not sure there are any kernel implementations for this that have Python wrappers.
So, in Python we have a bag of great tools like Twisted. Perhaps they are a better approach, though I have benchmarked Twisted and found it too slow on a multiple processor machine. Perhaps having 4 twisteds with a load balancer might do it, I don't know. Any advice would be appreciated. | [`asyncore`](http://docs.python.org/library/asyncore.html) is basically "1" - It uses `select` internally, and you just have one thread handling all requests. According to the docs it can also use `poll`. (EDIT: Removed Twisted reference, I thought it used asyncore, but I was wrong).
"2" might be implemented with [python-epoll](http://sourceforge.net/projects/pyepoll) (Just googled it - never seen it before).
EDIT: (from the comments) In python 2.6 the [select module](http://docs.python.org/library/select.html) has epoll, kqueue and kevent build-in (on supported platforms). So you don't need any external libraries to do edge-triggered serving.
Don't rule out "4", as the GIL will be dropped when a thread is actually doing or waiting for IO-operations (most of the time probably). It doesn't make sense if you've got huge numbers of connections of course. If you've got lots of processing to do, then python may not make sense with any of these schemes.
For flexibility maybe look at [Twisted](http://twistedmatrix.com/trac/)?
In practice your problem boils down to how much processing you are going to do for requests. If you've got a lot of processing, and need to take advantage of multi-core parallel operation, then you'll probably need multiple processes. On the other hand if you just need to listen on lots of connections, then select or epoll, with a small number of threads should work. | How about "fork"? (I assume that is what the ForkingMixIn does) If the requests are handled in a "shared nothing" (other than DB or file system) architecture, fork() starts pretty quickly on most \*nixes, and you don't have to worry about all the silly bugs and complications from threading.
Threads are a design illness forced on us by OSes with too-heavy-weight processes, IMHO. Cloning a page table with copy-on-write attributes seems a small price, especially if you are running an interpreter anyway.
Sorry I can't be more specific, but I'm more of a Perl-transitioning-to-Ruby programmer (when I'm not slaving over masses of Java at work)
---
Update: I finally did some timings on thread vs fork in my "spare time". Check it out:
<http://roboprogs.com/devel/2009.04.html>
Expanded:
<http://roboprogs.com/devel/2009.12.html> | Writing a socket-based server in Python, recommended strategies? | [
"",
"python",
"sockets",
"asynchronous",
"network-programming",
"c10k",
""
] |
The project I'm working on has just hit 4200 lines in the main C# file, which is causing IntelliSense to take a few seconds (sometimes up to 6 or so) to respond, during which Visual Studio locks up. I'm wondering how everyone else splits their files and whether there's a consensus.
I tried to look for some guides and found [Google's C++ guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml), but I couldn't see anything about semantics such as function sizes and file sizes; maybe it's there - I haven't looked at it for a while.
So how do you split your files? Do you group your methods by the functions they serve? By types (event handlers, private/public)? And at what size limit do you split functions?
To clarify, the application in question handles data - so its interface is a big-ass grid, and everything revolves around the grid. It has a few dialogs forms for management, but it's all about the data. The reason why it's so big is that there is a lot of error checking, event handling, and also the grid set up as master-detail with three more grids for each row (but these load on master row expanded). I hope this helps to clarify what I'm on about. | I think your problem is summed up with the term you use: "Main C# file".
Unless you mean main (as in the method main()) there is no place for that concept.
If you have a catch-all utility class or other common methods you should break them into similar functional parts.
Typically my files are just one-to-one mappings of classes.
Sometimes classes that are very related are in the same file.
If your file is too large it is an indication your class is too big and too general.
I try to keep my methods to half a screen or less. (When it is code I write from scratch it is usually 12 lines or fewer, but lately I have been working in existing code from other developers and having to refactor 100 line functions...)
Sometimes it is a screen, but that is getting very large.
EDIT:
To address your size limit question about functions - for me it is less about size (though that is a good indicator of a problem) and more about doing only one thing and keeping each one SIMPLE. | In the classic book "[Structured Programming](https://rads.stackoverflow.com/amzn/click/com/0122005503)" Dijkstra once wrote a section entitled: "On our inability to do much." His point was simple. Humans aren't very smart. We can't juggle more than a few concepts in our minds at one time.
It is very important to keep your classes and methods small. When a method gets above a dozen lines or so, it should be broken apart. When a class gets above a couple of hundred lines, it should be broken apart. This is the only way to keep code well organized and manageable. I've been programming for nearly 40 years, and with every year that has gone by, I realize just how important the word "small" is when writing software.
As to *how* you do this, this is a very large topic that has been written about many different times. It's all about dependency management, information hiding, and object-oriented design in general. Here is a reading list.
* [Clean Code](https://rads.stackoverflow.com/amzn/click/com/0132350882)
* [SOLID](http://ArticleS.UncleBob.PrinciplesOfOod)
* [Agile Principles, Patterns, and Pratices in C#](https://rads.stackoverflow.com/amzn/click/com/0131857258) | Coding guides: How do you split up your large source files? | [
"",
"c#",
"visual-studio",
"oop",
"class-design",
"coding-style",
""
] |
I have an event handler for a Textbox and a RichTextBox.
The code is identical, but
In handler #1 I do:
```
RichTextBox tb = (RichTextBox)sender
```
In handler #2 accordingly:
```
TextBox tb = (TextBox)sender
```
Doing so I can fully manipulate the sending control.
How can I cast the sending object to `Textbox` or `RichTextbox` according to its type using
```
sender.GetType().Name
```
and then create the control at runtime and work with it? That way I only need one event handler function: less code, less errors, easier to maintain and DRY :-) | Depending on what properties you need, you could cast the sender as a TextBoxBase as both the TextBox and RichTextBox both inherit from that sub-class. | You never have to cast. I used to think the same way when I started, this 'pattern' is incorrect, and not really logical.
Your best bet is to use something like:
```
if (sender is TextBox)
{
TextBox tb = (TextBox)sender;
}
else if (sender is RichTextBox)
{
RichTextBox rtb = (RichTextBox)sender;
}
else
{
// etc
}
``` | Cast sender object in event handler using GetType().Name | [
"",
"c#",
"late-binding",
""
] |
How can I make requests to other server(s) (i.e. get a page from any desired server) with a JavaScript within the user's browser? There are limitations in place to prevent this for methods like XMLHttpRequest, are there ways to bypass them or other methods?
That is a general question, specifically I want to check a series of random websites and see if they contain a certain element, so I need the HTML content of a website without downloading any additional files; all that in a JavaScript file, *without any forwarding or proxy mechanism on a server*.
(Note: one way is using Greasemonkey and its GM\_xmlhttpRequest.) | You should check out [jQuery](http://www.jquery.com). It has a rich base of [AJAX functionality](http://docs.jquery.com/Ajax) that can give you the power to do all of this. You can load in an external page, and parse it's HTML content with intuitive [CSS-like selectors](http://docs.jquery.com/Selectors).
An example using `$.get();`
```
$.get("anotherPage.html", {}, function(results){
alert(results); // will show the HTML from anotherPage.html
alert($(results).find("div.scores").html()); // show "scores" div in results
});
```
For external domains I've had to author a local PHP script that will act as a middle-man. jQuery will call the local PHP script passing in another server's URL as an argument, the local PHP script will gather the data, and jQuery will read the data from the local PHP script.
```
$.get("middleman.php", {"site":"http://www.google.com"}, function(results){
alert(results); // middleman gives Google's HTML to jQuery
});
```
Giving *middleman.php* something along the lines of
```
<?php
// Do not use as-is, this is only an example.
// $_GET["site"] set by jQuery as "http://www.google.com"
print file_get_contents($_GET["site"]);
?>
``` | > update 2018:
You can only access cross domain with the following 4 condition
* in response header has `Access-Control-Allow-Origin: *`
Demo
```
$.ajax({
url: 'https://api.myjson.com/bins/bq6eu',
success: function(response){
console.log(response.string);
},
error: function(response){
console.log('server error');
}
})
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
```
* use server as bridge or proxy to the target
Demo:
```
$.ajax({
url: 'https://cors-anywhere.herokuapp.com/http://whatismyip.akamai.com/',
success: function(response){
console.log('server IP: ' + response);
},
error: function(response){
console.log('bridge server error');
}
})
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
```
* using browser addon to enable `Allow-Control-Allow-Origin: *`
* disable browser web security
Chrome
```
chrome.exe --args --disable-web-security
```
Firefox
```
about:config -> security.fileuri.strict_origin_policy -> false
```
end
---
> noob old answer 2011
$.get(); can get data from *jsbin.com* but i don't know why it can't get data from another site like google.com
```
$.get('http://jsbin.com/ufotu5', {},
function(results){ alert(results);
});
```
demo: <http://jsfiddle.net/Xj234/>
tested with firefox, chrome and safari. | How to get data with JavaScript from another server? | [
"",
"javascript",
"cross-domain",
""
] |
I have a stored procedure that takes a comma-delimited string of IDs. I split them and put them into a temporary table and pull out records from another table using **where id IN [table]**
Is it ok to use this same procedure when only one id is passed in for the param? I could write a second stored procedure that would do exactly the samething but instead do **where id = @id**.
I have MANY stored procedures where multiple IDs or just one could be passed in. Do I try to reuse the existing procedures or write new ones? Is the performance hit significant? | You might like to try a JOIN instead of WHERE id IN - although I think you will get the same query plan.
So I assume you are doing:
```
SELECT COl1, Col2, ...
FROM MyTable
WHERE id IN (SELECT id FROM @MyTempTable)
```
in which case the equivalent JOIN syntax would be :
```
SELECT COl1, Col2, ...
FROM MyTable AS T1
JOIN @MyTempTable AS T2
ON T2.id = T1.id
```
and in the second case whether there is 1, or many rows, it will be very effective provided [id] is indexed (I am assuming it is the PK on your table, and using a Clustered Index).
(Beware that if you have DUP IDs in @MyTempTable you will wind up getting dupes from MyTable as well :( )
For best performance it would be worth explicitly declaring [id] as the PK on your temporary table (but given it only holds a few rows it probably won't make much odds)
```
DECLARE @TempTable TABLE
(
id int NOT NULL,
PRIMARY KEY
(
id
)
)
``` | I wouldn't worry about the performance hit of in with only one item until I had observed a performance problem with it. The query optimizer is smart and may very well deal with the one item in, but even if it doesn't, your routines will probably be slowest elsewhere.
I would look at the performance of the string parsing, temp table creation and insertion into the temp table. Making those as fast a possible, will have a bigger effect on overall performance than wether you use in or = for the one item case. | Performance hit using ' where id IN [table] ' with only 1 row in [table]? | [
"",
"sql",
"database",
"t-sql",
"sql-server-2008",
"stored-procedures",
""
] |
I am using an interface called Predicate which is used for sifting through Collections. For example, I can define
```
public class BlackCatPredicate implements Predicate<Cat> {
public boolean evaluate( Cat c ) {
return c.isBlack();
}
}
```
and then use some utility `findAll( Collection<T> coll, Predicate<T> pred)` method to apply the predicate to a collection of Cats, and get just the black ones, etc.
My question is this: I'm finding black cats all over my code, so there is no need to keep instantiating the BlackCatPredicate over and over again. It should just have one instance. (A singleton?) But then, over the course of writing many predicates, I don't want to have to implement each one as a singleton. So -- what is the proper design here? | I'd use an anonymous class constant and put it with the class it operates on:
```
public class Cat{
public static final Predicate<Cat> BLACK_PREDICATE = new Predicate<Cat>(){
public boolean evaluate( Cat c ) {
return c.isBlack();
}
};
// Rest of the Cat class goes here
}
```
If the predicate has parameters, you can use a static factory method.
**Edit:** As was pointed out in the comments, depending on the usage patterns, it may result in clearer code to collect the predicate constants (and/or factory methods) in a separate class, either only those for Cat, or all of them. It depends mainly on their number, how much additional organization is helpful. | Something like this should work:
```
class Predicates
{
private static class BlackCatPredicate implements Predicate<Cat>
{
public boolean evaluate(final Cat c)
{
return c.isBlack();
}
}
private static final BlackCatPredicate = new BlackCatPredicate();
public static Predicate<Cat> getBlackCatPredicate()
{
return (blackCatPredicate);
}
}
``` | Java: Design with Singletons and generics | [
"",
"java",
"singleton",
"generics",
"predicate",
""
] |
Is it legal to write the following in .net ?
```
public class A
{
public int i = 0;
~A()
{
Aref = this;
}
}
public static A Aref;
static void Main(string[] args)
{
Aref = new A();
int gen = GC.GetGeneration(Aref);
Aref = null;
GC.Collect(gen, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
Console.WriteLine(Aref.i);
Console.ReadLine();
}
```
It works and writes '0' to the console as expected, but I'm wondering if it's guaranteed to always work.
Does someone know what's happening behind the scene? | It's called resurrection, and it's legal. Google for ".net object resurrection" (and terms like it) and you'll find stuff like:
[Resurrection and the .NET Garbage collector](http://www.c-sharpcorner.com/UploadFile/raviramnath/ResurrectionGCRN12222005072151AM/ResurrectionGCRN.aspx?ArticleID=aa5775e4-8a46-49d1-8309-e03d8ef58372)
[Object Resurrection](http://blogs.msdn.com/clyon/archive/2006/04/25/583698.aspx)
Just make sure these zombie objects don't come back and try to eat your brain or something. Like all necromancy, this is dangerous stuff. (Mostly because the finalizers higher up in the class hierarchy can have released some essential resource. Also note that the finalizer won't be run a second time if the object gets "unreferenced", unless you call `GC.ReRegisterForFinalize`.) | It works because the first garbage collection doesn't collect the instance. It just schedules the instance to have its finalizer run. The finalizer then creates a new root to the instance, so when the next collection happens the instance is actually rooted and thus not up for collection.
You should be very careful with this tough. If the finalizer is used to make sure an object is disposed, this actually violates the protocol because the disposable patterns says that a disposed instance should throw an ObjectDisposedException if it is used after being disposed. | is it legal to recreate a rooted reference to 'this' in a .net destructor? | [
"",
"c#",
".net",
"garbage-collection",
"destructor",
"finalizer",
""
] |
> **Possible Duplicate:**
> [Why are mutable structs evil?](https://stackoverflow.com/questions/441309/why-are-mutable-structs-evil)
I read it in lots of places including here that it's better to make structs as immutable.
What's the reason behind this? I see lots of Microsoft-created structs that are mutable, like the ones in xna. Probably there are many more in the BCL.
What are the pros and cons of not following this guideline? | Structs should represent **values**. Values do not change. The number 12 is eternal.
However, consider:
```
Foo foo = new Foo(); // a mutable struct
foo.Bar = 27;
Foo foo2 = foo;
foo2.Bar = 55;
```
Now foo.Bar and foo2.Bar is different, which is often unexpected. Especially in the scenarios like properties (fortunately the compiler detect this). But also collections etc; how do you ever mutate them sensibly?
Data loss is far too easy with mutable structs. | The big con is that things don't behave how you expect them to - particularly if the mutability comes from a mixture of the direct value and a reference type within it.
To be honest, I can't remember off the top of my head all the weird problems I've seen people come up with in newsgroups when they've used mutable structs - but those reasons certainly exist. *Mutable structs cause problems.* Stay away.
EDIT: I've just found an email I wrote a while ago on this topic. It elaborates just a little bit:
* It's philosophically wrong: a struct should represent some sort of fundamental value. Those are basically immutable. You don't get to change the number 5. You can change a variable's value from 5 to 6, but you don't logically make a change to the value itself.
* It's practically a problem: it creates lots of weird situations. It's particularly bad if it's mutable via an interface. Then you can start changing boxed values. Ick. I've seen a lot of newsgroup posts which are due to people trying to use mutable structs and running into issues. I saw a very strange LINQ example which was failing because `List<T>.Enumerator` is a struct, for example. | Immutability of structs | [
"",
"c#",
".net",
"struct",
"immutability",
""
] |
I have a base32 string which I need to convert to a byte array. And I'm having trouble finding a conversion method in the .NET framework. I can find methods for base64 but not for base32.
`Convert.FromBase64String` – something like this for base32 would be perfect.
Is there such a method in the framework or do I have to roll my own? | I had a need for a base32 encoder/decoder, so I spent a couple hours this afternoon throwing this together. I believe it conforms to the standards listed here: <https://www.rfc-editor.org/rfc/rfc4648#section-6>.
```
public class Base32Encoding
{
public static byte[] ToBytes(string input)
{
if (string.IsNullOrEmpty(input))
{
throw new ArgumentNullException("input");
}
input = input.TrimEnd('='); //remove padding characters
int byteCount = input.Length * 5 / 8; //this must be TRUNCATED
byte[] returnArray = new byte[byteCount];
byte curByte = 0, bitsRemaining = 8;
int mask = 0, arrayIndex = 0;
foreach (char c in input)
{
int cValue = CharToValue(c);
if (bitsRemaining > 5)
{
mask = cValue << (bitsRemaining - 5);
curByte = (byte)(curByte | mask);
bitsRemaining -= 5;
}
else
{
mask = cValue >> (5 - bitsRemaining);
curByte = (byte)(curByte | mask);
returnArray[arrayIndex++] = curByte;
curByte = (byte)(cValue << (3 + bitsRemaining));
bitsRemaining += 3;
}
}
//if we didn't end with a full byte
if (arrayIndex != byteCount)
{
returnArray[arrayIndex] = curByte;
}
return returnArray;
}
public static string ToString(byte[] input)
{
if (input == null || input.Length == 0)
{
throw new ArgumentNullException("input");
}
int charCount = (int)Math.Ceiling(input.Length / 5d) * 8;
char[] returnArray = new char[charCount];
byte nextChar = 0, bitsRemaining = 5;
int arrayIndex = 0;
foreach (byte b in input)
{
nextChar = (byte)(nextChar | (b >> (8 - bitsRemaining)));
returnArray[arrayIndex++] = ValueToChar(nextChar);
if (bitsRemaining < 4)
{
nextChar = (byte)((b >> (3 - bitsRemaining)) & 31);
returnArray[arrayIndex++] = ValueToChar(nextChar);
bitsRemaining += 5;
}
bitsRemaining -= 3;
nextChar = (byte)((b << bitsRemaining) & 31);
}
//if we didn't end with a full char
if (arrayIndex != charCount)
{
returnArray[arrayIndex++] = ValueToChar(nextChar);
while (arrayIndex != charCount) returnArray[arrayIndex++] = '='; //padding
}
return new string(returnArray);
}
private static int CharToValue(char c)
{
int value = (int)c;
//65-90 == uppercase letters
if (value < 91 && value > 64)
{
return value - 65;
}
//50-55 == numbers 2-7
if (value < 56 && value > 49)
{
return value - 24;
}
//97-122 == lowercase letters
if (value < 123 && value > 96)
{
return value - 97;
}
throw new ArgumentException("Character is not a Base32 character.", "c");
}
private static char ValueToChar(byte b)
{
if (b < 26)
{
return (char)(b + 65);
}
if (b < 32)
{
return (char)(b + 24);
}
throw new ArgumentException("Byte is not a value Base32 value.", "b");
}
}
``` | Check this `FromBase32String` implementation for .NET found [here](http://www.atrevido.net/blog/PermaLink.aspx?guid=debdd47c-9d15-4a2f-a796-99b0449aa8af).
---
Edit: The above link was dead; you can find an archived copy at [archive.org](https://web.archive.org/web/20060422042142/http://www.atrevido.net/blog/PermaLink.aspx?guid=debdd47c-9d15-4a2f-a796-99b0449aa8af)
The actual code read:
```
using System;
using System.Text;
public sealed class Base32 {
// the valid chars for the encoding
private static string ValidChars = "QAZ2WSX3" + "EDC4RFV5" + "TGB6YHN7" + "UJM8K9LP";
/// <summary>
/// Converts an array of bytes to a Base32-k string.
/// </summary>
public static string ToBase32String(byte[] bytes) {
StringBuilder sb = new StringBuilder(); // holds the base32 chars
byte index;
int hi = 5;
int currentByte = 0;
while (currentByte < bytes.Length) {
// do we need to use the next byte?
if (hi > 8) {
// get the last piece from the current byte, shift it to the right
// and increment the byte counter
index = (byte)(bytes[currentByte++] >> (hi - 5));
if (currentByte != bytes.Length) {
// if we are not at the end, get the first piece from
// the next byte, clear it and shift it to the left
index = (byte)(((byte)(bytes[currentByte] << (16 - hi)) >> 3) | index);
}
hi -= 3;
} else if(hi == 8) {
index = (byte)(bytes[currentByte++] >> 3);
hi -= 3;
} else {
// simply get the stuff from the current byte
index = (byte)((byte)(bytes[currentByte] << (8 - hi)) >> 3);
hi += 5;
}
sb.Append(ValidChars[index]);
}
return sb.ToString();
}
/// <summary>
/// Converts a Base32-k string into an array of bytes.
/// </summary>
/// <exception cref="System.ArgumentException">
/// Input string <paramref name="s">s</paramref> contains invalid Base32-k characters.
/// </exception>
public static byte[] FromBase32String(string str) {
int numBytes = str.Length * 5 / 8;
byte[] bytes = new Byte[numBytes];
// all UPPERCASE chars
str = str.ToUpper();
int bit_buffer;
int currentCharIndex;
int bits_in_buffer;
if (str.Length < 3) {
bytes[0] = (byte)(ValidChars.IndexOf(str[0]) | ValidChars.IndexOf(str[1]) << 5);
return bytes;
}
bit_buffer = (ValidChars.IndexOf(str[0]) | ValidChars.IndexOf(str[1]) << 5);
bits_in_buffer = 10;
currentCharIndex = 2;
for (int i = 0; i < bytes.Length; i++) {
bytes[i] = (byte)bit_buffer;
bit_buffer >>= 8;
bits_in_buffer -= 8;
while (bits_in_buffer < 8 && currentCharIndex < str.Length) {
bit_buffer |= ValidChars.IndexOf(str[currentCharIndex++]) << bits_in_buffer;
bits_in_buffer += 5;
}
}
return bytes;
}
}
``` | Base32 Decoding | [
"",
"c#",
".net",
"base32",
""
] |
In my current project, I am using four grid views in different tabs. As the system has developed, they have some shared methods, such as show a custom tooltip and a right click menu for when on rows.
I am now going through a code cleaning exercise. What I see below is that I now have four event handlers calling the same method. Is it OK to change the event handlers all to point directly to GridMenu, avoiding the extra code? Will this cause me problems later in development?
Obviously at present I am using the default even handler names.
```
private void grdEnquiriesLevel1_ShowGridMenu(object sender, GridMenuEventArgs e)
{
GridMenu(sender, e);
}
private void grdApplicantsLevel1_ShowGridMenu(object sender, GridMenuEventArgs e)
{
GridMenu(sender, e);
}
private void grdApplicationsLevel1_ShowGridMenu(object sender, GridMenuEventArgs e)
{
GridMenu(sender, e);
}
private void grdInterviewsLevel1_ShowGridMenu(object sender, GridMenuEventArgs e)
{
GridMenu(sender, e);
}
private void GridMenu(object sender, GridMenuEventArgs e)
{
GridView view = (GridView)sender;
if (view.CalcHitInfo(e.Point).InRow)
popupMenu1.ShowPopup(Cursor.Position);
}
``` | Instead of registering directly to `GridMenu`, create a general event handler named `Grid_ShowGridMenu`.
Just register to the same event handler for each grid, instead of creating a separate event handler per grid.
```
grdEnquiriesLevel1.ShowGridMenu += Grid_ShowGridMenu;
grdApplicantsLevel1.ShowGridMenu += Grid_ShowGridMenu;
grdApplicationsLevel1.ShowGridMenu += Grid_ShowGridMenu;
grdInterviewsLevel1.ShowGridMenu += Grid_ShowGridMenu;
private void Grid_ShowGridMenu(object sender, GridMenuEventArgs e)
{
GridMenu((GridView)sender, e.Point);
}
```
Now, instead of passing `sender, e` directly to `GridMenu`, pass only *necessary* values to `GridMenu` and change the signature of `GridMenu` so it can be more *reusable*.
```
private void GridMenu(GridView grid, Point hitPoint)
{
if (grid.CalcHitInfo(hitPoint).InRow)
popupMenu1.ShowPopup(Cursor.Position);
}
``` | As long as the event code is generic for all controls then this method is fine and clean.
If you start having major if/else or switch blocks in the code then maybe it is time for a re-think. | Reuse event handler good practice in C# | [
"",
"c#",
".net",
""
] |
I know that for the image onload to work you have to set the src after the onload handler was attached. However I want to attach onload handlers to images that are static in my HTML. Right now I do that in the following way (using jQquery):
```
<img id='img1' src='picture.jpg'>
```
```
$('#img1').load( function() {
alert('foo');
})
.attr('src', $('img1').attr('src'));
```
But this is rather ugly and has the obvious flow that it can only be done for selectors that match only one image. Is there any other, nicer way to do this?
**edit**
What I meant by that it can only be done for selector that match only one image is that when doing this:
```
<img class='img1' src='picture.jpg'>
<img class='img1' src='picture2.jpg'>
```
```
$('.img1').load( function() {
alert('foo');
})
.attr('src', $('.img1').attr('src'));
```
That both images will have src='picture.jpg' | You can trigger the event (or it's handler) directly by calling `.trigger()` or `.load()`.
If you know that you want the event, because you know that the images are already loaded, then you can do it like this:
```
$('#img1').load(function() {
alert('foo');
})
.trigger('load'); // fires the load event on the image
```
If you are running your script on document ready or some moment where it isn't yet clear if the images are there or not, then I would use something like this:
```
$('img.static')
.load(function(){
alert('foo');
return false; // cancel event bubble
})
.each(function(){
// trigger events for images that have loaded,
// other images will trigger the event once they load
if ( this.complete && this.naturalWidth !== 0 ) {
$( this ).trigger('load');
}
});
```
Be warned that the load event bubbles (jQuery 1.3) and you might possibly be triggering a load handler on the document prematurely if you don't cancel the bubble in the img handler.
For the record: The `img.src=img.src` triggering solution will unfortunately not work correctly on Safari. You will need to set the `src` to something else (like # or about:blank) and then back for reload to happen. | Okay, I turned Borgars answer into a plugin, here it is:
```
$.fn.imageLoad = function(fn){
this.load(fn);
this.each( function() {
if ( this.complete && this.naturalWidth !== 0 ) {
$(this).trigger('load');
}
});
}
``` | Image onload for static images | [
"",
"javascript",
"events",
""
] |
`XMLHttpRequest` has 5 `readyState`s, and I only use 1 of them (the last one, `4`).
What are the others for, and what practical applications can I use them in? | The full list of `readyState` values is:
```
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete
```
(from <https://www.w3schools.com/js/js_ajax_http_response.asp>)
In practice you almost never use any of them except for 4.
*Some* XMLHttpRequest implementations may let you see partially received responses in `responseText` when `readyState==3`, but this isn't universally supported and shouldn't be relied upon. | [kieron](https://stackoverflow.com/users/588/kieron)'s answer contains w3schools ref. to which nobody rely ,
[bobince](https://stackoverflow.com/users/18936/bobince)'s answer gives link , which actually tells native implementation of IE ,
so here is the original documentation quoted to rightly understand what readystate represents :
> The XMLHttpRequest object can be in several states. The readyState attribute must return the current state, which must be one of the following values:
>
> UNSENT (numeric value 0)
> The object has been constructed.
>
> OPENED (numeric value 1)
> The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.
>
> HEADERS\_RECEIVED (numeric value 2)
> All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.
>
> LOADING (numeric value 3)
> The response entity body is being received.
>
> DONE (numeric value 4)
> The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).
Please Read here : [W3C Explaination Of ReadyState](https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate) | What do the different readystates in XMLHttpRequest mean, and how can I use them? | [
"",
"javascript",
"ajax",
"xmlhttprequest",
"readystate",
""
] |
I have a variable containing html string. This string has this particular code
```
<a href="http://www.pheedo.com/click.phdo?s=xxxxxxxx&p=1"><img border="0" src="http://www.pheedo.com/img.phdo?s=xxxxxxxxxx&p=1" style="border: 0pt none ;" alt=""/></a>
```
Using regex, how can I remove that. Basically looking for the pheedo.com domain, and stripping out the link and image tag.
Thanks | This should match the tags (written in PHP):
```
$regex = "#<a href=\"http:\/\/www\.pheedo\.com[^>]+><img[^>]+><\/a>#"
``` | This is an anti-answer: Don't manipulate arbitrary HTML with regexes! HTML is a really complicated spec, parsing it properly can be a nightmare.
Use a library like [phpQuery](http://code.google.com/p/phpquery/) or the built-in [DOMDocument](https://www.php.net/dom), they know how to deal with all the weirdnesses of HTML for you. | Strip out ad from html string | [
"",
"php",
"regex",
""
] |
I'm planning to build a small multiplayer game which could be run as a java applet or a flash file in the web browser. I haven't done any server programming before, so I'm wondering what sort of server architecture i should have.
It'll be easy for me to create perl/php files on the server, which the java/flash code contacts to update the player position/actions, etc. But I'm considering whether i should get a dedicated web host, which OS to use, which database, etc. Also, the amount of bandwidth used and scalability is a consideration.
Another option could be using a cloud hosting system (as opposed to a dedicated server), so they would take care of adding additional machines as the game grows. As long as each server ran the core perl/php files for updating the database, it should work fine.
Yet another option could be using Google app engine.
Any thoughts regarding the server architecture, OS/database choice, and whether my method of using perl/php/python scripts for server-side programing is a good one, will be appreciated! | You need to clarify more about the game, and think more about architecture rather than specific implementation details.
The main question is whether your game is going to be in real time, turn based, or long-delay based (e.g., email chess). Another question is whether or not you are going to be freezing the state for subsequent reloads.
I would highly recommend figuring out in advance whether or not all players in the same game are going to be hosted on the same server (e.g., 1000 of 4 player matches compared to 4 matches of 1000 players each). If possible, go with the first and stick everyone who is in the same game under the same server. You will have a hard enough time synchronizing multiple clients to one server, rather than having multiple servers against which players are synchronized. Otherwise, the definition of consistency is problematic.
If possible, have each client communicate with the server and then the server distributing updates to the clients. This way you have one "official state", and can do a variety of conflict resolutions, phantoms, etc. Peer to peer gives better performance in faster games (e.g., FPSs) but introduces tons of problems.
I cannot for the life of me see any convincing reason to do this and perl or PHP. Your game is not web based, why write it in a web oriented language? Use good old J2EE for the server, and exchange data with your clients via XML and AJAX. If possible, run a real Java application on clients rather than servlets. You can then benefit from using JMS which will take a huge load off your back by abstracting a lot of the communication details for you. | For your server architecture, you might have a look at [Three Rings' code](http://www.threerings.net/code/). They have written a number of very scalable games in Java (both client- and server-side). | Server architecture for a multiplayer game? | [
"",
"java",
"architecture",
"multiplayer",
""
] |
I have a situation where I'm marching through a vector, doing things:
```
std::vector<T>::iterator iter = my_list.begin();
for ( ; iter != my_list.end(); ++iter )
{
if ( iter->doStuff() ) // returns true if successful, false o/w
{
// Keep going...
}
else
{
for ( ; iter != m_list.begin(); --iter ) // ...This won't work...
{
iter->undoStuff();
}
}
}
```
Under normal conditions - assuming everything goes well - I march all the way to `my_list.end()` and end the loop successfully.
However, if something goes wrong while I'm doing stuff, I want to be able to undo everything - basically retrace my steps back to the very beginning of the vector, undoing everything one at a time in reverse order.
My problem is that when I get to `my_list.begin()` - as shown in the nested for loop - I'm really not done yet because I still need to call `undoStuff()` on my first element in the list. Now, I could just make the final call outside of the loop, but this seems a little unclean.
The way I see it, I'm only done when I get to `my_list.rend()`. However, I can't compare a `std::vector::iterator` to a `std::vector::reverse_iterator`.
Given what I'm trying to do, what's the best choice of iterator-type / loop combination? | While using reverse iterators via `rbegin()` and `rend()` works nicely, unfortunately I find that converting between reverse and non-reverse iterarotrs tends to be quite confusing. I can never remember without having to go through a logic-puzzle exercise whether I need to increment or decrement before or after the conversion. As a result I generally avoid the conversion.
Here's the way I'd probably code your error handling loop. Note that I'd think that you wouldn't have to call `undoStuff()` for the iterator that failed - after all, `doStuff()` said it didn't succeed.
```
// handle the situation where `doStuff() failed...
// presumably you don't need to `undoStuff()` for the iterator that failed
// if you do, I'd just add it right here before the loop:
//
// iter->undoStuff();
while (iter != m_list.begin()) {
--iter;
iter->undoStuff();
}
``` | I'm a little rusty when it comes to STL vectors, but would it be possible to create a `std::vector::reverse_iterator` from your initial iterator? Then you would only need to start at the last item you were at when going forward, and would be able to compare it to `my_list.rend()` to make sure that the first item is processed. | What's the cleanest way to walk and unwalk a std::vector using iterators? | [
"",
"c++",
"vector",
"loops",
"iterator",
"for-loop",
""
] |
I'm trying to unit test values that will eventually wind up in a web.config file. In my test project, I created an app.config file with a web.config section to hold the settings. In a normal situation, I would call System.Configuration.ConfigurationSettings.AppSettings, but in this case, that doesn't work. I saw [this question](https://stackoverflow.com/questions/76781/how-do-i-tdd-a-custom-membership-provider-and-custom-membership-user), which is very similar, but doesn't address how to get the NameValueCollection out of the config file. Here is an example of the config file:
```
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<membership defaultProvider="CustomMembershipProvider">
<providers>
<clear/>
<add
name="CustomMembershipProvider"
applicationName="SettlementInfo"
enablePasswordRetrieval="false"
enablePasswordReset="false"
requiresQuestionAndAnswer="true"
writeExceptionsToEventLog="true" />
</providers>
</membership>
</system.web>
</configuration>
```
Has anyone dealt with this before? | I guess I'm confused here; it looks like you're trying to test that ASP.NET is using your custom membership provider appropriately. Correct?
If so, I'm 99.999% sure that you cannot unit test this using the MS framework; you must integration test it by deploying it to the webserver (or running Cassini in VS) and typing a username/password into your login page.
Now, it's possible I've misunderstood your request. If so, let me know and I'll edit my answer accordingly.
**Edit:**
> For right now, I'm really just trying
> to test the NameValue pairs coming out
> of the config file, to make sure that
> if the values aren't present, my
> defaults are being applied. In other
> words, I want to try to pull
> applicationName, and verify that it
> equals "SettlementInfo", and so on.
> After that, I will be using
> integration testing to ensure that
> ASP.NET is using the custom framework
> in place of the default one. Does that
> make sense?
I need more than a comment to reply, so I'm editing. If I read you correctly, you are wanting to unit test your program to ensure that it deals with configuration correctly, yes? Meaning you want to ensure that your code grabs, for example, the correct AppSettings key and handles a null value therein, correct?
If that's the case, you're in luck; you don't need an app.config or web.config at all, you can set the values you need as part of your test setup.
For example:
```
[TestMethod]
public void Test_Configuration_Used_Correctly()
{
ConfigurationManager.AppSettings["MyConfigName"] = "MyConfigValue";
MyClass testObject = new MyClass();
testObject.ConfigurationHandler();
Assert.AreEqual(testObject.ConfigurationItemOrDefault, "MyConfigValue");
}
[TestMethod]
public void Test_Configuration_Defaults_Used_Correctly()
{
// you don't need to set AppSettings for a non-existent value...
// ConfigurationManager.AppSettings["MyConfigName"] = "MyConfigValue";
MyClass testObject = new MyClass();
testObject.ConfigurationHandler();
Assert.AreEqual(testObject.ConfigurationItemOrDefault, "MyConfigDefaultValue");
}
``` | I believe you only have access to the webconfig file while your application is actually beeing started up. The solution is rather easy -> "Fake" your config. Use a NameValueCollection and use that instead:
```
private static NameValueCollection CreateConfig()
{
NameValueCollection config = new NameValueCollection();
config.Add("applicationName", "TestApp");
config.Add("enablePasswordReset", "false");
config.Add("enablePasswordRetrieval", "true");
config.Add("maxInvalidPasswordAttempts", "5");
config.Add("minRequiredNonalphanumericCharacters", "2");
config.Add("minRequiredPasswordLength", "6");
config.Add("requiresQuestionAndAnswer", "true");
config.Add("requiresUniqueEmail", "true");
config.Add("passwordAttemptWindow", "10");
return config;
}
```
Now you could easily pass that collection into your class that parses data from it. | Get values from the web.config section in an app.config file? | [
"",
"c#",
".net",
"asp.net",
"web-config",
"app-config",
""
] |
There's a name for this, but I don't know what it is so it's hard to google.
What I'm looking for is something in the java concurrency utilities, which is a pair of queues, an "pending" queue used by a producer, and a "processing" queue used by a consumer, where the consumer can swap the queues atomically. If used in this way (1 producer thread, 1 consumer thread), the individual queues don't need to be threadsafe, just the references to them.
I know I've seen this somewhere before, and I can probably cobble together something like this on my own, but if it exists already I'd rather use that.
**edit:** I guess the primitive I'm looking for is a pair of atomic references that can be atomically swapped. (& I can add the queues myself.)
---
**edit 2:** @Alex Miller answered the nagging question of what it was that I was thinking of but couldn't remember. However that doesn't solve my problem since it's a thread barrier and I want the producer to not have to block.
@sfossin's point about swapping references to queues is a good one; what I wanted was that the instant the consumer starts retrieving and processing items from the queue, all those queue items have to be complete and the producer can't add any items afterwards; the producer now has to add items to the other queue. So the paired/swapped set of atomic references won't work.
(It's sort of like if there are 2 school buses, one of which is always waiting for passengers and the other is always delivering them elsewhere. Once the driver pulls away, that's it, you have to get on the other bus. Having references lets producers access the bus even though it's already left, which is not allowed.)
I think what I will do instead is to use a single [ConcurrentLinkedQueue](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html) and have a sentinel value that the consumer adds to the queue. This allows there to be multiple producers, not just 1. In order for the consumer to process batches of items on the queue, the consumer waits for there to be at least 1 item on the queue, then inserts the sentinel at the end of the queue, and removes items until the sentinel is removed. Then the consumer does whatever it has to do between batches. That's the behavior I wanted.
It doesn't necessarily need to be a guaranteed non-blocking approach (locking or `synchronized` methods are options), but if there's an easy way to architect it so that it is, that's preferred in my application. | [Exchanger](http://java.sun.com/javase/6/docs/api/java/util/concurrent/Exchanger.html)? | A reader/writer locked queue, is probably a better idea. Since, if you would otherwise have to copy to a local queue atomically.
Since you'd have a sync issue, if you swapped the references, while one was reading/deleting or writing.
[RWLock](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/ReadWriteLock.html) would allow multiple consumers/producers.
Is there any reason, why you'd like to stay away from RWLocks?
As with any locking, the lock should be held for the minimum time possible to prevent starvation.
or use something like this for the exchanging of data. With each thread holding it's own queue.
```
class LockedQueue
{
private final List<Data> q = new ArrayList<Data>();
private final Lock lock = new ReentrantLock();
public void get( List<Data> consumerQ ) {
if( lock.tryLock() ) { try { consumerQ .addAll( q ); q.clear(); } finally { lock.unlock(); }}
}
public Data put( List<Data> producerQ ) {
if( lock.tryLock() ) { try { return q.addAll( producerQ ); producerQ .clear(); } finally { lock.unlock(); }}
}
public void clear() {
lock.lock(); try { q.clear(); } finally { lock.unlock(); }
}
}
```
with the consumer calling get(), when empty or at the end of each loop and the consumer calling put, after adding so many items or time or ... | swappable work queue | [
"",
"java",
"concurrency",
"queue",
""
] |
I was poking around in XNA and saw that the `Vector3` class in it was using public fields instead of properties. I tried a quick benchmark and found that, for a `struct` the difference is quite dramatic (adding two Vectors together a 100 million times took 2.0s with properties and 1.4s with fields). For a reference type, the difference doesn't seem to be that large but it is there.
So why is that? I know that a property is compiled into `get_X` and `set_X` methods, which would incur a method call overhead. However, don't these simple getters/setters *always* get in-lined by the JIT? I know you can't guarantee what the JIT decides to do, but surely this is fairly high on the list of probability? What else is there that separates a public field from a property at the machine level?
And one thing I've been wondering: how is an auto-implemented property (`public int Foo { get; set; }`) 'better' OO-design than a public field? Or better said: how are those two *different*? I know that making it a property is easier with reflection, but anything else? I bet the answer to both questions is the same thing.
BTW: I am using .NET 3.5 SP1 which I believe fixed issues where methods with structs (or methods *of* structs, I'm not sure) weren't in-lined, so that isn't it. I think I am using it at least, it's certainly installed but then again, I'm using Vista 64-bit with SP1 which should have DX10.1 except that I don't have DX10.1 ..
Also: yeah, I've been running a release build :)
**EDIT**: I appreciate the quick answers guys, but I indicated that I *do* know that a property access is a method call, but that I don't know why the, presumably, in-lined method is slower than a direct field access.
**EDIT 2**: So I created another `struct` that used explicit GetX() methods (o how I don't miss my Java days *at all*) and that performed the same whether I disabled in-lining on it (through `[MethodImplAttribute(MethodImplOptions.NoInlining)]`) or not, so conclusion: non-static methods are apparently never inlined, not even on structs.
I thought that there were exceptions, where the JIT could optmize the virtual method call away. Why can't this happen on structs which know no inheritance and thus a method call can only point to one possible method, right? Or is that because you can implement an interface on it?
This is kind of a shame, since it will really make me think about using properties on performance critical stuff, yet using fields makes me feel dirty and I might as well write what I'm doing in C.
**EDIT 3**: I found [this](http://www.ademiller.com/blogs/tech/2008/08/c-inline-methods-and-optimization/) posting about the exact same subject. His end conclusion is that the property call did get optimized away. I also could've sworn that I've read plenty of times that simple getter/setter properties will get in-lined, despite being `callvirt` in the IL. So am I going insane?
**EDIT 4**: Reed Copsey posted the answer in a comment below:
> Re: Edit3 - see my updated comment: I believe this is x86 JIT vs x64 JIT issues. the JIT in x64 is not as mature. I'd expect MS to improve this quickly as more 64 bit systems are coming online every day. – Reed Copsey
And my response to his answer:
> Thanks, this is the answer! I tried forcing a x86 build and all methods are equally fast, and much faster than the x64. This is very shocking to me actually, I had no idea I was living in the stone age on my 64-bit OS.. I'll include your comment in my answer so it stands out better. – JulianR
Thanks everyone! | Edit 2:
I had another potential thought here:
You mentioned that you are running on x64. I've tested this same issue on x86, and seen the same performance when using auto-properties vs. fields. However, if you look around on Connect and mailing list/forum posts, there are many references online to the fact that the x64 CLR's JIT is a different code base, and has very different performance characteristics to the x86 JIT. My guess is this is one place where x64 is still lagging behind.
Also, FYI, the struct/method/etc thing fixed in .net 3.5sp1 was on the x86 side, and was the fact that method calls that took structs as a parameter would never be inlined on x86 prior to .net3.5sp1. That's pretty much irrelevant to this discussion on your system.
---
Edit 3:
Another thing: As to why XNA is using fields. I actually was at the Game Fest where they announced XNA. Rico Mariani gave a talk where he brought up many of the same points that are on his blog. It seems the XNA folks had similar ideas when they developed some of the core objects. See:
<http://blogs.msdn.com/ricom/archive/2006/09/07/745085.aspx>
Particularly, check out point #2.
---
As for why automatic properties are better than public fields:
They allow you to change the implementation in v2 of your class, and add logic into the property get/set routines as needed, without changing your interface to your end users. This can have a profound effect on your ability to maintain your library and code over time.
---- From original post - but discovered this wasn't the issue--------
Were you running a release build *outside* of VS? That can be one explanation for why things aren't being optimized. Often, if you are running in VS, even an optimized release build, the VS host process disables many functions of the JIT. This can cause performance benchmarks to change. | You should read this article by Vance. It goes into detail about why methods are not always inlined by the JIT'er even if it looks completely obvious that they should be.
<http://blogs.msdn.com/vancem/archive/2008/08/19/to-inline-or-not-to-inline-that-is-the-question.aspx> | Why are public fields faster than properties? | [
"",
"c#",
"oop",
"properties",
"struct",
"public-fields",
""
] |
I have a PHP script that creates an xml file from the db. I would like to have the script create the xml data and immediately make a .gzip file available for download. Can you please give me some ideas?
Thanks! | You can easily apply gzip compression with the [gzencode](http://www.php.net/manual/en/function.gzencode.php) function.
```
<?
header("Content-Disposition: attachment; filename=yourFile.xml.gz");
header("Content-type: application/x-gzip");
echo gzencode($xmlToCompress);
``` | Something like this?
```
<?php
header('Content-type: application/x-gzip');
header('Content-Disposition: attachment; filename="downloaded.gz"');
$data = implode("", file('somefile.xml'));
print( gzencode($data, 9) ); //9 is the level of compression
?>
``` | How can I offer a gzipped xml file for download using PHP | [
"",
"php",
"xml",
"gzip",
""
] |
Using Apache Derby with Java (J2ME, but I don't think that makes a difference) is there any way of checking if a database already exists and contains a table? | I know of none, except few work around, unlike MySQL where we have that facility of IF EXIST.
What you do is, try to connect to the database, if couldn't its likely its not there. And after a successful connection, you can do a simple select, like SELECT count(\*) FROM TABLE\_NAME, to know whether the table exist or not. You would be depending on the exception. Even in an official example from Sun, I have seen the similar work around.
In Oracle we have dictionary tables to know about the database objects. I doubt if we have anything like that in Derby.
**[Edited]**
Well, I found that there is a way to know if the table exist. Try, SELECT tablename FROM SYSTABLES. It is for checking the existence of a table, for checking database you may need to do similar thing, I explained above. | [Adeel](https://stackoverflow.com/questions/584497/apache-derby-check-database-already-created/584617#584617), you could also use [Connection.getMetaData](http://java.sun.com/javase/6/docs/api/java/sql/Connection.html#getMetaData()) to return a [DatabaseMetaData](http://java.sun.com/javase/6/docs/api/java/sql/DatabaseMetaData.html) object, then use the [getTables](http://java.sun.com/javase/6/docs/api/java/sql/DatabaseMetaData.html#getTables(java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String%5B%5D)), once you have the connection to the database of course. This has the advantage of working for any database with a JDBC driver worth it's salt.
For checking if the database exists, if you are using Derby in the embedded way, or the server is on the same machine, you could check if the folder for the database exists. Is a bit kludgy though. I would do as Adeel suggests and try to connect, catching the exception if it's not there. | Apache Derby - Check Database Already Created? | [
"",
"java",
"database",
"derby",
""
] |
```
struct Foo
{
void SayHello()
{
std::cout << "Hi, I am Foo";
}
};
```
I have the above given struct. I have seen a usage like this in one of our code base.
```
Foo foo;
{
foo.SayHello();
}
```
IMO, It does same like
```
Foo foo;
foo.SayHello();
```
Or is there any advantage/difference for the first method?
Any thoughts? | In that particular case, it looks quite strange and like a candidate for review. Can be useful in other cases:
```
Foo foo;
{
ReturnValue v = foo.SayHello();
Send(v);
}
...
```
Where it would limit the scope of `v`. One common use is to make the objects in it destroy earlier. Classes that do special stuff in their constructor and destructor can then be used inside the braces:
```
Foo foo;
{
MutexLocker locker(sendMutex);
ReturnValue v = foo.SayHello();
Send(v);
}
...
```
The lock for the send-queue would be held while sending `v` in that example, and be released when the locker is destroyed at the closing brace. | There's no difference in the two examples. The following, however, would create and destroy the foo object within the scope of the braces:
```
{
Foo foo;
foo.SayHello();
}
```
This is useful for objects that follow the [RAII](http://gethelp.devx.com/techtips/cpp_pro/10min/2001/november/10min1101.asp) idiom. | Different methods to use a class/struct - C++ | [
"",
"c++",
"methods",
""
] |
When a user installs my application how do I keep User Account Control from producing this dialog? And no I don't want to tell them to disable UAC.
[](https://i.stack.imgur.com/YBUGe.png)
(source: [netron.com](http://www.netron.com/images/VistaInstall02.png)) | You'd need to design your installation such that it doesn't require administrative access to install, which essentially means that you'll need to install inside the user's home directory instead of `ProgramFilesDir` and write registry entries only to `HKEY_CURRENT_USER`. For more details on how do this with a .MSI package, see [this article](http://blogs.msdn.com/rflaming/archive/2006/09/30/778690.aspx). [Inno Setup](http://www.jrsoftware.org/isinfo.php) also has [some details on limited user installs](http://www.jrsoftware.org/isfaq.php#ntsecur).
I don't think Visual Studio's setup project builder is capable of producing packages that don't require administrator rights to install. In any case, Vista seems to assume that anything that looks like a Setup.exe needs elevation (and results in the prompt).
Code signing will not remove the prompt, it will only make it say "*Program XYZ* from *Developer Name* wants access to your computer" instead of "An unknown program wants access to your computer". | You need a code signing digital certificate from a certificate authority like Comodo or VeriSign. It's debatable how useful it is, though, because it only replaces this scary-looking warning with a slightly less scary warning (yellow alert vs red alert) that says "Publisher: " instead of "Unidentified Publisher" and still tells the user only to run it if they trust you.
I'm somewhat doubtful that the average user really notices the difference between the two warnings. | How to keep the windows install dialog from popping up in .NET? | [
"",
"c#",
".net",
"windows",
""
] |
I'd like to do something like below: particularly the 'f.eval(field)' part, such that it evaluates the value of the variable as the field name. How does one accomplish this in Python?
```
def punctuated_object_list(objects, field):
field_list = [f.eval(field) for f in objects]
if len(field_list) > 0:
if len(field_list) == 1:
return field_list[0]
else:
return ', '.join(field_list[:-1]) + ' & ' + field_list[-1]
else:
return u''
``` | `getattr(f, field)`, if I understand you correctly (that is, if you might have `field = "foo"`, and want `f.foo`). If not, you might want to clarify. Python has an `eval()`, and I don't know what other languages' `eval()` you want the equivalent of. | ```
getattr( object, 'field' ) #note that field is a string
f = 'field_name'
#...
getattr( object, f )
#to get a list of fields in an object, you can use dir()
dir( object )
```
For more details, see: <http://www.diveintopython.org/power_of_introspection/index.html>
**Don't use eval**, even if the strings are safe in this particular case! Just don't get yourself used to it. If you're getting the string from the user it could be malicious code.
Murphy's law: if things can go wrong, they will. | Python, Evaluate a Variable value as a Variable | [
"",
"python",
""
] |
I am working on a game and have an interesting question. I have some game-wide constant values that I want to implement in one file. Right now I have something like this:
constants.cpp
```
extern const int BEGINNING_HEALTH = 10;
extern const int BEGINNING_MANA = 5;
```
constants.hpp
```
extern const int BEGINNING_HEALTH;
extern const int BEGINNING_MANA;
```
And then files just #include "constants.hpp"
This was working great, until I needed to use one of the constants as a template parameter, because externally-linked constants are not valid template parameters.
So my question is, what is the best way to implement these constants? I am afraid that simply putting the constants in a header file will cause them to be defined in each translation unit. And I don't want to use macros.
Thanks | Get rid of the `extern` and you're set.
This code works perfectly fine in a header, because everything is "truly constant" and therefore has internal linkage:
```
const int BEGINNING_HEALTH = 10;
const int BEGINNING_MANA = 5;
const char BEGINNING_NAME[] = "Fred";
const char *const BEGINNING_NAME2 = "Barney";
```
This code cannot safely be put in a header file because each line has external linkage (either explicitly or because of not being truly constant):
```
extern const int BEGINNING_HEALTH = 10;
extern const int BEGINNING_MANA = 5;
const char *BEGINNING_NAME = "Wilma"; // the characters are const, but the pointer isn't
``` | How about enums?
constants.hpp
```
enum {
BEGINNING_HEALTH = 10,
BEGINNING_MANA = 5
}
``` | C++ best way to define cross-file constants | [
"",
"c++",
"templates",
"constants",
"extern",
""
] |
I'm using a third party library to render an image to a GDI DC and I need to ensure that any text is rendered without any smoothing/antialiasing so that I can convert the image to a predefined palette with indexed colors.
The third party library i'm using for rendering doesn't support this and just renders text as per the current windows settings for font rendering. They've also said that it's unlikely they'll add the ability to switch anti-aliasing off any time soon.
The best work around I've found so far is to call the third party library in this way (error handling and prior settings checks ommitted for brevity):
```
private static void SetFontSmoothing(bool enabled)
{
int pv = 0;
SystemParametersInfo(Spi.SetFontSmoothing, enabled ? 1 : 0, ref pv, Spif.None);
}
// snip
Graphics graphics = Graphics.FromImage(bitmap)
IntPtr deviceContext = graphics.GetHdc();
SetFontSmoothing(false);
thirdPartyComponent.Render(deviceContext);
SetFontSmoothing(true);
```
This obviously has a horrible effect on the operating system, other applications flicker from cleartype enabled to disabled and back every time I render the image.
So the question is, does anyone know how I can alter the font rendering settings for a specific DC?
Even if I could just make the changes process or thread specific instead of affecting the whole operating system, that would be a big step forward! (That would give me the option of farming this rendering out to a separate process- the results are written to disk after rendering anyway)
**EDIT:** I'd like to add that I don't mind if the solution is more complex than just a few API calls. I'd even be happy with a solution that involved hooking system dlls if it was only about a days work.
**EDIT: Background Information**
The third-party library renders using a palette of about 70 colors. After the image (which is actually a map tile) is rendered to the DC, I convert each pixel from it's 32-bit color back to it's palette index and store the result as an 8bpp greyscale image. This is uploaded to the video card as a texture. During rendering, I re-apply the palette (also stored as a texture) with a pixel shader executing on the video card. This allows me to switch and fade between different palettes instantaneously instead of needing to regenerate all the required tiles. It takes between 10-60 seconds to generate and upload all the tiles for a typical view of the world.
**EDIT: Renamed GraphicsDevice to Graphics**
The class GraphicsDevice in the previous version of this question is actually System.Drawing.Graphics. I had renamed it (using GraphicsDevice = ...) because the code in question is in the namespace MyCompany.Graphics and the compiler wasn't able resolve it properly.
**EDIT: Success!**
I even managed to port the `PatchIat` function below to C# with the help of `Marshal.GetFunctionPointerForDelegate`. The .NET interop team really did a fantastic job! I'm now using the following syntax, where `Patch` is an extension method on `System.Diagnostics.ProcessModule`:
```
module.Patch(
"Gdi32.dll",
"CreateFontIndirectA",
(CreateFontIndirectA original) => font =>
{
font->lfQuality = NONANTIALIASED_QUALITY;
return original(font);
});
private unsafe delegate IntPtr CreateFontIndirectA(LOGFONTA* lplf);
private const int NONANTIALIASED_QUALITY = 3;
[StructLayout(LayoutKind.Sequential)]
private struct LOGFONTA
{
public int lfHeight;
public int lfWidth;
public int lfEscapement;
public int lfOrientation;
public int lfWeight;
public byte lfItalic;
public byte lfUnderline;
public byte lfStrikeOut;
public byte lfCharSet;
public byte lfOutPrecision;
public byte lfClipPrecision;
public byte lfQuality;
public byte lfPitchAndFamily;
public unsafe fixed sbyte lfFaceName [32];
}
``` | As requested, I have packaged up the code I wrote to solve this problem and placed it in a github repository: <http://github.com/jystic/patch-iat>
It looks like a lot of code because I had to reproduce all the Win32 structures for this stuff to work, and at the time I chose to put each one in its own file.
If you want to go straight to the meat of of the code it's in: `ImportAddressTable.cs`
It's licensed very freely and is for all intents and purposes, public domain, so feel free to use it in any project that you like. | Unfortunately you cant. The ability to control font anti aliasing is done per font. The GDI call CreateFontIndirect processes members of the LOGFONT struct to determine if its allowed to use cleartype, regular or no anti aliasing.
There are, as you noted, system wide settings. Unfortunately, changing the systemwide setting is pretty much the only (documented) way to downgrade the quality of font rendering on a DC if you cannot control the contents of the LOGFONT.
---
This code is not mine. Is unmanaged C. And will hook any function imported by a dll or exe file if you know its HMODULE.
```
#define PtrFromRva( base, rva ) ( ( ( PBYTE ) base ) + rva )
/*++
Routine Description:
Replace the function pointer in a module's IAT.
Parameters:
Module - Module to use IAT from.
ImportedModuleName - Name of imported DLL from which
function is imported.
ImportedProcName - Name of imported function.
AlternateProc - Function to be written to IAT.
OldProc - Original function.
Return Value:
S_OK on success.
(any HRESULT) on failure.
--*/
HRESULT PatchIat(
__in HMODULE Module,
__in PSTR ImportedModuleName,
__in PSTR ImportedProcName,
__in PVOID AlternateProc,
__out_opt PVOID *OldProc
)
{
PIMAGE_DOS_HEADER DosHeader = ( PIMAGE_DOS_HEADER ) Module;
PIMAGE_NT_HEADERS NtHeader;
PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor;
UINT Index;
assert( Module );
assert( ImportedModuleName );
assert( ImportedProcName );
assert( AlternateProc );
NtHeader = ( PIMAGE_NT_HEADERS )
PtrFromRva( DosHeader, DosHeader->e_lfanew );
if( IMAGE_NT_SIGNATURE != NtHeader->Signature )
{
return HRESULT_FROM_WIN32( ERROR_BAD_EXE_FORMAT );
}
ImportDescriptor = ( PIMAGE_IMPORT_DESCRIPTOR )
PtrFromRva( DosHeader,
NtHeader->OptionalHeader.DataDirectory
[ IMAGE_DIRECTORY_ENTRY_IMPORT ].VirtualAddress );
//
// Iterate over import descriptors/DLLs.
//
for ( Index = 0;
ImportDescriptor[ Index ].Characteristics != 0;
Index++ )
{
PSTR dllName = ( PSTR )
PtrFromRva( DosHeader, ImportDescriptor[ Index ].Name );
if ( 0 == _strcmpi( dllName, ImportedModuleName ) )
{
//
// This the DLL we are after.
//
PIMAGE_THUNK_DATA Thunk;
PIMAGE_THUNK_DATA OrigThunk;
if ( ! ImportDescriptor[ Index ].FirstThunk ||
! ImportDescriptor[ Index ].OriginalFirstThunk )
{
return E_INVALIDARG;
}
Thunk = ( PIMAGE_THUNK_DATA )
PtrFromRva( DosHeader,
ImportDescriptor[ Index ].FirstThunk );
OrigThunk = ( PIMAGE_THUNK_DATA )
PtrFromRva( DosHeader,
ImportDescriptor[ Index ].OriginalFirstThunk );
for ( ; OrigThunk->u1.Function != NULL;
OrigThunk++, Thunk++ )
{
if ( OrigThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG )
{
//
// Ordinal import - we can handle named imports
// ony, so skip it.
//
continue;
}
PIMAGE_IMPORT_BY_NAME import = ( PIMAGE_IMPORT_BY_NAME )
PtrFromRva( DosHeader, OrigThunk->u1.AddressOfData );
if ( 0 == strcmp( ImportedProcName,
( char* ) import->Name ) )
{
//
// Proc found, patch it.
//
DWORD junk;
MEMORY_BASIC_INFORMATION thunkMemInfo;
//
// Make page writable.
//
VirtualQuery(
Thunk,
&thunkMemInfo,
sizeof( MEMORY_BASIC_INFORMATION ) );
if ( ! VirtualProtect(
thunkMemInfo.BaseAddress,
thunkMemInfo.RegionSize,
PAGE_EXECUTE_READWRITE,
&thunkMemInfo.Protect ) )
{
return HRESULT_FROM_WIN32( GetLastError() );
}
//
// Replace function pointers (non-atomically).
//
if ( OldProc )
{
*OldProc = ( PVOID ) ( DWORD_PTR )
Thunk->u1.Function;
}
#ifdef _WIN64
Thunk->u1.Function = ( ULONGLONG ) ( DWORD_PTR )
AlternateProc;
#else
Thunk->u1.Function = ( DWORD ) ( DWORD_PTR )
AlternateProc;
#endif
//
// Restore page protection.
//
if ( ! VirtualProtect(
thunkMemInfo.BaseAddress,
thunkMemInfo.RegionSize,
thunkMemInfo.Protect,
&junk ) )
{
return HRESULT_FROM_WIN32( GetLastError() );
}
return S_OK;
}
}
//
// Import not found.
//
return HRESULT_FROM_WIN32( ERROR_PROC_NOT_FOUND );
}
}
//
// DLL not found.
//
return HRESULT_FROM_WIN32( ERROR_MOD_NOT_FOUND );
}
```
You would call this from your code by doing something like (I haven't checked that this in any way compiles :P):
1. Declare a pointer type to the funciton you want to hook:
```
typedef FARPROC (WINAPI* PFNCreateFontIndirect)(LOGFONT*);
```
2. Implement a hook function
```
static PFNCreateFontIndirect OldCreateFontIndirect = NULL;
WINAPI MyNewCreateFontIndirectCall(LOGFONT* plf)
{
// do stuff to plf (probably better to create a copy than tamper with passed in struct)
// chain to old proc
if(OldCreateFontIndirect)
return OldCreateFontIndirect(plf);
}
```
3. Hook the function sometime during initialization
```
HMODULE h = LoadLibrary(TEXT("OtherDll"));
PatchIat(h, "USER32.DLL", "CreateFontIndirectW", MyNewCreateFontIndirectProc, (void**)&OldCreateFontIndirectProc);
```
Of course, if the module you are hooking exists in .NET land its very unclear as to where the `CreateFontIndirect` call is going to originate from. `mscoree.dll`? The actual module you call? Good luck I guess :P | Disable antialiasing for a specific GDI device context | [
"",
"c#",
"winapi",
"hook",
"gdi",
"cleartype",
""
] |
Is there a way to achieve the equivalent of a [negative lookbehind](http://www.regular-expressions.info/lookaround.html#lookbehind) in JavaScript regular expressions? I need to match a string that does not start with a specific set of characters.
It seems I am unable to find a regex that does this without failing if the matched part is found at the beginning of the string. Negative lookbehinds seem to be the only answer, but JavaScript doesn't has one.
This is the regex that I would like to work, but it doesn't:
`(?<!([abcdefg]))m`
So it would match the 'm' in 'jim' or 'm', but not 'jam' | ## [Lookbehind Assertions](https://github.com/tc39/proposal-regexp-lookbehind) got [accepted](https://github.com/tc39/proposals/blob/master/finished-proposals.md) into the [ECMAScript specification](https://tc39.github.io/ecma262/) in 2018.
Positive lookbehind usage:
```
console.log(
"$9.99 €8.47".match(/(?<=\$)\d+\.\d*/) // Matches "9.99"
);
```
Negative lookbehind usage:
```
console.log(
"$9.99 €8.47".match(/(?<!\$)\d+\.\d*/) // Matches "8.47"
);
```
## [Platform support](https://caniuse.com/js-regexp-lookbehind)
* ✔️ [V8](https://developers.google.com/v8/)
+ ✔️ [Google Chrome 62.0](https://bugs.chromium.org/p/v8/issues/detail?id=4545)
+ ✔️ Microsoft Edge 79.0
+ ✔️ [Node.js 6.0 behind a flag and 9.0 without a flag](https://node.green/)
+ ✔️ Deno (all versions)
* ✔️ [SpiderMonkey](https://bugzilla.mozilla.org/show_bug.cgi?id=1225665)
+ ✔️ [Mozilla Firefox 78.0](https://bugzilla.mozilla.org/show_bug.cgi?id=1634135)
* ✔️ JavaScriptCore: [the feature](https://bugs.webkit.org/show_bug.cgi?id=174931) has been [merged](https://github.com/WebKit/WebKit/commit/46e6b3f97425a4a7bb16fc175288903a5f74d5f2)
+ ✔️ [Apple Safari 16.4](https://webkit.org/blog/13878/web-push-for-web-apps-on-ios-and-ipados/)
+ ✔️ [iOS 16.4 WebView](https://webkit.org/blog/13878/web-push-for-web-apps-on-ios-and-ipados/) (all browsers on iOS + iPadOS)
+ ✔️ [Bun 0.2.2](https://github.com/oven-sh/bun/releases/tag/bun-v0.2.2)
* ❌ Chakra: [Microsoft was working on it](https://github.com/Microsoft/ChakraCore/issues/3448) but Chakra is now abandoned in favor of V8
+ ❌ Internet Explorer
+ ❌ Edge versions prior to 79 (the ones based on EdgeHTML+Chakra) | Since 2018, [Lookbehind Assertions](https://github.com/tc39/proposal-regexp-lookbehind) are part of the [ECMAScript language specification](https://github.com/tc39/proposals/blob/master/finished-proposals.md).
```
// positive lookbehind
(?<=...)
// negative lookbehind
(?<!...)
```
---
**Answer pre-2018**
As Javascript supports [negative lookahead](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-negated-look-ahead), one way to do it is:
1. reverse the input string
2. match with a reversed regex
3. reverse and reformat the matches
---
```
const reverse = s => s.split('').reverse().join('');
const test = (stringToTests, reversedRegexp) => stringToTests
.map(reverse)
.forEach((s,i) => {
const match = reversedRegexp.test(s);
console.log(stringToTests[i], match, 'token:', match ? reverse(reversedRegexp.exec(s)[0]) : 'Ø');
});
```
**Example 1:**
Following @andrew-ensley's question:
```
test(['jim', 'm', 'jam'], /m(?!([abcdefg]))/)
```
Outputs:
```
jim true token: m
m true token: m
jam false token: Ø
```
**Example 2:**
Following @neaumusic comment (match `max-height` but not `line-height`, the token being `height`):
```
test(['max-height', 'line-height'], /thgieh(?!(-enil))/)
```
Outputs:
```
max-height true token: height
line-height false token: Ø
``` | Negative lookbehind equivalent in JavaScript | [
"",
"javascript",
"regex",
"negative-lookbehind",
""
] |
Right now I have a central module in a framework that spawns multiple processes using the Python 2.6 [`multiprocessing` module](http://docs.python.org/library/multiprocessing.html?#module-multiprocessing). Because it uses `multiprocessing`, there is module-level multiprocessing-aware log, `LOG = multiprocessing.get_logger()`. Per [the docs](http://docs.python.org/library/multiprocessing.html#logging), this logger (**EDIT**) does **not** have process-shared locks so that you don't garble things up in `sys.stderr` (or whatever filehandle) by having multiple processes writing to it simultaneously.
The issue I have now is that the other modules in the framework are not multiprocessing-aware. The way I see it, I need to make all dependencies on this central module use multiprocessing-aware logging. That's annoying *within* the framework, let alone for all clients of the framework. Are there alternatives I'm not thinking of? | The only way to deal with this non-intrusively is to:
1. Spawn each worker process such that its log goes to **a different file descriptor** (to disk or to pipe.) Ideally, all log entries should be timestamped.
2. Your controller process can then do *one* of the following:
* **If using disk files:** Coalesce the log files at the end of the run, sorted by timestamp
* **If using pipes (recommended):** Coalesce log entries on-the-fly from all pipes, into a central log file. (E.g., Periodically [`select`](http://docs.python.org/library/select.html) from the pipes' file descriptors, perform merge-sort on the available log entries, and flush to centralized log. Repeat.) | I just now wrote a log handler of my own that just feeds everything to the parent process via a pipe. I've only been testing it for ten minutes but it seems to work pretty well.
(**Note:** This is hardcoded to `RotatingFileHandler`, which is my own use case.)
---
## Update: @javier now maintains this approach as a package available on Pypi - see [multiprocessing-logging](https://pypi.python.org/pypi/multiprocessing-logging/) on Pypi, github at <https://github.com/jruere/multiprocessing-logging>
---
## Update: Implementation!
This now uses a queue for correct handling of concurrency, and also recovers from errors correctly. I've now been using this in production for several months, and the current version below works without issue.
```
from logging.handlers import RotatingFileHandler
import multiprocessing, threading, logging, sys, traceback
class MultiProcessingLog(logging.Handler):
def __init__(self, name, mode, maxsize, rotate):
logging.Handler.__init__(self)
self._handler = RotatingFileHandler(name, mode, maxsize, rotate)
self.queue = multiprocessing.Queue(-1)
t = threading.Thread(target=self.receive)
t.daemon = True
t.start()
def setFormatter(self, fmt):
logging.Handler.setFormatter(self, fmt)
self._handler.setFormatter(fmt)
def receive(self):
while True:
try:
record = self.queue.get()
self._handler.emit(record)
except (KeyboardInterrupt, SystemExit):
raise
except EOFError:
break
except:
traceback.print_exc(file=sys.stderr)
def send(self, s):
self.queue.put_nowait(s)
def _format_record(self, record):
# ensure that exc_info and args
# have been stringified. Removes any chance of
# unpickleable things inside and possibly reduces
# message size sent over the pipe
if record.args:
record.msg = record.msg % record.args
record.args = None
if record.exc_info:
dummy = self.format(record)
record.exc_info = None
return record
def emit(self, record):
try:
s = self._format_record(record)
self.send(s)
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
def close(self):
self._handler.close()
logging.Handler.close(self)
``` | How should I log while using multiprocessing in Python? | [
"",
"python",
"logging",
"multiprocessing",
"python-logging",
""
] |
I've come across a design pattern that's been referred to as a "Handler Pattern," but I can't find any real references to this pattern anywhere. It's basically just a one-method interface that allows you to easily extend the functionality on the back-end without making clients recompile. Might be useful for a web-service that has to handle many different types of requests. Here's an example:
```
public interface IHandler
{
IDictionary<string, string> Handle(IDictionary<string, string> args);
}
```
The args would typically include one key like "Action" with a value that tells the implmentation what to do. Additional args can be passed in to give the impl more information. The impl then passes back an arbitrary list of args that the client "should" understand.
Is this an anti-pattern, or maybe another pattern in disguise? Is this type of design recommended?
EDIT:
A little more info: The way I've seen this implemented, the "root" Handler would act as a dispatcher to other concrete handlers (maybe?). The root handler has a "HandlerResolver," which decides which concrete handler should get the message based on it's contents. Maybe it's actually like a "dispatcher" pattern, although I don't know if that's really a pattern either. I guess it could also have a chain-of-responsibility pattern in the root, that allows you to chain together a bunch of concrete handlers, then let them decide which one will handle it. | it's the OOP way to do closures on languages that doesn't have them. it didn't have a 'pattern' name because on functional languages it's the obvious way to work. on OOP languages, OTOH, you have to do some work, so it seems a nameable idiom. 'Handler' sounds right.
(it's not a singleton, BTW) | I use it under the name of "SingletonRegistry"
See [this thread](https://stackoverflow.com/questions/401720/brokered-definition-set-design-pattern-well-known-under-another-name)
I've use it a couple of times. Specially when the actions to take are unknown upfront ( in the first phases of the design ) or the app should support extreme flexibility.
I load the dictionary either from a file or a database, and create a single instance of the class that will handle the request under certain "key".
I've found this [class also](http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.prefs/toxi/util/datatypes/SingletonRegistry.java?spec=svn144&r=144) searching the web for that name.
Looks like the same isn't? | "Handler" pattern? | [
"",
"c#",
".net",
"design-patterns",
""
] |
I ask because I have an unsigned jar that runs and a signed version that doesn't. Looking at the manifests, I see no main class thing for the signed one.
Do I have to run a signed jar from web start? | Not necessarily, but if you don't have a Main-class: in the manifest, you can't run it as an executable. If you know the main class, you can run it using the java executable, eg
```
$ java -classpath ./myjar.jar MyClass
``` | Sounds like you build process is updated the manifast.mf | Can a signed Jar be run as an executable? | [
"",
"java",
"jar",
"java-web-start",
""
] |
[The CRTP](https://stackoverflow.com/questions/262254/c-crtp-to-avoid-dynamic-polymorphism) is suggested in this question about dynamic polymorphism. However, this pattern is allegedly only useful for static polymorphism. The design I am looking at seems to be hampered speedwise by virtual function calls, as [hinted at here.](http://assemblyrequired.crashworks.org/2009/01/19/how-slow-are-virtual-functions-really/) A speedup of even 2.5x would be fantastic.
The classes in question are simple and can be coded completely inline, however it is not known until runtime which classes will be used. Furthermore, they may be chained, in any order, heaping performance insult onto injury.
Any suggestions (including how the CRTP can be used in this case) welcome.
**Edit:** Googling turns up a mention of function templates. These look promising. | I agree with m-sharp that you're not going to avoid runtime polymorphism.
If you value optimisation over elegance, try replacing say
```
void invoke_trivial_on_all(const std::vector<Base*>& v)
{
for (int i=0;i<v.size();i++)
v[i]->trivial_virtual_method();
}
```
with something like
```
void invoke_trivial_on_all(const std::vector<Base*>& v)
{
for (int i=0;i<v.size();i++)
{
if (v[i]->tag==FooTag)
static_cast<Foo*>(v[i])->Foo::trivial_virtual_method();
else if (v[i]->tag==BarTag)
static_cast<Bar*>(v[i])->Bar::trivial_virtual_method();
else...
}
}
```
it's not pretty, certainly not OOP (more a reversion to what you might do in good old 'C') but if the virtual methods are trivial enough you should get a function with no calls (subject to good enough compiler & optimisation options). A variant using dynamic\_cast or typeid might be slightly more elegant/safe but beware that those features have their own overhead which is probably comparable to a virtual call anyway.
Where you'll most likely see an improvement from the above is if some classes methods are no-ops, and it saved you from calling them, or if the functions contain common loop-invariant code and the optimiser manages to hoist it out of the loop. | Polymorphism literally means multiple (poly) forms (morphs). In statically typed languages (such as C++) there are three types of polymorphism.
1. Adhoc polymorphism: This is best seen in C++ as function and method overloading. The same function name will bind to different methods based on matching the **compile time** type of the parameters of the call to the function or method signature.
2. Parametric polymorphism: In C++ this is templates and all the fun things you can do with it such as CRTP, specialization, partial specialization, meta-programming etc. Again this sort of polymorphism where the same template name can do different things based on the template parameters is a **compile time** polymorphism.
3. Subtype Polymorphism: Finally this is what we think of when we hear the word polymorphism in C++. This is where derived classes override virtual functions to specialize behavior. The same type of pointer to a base class can have different behavior based on the concrete derived type it is pointing to. This is the way to get **run time** polymorphism in C++.
If it is not known until runtime which classes will be used, you must use Subtype Polymorphism which will involve virtual function calls.
Virtual method calls have a very small performance overhead over statically bound calls. I'd urge you to look at the answers to this [SO question.](https://stackoverflow.com/questions/449827/virtual-functions-and-performance-c) | Are there alternatives to polymorphism in C++? | [
"",
"c++",
"virtual-functions",
""
] |
If I write a class in C# that implements IDisposable, why isn't is sufficient for me to simply implement
```
public void Dispose(){ ... }
```
to handle freeing any unmanaged resources?
Is
```
protected virtual void Dispose(bool disposing){ ... }
```
always necessary, sometimes necessary, or something else altogether? | It's not strictly necessary. It is part of the recommended Disposable pattern. If you haven't read the Framework Design Guidelines section on this (9.3 in the first edition, don't have the second edition handy sorry) then you should. [Try this link](https://msdn.microsoft.com/en-us/library/b1yfkh5e(v=vs.110).aspx).
It's useful for distinguishing between disposable cleanup and finalizable garbage-collection-is-trashing-me.
You don't have to do it that way but you should read up on it and understand why this is recommended before discounting it as unnecessary. | The full pattern including a finalizer, introduction of a new virtual method and "sealing" of the original dispose method is very general purpose, covering all bases.
Unless you have *direct* handles on unmanaged resources (which should be [almost](http://joeduffyblog.com/2008/02/17/idisposable-finalization-and-concurrency/) [never](http://joeduffyblog.com/2005/12/27/never-write-a-finalizer-again-well-almost-never/)) you don't need a finalizer.
If you seal your class (and my views on sealing classes wherever possible are probably well known by now - [design for inheritance or prohibit it](https://stackoverflow.com/questions/268251/why-seal-a-class/268287#268287)) there's no point in introducing a virtual method.
I can't remember the last time I implemented `IDisposable` in a "complicated" way vs doing it in the most obvious way, e.g.
```
public void Dispose()
{
somethingElse.Dispose();
}
```
One thing to note is that if you're going for really robust code, you *should* make sure that you don't try to do anything after you've been disposed, and throw `ObjectDisposedException` where appropriate. That's good advice for class libraries which will be used by developers all over the world, but it's a lot of work for very little gain if this is just going to be a class used within your own workspace. | What's the point of overriding Dispose(bool disposing) in .NET? | [
"",
"c#",
".net",
"dispose",
"idisposable",
""
] |
I'm using a class I've derived from DocumentPaginator (see below) to print simple (text only) reports from a WPF application. I've got it so that everything prints correctly, **But how do I get it to do a print preview before printing?** I have a feeling I need to use a DocumentViewer but I can't figure out how.
Here's my Paginator Class:
```
public class RowPaginator : DocumentPaginator
{
private int rows;
private Size pageSize;
private int rowsPerPage;
public RowPaginator(int rows)
{
this.rows = rows;
}
public override DocumentPage GetPage(int pageNumber)
{
int currentRow = rowsPerPage * pageNumber;
int rowsToPrint = Math.Min(rowsPerPage, rows - (rowsPerPage * pageNumber - 1));
var page = new PageElementRenderer(pageNumber + 1, PageCount, currentRow, rowsToPrint)
{
Width = PageSize.Width,
Height = PageSize.Height
};
page.Measure(PageSize);
page.Arrange(new Rect(new Point(0, 0), PageSize));
return new DocumentPage(page);
}
public override bool IsPageCountValid { get { return true; } }
public override int PageCount { get { return (int)Math.Ceiling(this.rows / (double)this.rowsPerPage); } }
public override Size PageSize
{
get { return this.pageSize; }
set
{
this.pageSize = value;
this.rowsPerPage = PageElementRenderer.RowsPerPage(this.pageSize.Height);
if (rowsPerPage <= 0)
throw new InvalidOperationException("Page can't fit any rows!");
}
}
public override IDocumentPaginatorSource Source { get { return null; } }
}
```
The PageElementRenderer is just a simple UserControl that displays the data (at the moment just a list of rows).
Here's how I use my Row Paginator
```
PrintDialog dialog = new PrintDialog();
if (dialog.ShowDialog() == true)
{
var paginator = new RowPaginator(rowsToPrint) { PageSize = new Size(dialog.PrintableAreaWidth, dialog.PrintableAreaHeight) };
dialog.PrintDocument(paginator, "Rows Document");
}
```
Sorry for the code dump, but I didn't want to miss something relevant. | So I got it working after reading [Pro WPF in C# 2008](https://rads.stackoverflow.com/amzn/click/com/1590599551) (Page 726).
Basically the DocumentViewer class needs an XPS file to present a print preview of it. So I do the following:
```
PrintDialog dialog = new PrintDialog();
var paginator = new RowPaginator(rowsToPrint) { PageSize = new Size(dialog.PrintableAreaWidth, dialog.PrintableAreaHeight) };
string tempFileName = System.IO.Path.GetTempFileName();
//GetTempFileName creates a file, the XpsDocument throws an exception if the file already
//exists, so delete it. Possible race condition if someone else calls GetTempFileName
File.Delete(tempFileName);
using (XpsDocument xpsDocument = new XpsDocument(tempFileName, FileAccess.ReadWrite))
{
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
writer.Write(paginator);
PrintPreview previewWindow = new PrintPreview
{
Owner = this,
Document = xpsDocument.GetFixedDocumentSequence()
};
previewWindow.ShowDialog();
}
```
I'm creating the print dialog to get the default page size. There's probably a better way to do this.
XpsDocument is in ReachFramework.dll (Namespace System.Windows.Xps.Packaging);
Here's the PrintPreview Window.
```
<Window x:Class="WPFPrintTest.PrintPreview"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="previewWindow"
Title="PrintPreview" Height="800" Width="800">
<Grid>
<DocumentViewer Name="viewer"
Document="{Binding ElementName=previewWindow, Path=Document}" />
</Grid>
</Window>
```
The code behind just has a Document property like so:
```
public IDocumentPaginatorSource Document
{
get { return viewer.Document; }
set { viewer.Document = value; }
}
``` | The following code uses a MemoryStream to do a print preview.
```
MemoryStream stream = new MemoryStream();
Package package = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite);
var uri = new Uri(@"memorystream://myXps.xps");
PackageStore.AddPackage(uri, package);
var xpsDoc = new XpsDocument(package);
xpsDoc.Uri = uri;
XpsDocument.CreateXpsDocumentWriter(xpsDoc).Write(paginator);
documentViewer.Document = xpsDoc.GetFixedDocumentSequence();
```
Remember to use close() and remove package from PackageStore when the print preview is closed. | How to Print Preview when using a DocumentPaginator to print? | [
"",
"c#",
".net",
"wpf",
"printing",
""
] |
I'm trying to combine the following expressions into a single expression: item => item.sub, sub => sub.key to become item => item.sub.key. I need to do this so I can create an OrderBy method which takes the item selector separately to the key selector. This can be accomplished using one of the overloads on OrderBy and providing an `IComparer<T>`, but it won't translate to SQL.
Following is a method signature to further clarify what I am trying to achive, along with an implementation that doesn't work, but should illustrate the point.
```
public static IOrderedQueryable<TEntity> OrderBy<TEntity, TSubEntity, TKey>(
this IQueryable<TEntity> source,
Expression<Func<TEntity, TSubEntity>> selectItem,
Expression<Func<TSubEntity, TKey>> selectKey)
where TEntity : class
where TSubEntity : class
{
var parameterItem = Expression.Parameter(typeof(TEntity), "item");
...
some magic
...
var selector = Expression.Lambda(magic, parameterItem);
return (IOrderedQueryable<TEntity>)source.Provider.CreateQuery(
Expression.Call(typeof(Queryable), "OrderBy", new Type[] { source.ElementType, selector.Body.Type },
source.Expression, selector
));
}
```
which would be called as:
```
.OrderBy(item => item.Sub, sub => sub.Key)
```
Is this possible? Is there a better way? The reason I want an OrderBy method that works this way is to support a complex key selection expression that applies to many entities, though they are exposed in different ways. Also, I'm aware of a way to do this using String representations of deep properties, but I'm trying to keep it strongly typed. | Since this is LINQ-to-SQL, you can usually use `Expression.Invoke` to bring a sub-expression into play. I'll see if I can come up with an example (**update: done**). Note, however, that EF doesn't support this - you'd need to rebuild the expression from scratch. I have some code to do this, but it is quite lengthy...
The expression code (using `Invoke`) is quite simple:
```
var param = Expression.Parameter(typeof(TEntity), "item");
var item = Expression.Invoke(selectItem, param);
var key = Expression.Invoke(selectKey, item);
var lambda = Expression.Lambda<Func<TEntity, TKey>>(key, param);
return source.OrderBy(lambda);
```
Here's example usage on Northwind:
```
using(var ctx = new MyDataContext()) {
ctx.Log = Console.Out;
var rows = ctx.Orders.OrderBy(order => order.Customer,
customer => customer.CompanyName).Take(20).ToArray();
}
```
With TSQL (reformatted to fit):
```
SELECT TOP (20) [t0].[OrderID], -- snip
FROM [dbo].[Orders] AS [t0]
LEFT OUTER JOIN [dbo].[Customers] AS [t1]
ON [t1].[CustomerID] = [t0].[CustomerID]
ORDER BY [t1].[CompanyName]
``` | I needed the same so made this small extension method:
```
/// <summary>
/// From A.B.C and D.E.F makes A.B.C.D.E.F. D must be a member of C.
/// </summary>
/// <param name="memberExpression1"></param>
/// <param name="memberExpression2"></param>
/// <returns></returns>
public static MemberExpression JoinExpression(this Expression memberExpression1, MemberExpression memberExpression2)
{
var stack = new Stack<MemberInfo>();
Expression current = memberExpression2;
while (current.NodeType != ExpressionType.Parameter)
{
var memberAccess = current as MemberExpression;
if (memberAccess != null)
{
current = memberAccess.Expression;
stack.Push(memberAccess.Member);
}
else
{
throw new NotSupportedException();
}
}
Expression jointMemberExpression = memberExpression1;
foreach (var memberInfo in stack)
{
jointMemberExpression = Expression.MakeMemberAccess(jointMemberExpression, memberInfo);
}
return (MemberExpression) jointMemberExpression;
}
``` | How do I combine two Member Expression Trees? | [
"",
"c#",
".net",
"linq-to-sql",
"lambda",
"expression-trees",
""
] |
How to do conditional compilation in Python ?
Is it using DEF ? | Python isn't compiled in the same sense as C or C++ or even Java, python files are compiled "on the fly", you can think of it as being similar to a interpreted language like Basic or Perl.1
You can do something equivalent to conditional compile by just using an if statement. For example:
```
if FLAG:
def f():
print "Flag is set"
else:
def f():
print "Flag is not set"
```
You can do the same for the creation classes, setting of variables and pretty much everything.
The closest way to mimic IFDEF would be to use the hasattr function. E.g.:
```
if hasattr(aModule, 'FLAG'):
# do stuff if FLAG is defined in the current module.
```
You could also use a try/except clause to catch name errors, but the idiomatic way would be to set a variable to None at the top of your script.
1. Python code is byte compiled into an intermediate form like Java, however there generally isn't a separate compilation step. The "raw" source files that end in .py are executable. | There is actually a way to get conditional compilation, but it's very limited.
```
if __debug__:
doSomething()
```
The `__debug__` flag is a special case. When calling python with the `-O` or `-OO` options, `__debug__` will be false, and the compiler will ignore that statement. This is used primarily with asserts, which is why assertions go away if you 'really compile' your scripts with optimization.
So if your goal is to add debugging code, but prevent it from slowing down or otherwise affecting a 'release' build, this does what you want. But you cannot assign a value to `__debug__`, so that's about all you can use it for. | Conditional compilation in Python | [
"",
"python",
"conditional-compilation",
""
] |
I have an application in Python 2.5 that listens to a beanstalk queue. It works fine on all machines I tested so far, except from my newly acquired MacBook Pro.
On that computer, when I try to run it I get this error:
```
Traceback (most recent call last):
File "jobs.py", line 181, in <module>
Jobs().start()
File "jobs.py", line 154, in start
self.jobQueue = Queue()
File "src/utils/queue.py", line 16, in __init__
self.connection = serverconn.ServerConn(self.server, self.port)
File "src/beanstalk/serverconn.py", line 25, in __init__
self.poller = select.poll()
AttributeError: 'module' object has no attribute 'poll'
```
The serverconn.py has the following imports:
```
import socket, select
```
And when I try to run it from command line, it fails as well:
```
Python 2.5.1 (r251:54863, Jul 23 2008, 11:00:16)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import select
>>> select.poll()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'poll'
```
Do you have any idea on what can be happening?
PS: Even though I am pretty confident it's not a source problem, if you need some background on the source that's failing, it's available at [<http://pastie.org/399342](this> pastie).
*Updated:* since the first answer I got speculates whether select.poll() is or not supported on Mac OS, but I have an iMac too and with the exact same OS version and it works fine:
```
2009-02-25 00:27:10,067 - Queue - DEBUG - Connecting to BeansTalk daemon @ localhost:11300
``` | use the [MacPorts](http://www.macports.org/) version of `python` on your MBP.
Mac OS X supports this. Apple stock Leopard `python 2.5.1` does not.
you will want to download and install MacPorts if you have not already. FYI, I find [Porticus](http://porticus.alittledrop.com/) to be an excellent GUI around MacPorts.
here is a comparison of stock Leopard python vs. latest MacPorts python2.5...
---
Leopard python from Apple (python 2.5.1) - **`select.poll()` broken**
```
$ /usr/bin/python
Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket, select
>>> select.poll()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'poll'
>>>
```
Macports (python 2.5.4) - **`select.poll()` works!**
```
$ /opt/local/bin/python2.5
Python 2.5.4 (r254:67916, Feb 3 2009, 21:40:31)
[GCC 4.0.1 (Apple Inc. build 5488)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket, select
>>> select.poll()
<select.poll object at 0x11128>
>>>
``` | According to [this macports ticket](http://trac.macports.org/ticket/18376) Apple's implementation of poll() is straight up broken. Apple worked around this by disabling poll() in Python and macports now disables poll in their Pythons as well. I think this means you need to look into Python's select.kevent() instead of poll on mac. | Problems on select module on Python 2.5 | [
"",
"python",
"macos",
"beanstalkd",
""
] |
If my application has too many static variables or methods, then as per definition they will be stored in heap. Please correct me if I am wrong
1) Will these variables be on heap until application is closed?
2) Will they be available for GC at any time? If not can I say it is a memory leak? | Static methods are just methods, they are not stored on the heap, they just don't get to use a "this" parameter.
Static variables serve as "roots" to the GC. As a result, unless you explicitly set them to null, they will live as long as the program lives, and so is everything reachable from them.
A situation is only considered a memory leak if you intend for the memory to become free and it doesn't become free. If you intend for your static variable to contain a reference to an object for part of the time, and you forget to set it to null when you're done with that object, you would likely end up with a leak. However, if you put it in the static variable and intend for it to be there for as long as the program is running, then it is most definitely not a leak, it is more likely a "permanent singleton". If the object got reclaimed while you wanted it to still exist, that would have been very bad.
As for your question about the heap: All objects in Java exist either on the heap or on the stack. Objects are created on the heap with the new operator. A reference is then attached to them. If the reference becomes null or falls out of scope (e.g., end of block), the GC realizes that there is no way to reach that object ever again and reclaims it. If your reference is in a static variable, it never falls out of scope but you can still set it to null or to another object. | If you have a static hashmap and you add data to it... the data will never disappear and you have a leak - in case you do not need the data anymore. If you need the data, it is not a leak, but a huge pile of memory hanging around. | Can using too many static variables cause a memory leak in Java? | [
"",
"java",
"memory-management",
"memory-leaks",
""
] |
I have form with button and checkbox. if i hit button static void is called which call non static void which shows messagebox with the checkbox.checked.toString()
The problem is if i change the checkbox value it always shows false
Code is
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void y()
{
MessageBox.Show(checkBox1.Checked.ToString());
}
static void x()
{
Form1 f = new Form1();
f.y();
}
private void button1_Click(object sender, EventArgs e)
{
x();
}
}
}
``` | Try
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void y()
{
MessageBox.Show(checkBox1.Checked.ToString());
}
static void x(Form f)
{
f.y();
}
private void button1_Click(object sender, EventArgs e)
{
x(this);
}
}
``` | I guess you have probably came from a Visual Basic background like I do.
In C#, form are just instances of a Form class, they does not have special status like in the days of VB6.
When you call `new Form1()` you are basically creating a **new** form *not* accessing the same form. As anyone form can have multiple instances because it really is just a C# class underneath.
You can fix this by having the x() method takes the current form as a parameter
```
static void x(Form1 theForm)
{
theForm.y();
}
private void button1_Click(object sender, EventArgs e)
{
x(this);
}
```
The this parameter inside a form class points to the form instance itself.
You should now gets the correct value instead of the default value when the form is being created.
I suppose you have a need for `x()` to be `static`, no? But if that isn't the case, removing `static` from `x()` might be a better solution.
```
void x()
{
this.y();
// or you can just omit the this qualifier and call just y();
}
``` | C# accessing control propertes from static void | [
"",
"c#",
"static",
""
] |
Alright, so my title sucked. An example works better:
```
input = 'check yahoo.com'
```
I want to parse input, using the first word as the "command", and the rest of the string as a parameter. Here's the simple version of how my non-Pythonic mind is coding it:
```
if len(input) > 0:
a = input.split(' ')
if a[0] == 'check':
if len(a) > 1:
do_check(a[1])
elif a[0] == 'search':
if len(a) > 1:
do_search(a[1])
```
I like Python because it makes normally complicated things into rather simple things. I'm not too experienced with it, and I am fairly sure there's a much better way to do these things... some way more pythonic. I've seen some examples of people replacing switch statements with dicts and lambda functions, while other people simply recommended if..else nests. | ```
dispatch = {
'check': do_check,
'search': do_search,
}
cmd, _, arg = input.partition(' ')
if cmd in dispatch:
dispatch[cmd](arg)
else:
do_default(cmd, arg)
``` | > I am fairly sure there's a much better way to do these things... some way more pythonic.
Not really. You code is simple, clear, obvious and English-like.
> I've seen some examples of people replacing switch statements with dicts and lambda functions,
Yes, you've seen them and they're not clear, obvious or English-like. They exist because some people like to wring their hands over the switch statement.
> while other people simply recommended if..else nests.
Correct. They work. They're simple, clear, ...
Your code is good. Leave it alone. Move on. | "Pythonic" equivalent for handling switch and multiple string compares | [
"",
"conditional-statements",
"python",
""
] |
Seems a common enough problem this, but most solutions refer to concatenating multiple SQL commands, something which I believe can't be done with ADO/VBA (I'll be glad to be shown wrong in this regard however).
I currently insert my new record then run a select query using (I hope) enough fields to guarantee that only the newly inserted record can be returned. My databases are rarely accessed by more than one person at a time (negligible risk of another insert happening between queries) and due to the structure of the tables, identifying the new record is normally pretty easy.
I'm now trying to update a table that does not have much scope for uniqueness, other than in the artificial primary key. This means there is a risk that the new record may not be unique, and I'm loathe to add a field just to force uniqueness.
What's the best way to insert a record into an Access table then query the new primary key from Excel in this situation?
Thanks for the replies. I have tried to get `@@IDENTITY` working, but this always returns 0 using the code below.
```
Private Sub getIdentityTest()
Dim myRecordset As New ADODB.Recordset
Dim SQL As String, SQL2 As String
SQL = "INSERT INTO tblTasks (discipline,task,owner,unit,minutes) VALUES (""testDisc3-3"",""testTask"",""testOwner"",""testUnit"",1);"
SQL2 = "SELECT @@identity AS NewID FROM tblTasks;"
If databaseConnection Is Nothing Then
createDBConnection
End If
With databaseConnection
.Open dbConnectionString
.Execute (SQL)
.Close
End With
myRecordset.Open SQL2, dbConnectionString, adOpenStatic, adLockReadOnly
Debug.Print myRecordset.Fields("NewID")
myRecordset.Close
Set myRecordset = Nothing
End Sub
```
Anything stand out being responsible?
However, given the caveats helpfully supplied by Renaud (below) there seems nearly as much risk with using `@@IDENTITY` as with any other method, so I've resorted to using `SELECT MAX` for now. For future reference though I would be interested to see what is wrong with my attempt above. | About your question:
> *I'm now trying to update a table that
> does not have much scope for
> uniqueness, other than in the
> artificial primary key. This means
> there is a risk that the new record
> may not be unique, and I'm loathe to
> add a field just to force uniqueness.*
If you **are** using an AutoIncrement for your primary key, then you have uniqueness and you could use `SELECT @@Identity;` to get the value of the last autogenerated ID (see caveats below).
If you are **not** using autoincrement, and you are inserting the records from Access but you want to retrieve the last one from Excel:
* make sure your primary key is sortable, so you can get the last one using a query like either of these:
```
SELECT MAX(MyPrimaryField) FROM MyTable;
SELECT TOP 1 MyPrimaryField FROM MyTable ORDER BY MyPrimaryField DESC;
```
* or, if sorting your primary field wouldn't give you the last one, you would need to add a DateTime field (say `InsertedDate`) and save the current date and time every time you create a new record in that table so you could get the last one like this:
```
SELECT TOP 1 MyPrimaryField FROM MyTable ORDER BY InsertedDate DESC;
```
In either of these cases, I think you would find adding an AutoIncrement primary key as being a lot easier to deal with:
* It's not going to cost you much
* It's going to guarantee you uniqueness of your records without having to think about it
* It's going to make it easier for you to pick the most recent record, either using `@@Identity` or through sorting by the primary key or getting the `Max()`.
**From Excel**
To get the data into Excel, you have a couple of choices:
* create a data link using a query, so you can use the result directly in a Cell or a range.
* query from VBA:
```
Sub GetLastPrimaryKey(PrimaryField as string, Table as string) as variant
Dim con As String
Dim rs As ADODB.Recordset
Dim sql As String
con = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source= ; C:\myDatabase.accdb"
sql = "SELECT MAX([" & PrimaryField & "]) FROM [" & MyTable & "];"
Set rs = New ADODB.Recordset
rs.Open sql, con, adOpenStatic, adLockReadOnly
GetLastPrimaryKey = rs.Fields(0).Value
rs.Close
Set rs = Nothing
End Sub
```
**Note about `@@Identity`**
You have to be [careful of the caveats](http://www.accessmonster.com/Uwe/Forum.aspx/access/8107/Select-Identity) when using `@@Identity` in standard Access databases(\*):
* It only works with AutoIncrement Identity fields.
* It's only available if you use ADO and run `SELECT @@IDENTITY;`
* It returns the latest used counter, [but that's for **all tables**](http://msdn.microsoft.com/en-us/library/bb208866.aspx). You can't use it to return the counter for a specific table in MS Access (as far as I know, if you specify a table using `FROM mytable`, it just gets ignored).
In short, the value returned may not be at all the one you expect.
* You must query it straight after an `INSERT` to minimize the risk of getting a wrong answer.
That means that if you are inserting your data at one time and need to get the last ID at another time (or another place), it won't work.
* Last but not least, the variable is set only when records are inserted through programming code.
This means that is the record was added through the user interface, `@@IDENTITY` will not be set.
(\*): just to be clear, `@@IDENTITY` behaves differently, and in a more predictive way, if you use ANSI-92 SQL mode for your database.
The issue though is that ANSI 92 has a slightly different syntax than
the ANSI 89 flavour supported by Access and is meant to increase compatibility with SQL Server when Access is used as a front end. | If the artificial key is an autonumber, you can use @@identity.
Note that with both these examples, the transaction is isolated from other events, so the identity returned is the one just inserted. You can test this by pausing the code at Debug.Print db.RecordsAffected or Debug.Print lngRecs and inserting a record manually into Table1, continue the code and note that the identity returned is not that of the record inserted manually, but of the previous record inserted by code.
**DAO Example**
```
'Reference: Microsoft DAO 3.6 Object Library '
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
db.Execute ("INSERT INTO table1 (field1, Crdate ) " _
& "VALUES ( 46, #" & Format(Date, "yyyy/mm/dd") & "#)")
Debug.Print db.RecordsAffected
Set rs = db.OpenRecordset("SELECT @@identity AS NewID FROM table1")
Debug.Print rs.Fields("NewID")
```
**ADO Example**
```
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Set cn = CurrentProject.Connection
cn.Execute ("INSERT INTO table1 (field1, Crdate ) " _
& "VALUES ( 46, #" & Format(Date, "yyyy/mm/dd") & "#)"), lngRecs
Debug.Print lngRecs
rs.Open "SELECT @@identity AS NewID FROM table1", cn
Debug.Print rs.Fields("NewID")
``` | How to get id of newly inserted record using Excel VBA? | [
"",
"sql",
"excel",
"ms-access",
"vba",
"jet",
""
] |
I'm about to start working on a PHP application that allows a user to track their progress on a day to day basis.
I'm looking for a good graphing library, preferably PHP and or Javascript (JQuery would be good) which will allow me to name each bar on a bar graph with a date (10 Feb, 11 Feb, 12 Feb, etc.) probably on it's side or at a 45 degree angle, or something that will have the day number at the bottom of each bar with the month under the 1st of each month) The time span for each graph will be range from 1 - 3 months, but if there is something that can handle larger time frames that would be good too.
I'm assuming this is a common problem, and that there is a common best practice way to do this. I'd prefer to use bar charts rather than an line graph (like stack over flows reputation tracker)
Any ideas? I've looked at JpGraph and Graphpite and neither of them look very nice. I don't mind one that is flash integrated, so long as I can feed it data from my php script. | Look at Google Charts. Easy to use and readily available.
<http://code.google.com/apis/chart/> | We use [JPGraph](http://www.aditus.nu/jpgraph), which does all sorts of graphs and charts and spits out JPG images. | Can anyone recommend a good bar chart component for Showing goal progress? | [
"",
"php",
"graphing",
"bar-chart",
""
] |
I'm trying to design a class that needs to dynamically allocate some memory..
I had planned to allocate the memory it needs during construction, but how do I handle failed memory allocations? Should I throw an exception? I read somewhere that exceptions should only be used for "exceptional" cases, and running out of memory doesn't seem like an exceptional case to me..
Should I allocate memory in a separate initialization routine instead and check for failures and then destroy the class instance gracefully?
Or should I use exceptions instead? The class won't have anything useful to do if these memory allocations should fail..
---
EDIT: The consensus seems to be that running out of memory IS an exceptional case.
Will see how to go about this.. Thanks.. :) | Assuming you are using new to allocate memory, and are not overriding the `new` operator, it will automatically throw the `std::bad_alloc` exception if it fails to allocate memory properly.
> I read somewhere that exceptions
> should only be used for "exceptional"
> cases, and running out of memory
> doesn't seem like an exceptional case
> to me..
Running out of memory seems like a pretty exceptional case to me :)
It is very difficult to handle this sort of situation. You may want to return a meaningful error to the user of your application, but if it's a problem caused by lack of memory, you may not even be able to afford the memory to allocate the error message. It's a bit of a catch-22 situation really.
There is a defensive programming technique (sometimes called a memory parachute or rainy day fund) where you allocate a chunk of memory when your application starts. When you then handle the `bad_alloc` exception, you free this memory up, and use the available memory to close down the application gracefully, including displaying a meaningful error to the user. This is much better than crashing :) | I would argue that running out of memory (particularly heap memory) is an exceptional case, and if your class - and further, your application - cannot continue, I think exception throwing/handling is a very appropriate and graceful approach. | When is it appropriate to use C++ exceptions? | [
"",
"c++",
"exception",
"memory",
"error-handling",
"raii",
""
] |
Since java.util.Date is mostly deprecated, what's the right way to get a timestamp for a given date, UTC time? The one that could be compared against `System.currentTimeMillis()`. | Using the [Calendar](http://java.sun.com/j2se/1.4.2/docs/api/java/util/Calendar.html) class you can create a time stamp at a specific time in a specific timezone. Once you have that, you can then get the millisecond time stamp to compare with:
```
Calendar cal = new GregorianCalendar();
cal.set(Calendar.DAY_OF_MONTH, 10);
// etc...
if (System.currentTimeMillis() < cal.getTimeInMillis()) {
// do your stuff
}
```
edit: changed to use more direct method to get time in milliseconds from Calendar instance. Thanks Outlaw Programmer | The "official" replacement for many things Date was used for is Calendar. Unfortunately it is rather clumsy and over-engineered. Your problem can be solved like this:
```
long currentMillis = System.currentTimeMillis();
Date date = new Date(currentMillis);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
long calendarMillis = calendar.getTimeInMillis();
assert currentMillis == calendarMillis;
```
Calendars can also be initialized in different ways, even one field at a time (hour, minute, second, etc.). Have a look at the Javadoc. | System.currentTimeMillis() for a given date? | [
"",
"java",
"timestamp",
""
] |
I want to upload a large file of maximum size 10MB to my MySQL database. Using `.htaccess` I changed PHP's own file upload limit to "10485760" = 10MB. I am able to upload files up to 10MB without any problem.
But I can not insert the file in the database if it is more that 1 MB in size.
I am using `file_get_contents` to read all file data and pass it to the insert query as a string to be inserted into a LONGBLOB field.
But files bigger than 1 MB are not added to the database, although I can use `print_r($_FILES)` to make sure that the file is uploaded correctly. Any help will be appreciated and I will need it within the next 6 hours. So, please help! | As far as I know it's generally quicker and better practice not to store the file in the db as it will get massive very quickly and slow it down. It's best to make a way of storing the file in a directory and then just store the location of the file in the db.
We do it for images/pdfs/mpegs etc in the CMS we have at work by creating a folder for the file named from the url-safe filename and storing the folder name in the db. It's easy just to write out the url of it in the presentation layer then. | You will want to check the MySQL configuration value "max\_allowed\_packet", which might be set too small, preventing the INSERT (which is large itself) from happening.
Run the following from a mysql command prompt:
```
mysql> show variables like 'max_allowed_packet';
```
Make sure its large enough. For more information on this config option see
[MySQL max\_allowed\_packet](http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html)
This also impacts mysql\_escape\_string() and mysql\_real\_escape\_string() in PHP limiting the size of the string creation. | How can I insert large files in MySQL db using PHP? | [
"",
"php",
"mysql",
"blob",
"large-files",
""
] |
I'm trying to convert a single-columned subquery into a command-separated `VARCHAR`-typed list of values.
This is identical to [this question](https://stackoverflow.com/questions/111341/combine-multiple-results-in-a-subquery-into-a-single-comma-separated-value), but for Oracle rather than SQL Server or MySQL. | There is an excellent summary of the [available string aggregation techniques](http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php) on Tim Hall's site. | I found this that seems to work. Thoughts?
```
SELECT SUBSTR (c, 2) concatenated
FROM (SELECT SYS_CONNECT_BY_PATH ( myfield, ',') c, r
FROM (SELECT ROWNUM ID, myfield,
RANK () OVER (ORDER BY ROWID DESC) r
FROM mytable
ORDER BY myfield)
START WITH ID = 1
CONNECT BY PRIOR ID = ID - 1)
WHERE r = 1;
``` | Oracle: Combine multiple results in a subquery into a single comma-separated value | [
"",
"sql",
"oracle",
"subquery",
"string-aggregation",
""
] |
I've got a parent page and an iframe inside that page. The links in the parent control the page that gets loaded in the iframe. What I want to do is refresh the parent page when the iframe gets loaded.
I've got this in the iframe:
```
RefreshParent(){
parent.location.reload();
}
<body onload="RefreshParent();">
```
But, the above code refreshes the whole parent page along with the iframe inside it which in turn reloads the parent page and goes into an infinite loop. | You can't refresh the parent page without reloading the iframe.
What you could do is use [AJAX](http://en.wikipedia.org/wiki/AJAX) to update the parent's content, but that could be a fair amount of work (using the jQuery or Prototype frameworks would make this easier). | You won't need to use ajax techniques either. You can simply call a javascript function in parent page from the page contained in the iframe of parent page. This way you can easily perform actions on parent page. [How to refresh parent page partially from page in iframe without affecting the iframe](http://dotnetspidor.blogspot.com/2011/07/refresh-parent-page-partially-from.html) illustrates how.
Hope this helps. | How can I refresh parent window from an iframe? | [
"",
"javascript",
"iframe",
""
] |
**Duplicate**: [Function overloading by return type?](https://stackoverflow.com/questions/442026/function-overloading-by-return-type)
---
Maybe this is a very silly question but I don't understand why I can't declare two methods that have the same signature when they have different return types.
```
public class MyClass
{
private double d = 0;
public double MyMethod()
{
return d;
}
public string MyMethod()
{
return d.ToString();
}
}
```
I get a compile error that states that the class already defines a member with the same parameter types.
(Obviously the way I'm using this in my code isn't as simple as my example code...but I think it gets the idea across.)
Am I missing something concerning OO design that makes what I'm trying to do an OOP anti-pattern? Surely the compiler should be able to determine which method I'm trying to use as long as I specifically tell it which one I want.
Given `MyClass myClass = new MyClass();` I would expect the following code to work:
```
double d = myClass.MyMethod();
string s = myClass.MyMethod();
```
I would expect the following code to have problems:
```
var v = myClass.MyMethod();
```
But even in the case of `var` it should result in a compile error.
Can anyone see what I'm doing wrong here? I'm more than happy to be corrected. :-) | It's because of type coercion.
Say you have the following functions:
```
int x(double);
float x(double);
double y = x(1.0);
```
Now, which of the two prototypes should you call, especially if they do two totally different things?
Basically, a decision was made early on in the language design to only use the function name and arguments to decide which actual function gets called, and we're stuck with that until a new standard arrives.
Now, you've tagged your question `C#` but I see nothing wrong with designing a language that can do what you suggest. One possibility would be to flag as an error any ambiguous commands like above and force the user to specify which should be called, such as with casting:
```
int x(double);
float x(double);
double y = (float)(x(1.0)); // overload casting
double y = float:x(1.0); // or use new syntax (looks nicer, IMNSHO)
```
This could allow the compiler to choose the right version. This would even work for some issues that other answers have raised. You could turn the ambiguous:
```
System.out.Println(myClass.MyMethod());
```
into the specific:
```
System.out.Println(string:myClass.MyMethod());
```
This may be possible to get added to `C#` if it's not too far into a standards process (and Microsoft will listen) but I don't think much of your chances getting it added to `C` or `C++` without an awfully large amount of effort. Maybe doing it as an extension to `gcc` would be easier. | There's nothing from stopping you from calling your method without "capturing" the return type. There's nothing from stopping you from doing this:
```
myClass.MyMethod();
```
How will the compiler know which one to call in that case?
Edit: Adding to that, in C# 3.0, when you can use **var**, how will the compiler know which method you're calling when you do this:
```
var result = myClass.MyMethod();
``` | Why can't two methods be declared with the same signature even though their return types are different? | [
"",
"c#",
"method-signature",
""
] |
```
LastAccessed=(select max(modifydate) from scormtrackings WHERE
bundleid=@bundleid and userid=u.userid),
CompletedLessons=(select Value from scormtrackings WHERE
bundleid=@bundleid and userid=u.userid AND param='vegas2.progress'),
TotalLessons=100,
TotalNumAvail=100,
TotalNumCorrect=(SELECT Value FROM scormtrackings WHERE
bundleid=@bundleid AND userid=u.userid AND param='cmi.score.raw')
```
This is only part of a large select statement used by my ASP.NET `Repeater` that keeps crashing when the values are `NULL`, I have tried `ISNULL()` but either it didn't work, or I did it wrong.
```
ISNULL((SELECT max(modifydate) FROM scormtrackings WHERE
bundleid=@bundleid AND userid=u.userid),'') AS LastAccessed,
```
*(...)*
???
UPDATE: I've tried all these things with returning '', 0, 1, instead of the value that would be null and it still doesn't work, I wonder if the problem is with the `Repeater`?
### Related Question:
> [Why does my repeater keep crashing on Eval(NULL) values?](https://stackoverflow.com/questions/584570/why-does-my-repeater-keep-crashing-on-evalnull-values) | You can use the [COALESCE](http://msdn.microsoft.com/en-us/library/ms190349.aspx) function to avoid getting nulls. Basically it returns the first non-null value from the list.
```
SELECT COALESCE(dateField, '') FROM Some_Table
```
This is an ANSI standard, though I have noticed that it isn't available in Access SQL. | You can use CASE:
```
CASE WHEN MyField IS Null THEN ''
ELSE MyField
End As MyField
``` | How do I make this SQL statement return empty strings instead of NULLS? | [
"",
"sql",
"null",
""
] |
How to make PDO adapter run SET NAMES utf8 each time I connect, In ZendFramework.
I am using an INI file to save the adapter config data. what entries should I add there?
If it wasn't clear, I am looking for the correct syntax to do it in the config.ini file of my project and not in php code, as I regard this part of the configuration code. | Itay,
A very good question. Fortunately for you the answer is very simple:
```
database.params.driver_options.1002 = "SET NAMES utf8"
```
1002 is the value of constant PDO::MYSQL\_ATTR\_INIT\_COMMAND
You can't use the constant in the config.ini | fear my [google-fu](http://www.google.nl/search?rlz=1C1GGLS_nlNL291NL303&sourceid=chrome&ie=UTF-8&q=php+pdo+mysql+set+names+utf+8+connect)
```
$pdo = new PDO(
'mysql:host=mysql.example.com;dbname=example_db',
"username",
"password",
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
```
first hit ;) | How to make PDO run SET NAMES utf8 each time I connect, In ZendFramework | [
"",
"php",
"zend-framework",
"pdo",
"zend-db-table",
""
] |
I've always wondered why Javascript has the global Math object instead of giving numbers their own methods. Is there a good reason for it?
Also are there any drawbacks (other than efficiency) to doing something like this?:
```
Number.prototype.round = function(){
return Math.round(this);
};
```
Just to make clear, I understand that constants like π need somewhere and functions that are applied on more than one number like min/max. The question was mainly concerning methods which only effect a single number such as round, abs, sin, pow, etc. | The reason for the `Math` object is simple: "because Java does it". Not the best of reasons, but here we are. I guess things made more sense back then, before Douglas Crockford started his campaign to suppress half the language\*. Originally you were "allowed", or meant, to do things like this:
```
with (Math) {
var n = min( round(a) * round(b), sqrt(c) );
var result = exp( n + d );
}
```
The drawback to extending `Number.prototype` is that someone else might do the same thing. Or worse, for example, define `Number.prototype.round` as a *symmetrical* rounding function.
If you are looking for ways to make your life easier, why stop there? Why not simply include `Math` functions as global functions?
```
var m = 'abs acos asin atan atan2 ceil cos exp floor log max min ' +
'pow random round sin sqrt tan PI').split(' ');
for (var i=0,l=m.length; i<l; i++) {
window[ m[i] ] = Math[ m[i] ];
}
```
This will drop all the math functions into the global scope, effectively allowing you to stop typing "Math." Ask yourself: Is there any real difference between extending `Number` and extending `window` with these functions?
\* Before you flame me: The Crockford comment is not meant to be taken too seriously. I do agree with him that `with` is very dangerous in an implicit global environment. | There is no drawback in extending `Number.prototype` other than confusing other people. What's the point? What is better in using `value.round()` instead of `Math.round(value)`?
There are several good reasons for the `Math` object:
1. It works for non-numbers, too: `Math.round("5")` works whereas `value.round()` won't work when value is a string (for example, the value of a textbox)
2. Some members of the Math object don't belong to a "primary" number value, like `Math.min()` or `Math.max()`. Or do you want to use it like `a.max(b)`?
3. Other members are global and do not belong to a specialized number. Examples are constants like `Math.PI` or the function `Math.random()`. | Extending Number.prototype in javascript and the Math object? | [
"",
"javascript",
"oop",
"prototype",
"methods",
""
] |
In C# 2.0+, is it necessary to lock around a closure that another thread will execute? Specifically, in the example below, is the locking necessary to ensure that the Maint thread flushes its value of x to shared memory and that thread t reads its value of x from shared memory?
I think it is, but if I'm wrong, please reference e.g. an authoritative (e.g., MSDN) article indicating why not. Thanks!
```
delegate void Foo();
public static void Main()
{
Foo foo = null;
object guard = new object();
int x = 1;
lock (guard)
{
foo = () =>
{
int temp;
lock (guard) temp = x;
Console.WriteLine(temp);
};
}
Thread t = new Thread(() => foo());
t.Start();
t.Join();
}
```
Edit: Clarified that I want to know for C# 2.0+, which is to say that the .NET 2.0+'s stronger memory model (than ECMA 335 CLI) is in effect. | Calling any constructor has release semantics in the .NET memory model. (Not in the CLI memory model, but in the .NET one.) So by calling the `Thread` constructor - and the delegate constructor itself - I believe you're okay. If you set x to 1 *after* the final constructor I'd be less sure. (EDIT: It's possible that the constructor business is more to do with the new *Java* memory model than .NET, given the later stuff about writes...)
In fact, I have a *suspicion* that *all* writes have release semantics (again, in the implemented .NET memory model) but not all reads have acquire semantics. In other words, the data will always be *available* to other threads, but it might not be *used* by those threads. In this case the new thread won't "have" the old value of the variable - there's no way it could have logically read the value before it started, so you're safe on that front.
I can check up on the "all writes" side of things - I suspect there's something in Joe Duffy's blog or book about it.
EDIT: From "Concurrent Programming on Windows" P516:
> The major difference in the stronger
> 2.0+ model is that it prevents stores from being reordered.
I *believe* that's enough. I *suspect* that there are very few people on Stack Overflow who are capable of saying for sure - I wouldn't fully trust many people who aren't in the MS CLR or concurrency teams, except maybe Jeff Richter. | Unless more than 1 thread will execute it possibly the same time, no locking is needed. | In C# 2.0+, is it necessary to lock around a closure that another thread will execute? | [
"",
"c#",
"concurrency",
""
] |
I'm writing some code that uses a Tree (a regular tree that can have an unlimited number of nodes, but no crossover, i.e. two parent nodes will not point the the same child node). Anyway, two things:
1) Are there any well-known algorithms for finding a sub-tree within a tree.
2) Are there any Java libraries (or any libraries for that matter) that already implement this algorithm? Even if there are none, can anyone recommend any good general purpose Java tree library?
I want to use these trees for holding data in a tree format, not for their searching capabilities.
To expand a bit: I'm using the tree as part of game to keep a history of what happens when a certain events happen. For example, an A can hit a B which can hit two A's which can hit another two A's etc.
That would look something like:
```
A
|
B
/
A
/ \
A A
/ \
A A
```
Of course there's more than just A and B. What I want to do is (for an achievement system) is be able to tell when, say an A has hit two A's:
```
A
/ \
A A
```
I want to be able to easily know if the first tree contains that subtree. And I don't want to have to write all the code for doing so if I don't have to :) | Looks like a straightforward algorithm: Find the root of the search tree in the game tree and check whether the children of the search tree are a subset of the children in the game tree.
From your explanations, I'm not sure whether the search tree
```
A
/ \
A A
```
should match this tree:
```
A
/|\
A C A
```
(i.e. if non-matching children are supposed to be ignored.)
Anyway, here's the code I just toyed around with. It's a fully running example and comes with a main method and a simple `Node` class. Feel free to play with it:
```
import java.util.Vector;
public class PartialTreeMatch {
public static void main(String[] args) {
Node testTree = createTestTree();
Node searchTree = createSearchTree();
System.out.println(testTree);
System.out.println(searchTree);
partialMatch(testTree, searchTree);
}
private static boolean partialMatch(Node tree, Node searchTree) {
Node subTree = findSubTreeInTree(tree, searchTree);
if (subTree != null) {
System.out.println("Found: " + subTree);
return true;
}
return false;
}
private static Node findSubTreeInTree(Node tree, Node node) {
if (tree.value == node.value) {
if (matchChildren(tree, node)) {
return tree;
}
}
Node result = null;
for (Node child : tree.children) {
result = findSubTreeInTree(child, node);
if (result != null) {
if (matchChildren(tree, result)) {
return result;
}
}
}
return result;
}
private static boolean matchChildren(Node tree, Node searchTree) {
if (tree.value != searchTree.value) {
return false;
}
if (tree.children.size() < searchTree.children.size()) {
return false;
}
boolean result = true;
int treeChildrenIndex = 0;
for (int searchChildrenIndex = 0;
searchChildrenIndex < searchTree.children.size();
searchChildrenIndex++) {
// Skip non-matching children in the tree.
while (treeChildrenIndex < tree.children.size()
&& !(result = matchChildren(tree.children.get(treeChildrenIndex),
searchTree.children.get(searchChildrenIndex)))) {
treeChildrenIndex++;
}
if (!result) {
return result;
}
}
return result;
}
private static Node createTestTree() {
Node subTree1 = new Node('A');
subTree1.children.add(new Node('A'));
subTree1.children.add(new Node('A'));
Node subTree2 = new Node('A');
subTree2.children.add(new Node('A'));
subTree2.children.add(new Node('C'));
subTree2.children.add(subTree1);
Node subTree3 = new Node('B');
subTree3.children.add(subTree2);
Node root = new Node('A');
root.children.add(subTree3);
return root;
}
private static Node createSearchTree() {
Node root = new Node('A');
root.children.add(new Node('A'));
root.children.add(new Node('A'));
return root;
}
}
class Node {
char value;
Vector<Node> children;
public Node(char val) {
value = val;
children = new Vector<Node>();
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('(');
sb.append(value);
for (Node child : children) {
sb.append(' ');
sb.append(child.toString());
}
sb.append(')');
return sb.toString();
}
}
``` | Are you looking for any particular constraints on a subtree? If not, a [simple traversa](http://en.wikipedia.org/wiki/Tree_traversal)l should suffice for identifying subtrees (basically treat each node as the root of a subtree).
I believe you'll find that the API you'll want for a tree varies a great deal by your particular application -- so much that generic implementations are not very useful. Perhaps if you could tell us what kind of application the tree will be used for, we could provide particulars.
Also, if you're *just* using a tree for data storage, you might want to ask yourself why you need a tree. That answer should also answer the question in my previous paragraph. | Easy way to find Subtree in a Tree | [
"",
"java",
"algorithm",
"tree",
""
] |
## Question
I'm writing some code that needs to be able to get the **values** of the parameters from the method that called into the class. I know how to get all the way to the ParameterInfo[] array, but I don't know how to then get the values. Is this even possible?
If it is, I think it has something to do with using the MethodBody property from the MethodInfo object, which allows you to inspect the IL stream, including properties, but I don't know how to do it, and I haven't found applicable code on Google.
## Code
```
// Finds calling method from class that called into this one
public class SomeClass
{
public static void FindMethod()
{
for (int i = 1; i < frameCount; i++)
{
var frame = new StackFrame(i);
var methodInfo = frame.GetMethod();
if (methodInfo.DeclaringType != this.GetType())
{
string methodName = frame.GetMethod().Name;
var paramInfos = methodInfo.GetParameters();
// Now what?? How do I get the values from the paramInfos
break;
}
else if (i == frameCount - 1)
{
throw new TransportException("Couldn't find method name");
}
}
}
}
``` | You cannot do it without introspecting the stack yourself (and this is fragile since many optimizations may mean the stack frame is not what you expect, or even that the parameter passed is not in fact what the method signature would suggest (it is perfectly possible for an optimizing JIT compiler to spot that you are only using a sub field of an object/struct and pass that instead).
The ParameterInfo simply tells you the *signature* of the method as compiled, not the values that were passed.
The only realistic way to achieve this automatically is via code injection (via something like AOP) to create the data and do what you want with it based on analysing the IL.
This is generally not a good idea, if you need to debug something use a debugger, if you need to log something be explicit about what you are logging.
To be clear simple reflective techniques **cannot** achieve what you desire with full generality | Jonathan Keljo at Microsoft says, in [this news group post](http://groups.google.com/group/microsoft.public.dotnet.framework.clr/tree/browse_frm/thread/c17adcb277967565/b66c524f39aa4030?hl=en&rnum=1&_done=%2Fgroup%2Fmicrosoft.public.dotnet.framework.clr%2Fbrowse_frm%2Fthread%2Fc17adcb277967565%3Fhl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26rnum%3D7%26prev%3D%252Fgroups%253Fhl%253Den%2526lr%253D%2526ie%253DUTF-8%2526oe%253DUTF-8%2526q%253DStackTrace%252Bclass%252BValue%26#doc_71890d2ce5924b0d "Display Exception Stack Trace"), :
> Unfortunately, the only easy way to get argument information from a
> callstack today is with a debugger. If you're trying to do this as part of
> error logging in an application and you plan to send the error log back to
> your support department, we're hoping to have you use minidumps for that
> purpose in the future. (Today, using a minidump with managed code is a
> little problematic as it does not include enough information to even get a
> stack trace by default. A minidump with heap is better, but not so "mini"
> if you know what I mean.)
>
> A purist would say that allowing people to write code that can get
> arguments from functions elsewhere on the callstack would encourage them to
> break encapsulation and create code that's very fragile in the face of
> change. (Your scenario does not have this particular problem, but I've
> heard other requests for this feature that would. Anyway most of those
> requests can be solved in other ways, like using thread stores.) However,
> more importantly there would be security implications of this--applications
> that allow plugins would be at risk of those plugins scraping the stack for
> sensitive information. We could certainly mark the function as requiring
> full-trust, but that would make it unusable for pretty much every scenario
> I've heard of.
>
> Jonathan
So... I guess the short answer is "I can't." That sucks. | How can I get the values of the parameters of a calling method? | [
"",
"c#",
"reflection",
"dynamic",
""
] |
I'm trying to use a third-party java library within oracle. The library seems compatible with the same 1.4 version of the jvm that our Oracle 10g server hosts, since it runs fine outside of Oracle, so I feel like I should be able to get this to work. This library ends up making SOAP-based http requests, and I get class resolution errors when I run in Oracle.
Here's a line that shows the difference:
```
Class msgfact = Class.forName("com.sun.xml.messaging.saaj.soap.MessageFactoryImpl");
```
I tried to register these libraries into Oracle with the loadjava utility, and I got what I thought was a successful result:
```
C:\>loadjava -verbose -schema MYUSER -user MYUSER/MYPWD@dbinstance -force saaj-impl.jar
```
It looks like everything gets loaded, and I can see this MessageFactoryImpl class in that list. But then I try to run this line of code from Oracle SQL (inside another class I wrote and loaded with loadjava), this line throws a ClassNotFoundException (java.lang.ClassNotFoundException: com/sun/xml/messaging/saaj/soap/MessageFactoryImpl).
Then I went back and tried to add the "-resolve" switch at the loadjava command line. It acts like these saaj classes are getting registered, but they aren't resolving properly.
How can I successfully get these saaj classes into Oracle, or if for some reason Oracle already has these loaded, how can I convince my own code to successfully use the existing class?
FWIW, I already took the steps to make sure that the appropriate socket permissions were granted and my code can successfully make a generic http request to the target url. It just has trouble using the library's SOAP stack to make it happen.
EDIT:
Here is a sample of my loadjava result. This seems to be showing exactly what's failing, but I'm confused as to why these particular classes aren't being resolved when they seem to be handled properly in the pre-resolution steps. I've eliminated about 80% of the file here, but there are other classes that show the same class resolution issues.
```
arguments: '-verbose' '-schema' 'MYSCHEMA' '-user' 'MYSCHEMA/MYSCHEMA@actest' '-resolve' '-force' 'saaj-impl.jar'
[snip]
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
loading : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandler
loading : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandler
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandler
loading : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandler
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
loading : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl
loading : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl
[snip]
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/AttachmentPartImpl
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/Envelope
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
errors : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/SOAPPartImpl could not be resolved
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandler
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandler
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
errors : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl could not be resolved
errors : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl
ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/impl/EnvelopeImpl could not be resolved
errors : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$1
ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl could not be resolved
skipping : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$2
[snip]
The following operations failed
class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory: resolution
class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl: resolution
class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl: resolution
class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$1: resolution
[snip]
exiting : Failures occurred during processing
``` | First of all, verify outside of Oracle that the class you are looking for is actually in that jar file. I expect it is, but it doesn't hurt to check.
Then, I would check what classes have been loaded and whether they have valid statuses.
```
SELECT object_name, dbms_java.longname(object_name), status
FROM user_objects
WHERE object_type='JAVA CLASS'
ORDER BY 1
```
You might want to limit this somewhat if there are a lot of classes, e.g.:
```
WHERE dbms_java.longname(object_name) LIKE '%MessageFactoryImpl'
```
If the class is not there, or it is there with the wrong package name, then the problem is with the loadjava command.
If the class is there but its status is INVALID, then check USER\_ERRORS to see what the errors are. I don't recall if I've done dynamic class loading within Oracle, but I recall that static linking would give errors that implied a class didn't exist when it really existed but had errors.
**New info after loadjava output posted**
The loadjava output seems inconsistent with your attempt to find the class in the database. If it is being loaded but not resolved, it should still be listed, but with an INVALID status.
I got the JAR and tried it myself in an empty schema. The class loads but is invalid as expected:
```
dev> select object_name, dbms_java.longname(object_name),status
2 from user_objects
3 where object_name like '%MessageFactoryImpl';
OBJECT_NAME
--------------------------------------------------------------------------------
DBMS_JAVA.LONGNAME(OBJECT_NAME)
--------------------------------------------------------------------------------
STATUS
-------
/3e484eb0_MessageFactoryImpl
com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
INVALID
```
I then checked what the error were on the class:
```
dev> alter java class "com/sun/xml/messaging/saaj/soap/MessageFactoryImpl" resolve;
dev> /
Warning: Java altered with compilation errors.
dev> show error
Errors for JAVA CLASS "/3e484eb0_MessageFactoryImpl":
LINE/COL ERROR
-------- -----------------------------------------------------------------
0/0 ORA-29521: referenced name javax/xml/soap/MessageFactory could
not be found
0/0 ORA-29521: referenced name javax/xml/soap/SOAPMessage could not
be found
0/0 ORA-29521: referenced name javax/xml/soap/MimeHeaders could not
be found
0/0 ORA-29521: referenced name javax/xml/soap/SOAPException could not
be found
```
(These errors would also be listed in USER\_ERRORS, assuming resolution was attempted at least once.)
So clearly this class references classes from the base SOAP library. You would have to load that too -- have you done that?
FYI, when I write some code to do the Class.forName() call, I do get the ClassNotFoundException. Which may seem counter-intuitive since the class object does exist in the schema. However, an invalid class doesn't really "exist" from the point of view of the class loader in Oracle; and in order for the class to be valid Oracle has to be able to resolve all of its references to other classes. | Is this the first time your executing Java on the database? Here is hello world implementation to make sure your Oracle JVM is running properly and you have the necessary permissions. You said "my database schema, so I can do whatever I want" -doesn't mean you have the proper grants.
```
SQL> create or replace and compile java source named "Hello" as
public class Hello{
public static String world() {
return "Hello World ";
}
};
/
Java created.
```
Now the wrapper function
```
SQL> create or replace function Hello RETURN VARCHAR2
as LANGUAGE JAVA NAME 'Hello.world() return String';
/
Function created.
```
Now test it
```
SQL> select Hello from dual;
HELLO
-----------------------------------
Hello World
``` | Confusion over class resolution in Oracle java stored procedures | [
"",
"java",
"oracle",
"java-stored-procedures",
"loadjava",
""
] |
Can someone please explain to me what is the difference between `protected` / `public` **Inner** classes?
I know that `public` inner classes are to avoid as much as possible (like explained in this [article](http://www.onjava.com/pub/a/onjava/excerpt/HardcoreJava_chap06/index.html)).
But from what I can tell, there is no difference between using `protected` or `public` modifiers.
Take a look at this example:
```
public class Foo1 {
public Foo1() { }
protected class InnerFoo {
public InnerFoo() {
super();
}
}
}
```
...
```
public class Foo2 extends Foo1 {
public Foo2() {
Foo1.InnerFoo innerFoo = new Foo1.InnerFoo();
}
}
```
...
```
public class Bar {
public Bar() {
Foo1 foo1 = new Foo1();
Foo1.InnerFoo innerFoo1 = foo1.new InnerFoo();
Foo2 foo2 = new Foo2();
Foo2.InnerFoo innerFoo2 = foo2.new InnerFoo();
}
}
```
All of this compiles and is valid whether I declare `InnerFoo` `protected` or `public`.
What am I missing? Please, point me out a case where there's a difference in using `protected` or `public`.
Thanks. | The `protected` access modifier will restrict access from classes other than the ones in the same package and its subclasses.
In the example shown, the `public` and `protected` will have the same effect, as they are in the same package.
For more information on access modifiers, the [Controlling Access to Members of a Class](http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html) page of [The Java Tutorials](http://java.sun.com/docs/books/tutorial/index.html) may be of interest. | You can just think protected inner class is protected member, so it only access for class, package, subclass but not for the world.
In addition, for outter class, there is only two access modifier for it. Just public and package. | protected/public Inner Classes | [
"",
"java",
"inner-classes",
"access-modifiers",
""
] |
Lately, I've come across a lot of Java code that relies on "properties files" for configuration. But instead of plain old string literals, the code uses constants (static final Strings) to retrieve the property values .
I find this extra level of indirection annoying because I need to perform **TWO** lookups in **EITHER** direction. If I start with the property observed in the config file, I have to first search for the property name to find the Java constant, and then search again to find the references to the constant in the code. If I start in the code, I have to find the actual value of the constant before I can then determine the value of the property in the config file!
**What's the point?**
I understand the value of using constants to reference keys in a resource bundle, usually in support of i18n. I'm referring to simple, non-user-facing config values. The **only** reason I can think of is to make it easy to change the property name later, but this benefit is far less than the annoyance IMHO, especially given the ease of a global search and replace. | If a value needs to be changed without a recompile you inevitably need some redirection but doing yet another is pretty foolish unless the key needs to be referenced in more than one place (itself a possible sign of poor separation of concerns).
Key strings should be sufficiently descriptive that they cannot collide with others outside their scope (normally class) and keeping literals within a single class unique is neither complex nor likely to be so serious a concern as to merit their declaration in single block. Therefore (IMO) this practice is simply someone slavishly following rules without understanding the rule's original intent.
If you need to quote an alternate guideline to them to justify the relaxing of this one may I suggest KISS. | For one thing, you cannot mistype the keys when using constants without getting a compiler error. | What's the point of using constants for property keys? | [
"",
"java",
"properties",
"constants",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.