Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm getting different errors with a WCF service. This service has worked fine in all of our test environments so far, until now. We normally having it running under IIS 6 on Windows Server 2003. I had it running under a Windows XP Pro VM that was connected to our company's domain. Our IT guy removed the VM from the company domain just recently.
Now I'm getting errors like these:
> An existing connection was forcibly
> closed by the remote host.
>
> The remote server returned an error:
> (403) Forbidden.
>
> The HTTP request was forbidden with
> client authentication scheme
> 'Anonymous'.
IIS is configured to allow Anonymous access. The IIS user also has permission to view/execute in the service folder.
The service works fine for some calls but not for others. The application calls the service when loading, but then later on in a separate call it does this.
The service is using wsHttpBinding:
```
<wsHttpBinding>
<binding name="wsHttpBindingSettings" maxReceivedMessageSize="2147483647">
<security mode="None">
<transport clientCredentialType="None" />
<message establishSecurityContext="false" />
</security>
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
</wsHttpBinding>
``` | I think the key to this issue was that it was running in IIS 5 on Windows XP. IIS 5 in XP has a maximum number of connections of 10. Once we exceeded that limit I believe we received 403 errors. We fixed this issue by using a Server 2008 VM instead of XP for doing demos on a laptop. | same problem here, i've mitigated the problem by adding a default binding to the endpoint and explicitly setting the security level to "None" where possible, now it works better but if calls are made too frequently to the server it fails again, i've also noticed that the development webserver in VS2008 nnever fails even with very high frequency call.
so it should be related to IIS in some way and i suspect that is something related to the duration of the security context but these are only my guess so far, i've not found a real solution | WCF 403 Errors | [
"",
"c#",
"wcf",
"web-services",
"iis",
""
] |
I have a numeric value in a `Textbox` that I'd like to format as a percent. How can I do this in C# or VB.NET? | In VB.NET...
```
YourTextbox.Text = temp.ToString("0%")
```
And C#...
```
YourTextbox.Text = temp.ToString("0%");
``` | Building on Larsenal's answer, how about using the TextBox.Validating event something like this:
```
yourTextBox_Validating(object sender, CancelEventArgs e)
{
double doubleValue;
if(Double.TryParse(yourTextBox.Text, out doubleValue))
{
yourTextBox.Text = doubleValue.ToString("0%");
}
else
{
e.Cancel = true;
// do some sort of error reporting
}
}
``` | Format Text from a Textbox as a Percent | [
"",
"c#",
".net",
"vb.net",
"formatting",
""
] |
I've got image tags that look like this:
```
<img src="/path/to/my/image.jpg" />
```
But when I access the src bit using jQuery, jQuery gives me back:
```
http://example.com/path/to/my/image.jpg
```
This is causing problems in some comparisons I'm doing. I don't want to change my image paths to use absolute URLs.
Any ideas as to how I can either get the absolute URL from the image path (this might not be as simple as concatenating the domain - since the URLs may occasionally be absolute), or get the path I provided in the HTML? Either way I need them to match up.
### Edit per comment from activa
There's not really a lot of jQuery code to post, I'm using the [cycle](http://malsup.com/jquery/cycle/) plugin, and in the `onbefore` function, I'm just calling `next.src`. My jQuery and JavaScript foo isn't sufficient to really understand what the cycle plugin is doing to generate `next` - I think it's the DOM element for the next image being cycled in, if you're familiar with what cycle does.
My image tag is actually this:
```
<img src="/site_media/photologue/photos/cache/6927d406810ee9750a754606dcb61d28.jpg" alt="" class="landscape slideshow-image-1" />
```
and in my `onbefore` function this code:
```
alert(next.src);
```
results in an alert with:
```
http://127.0.0.1:8000/site_media/photologue/photos/cache/6927d406810ee9750a754606dcb61d28.jpg
``` | `$("img").attr("src")` gives back the actual value of the src attribute (tried in FF3 and IE7)
So when you have
```
<img src="http://example.com/path/to/my/image.jpg" />
```
it will return
```
http://example.com/path/to/my/image.jpg
```
And when you have
```
<img src="/path/to/my/image.jpg" />
```
it will return
```
/path/to/my/image.jpg
```
**Edit after edit of question**
Sounds like you may want to try
```
$(next).attr("src")
``` | To always get the full resolved path, use `Element.src` , not `Element.getAttribute("src")` (which seems to be the equivalent of attr("src")).
E.g.:
```
document.getElementsByTagName("img")[0].src
```
rather than:
```
document.getElementsByTagName("img")[0].getAttribute("src")
```
. I'll let you jqueryify .src. | Getting relative image src with jQuery | [
"",
"javascript",
"jquery",
""
] |
Given the variable
```
string ids = Request.QueryString["ids"]; // "1,2,3,4,5";
```
Is there any way to convert it into a List without doing something like
```
List<int> myList = new List<int>();
foreach (string id in ids.Split(','))
{
if (int.TryParse(id))
{
myList.Add(Convert.ToInt32(id));
}
}
``` | To create the list from scratch, use LINQ:
```
ids.Split(',').Select(i => int.Parse(i)).ToList();
```
If you already have the list object, omit the ToList() call and use AddRange:
```
myList.AddRange(ids.Split(',').Select(i => int.Parse(i)));
```
If some entries in the string may not be integers, you can use TryParse:
```
int temp;
var myList = ids.Split(',')
.Select(s => new { P = int.TryParse(s, out temp), I = temp })
.Where(x => x.P)
.Select(x => x.I)
.ToList();
```
One final (slower) method that avoids temps/TryParse but skips invalid entries is to use Regex:
```
var myList = Regex.Matches(ids, "[0-9]+").Cast<Match>().SelectMany(m => m.Groups.Cast<Group>()).Select(g => int.Parse(g.Value));
```
However, this can throw if one of your entries overflows int (999999999999). | This should do the trick:
```
myList.Split(',').Select(s => Convert.ToInt32(s)).ToList();
```
If the list may contain other data besides integers, a `TryParse` call should be included. See the accepted answer. | How to create a List<T> from a comma separated string? | [
"",
"c#",
"generics",
""
] |
Suppose I've got two dicts in Python:
```
mydict = { 'a': 0 }
defaults = {
'a': 5,
'b': 10,
'c': 15
}
```
I want to be able to expand `mydict` using the default values from `defaults`, such that 'a' remains the same but 'b' and 'c' are filled in. I know about [`dict.setdefault()`](http://docs.python.org/library/stdtypes.html#dict.setdefault) and [`dict.update()`](http://docs.python.org/library/stdtypes.html#dict.update), but each only do half of what I want - with `dict.setdefault()`, I have to loop over each variable in `defaults`; but with `dict.update()`, `defaults` will blow away any pre-existing values in `mydict`.
Is there some functionality I'm not finding built into Python that can do this? And if not, is there a more Pythonic way of writing a loop to repeatedly call `dict.setdefaults()` than this:
```
for key in defaults.keys():
mydict.setdefault(key, defaults[key])
```
Context: I'm writing up some data in Python that controls how to parse an XML tree. There's a dict for each node (i.e., how to process each node), and I'd rather the data I write up be sparse, but filled in with defaults. The example code is just an example... real code has many more key/value pairs in the default dict.
(I realize this whole question is but a minor quibble, but it's been bothering me, so I was wondering if there was a better way to do this that I am not aware of.) | Couldnt you make mydict be a copy of default, That way, mydict would have all the correct values to start with?
```
mydict = default.copy()
``` | Since Python 3.9, you can do:
```
mydict = defaults | mydict
```
I found this solution to be the most elegant in my usecase. | Is there a way to set multiple defaults on a Python dict using another dict? | [
"",
"python",
"dictionary",
""
] |
I wish to make a trigger but i'm not sure how to grab the data for whatever caused the trigger.
I have a simlpe table.
```
FooId INT PK NOT NULL IDENTITY
Name VARCHAR(100) NOT NULL
```
I wish to have a trigger so that when an UPDATE, INSERT or DELETE occurs, i then do the following.
### Pseduocode
```
IF INSERT
Print 'Insert' & Name
ELSE IF UPDATE
Print 'Update' & FooId & Name
ELSE IF DELETE
Print 'Delete' & FooId & Name
```
Now, I know how to make a trigger for a table.
What i don't know how to do is figure out the values based on what the trigger type is.
Can anyone help?
### Edit: Not sure if it helps, but db is Sql Server 2008 | the pseudo table "inserted" contains the new data, and "deleted" table contains the old data.
You can do something like
```
create trigger mytrigger on mytable for insert, update, delete
as
if ( select count(*) from inserted ) > 0
-- insert or update
select FooId, Name from inserted
else
-- delete
select FooId, Name from deleted
```
To clarify all the comments made by others, on an insert, the *inserted* table contains data and *deleted* is empty. On a delete, the situation is reversed. On an update, *deleted* and *inserted* contain the "before" and "after" copy of any updated rows. | When you are writing a trigger, you have to account for the fact that your trigger may be called by a statement that effects more than one row at a time.
As others have pointed out, you reference the **inserted** table to get the values of new values of updated or inserted rows, and you reference the deleted table to get the value of **deleted** rows. | Need some help with Sql Server and a simple Trigger | [
"",
"sql",
"sql-server-2008",
"triggers",
""
] |
I'm fairly new to C++, and I'm not sure about this one. Have a look at the following example which sums up my current problem.
```
class Foo
{
//stuff
};
class Bar
{
Foo foo;
};
```
So Bar constains a full Foo object, not just a reference or pointer. Is this object initialized by its default constructor ? Do I need to explicitly call its constructor, and if so, how and where ?
Thanks. | It will be initialized by its default constructor. If you want to use a different constructor, you might have something like this:
```
class Foo
{
public:
Foo(int val) { }
//stuff
};
class Bar
{
public:
Bar() : foo(2) { }
Foo foo;
};
``` | Construction is a fairly hard topic in C++. The simple answer is *it depends*. Whether Foo is initialized or not depends on the definition of Foo itself. About the second question: how to make Bar initialize Foo: *initialization lists* are the answer.
While general consensus is that Foo will be default initialized by the implicit default constructor (compiler generated), that does not need to hold true.
If Foo does not have a user defined default constructor then Foo will be uninitialized. To be more precise: *each member of Bar or Foo lacking a user defined default constructor will be uninitialized by the compiler generated default constructor of Bar*:
```
class Foo {
int x;
public:
void dump() { std::cout << x << std::endl; }
void set() { x = 5; }
};
class Bar {
Foo x;
public:
void dump() { x.dump(); }
void set() { x.set(); }
};
class Bar2
{
Foo x;
public:
Bar2() : Foo() {}
void dump() { x.dump(); }
void set() { x.set(); }
};
template <typename T>
void test_internal() {
T x;
x.dump();
x.set();
x.dump();
}
template <typename T>
void test() {
test_internal<T>();
test_internal<T>();
}
int main()
{
test<Foo>(); // prints ??, 5, 5, 5, where ?? is a random number, possibly 0
test<Bar>(); // prints ??, 5, 5, 5
test<Bar2>(); // prints 0, 5, 0, 5
}
```
Now, if Foo had a user defined constructor then it would be initialized always, regardless of whether Bar has or not a user initialized constructor. If Bar has a user defined constructor that explicitly calls the (possibly implicitly defined) constructor of Foo, then Foo will in fact be initialized. If the initialization list of Bar does not call the Foo constructor then it will be equivalent to the case where Bar had no user defined constructor.
The test code may need some explaining. We are interested on whether the compiler does initialize the variable without the user code actually calling the constructor. We want to test whether the object is initialized or not. Now if we just create an object in a function it might happen to hit a memory position that was untouched and already contains zeroes. We want to differentiate luck from success, so we define a variable in a function and call the function twice. In the first run, it will print the memory contents and force a change. In the second call to the function, as the stack trace is the same, the variable will be held in exactly the same memory position. If it was initialized, it would be set to 0, else it would keep the same value the old variable in exactly the same position had.
In each of the test runs, the first value printed is the initialized value (if it was actually initialized) or the value in that memory position, that in some cases happen to be 0. The second value is just a test token representing the value at the memory position after manually changing it. The third value comes from the second run of the function. If the variable is being initialized it will fall back to 0. If the object is not initialized, its memory will keep the old contents. | C++ - construction of an object inside a class | [
"",
"c++",
"constructor",
"oop",
""
] |
How would I go about doing calculations with extremely large numbers in Java?
I have tried `long` but that maxes out at 9223372036854775807, and when using an integer it does not save enough digits and therefore is not accurate enough for what I need.
Is there anyway around this? | You can use the `BigInteger` class for integers and `BigDecimal` for numbers with decimal digits. Both classes are defined in `java.math` package.
Example:
```
BigInteger reallyBig = new BigInteger("1234567890123456890");
BigInteger notSoBig = new BigInteger("2743561234");
reallyBig = reallyBig.add(notSoBig);
``` | Use the `BigInteger` class that is a part of the Java library.
<http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html> | Large Numbers in Java | [
"",
"java",
"numbers",
"integer",
"biginteger",
""
] |
I'm coding an application that uses a third party SDK (OCXs). I use the SDK in C# and it works just fine. However, I can create the simplest test application with the same objects from the SDK in Delphi 2007 and it compiles ok, but BSODs on the same machine when it gets to a certain point. I've run some other test applications that use the SDK and they operate correctly, so I know the SDK is installed ok and functioning properly.
Other Delphi projects I work on that don't use this specific SDK operate properly.
Any ideas on how to try to fix this problem? Might I need to remove the OCXs that I've installed in Delphi and add them back? How do you do that? | It turns out this was caused by Kaspersky antivirus. I tracked it down by running [Windbg](http://www.microsoft.com/whdc/devtools/debugging/install64bit.mspx#) against the crash dump and it pointed to kl1.dll. After searching around I tracked down [this article](http://www.techsupportforum.com/microsoft-support/windows-vista-support/296140-bsod-problems.html) which identified it as Kaspersky. I disabled Kaspersky and the BSOD no longer occurs. | Very unusual problem. Windows NT based OS's are normally very good at containing faults that occur at Ring 3 inside of user applications. Does the SDK in question interact with hardware through kernel level drivers? Also, what information appears on screen when the system BSOD's. Sometimes this is a clue as to the nature of the problem (e.g. Interrupt handler reentrancy problems, faulty hardware, interrupt conflicts). I have seen this type of problem with Dialogic boards on occasion. The problem may also be a kernel level fault that is not driver related.
Without additional details it has hard to do more than speculate as to the cause. I am inclined to think this is not a FPU control word problem, but I could be wrong. FPU control word problems can result in exceptions, but the exception would need to occur in a critical execution context like a driver where it would not be caught and handled by the OS.
FWIW I have seen FPU control word problems in Delphi JNI libraries that crashed the JVM and host application. The fix was to explicitly wrap the call with code to change and restore the control word as suggested by NineBerry. This works provided the application is not multi-threaded. | App That Uses SDK BSODs in Delphi 2007 But Works in C# | [
"",
"c#",
"delphi",
"delphi-2007",
""
] |
I made a simple news system with comments using PHP and MySQL, and it worked great on my local Apache server, both on my Fedora 10 machine, and my Windows 7 one. Now I have a problem though, I uploaded it to a web host and it keeps returning all the ' and " as \' and \".
I believe this is either the web host who by automatic adds them for security reasons or that the MySQL is the wrong collation, but I have not been able to resolve it yet, testing multiple MySQL collations.
Here is a example of a query:
```
mysql_query("INSERT INTO news (title, poster, text, time) VALUES ('$newstitle', '1', '$newstext', '$time')") or die(mysql_error());
```
`$time` is `time();`
`$newstitle` and `$newstext` are parsed from `$_POST` and both are ran through `mysql_real_escape_string()` before I run the query (I guess this might be the problem, but since it is a part of the security I just don't want to remove it, and since it did not cause problems on my local servers)
As a final note: On my local apache servers I had `latin1_swedish_ci` which did not work on the web hosts server.
**EDIT:**
They look like this in the database:
```
\'\'\'\"\"\"
```
While on my local ones they didn't have the extra backslash, so it must be the PHP adding it. Is there any way to solve this except adding a function that removes extra backslashes? | These additional backslashes are probably [Magic Quotes](http://docs.php.net/manual/en/security.magicquotes.php). Try to [disable them or remove them](http://docs.php.net/manual/en/security.magicquotes.disabling.php) before processing the data. | **Edit**: As mentioned several times below, and in comments, the correct way to go about this is to disable magic quotes. Had I fully read and comprehended the question before replying, then that would probably have been better ;)
---
`mysql_real_escape_string()` will be doing what it says, and escaping the relevant characters within the string. Escaping quotes is done by prefixing them with the escape character (a back-slash in PHP, and many other languages). **When you pull the data back from the database**, do something like run `stripslashes()` (see the [PHP doc](https://www.php.net/stripslashes)) on the content, to remove the slashes from things like quotes.
**Edit**: As Gumbo mentioned, it could also be due to Magic Quotes being enabled on the server. You should disable these [as per his answer](https://stackoverflow.com/questions/865086/mysql-php-problem-with-and/865120#865120). | MySQL / PHP problem with " and ' | [
"",
"php",
"mysql",
"collation",
""
] |
I have not had much experience with Webservices or API's.
We have a website built on Oracle->Sun App Server->Java->Struts2 framework. We have a requirement to provide an API for our system. This API will be used by other systems outside of our system. API is just for a simple SP that we have on our database. The other system does not want to connect to our DB to gain access to the SP but instead and an API as a 'webservice'
Can the community please shed some light on how to go about this? Will the API be put on our webserver? is that how the other system will connect to it? And how to go about creating a public API? | If you are using the Sun App Server, it should be fairly trivial to make an EJB exposed as a web service with the @WebService tag, and then have that EJB call the Stored Proceedure and return the data. The app server gives you tools to publish a WSDL which is what they will use to know how to call you API.
That being said, what sounds easy at 50,000 feet is a real pain to deal with all the details. First, what about security? Second, are WebServices really required, or is there a better communication mechanism that is more obvious, such as (at a minimum) REST, if not some simple servlet communication. And the hardest part: In exactly what format will you return this result set?
Anyway, you could be dealing with a bit of a political football here ("what, you don't know how to do web services, everyone knows that, etc.") so it can be a bit hard to probe the requirements. The good news is that publishing a web service is pretty trivial in the latest Java EE (much easier than consuming one). The bad news is that the details will be a killer. I have seen experienced web service developers spend hours on namespace issues, for example. | Some things you'll need to think about are:
* SOAP vs REST ([Why would one use REST instead of SOAP based services?](https://stackoverflow.com/questions/90451/why-would-one-use-rest-instead-of-web-services))
* How will you handle authentication?
* Does it need to scale?
You might want to take a look at <https://jersey.dev.java.net/>.
It would also be helpful to look at how another company does it, check <http://www.flickr.com/services/api/> for some ideas. | how to provide API for our system | [
"",
"java",
"api",
""
] |
Does anyone here know how i can determine the version of SQL running on my linked server through use of TSQL statements?
I am running SQL2005 my linked servers are running a mix of sql2000, 2005 and 2008. | ```
select * from openquery(MyLinkedServer,'SELECT SERVERPROPERTY(''productversion'')')
```
Works | One minor nitpick about OPENQUERY is that one cannot use anything other than string literals for both the server and the query.
With EXEC AT you can at least use varchar variables for the query (although it can be a pain to quote the stuff correctly) although not for the server-name:
declare @sql AS varchar(max) = 'SELECT SERVERPROPERTY(''productversion'')'
EXEC(@sql) AT MyLinkedServer
I assume this is just a parser limitation rather than some deliberate limitation in the design. | Determine SQL Server version of linked server | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
I'm creating a library to allow OCaml/Haskell-like algebraic data types and pattern matching. The algebraic data types are implemented using a class similar to [Boost.Variant](http://www.boost.org/doc/libs/1_39_0/doc/html/variant.html). I would like to be able to define new types (the constructor) in the template arguments, but I get an error. I'm using my own type with variadic templates, but I'll use Boost's `variant` here for simplicity. Why isn't something like this:
```
typedef variant <
class Foo { ... },
class Bar { ... }
> Baz;
```
allowed? I know I can define the types separately, but that means I can't use some nice macros. In most cases in C++ you *are* allowed to define a new type where you are using it, for example:
```
struct Foo { ... } bar;
```
Here I am defining a new type `Foo`, and a variable `bar` of type `Foo`. If things like this are allowed, why doesn't it work with templates? | I guess it's because template arguments are treated similar to function arguments and you can not declare
```
void func( class A{} a, class B{} b );
```
either. I also think it would be impossible to obey the [ODR](http://en.wikipedia.org/wiki/One_Definition_Rule) if you need the classes in more than one template (typedef). | There really isn't a reason why except for that it's not there and I guess it hasn't been proposed to be added, or if it has, didn't have enough support.
If you want to pursue it, I'd suggest starting with the standards committee
<http://www.open-std.org/Jtc1/sc22/wg21/> | Why can't you define new types in a C++ template argument? | [
"",
"c++",
"templates",
""
] |
I have an application that has upwards of a hundred different ToolTips set on a Ribbon control. All of the ToolTips pop up rather quickly (about half a second), and I would like to increase the pop up delay. After some research it appears the only way to do this in WPF is through the ToolTipService.InitialShowDelay property.
My question is, do I have to go through the XAML and explicitly say
```
ToolTipService.InitialShowDelay="2000"
```
For every single control that has a ToolTip? Or is there some way to set this property globally, using something like a Style?
Thanks for any ideas. | Unfortunately, there's no easy way to do this. Ideally, you'd set ToolTipService.InitialShowDelay on FrameworkElement and let it propagate from there, but it turns out that doesn't seem to work.
Instead, you can set it on each **type** of control you want to set it on, for instance:
```
<Style TargetType="RibbonButton">
<Setter Property="ToolTipService.InitialShowDelay" Value="2000"/>
</Style>
<Style TargetType="RibbonToggleButton">
<Setter Property="ToolTipService.InitialShowDelay" Value="2000"/>
</Style>
<Style TargetType="RibbonDropDownButton">
<Setter Property="ToolTipService.InitialShowDelay" Value="2000"/>
</Style>
```
etc.
Although this is a pretty verbose way of doing it, at least you only have to set it on each type of control and not every control itself - and if you're using it in the Ribbon, then there's only a handful of controls to begin with.
To save yourself some hassle should you ever want to change the value, you may want to architect the above code using a resource value:
```
<sys:Int32 x:Key="ToolTipInitialShowDelay">2000</sys:Int32>
<Style TargetType="RibbonButton">
<Setter Property="ToolTipService.InitialShowDelay"
Value="{StaticResource ToolTipInitialShowDelay}"/>
</Style>
<Style TargetType="RibbonToggleButton">
<Setter Property="ToolTipService.InitialShowDelay"
Value="{StaticResource ToolTipInitialShowDelay}"/>
</Style>
<Style TargetType="RibbonDropDownButton">
<Setter Property="ToolTipService.InitialShowDelay"
Value="{StaticResource ToolTipInitialShowDelay}"/>
</Style>
```
Alternatively, if you are not already using BasedOn styles, you could shorten it to:
```
<Style x:Key="ToolTipDefaults">
<Setter Property="ToolTipService.InitialShowDelay" Value="2000"/>
</Style>
<Style TargetType="RibbonButton" BasedOn="{StaticResource ToolTipDefaults}"/>
<Style TargetType="RibbonToggleButton" BasedOn="{StaticResource ToolTipDefaults}"/>
<Style TargetType="RibbonDropDownButton" BasedOn="{StaticResource ToolTipDefaults}"/>
```
The limitation to this approach being that a style can only be based on one parent style, so if you're already using this pattern, you won't be able to do this. | I've run into the same problem and achieved an appreciable solution. Two of them, actually.
Both of them are based on DependencyProperty metadata system. For both of them you will need some pretty similar static-initialization code:
```
public static class ToolTipServiceHelper
{
static ToolTipServiceHelper()
{
ToolTipService.InitialShowDelayProperty
.OverrideMetadata(typeof(FrameworkElement),
new FrameworkPropertyMetadata(...));
}
}
```
What goes instead of "..."?
First solution is pretty obvious: place there the desired default value which will apply to the entire application except places where an actual value is provided.
The second solution is the tricky one: instead of "..." you provide default value from default metadata, but aside from that you change the options, actually you have to make the property inheritable.
```
new FrameworkPropertyMetadata(
ToolTipService.InitialShowDelayProperty.DefaultMetadata.DefaultValue,
FrameworkPropertyMetadataOptions.Inherits)
```
When the property is inheritable you can make things like this:
```
<Window xmlns="..."
...
ToolTipService.InitialShowDelay="2000">
...
</Window>
```
That will do the trick for the entire window or any other element you apply the property to.
HTH | Change the ToolTip InitialShowDelay Property Globally | [
"",
"c#",
"wpf",
"xaml",
"tooltip",
""
] |
I'm trying to do a query like this:
```
Widget.find(:all, :conditions => ["name like %awesome%"])
```
However, I'm getting a "malformed format string" exception from sanitize\_sql, specifying the "%" as the problem.
How can I perform this query? | Try this syntax:
```
term = "awesome"
Widget.all(:conditions => ["name LIKE ?", "%#{term}%"])
``` | Try
```
Widget.find(:all, :conditions => ["name like '%awesome%'"])
```
Just added single quotes around the string `%awesome%`
**Edit:** Ok, that doesn;t actually work. The sql sanitizer is doing something screwy with the %s.
This will work.
```
Widget.find(:all, :conditions => ["name like ?","%awesome%"])
```
As per John Topley's answer you can make the string a variable if that is what you really need.
One tip I find useful when running into SQL errors is checking the `development.log` - that will list all the queries that are actually running against the database. Assuming you have basic knowledge of SQL it is often useful to debug them directly in a console, rather than making stabs at the ActiveRecord level (although I think in your case the code was barfing before it got to that stage) | How can I use % in a :conditions argument to ActiveRecord.find? | [
"",
"sql",
"ruby-on-rails",
"ruby",
"activerecord",
""
] |
I am storing dates in a MySQL database in datetime fields in UTC. I'm using PHP, and I've called date\_timezone\_set('UTC') so that all calls to date() (without timestamp) return the date in UTC.
I then have it so a given web site can select its timezone. Now I want dates to display in the site's timezone. So, if I have a date stored as '2009-04-01 15:36:13', it should display for a user in the PDT timezone (-7 hours) as '2009-04-01 08:36:13'.
What is the easiest (least code) method for doing this via PHP? So far all I've thought of is
```
date('Y-m-d H:i:s', strtotime($Site->getUTCOffset() . ' hours', strtotime(date($utcDate))));
```
Is there a shorter way? | Here's what we did with our servers. We set everything to use UTC, and we display in the user's time zone by converting from UTC on the fly. The code at the bottom of this post is an example of how to get this to work; you should confirm that it works in all cases with your setup (i.e. daylight savings, etc).
## Configuring CentOS
1. Edit `/etc/sysconfig/clock` and set `ZONE` to `UTC`
2. `ln -sf /usr/share/zoneinfo/UTC /etc/localtime`
## Configuring MySQL
1. Import timezones into MySQL if necessary:
`mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql`
2. Edit my.cnf and add the following within the [mysqld] section:
`default-time-zone = 'UTC'`
## PHP Code
```
<?php
/*
Example usage:
$unixtime = TimeUtil::dateTimeToTimestamp('2009-04-01 15:36:13');
echo TimeUtil::UTCToPST("M d, Y - H:i:s", $unixtime);
*/
// You should move this to your regular init method
date_default_timezone_set('UTC'); // make this match the server timezone
class TimeUtil {
public static function timestampToDateTime($timestamp) {
return gmdate('Y-m-d H:i:s', $timestamp);
}
public static function dateTimeToTimestamp($dateTime) {
// dateTimeToTimestamp expects MySQL format
// If it gets a fully numeric value, we'll assume it's a timestamp
// You can comment out this if block if you don't want this behavior
if(is_numeric($dateTime)) {
// You should probably log an error here
return $dateTime;
}
$date = new DateTime($dateTime);
$ret = $date->format('U');
return ($ret < 0 ? 0 : $ret);
}
public static function UTCToPST($format, $time) {
$dst = intval(date("I", $time));
$tzOffset = intval(date('Z', time()));
return date($format, $time + $tzOffset - 28800 + $dst * 3600);
}
}
``` | Why not use the built in [DateTime/TimeZone](https://www.php.net/manual/en/ref.datetime.php) functionality?
```
<?php
$mysqlDate = '2009-04-01 15:36:13';
$dateTime = new DateTime ($mysqlDate);
$dateTime->setTimezone(new DateTimeZone('America/Los_Angeles'));
?>
```
DateTime Class: <https://www.php.net/manual/en/class.datetime.php>
DateTimeZone Class: <https://www.php.net/manual/en/class.datetimezone.php>
PHP's supported Timezones: <http://php.net/manual/en/timezones.php> | How can I easily convert dates from UTC via PHP? | [
"",
"php",
"timezone",
""
] |
How do I alter the contents of an IDictionary using C# 3.0 (Linq, Linq extensions) ?
```
var enumerable = new int [] { 1, 2};
var dictionary = enumerable.ToDictionary(a=>a,a=>0);
//some code
//now I want to change all values to 1 without recreating the dictionary
//how it is done?
``` | This is not nearly as clear as other ways, but it should work fine:
```
dictionary.Keys.ToList().ForEach(i => dictionary[i] = 0);
```
My other alternative would have been to make a ForEach extension method similar to this:
```
public static class MyExtensions
{
public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
{
action(item);
}
}
}
```
Then use it like this:
```
dictionary.ForEach(kvp => kvp.Value = 0);
```
This won't work in this case though, as Value cannot be assigned to. | LINQ is a query dialect - it isn't directly a mutation language.
To change the values of an existing dictionary, `foreach` is probably your friend:
```
foreach(int key in dictionary.Keys) {
dictionary[key] = 1;
}
``` | How do I alter the contents of IDictionary using LINQ (C# 3.0) | [
"",
"c#",
".net",
"linq",
"c#-3.0",
"idictionary",
""
] |
I have an XElement variable named *content* which consists of the following XML:
```
<content>
<title>Contact Data</title>
<p>This is a paragraph this will be displayed in front of the first form.</p>
<form idCode="contactData" query="limit 10; category=internal"/>
<form idCode="contactDataDetail" query="limit 10; category=internal">
<title>Contact Data Detail</title>
<description>This is the detail information</description>
</form>
</content>
```
I now want to simply **run through each of the level-1 nodes** and parse them into objects. Back in C# 2.0 I use to do this with **XmlReader**, check the type of node, and parse it accordingly.
**But what is the best way to parse the XML nodes with LINQ**, I would expect something like this:
```
var contentItems = from contentItem in pageItem.content.DescendantNodes()
select new ContentItem
{
Type = contentItem.Element()
};
foreach (var contentItem in contentItems)
{
switch (contentItem.Type)
{
case "title":
...(parse title)...
case "p":
...(parse p)...
case "form":
...(parse form)...
}
}
```
where:
```
public class ContentItem
{
public string Type { get; set; }
public string IdCode { get; set; }
public XElement Content { get; set; }
}
``` | Does it have to be `XElement`? I would (either manually, or via xsd.exe) just create classes that map to the element/attribute names - and use `XmlSerializer` - in particular via `StringReader`:
```
Content content;
using(StringReader sr = new StringReader(xml))
using(XmlReader xr = XmlReader.Create(sr)) {
XmlSerializer ser = new XmlSerializer(typeof(Content));
content = (Content)ser.Deserialize(xr);
}
```
(edit)
With entity classes:
```
[XmlRoot("content")]
public class Content {
[XmlElement("title")]
public string Title { get; set; }
[XmlElement("p")]
public string Description { get; set; }
[XmlElement("form")]
public List<ContentForm> Forms { get; set; }
}
public class ContentForm {
[XmlAttribute("idCode")]
public string Id { get; set; }
[XmlAttribute("query")]
public string Query { get; set; }
[XmlElement("title")]
public string Title { get; set; }
[XmlElement("description")]
public string Description { get; set; }
}
``` | I'd suggest inheriting XElement, and implement properties for the stuff you want in it.
These properties shouldn't use backing fields, but rather work directly with the underlying XML element. That way, you'll keep object in sync with XML. | What is the best way to manually parse an XElement into custom objects? | [
"",
"c#",
"xml",
"parsing",
""
] |
I have the function below.
Everything works fine except for the `Push`, `Pop` and `Remove` method. These method should be called by the event-handler. This event is fired by the Google Maps API.
The problem is that when the event is fired, these method are not found. I have a "**Push is not defined**" error message.
I tried with **this** but that's not working.
How do I call the public method from the event handler?
```
function Track(mapContainer) {
var map = mapContainer;
var points = new Array();
var isEditMode = false;
var clickListener;
this.Push = function(point) { ... }
this.Pop = function() { ... }
this.Remove = function(point) { ... }
//Enable / disable the marker placements
this.PlaceWaypoint = function(isPlacing) {
if (isPlacing != true) {
if (clickListener != null) {
google.maps.event.removeListener(clickListener);
clickListener = null;
}
} else {
clickListener = map.AddEvent("click", function(event) {
if (!IsDoubleClick()) {
var point = map.PlaceMarker(new WayPoint(event.latLng))
point.RemoveListener(function() { Remove(point); });
Push(point);
} else {
Pop();
}
});
}
}
}
``` | You've got a closure/binding problem. One convention that is frequently used it to assign a variable called **self** of **that**, which can later be used in place of **this**, thanks to the closure properties of JS.
```
function Track(mapContainer) {
var map = mapContainer,
points = new Array(),
isEditMode = false,
clickListener,
// Make a variable self that points to this, that can be used inside closures
// where the original context is lost
self = this;
this.Push = function(point) { ... }
this.Pop = function() { ... }
this.Remove = function(point) { ... }
//Enable / disable the marker placements
this.PlaceWaypoint =
function(isPlacing) {
if (isPlacing != true) {
if (clickListener != null) {
google.maps.event.removeListener(clickListener);
clickListener = null;
}
} else {
clickListener = map.AddEvent("click", function(event) {
if (!IsDoubleClick()) {
var point = map.PlaceMarker(new WayPoint(event.latLng))
point.RemoveListener(function() { Remove(point); });
// Use the closure reference self instead of this
self.Push(point);
} else {
// Use the closure reference self instead of this
self.Pop();
}
});
};
}
``` | First of all Pop and Push is not global, second this in the inner scope has another meaning. So you can use closure and rename the "**this**" to variable of more global scope.
```
function Track(mapContainer) {
//....
var $this = this;
//Enable / disable the marker placements
this.PlaceWaypoint = function(isPlacing) {
if (isPlacing != true) {
if (clickListener != null) {
google.maps.event.removeListener(clickListener);
clickListener = null;
}
} else {
clickListener = map.AddEvent("click", function(event) {
if (!IsDoubleClick()) {
var point = map.PlaceMarker(new WayPoint(event.latLng))
point.RemoveListener(function() { $this.Remove(point); });
$this.Push(point);
} else {
$this.Pop();
}
});
}
}
}
``` | How to call public method from a event handler | [
"",
"javascript",
"google-maps",
"dom-events",
""
] |
I've created a python script that gets a list of files from a text file and deletes them if they're empty. It correctly detects empty files but it doesn't want to delete them. It gives me:
```
(32, 'The process cannot access the file because it is being used by another process')
```
I've used two different tools to check whether the files are locked or not and I'm certain that they are not. I used sysinternals process explorer and LockHunter. Furthermore, I'm able to just manually delete the files myself. I obviously don't want to do that for all of them as there are hundreds in various locations.
The script:
```
import os.path
import sys
def DeleteFilesFromListIfBlank(PathToListOfFiles):
ListOfFiles = open(PathToListOfFiles)
FilesToCheck = [];
for line in ListOfFiles.readlines():
if(len(line) > 1):
line = line.rstrip();
FilesToCheck.append(line)
print "Found %s files to check. Starting check." % len(FilesToCheck)
FilesToRemove = [];
for line in FilesToCheck:
#print "Opening %s" % line
try:
ActiveFile = open(line);
Length = len(ActiveFile.read())
if(Length < 691 and ActiveFile.read() == ""):
print "Deleting %s" % line
os.unlink(line);
else:
print "Keeping %s" % line
except IOError,message:
print "Could not open file: $s" % message
except Exception as inst:
print inst.args
DeleteFilesFromListIfBlank("C:\\ListOfResx.txt")
```
I've tried using both os.unlink and os.remove. I'm running Python 2.6 on Vista64
Thanks | You need to call `.close()` on the file object before you try and delete it.
Edit: And really you shouldn't be opening the file at all. `os.stat()` will tell you the size of a file (and 9 other values) without ever opening the file.
This (I think) does the same thing but is a little cleaner (IMHO):
```
import os
_MAX_SIZE = 691
def delete_if_blank(listFile):
# Make a list of files to check.
with open(listFile) as listFile:
filesToCheck = filter(None, (line.rstrip() for line in listFile.readlines()))
# listFile is automatically closed now because we're out of the 'with' statement.
print "Found %u files to check. Starting check." % len(filesToCheck)
# Remove each file.
for filename in filesToCheck:
if os.stat(filename).st_size < _MAX_SIZE:
print "Deleting %s" % filename
os.remove(filename)
else:
print "Keeping %s" % filename
``` | Try ActiveFile.close() before doing the unlink.
Also, reading the whole file isn't necessary, you can use os.path.getsize(filename) == 0. | Why won't python allow me to delete files? | [
"",
"python",
"file-io",
""
] |
Consider:
<http://msdn.microsoft.com/en-us/library/2tw134k3.aspx>
When you are creating your custom types in the app.config do you get intellisense to aid you?
Or is it a case of programming in XML 'on your own'? It does not appear to be working for me, if this is the case that's fine but if intellisense is meant to work I know I'm doing something wrong.
Thanks | No, not by default.
If you want intellisense, it is possible. Then you should write an XML schema for your configuration section, and reference it in the config file (put xmlns=yournamespace on the the configuration element and make sure Visual Studio knows where to find the schema). | Same for me. I don't usually find this to be problematic though, since the configuration sections typically are not very complicated.
I often put in a commented template element for custom sections, explaning the syntax, which may help in editing the config file when you revisit it after a couple of months and have a somewhat vaguer idea of the structure than when it was first implemented... | When using ConfigurationSections in app.config - do you get intellisense? | [
"",
"c#",
"app-config",
""
] |
Linq has a convenient operator method called `Take()` to return a given number of elements in anything that implements `IEnumerable`. Is there anything similar in jQuery for working with arrays?
Or, asked differently: how can I truncate an array in Javascript? | There is a [slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) method
```
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr = arr.slice(0, 4);
console.log(arr);
```
Will return the first four elements.
Don't forget to assign it back to your variable if you want to discard the other values.
Note: This is just regular javascript, no need for jquery. | (2 years later...) If you're truly looking to truncate an array, you can also use the `length` attribute:
```
var stooges = ["Moe", "Larry", "Shemp", "Curly", "Joe"];
stooges.length = 3; // now stooges is ["Moe", "Larry", "Shemp"]
```
Note: if you assign a length which is **longer** than current length, undefined array elements are introduced, as shown below.
```
var stooges = ["Moe", "Larry", "Shemp"];
stooges.length = 5;
alert(typeof stooges[4]); // alerts "undefined"
```
EDIT:
As @twhitehead mentioned below, the addition of undefined elements can be avoided by doing this:
```
var stooges = ["Moe", "Larry", "Shemp"];
stooges.length = Math.min(stooges.length, 5);
alert(stooges.length)// alerts "3"
``` | How to easily truncate an array with JavaScript? | [
"",
"javascript",
"arrays",
""
] |
Basically, I have something like the following:
```
public string SomeDBMethod(string server, string dbName, string userName, string password,...)
```
Is it good practice to refactor it to the following:
```
public string SomeDbMethod(DBParams parameters, ...)
```
Where DBParams is defined as follows:
```
public struct DBParams
{
string Server {get;set;}
string DbName {get;set;}
string UserName {get;set;}
string Password {get;set;}
}
```
My point is really to be able to pass around less parameters as I find functions with long parameter lists really quite ugly.
I have also found that there are some limitations to this approach: if SomeDbMethod is to be exposed as a web service method, I cannot use the DBParams struct as a parameter (as far as my understanding on the subject of web services go...which isn't very far).
So, is this too much trouble for little benefit or am I on to something here? | I always group parameters that go together into a single object - the code is cleaner this way, it is obvious that they are related to each other and always used together.
However, in most cases I use a class and not a struct. The benefits of structs were never clear to me, and they are pain in the back in many situations (I guess the webservices scenario is just one example).
You can make a class immutable if you don't want people to change it (if this was the reason to use struct) | Unless you actually need to pass around this set of parameter very frequently (with the same data), I don't see any need. Long parameter lists are sometimes a sign of a need to refactor your code, but then again are sometimes inevitable. (In your situation is seems more like the latter.) So, simply go with the straightforward method of passing the parameters directly unless you find yourself needing to store the parameter sets (at least temporarily) - you really won't be saving any code otherwise, and certainly not increasing readability.
The method use a struct does not impose any limitations in relation to web services. You just need to make the type as serialisable (`DataContract` in WPF, I believe), and there shouldn't be any problems. | Is it good practice to encapsulate many parameters that are alike into a struct | [
"",
"c#",
"parameters",
"struct",
""
] |
I'm using sifr for a few items on this page: <http://blueprint.staging.dante-studios.com/public/templates/home.php>
unfortunately it seems that the rendering is very slow, does anyone have any idea of how to:
a) speed up the rendering process
b) hide all "to be sifr'd" items until all of them are ready? | Here are a few suggestions:
* The Flash movie has the bold and italic and bold + italic glyphs embedded. If you don't need those, they're adding needless weight to the movie. Same goes for other characters.
* You could get rid of all JavaScript comments in the `sifr-config` file.
* Flash transparency is not advised as it's a bit heavier to render.
* To improve the initial display, look into [ratios](http://wiki.novemberborn.net/sifr3/Ratio+Calculation)
* Try loading the sIFR code before jQuery | Yes.. I’ve used sIFR in many times and help me so much.. Visitors said rendering is very slow too. I has one solution which change to **[Cufon](http://cufon.shoqolate.com/generate/)**.
Cufon is more exciting because, it doesn’t use any browser plugins. Cufon, on the other hand just needs JavaScript to be enabled. Just a suggestion ;)
[Cufon Demo](http://www.cameronmoll.com/articles/cufon/) | decreasing sifr render time | [
"",
"javascript",
"flash",
"sifr",
"render",
"lag",
""
] |
The whole question fits in the title. And to add some context: I'm not asking what is the best according to what the specs are saying, but rather what works the best given the mix of browsers deployed nowadays.
Some data points:
* Google uses `text/javascript` for the JS used on their home page.
* Google uses `text/javascript` on Google Docs.
* Google uses `application/x-javascript` to serve JavaScript files with their [Ajax libraries service](http://code.google.com/apis/ajaxlibs/).
* Yahoo uses `application/x-javascript` to serve their JS.
* Yahoo uses `application/x-javascript` for the JavaScript served on their home page. | According to the IETF's [ECMAScript Media Types Updates](https://datatracker.ietf.org/doc/draft-ietf-dispatch-javascript-mjs/) as of 22 February 2021, the [RFC-4329](https://www.rfc-editor.org/rfc/rfc4329) is obsolete.
Therefore:
* `text/javascript` is a recommended standard (both by IETF and by MDN)
* `application/x-javascript` was experimental while deciding to move to…
* `application/javascript` is obsolete | Here's the 2020 answer to this question.
`text/javascript` is the correct JavaScript MIME type per [the HTML Standard](https://html.spec.whatwg.org/multipage/scripting.html#scriptingLanguages:javascript-mime-type), which states:
> Servers should use `text/javascript` for JavaScript resources. Servers should not use other JavaScript MIME types for JavaScript resources, and must not use non-JavaScript MIME types.
And [also](https://html.spec.whatwg.org/multipage/infrastructure.html#dependencies:willful-violation):
> […] the MIME type used to refer to JavaScript in this specification is `text/javascript`, since that is the most commonly used type, despite it being an officially obsoleted type according to RFC 4329.
Work is underway to reflect this reality in an RFC at the IETF level: <https://datatracker.ietf.org/doc/draft-ietf-dispatch-javascript-mjs/>
Any claim that "`text/javascript` is the obsolete one" is saying so based on RFC 4329, which both the HTML Standard and the abovementioned IETF draft (i.e. an upcoming RFC) are explicitly correcting. | When serving JavaScript files, is it better to use the application/javascript or application/x-javascript | [
"",
"javascript",
"http",
"content-type",
""
] |
i have some questions about the HashCode of immutable types.
* May i "pre"-generate the HashCode of an immutable type in the constructor or are there any reason not do that?
* Should i always generate the Hashcode again, when the method GetHashCode() is called?
Here´s a sample class :
```
public class Id {
private readonly object _value;
private readonly int _hash = -1;
public Id( object value ) {
_value = value;
_hash = ( int ) ( 7 * value.GetType().GetHashCode() + 7 + 7 * _value.GetHashCode() );
}
public object Value {
get {
return _value;
}
}
public override int GetHashCode() {
return _hash;
}
public override bool Equals( object obj ) {
Id other = obj as Id;
if ( other == null ) {
return false;
}
return this.GetHashCode() == other.GetHashCode();
}
}
``` | You may pregenerate the hashcode but why? Just generate it when needed (in `GetHashCode`) and then maybe store it - Most objects are never required to have a hash so it would just slow down the programm.
> Should i always generate the Hashcode again, when the method GetHashCode() is called?
The hashcode of an immutable object should always be the same so it shouldn't have any effect whether you generate it again or store it except that storing increases the performance.
Note: You shouln't define `Equals` by comparing HashCodes - Two different object *may* have equal HashCodes (hash collsion). | This really depends on the use-case.
Do you use the hash a lot? Then pregenerate it, because the object is immutable, calculating it every time would be unnecessary since the result is always the same.
Isn't the hash used a lot? Then don't pregenerate it, since it will slow down the program unnecessarily, calculating a hash that's likely not to be used.
A third (and best, in my opinion) option is to calculate the hash in GetHashCode and cache the result, calculating the hash only once and return this cached hash every time after that. This way, no time is spent calculating a hash when it's never used, nor is it calculated unnecessarily every time GetHashCode is called. Although this does mean memory is used to store the hash in the object. | Generate HashCode in constructor of immutable type | [
"",
"c#",
".net",
"constructor",
""
] |
I'm testing some code in C# from Visual Studio Express 2008:
```
delegate void Hm(int k);
static void Main(string[] args)
{
char[] m = new char[10];
m[0] = 'H'; m[5] = 'M';
m[1] = 'o'; m[6] = 'u';
m[2] = 'l'; m[7] = 'n';
m[3] = 'a'; m[8] = 'd';
m[4] = ' '; m[9] = 'o';
unsafe { fixed (char* p = m) { Hm H = (k) => recurd(k, p); H(0); } }
Console.ReadLine();
}
static unsafe int recurd(int i, char* p)
{
Console.WriteLine(p[i]);
if (i == 10) return 0; else return recurd(i + 1, p);
}
```
It compiles perfectly, but if I make a little change in the "recurd" function:
```
static unsafe int recurd(int i, char* p)
{
Console.WriteLine(p[i]);
i == 10 ? 0 : recurd(i + 1, p);
// if (i == 10) return 0; else return recurd(i + 1, p);
}
```
I got an error that says "Just the expressions of object assignment, call, increment, decrement and new can be used as instruction" (It's a translation from spanish).
Why do I get this error? How can I fix it? | You're missing the "return" keyword:
```
return i == 10 ? 0 : recurd(i + 1, p);
``` | Try this:
```
static unsafe int recurd(int i, char* p)
{
Console.WriteLine(p[i]);
return i == 10 ? 0 : recurd(i + 1, p);
}
```
It's complaining because you're not doing anything with the result of the expression. | Why doesn't this code compile? - object assignment, call, increment, decrement and new can be used as instruction | [
"",
"c#",
""
] |
Can a component *designer* access and modify the app.config or web.config file of a project at design time? More specifically, is there some hosting service exposed by VS to do this 'the proper way' ? I know I can locate the .config file myself, open it and have my way with it as I please, but I want this to go through the VS sanctioned way, primarily because of source control integration concerns. | You can hook up an [**`IEventBindingService`**](http://msdn.microsoft.com/en-us/library/system.componentmodel.design.ieventbindingservice(VS.80,loband).aspx) (I linked to the .NET 2.0 version, there are 1.1, 3.0, and 3.5 versions too)
Excerpt from the page:
> The event binding service provides a
> way to link an event handler with a
> component event from designer code.
You can put your custom app.config manipulating code into the event handler that you expose. | VS can and will edit you web/app config for all sorts of reasons. Also, there are certain situations where VS tools will give you a GUI for sections of the file (Which im guessing is what you are after). But for the most part the "the proper way" as you say is to hand edit it.
It could also be likely that if your project is big enough you'll have CI concerns and roll outs to several servers, which would mean scripting the generation of sections of your config files.
One final thing that's worth saying is that you shouldn't be looking for an MS blessed approach to anything, you should take your needs and come up with the most pragmatic approach with all the facts at hand. | Can a Visual Studio component designer access and modify the project .config file? | [
"",
"c#",
".net",
"visual-studio",
"components",
"designer",
""
] |
I have a need for generating JavaScript on the server. I can do this by using ASPX pages to template JavaScript but I'm getting warnings and I don't benefit from syntax hilighting which I would like. Is there a way to tell the .Net environment/Visual Studio that a certain ASPX page is supposed to output non-HTML text?
The reason for this is localization. My localized strings come from the server and I need these in JavaScript constructs on the pages. The easiest way I came up with is to have one JS file (I'll call it l18n.js for now) which defines the localized strings in a JSON object.
```
l18n = {
OK: <%= GetString("OK") %>,
Cancel: <%= GetString("Cancel") %>,
ConfirmDialog: {
Title: <%= GetString("ConfirmTitle") %>,
Message: <%= GetString("ConfirmMessage") %>
}
// .. etc.
}
```
This lets me use the localized strings in other parts of the UI
```
var okButton = $('<button>' + l18n.OK + '</button>')
```
But as said, just throwing the JavaScript inside an ASPX page, l18n.js.aspx, results in warnings and doesn't provide syntax hilighting. Is there a better way which would at least get rid of the warning? The current one is
> Generation of designer file failed: Exception from HRESULT: 0x80042929
And in case it matters the project is built on top of .Net 2.0
**Clarification**
The language isn't user chosen so it shouldn't change all the time and I should be able to use the language value as the ETag so caching shouldn't be that big of an issue. From the browser perspective I'd consider the templated JS a static file just like rest of the files. I just don't want to declare the ~10 static JS files separately if I can automate it. | An ASPX is a ASP.NET Form. It is expected to represent a Web Form which the user may interact with running further code in the ASPX. Hence the ASPX lifecycle represents much of this.
For raw output such as JS you should use an ASHX which does not have all this Forms overhead.
In your specific case I would be looking into creating a set of classes that can be serialised as JSON. Send the serialised JSON as the output of your ASHX. | You could also load all your current pages language-elements in 'global' variables (constants) at the top of each page in a script block.
```
var LANG_OK = 'ok string';
var LANG_CANCEL = 'cancel string';
var LANG_CONFIRM_TITLE = 'title string';
var LANG_CONFIRM_MESSAGE = 'message string';
```
This keeps the dynamic part away from your javascript file. This means the javascript files are static like they are supposed to be.
**update**
You could consider creating javascript repositories for each language based on my solution above.
* language\_EN.js
* language\_NL.js
* language\_FR.js
This would mean you just have to select which file to include in the page:
```
<% Response.Write "<script type='text/javascript' src='/js/language_" & User.LanguageCode & ".js'></script>" %>
``` | Generating JavaScript with templates in ASP.Net | [
"",
".net",
"asp.net",
"javascript",
"templates",
""
] |
In the process of learning Django and Python. I can't make sense of this.
(Example Notes:'helloworld' is the name of my project. It has 1 app called 'app'.)
```
from helloworld.views import * # <<-- this works
from helloworld import views # <<-- this doesn't work
from helloworld.app import views # <<-- but this works. why?
```
It seems like line #2 and #3 are practically the same. Why does like #2 not work?
**Edit -- Added the source of the two files.**
You might recognize this code from the Django Book project ([http://www.djangobook.com/en/2.0](http://www.djangobook.com/en/2.0/))
## helloworld/views.py
```
from django.shortcuts import render_to_response
from django.http import HttpResponse, Http404
import datetime
def hello(request):
return HttpResponse("Hello world")
def current_datetime(request):
current_date = datetime.datetime.now()
return render_to_response('current_datetime.html', locals())
def offset_datetime(request, offset):
try:
offset = int(offset)
except ValueError:
raise Http404()
next_time = datetime.datetime.now() + datetime.timedelta(hours=offset)
return render_to_response('offset_datetime.html', locals())
def display_meta(request):
values = request.META.items()
values.sort()
path = request.path
return render_to_response('metavalues.html', locals())
```
## helloworld/app/views.py
```
from django.shortcuts import render_to_response
def search_form(request):
return render_to_response('search_form.html')
def search(request):
if 'q' in request.GET:
message = 'You searched for: %r' % request.GET['q']
else:
message = 'You searched for nothing.'
return render_to_response('search_results.html', locals())
``` | Python imports can import two different kinds of things: modules and objects.
```
import x
```
Imports an entire module named `x`.
```
import x.y
```
Imports a module named `y` and it's container `x`. You refer to `x.y`.
When you created it, however, you created this directory structure
```
x
__init__.py
y.py
```
When you add to the import statement, you identify specific objects to pull from the module and move into the global namespace
```
import x # the module as a whole
x.a # Must pick items out of the module
x.b
from x import a, b # two things lifted out of the module
a # items are global
b
```
If helloworld is a package (a directory, with an `__init__.py` file), it typically doesn't contain any objects.
```
from x import y # isn't sensible
import x.y # importing a whole module.
```
Sometimes, you will have objects defined in the `__init__.py` file.
Generally, use "from module import x" to pick specific objects out of a module.
Use `import module` to import an entire module. | ```
from helloworld.views import * # <<-- this works
from helloworld import views # <<-- this doesn't work
from helloworld.app import views # <<-- but this works. why?
```
#2 and #3 are *not* the same.
The second one imports `views` from the package `helloworld`. The third one imports `views` from the package `helloworld.app`, which is a subpackage of `helloworld`. What it means is that views are specific to your django apps, and not your projects. If you had separate apps, how would you import views from each one? You have to specify the name of the app you want to import from, hence the syntax `helloworld.app`. | Understanding python imports | [
"",
"python",
"django",
"import",
""
] |
I'm learning Python and can't even write the first example:
```
print 2 ** 100
```
this gives `SyntaxError: invalid syntax`
pointing at the 2.
Why is this? I'm using version 3.1 | That is because in Python 3, they have replaced the `print` *statement* with the `print` *function*.
The syntax is now more or less the same as before, but it requires parens:
From the "[what's new in python 3](http://docs.python.org/3.0/whatsnew/3.0.html)" docs:
```
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Old: print # Prints a newline
New: print() # You must call the function!
Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)
Old: print (x, y) # prints repr((x, y))
New: print((x, y)) # Not the same as print(x, y)!
``` | You need parentheses:
```
print(2**100)
``` | Invalid syntax when using "print"? | [
"",
"python",
""
] |
Just found a bit of code someone here had written to access some DB Entities...
```
public static OurCustomObject GetOurCustomObject(int primaryKey)
{
return GetOurCustomObject<int>(primaryKey, "usp_GetOurCustomObjectByID");
}
public static OurCustomObject GetOurCustomObject(Guid uniqueIdent)
{
return GetOurCustomObject<Guid>(uniqueIdent, "usp_GetOurCustomObjectByGUID");
}
private static OurCustomObject<T>(T identifier, string sproc)
{
if((T != typeof(int)) && (T == typeof(Guid)))
{
throw new ArgumentException("Identifier must be a string or an int");
}
//ADO.NET Code to make DB Call with supplied sproc.
}
```
Theres just something about it that doesn't seem very `generic`. The fact that the
sprocs are passed into the inner method feels ugly. but the only way I can see around that is to have an if/else in the private method along the lines of
```
if(type == int)
sproc = "GetByID";
else if (type == Guid)
sproc = "GetByGUID";
```
Also the exception throwing looks ugly as well... is there anyway to use a where T : clause
e.g.
```
private static OurCustomObject<T>(T identifier) where T : int OR Guid
```
Any suggestions on how to clean this up a little. | You can't specify a constraint which says "it's one of these two", no.
What you *could* do is:
```
Dictionary<Type, string> StoredProcedureByType = new Dictionary<Type, string>
{
{ typeof(Guid), "GetByGUID" },
{ typeof(int), "GetByID" }
};
```
Then use:
```
string sproc;
if (!StoredProcedureByType.TryGetValue(typeof(T), out sproc))
{
throw new ArgumentException("Invalid type: " + typeof(T).Name);
}
```
This is probably overkill for just a couple of types, but it scales well if you have a lot of types involved.
Given that both types are value types, you can make it a *bit* more robust with a constraint of:
```
where T : struct
```
but that will still allow `byte` etc. | The code you provided looks reasonably fine to me, because `private static OurCustomObject<T>(T identifier, string sproc)` is private. I would even drop the exception checking from this method, because again - its private, so this class controls what gets passed to the method. The if statement would be rather horrible and over-engineered. | Using the `where T : SOMETHING` construct in C# | [
"",
"c#",
"generics",
""
] |
I have a normalized database and need to produce web based reports frequently that involve joins across multiple tables. These queries are taking too long, so I'd like to keep the results computed so that I can load pages quickly. There are frequent updates to the tables I am summarising, and I need the summary to reflect all update so far.
All tables have autoincrement primary integer keys, and I almost always add new rows and can arrange to clear the computed results in they change.
I approached a similar problem where I needed a summary of a single table by arranging to iterate over each row in the table, and keep track of the iterator state and the highest primary keen (i.e. "highwater") seen. That's fine for a single table, but for multiple tables I'd end up keeping one highwater value per table, and that feels complicated. Alternatively I could denormalise down to one table (with fairly extensive application changes), which feels a step backwards and would probably change my database size from about 5GB to about 20GB.
(I'm using sqlite3 at the moment, but MySQL is also an option). | Can the reports be refreshed incrementally, or is it a full recalculation to rework the report? If it has to be a full recalculation then you basically just want to cache the result set until the next refresh is required. You can create some tables to contain the report output (and metadata table to define what report output versions are available), but most of the time this is overkill and you are better off just saving the query results off to a file or other cache store.
If it is an incremental refresh then you need the PK ranges to work with anyhow, so you would want something like your high water mark data (except you may want to store min/max pairs). | I see two approaches:
1. You move the data in a separate database, denormalized, putting some precalculation, to optimize it for quick access and reporting (sounds like a small datawarehouse). This implies you have to think of some jobs (scripts, separate application, etc.) that copies and transforms the data from the source to the destination. Depending on the way you want the copying to be done (full/incremental), the frequency of copying and the complexity of data model (both source and destination), it might take a while to implement and then to optimizie the process. It has the advantage that leaves your source database untouched.
2. You keep the current database, but you denormalize it. As you said, this might imply changing in the logic of the application (but you might find a way to minimize the impact on the logic using the database, you know the situation better than me :) ). | How should I keep accurate records summarising multiple tables? | [
"",
"sql",
"algorithm",
"sqlite",
"normalization",
""
] |
I have a `LinkedHashMap<String,Object>` and was wondering what the most efficient way to put the `String` portion of each element in the `LinkedHashMap` into a `JList`. | You could also use the [setListData(Vector)](http://java.sun.com/javase/6/docs/api/javax/swing/JList.html#setListData(java.util.Vector)) method:
```
jList1.setListData(new Vector<String>(map.keySet()));
```
With each of the `setListData` methods, you're making a copy of the actual data, so changes to the map will not be reflected in the list. You could instead create a custom [`ListModel`](http://java.sun.com/javase/6/docs/api/javax/swing/ListModel.html) and pass it to the [`setModel`](http://java.sun.com/javase/6/docs/api/javax/swing/JList.html#setModel(javax.swing.ListModel)) method instead, but because there is no way to access an arbitrary element of a `LinkedHashMap` by index, this is probably infeasible. | If the jList is not sensitive to changes of the original Map, the original method you used is fine (better than using Vector, which has the extra layer of sychronization).
If you want jList to change when the map changes, then you will have to write your own ListModel (which is not that hard). You will also have to figure out how to know when the map changes. | How can I add the keys of a LinkedHashMap to a JList? | [
"",
"java",
"user-interface",
"jlist",
"linkedhashmap",
""
] |
I have a requirement to add a RequiredFieldValidator and RegularExpressionValidator to a dynamically created textbox in a dynamically generated tablecell, inside a Web User Control in the Content Area of a Page created from a Master.
The problem, as you can probably guess, is trying to dynamically set the ControlToValidate property to look at my dynamically created text box.
After some research the code now:
* Creates a Panel (As I have heard the ControlToValidate and Validator must be within the same container). This was originally a placeholder but was trying a suggestion listed below.
* Creates the Textbox and sets its ID.
* Adds the Textbox to the Panel.
* Creates the RequiredFieldValidator.
* Sets the id of the ControlToValidate. Values I have attempted to use:
+ The ID of the control
+ the ClientID of the control
+ the ID of the control prefixed by the added text the server appends to child controls of the Web User Control
+ the Client ID modified the same way
+ the name of the control (on the off chance)
+ the name of the control prefixed by the text the server adds to the names of controls
+ using a bespoke Recursive FindControl Method in an attempt to cast a new Control object to Textbox and then using its ID and ClientID
+ the UniqueID of the control
+ the same modified with the prefix as detailed above
* Add the validator to the panel.
* Add the panel to the tablecell.
Needless to say I am still unable to convince the Validator to "see" the control it is supposed to validate and I am completely out of new ways to approach the problem.
EDIT: Further detective work has lead me to the point that the page doesn't have a problem until the page\_load event has finished. The server seems to have a problem after the code for building the page has finished executing. I'm starting to wonder if I'm actually adding the controls into naming containers much too late instead of too early.
Any suggestions? | What about creating a user control that contains the textbox and the two validators? Then you can set the `ControlToValidate` via Visual Studio, as usual, and then dynamically add this new control to your tablecell dynamically. | I used a repeater in a similar situation:
```
<table>
<colgroup>
<col style="white-space: nowrap;" />
<col />
<col />
</colgroup>
<asp:Repeater ID="InputFields" runat="server">
<ItemTemplate>
<tr>
<td class="labelCell">
<asp:Label id="FieldName" runat="server" Font-Bold="True" Text='<%# Eval("Name") %>'></asp:Label>:
</td>
<td class="fieldCell">
<asp:TextBox id="FieldData" runat="server" autocomplete="off" />
</td>
<td class="errorCell">
<asp:RequiredFieldValidator ID="FieldNameRequiredValidator" runat="server" CssClass="errorValidator" ErrorMessage='<%# Eval("Name") %> is required'
ControlToValidate="FieldData" Display="Dynamic"> </asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="FieldNameRegexValidator" runat="server" CssClass="errorValidator" ErrorMessage='A valid <%# Eval("Name") %> is required'
ControlToValidate="FieldData" Display="Dynamic" ValidationExpression='<%# Eval("RegEx") %>'> </asp:RegularExpressionValidator>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
```
The repeater creates a "naming container" that ensures that the FieldData control ID is unique within the container. | Validator nightmare on dynamic control C# | [
"",
"c#",
"asp.net",
"validation",
"dynamic-controls",
""
] |
I am currently in [British summer time](http://www.timeanddate.com/library/abbreviations/timezones/eu/bst.html) which is UTC +1 Hour. I confirmed my PC is correct with the following code and it returns true.
```
System.TimeZone.CurrentTimeZone.IsDaylightSavingTime(Date.Now)
```
My question is then why does the UTC formatter not work as I would expect:
```
DateTime.Now.ToString("u")
```
It returns the exact current system date as below in UTC format as expected but with the Z ([Zulu Time](http://en.wikipedia.org/wiki/Zulu_time#Time_zones)) at the end not +01:00?
i.e.
```
2009-05-27 14:21:22Z
```
not
```
2009-05-27 14:21:22+01:00
```
Is this correct functionality? | MSDN states the following:
> Represents a custom date and time format string defined by the DateTimeFormatInfo.UniversalSortableDateTimePattern property. The pattern reflects a defined standard and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd HH':'mm':'ss'Z'".
>
> When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.
>
> **Formatting does not convert the time zone for the date and time object. Therefore, the application must convert a date and time to Coordinated Universal Time (UTC) before using this format specifier.**
You should use the following code to convert your current Date to UTC before formatting it:
```
DateTime.UtcNow.ToString("u")
```
or
```
DateTime.Now.ToUniversalTime().ToString("u")
```
To display in the format you expected (i.e. 2009-05-27 14:21:22+01:00), you would need to use a custom date format:
```
DateTime.Now.ToString("yyyy-MM-dd HH:mm:sszzz");
``` | "u" is the Universal sortable date/time pattern, not UTC format; To quote the [documentation](http://msdn.microsoft.com/en-us/library/az4se3k1.aspx):
> Represents a custom date and time format string defined by the DateTimeFormatInfo..::.UniversalSortableDateTimePattern property. The pattern reflects a defined standard and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd HH':'mm':'ss'Z'".
>
> When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.
>
> Formatting does not convert the time zone for the date and time object. Therefore, the application must convert a date and time to Coordinated Universal Time (UTC) before using this format specifier. | Why does DateTime.Now.ToString("u") not work? | [
"",
"c#",
".net",
"vb.net",
"datetime",
"utc",
""
] |
I'm trying to create a LinqDataSource to bind to a DropDownList in an ASP.NET form. I only want to show the elements according to a date (which is one of the fields in the database).
Basically, the elements I want to show are the ones that will happen in the futures (i.e. after DateTime.Now).
I was trying the following markup :
```
<asp:DropDownList runat="server" ID="DropDownList1"
AppendDataBoundItems="True" DataSourceID="LinqDataSource1"
DataTextField="TextField" DataValueField="ValueField">
</asp:DropDownList>
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="DataContext1" TableName="Table"
Where="DateField >= @DateField">
<WhereParameters>
<asp:Parameter DefaultValue="DateTime.Now" Name="DateField"
Type="DateTime" />
</WhereParameters>
</asp:LinqDataSource>
```
I'm getting a format exception saying that "The string was not recognized as a valid DateTime" when I try to run it. However, the dates in my database seem to be fine, because a DateTime.Parse works perfectly on them. The DateField is of type datetime in SQL.
What am I missing here?
Thanks! | The `DefaultValue` was what was wrong with the code as was suggested by the others.
However, setting the `DefaultValue` to
```
"<%# DateTime.Now %>"
```
like Andomar suggested (which would make the markup look something like this :
```
<WhereParameters>
<asp:Parameter DefaultValue="<%# DateTime.Now %>" Name="DateField" Type="DateTime" />
</WhereParameters>
```
will not work either because DataBinding expressions are only supported on objects that have a DataBinding Event, and neither `Parameter` or `ControlParameter` have one.
For a String, it's fairly easy to create a TextBox or Label and put the <%# %> expression in the value of that new field (more details [here](http://www.neovolve.com/post/2006/11/07/Binding-data-to-ObjectDataSource-parameters.aspx)), but it was a bit more complicated with a DateTime value, as comparing an SQL DateTime with a .NET DateTime caused an exception.
It can be done quite easily in the Page\_Load event by using
```
DataContext DataContext1 = new DataContext();
var c = from a in DataContext1.Field
where a.DateField >= DateTime.Now
select a;
DropDownList.DataSource = c;
DropDownList.DataBind();
``` | I suspect it is failing on the DefaultValue. | LinqDataSource and DateTime Format | [
"",
"asp.net",
"sql",
"linq",
"linq-to-sql",
""
] |
I'm currently doing it this way, but seems to not be the proper way:
```
class Name
{
protected $jobs2do;
public function __construct($string) {
$this->jobs2do[] = $this->do;
}
public function do() {
...
}
}
```
Because directly assign a function will cause warning, should do something like:
```
function func()
{
...
}
$func_array[] = 'func';
```
say, put it into a string, but I don't know how to do it when it's a member function.
Is the following version OK?:
```
class Name
{
public $jobs2do;
public function __construct($string) {
$this->jobs2do[] = array($this,'do');
}
public function do() {
...
}
}
```
when call it, just:
```
$instance = new Name();
foreach ($instance->jobs2do as $job)
{
call_user_func($job);
}
``` | Write a class for Job and use [factory](http://www.php.net/manual/en/language.oop5.patterns.php) pattern to create them. Then Write a class JobManager wihich should maintain a list ob Job instances.
```
interface iCallableJob
{
public function run();
}
class Job implements iCallableJob
{
// The parameterized factory method
public static function factory($type)
{
$classname = 'Job_' . $type;
if (class_exists($classname) && in_array('iCallableJob', class_implements('Job')))
{
return new $classname();
}
return null;
}
public function run() { return null; }
}
class Job_type1 extends Job
{
public function run()
{
echo 'Job 1';
}
}
class JobManager
{
protected $jobs2do = array();
public function addJob($type)
{
if ($job = Job::factory($type))
{
$this->jobs2do[] = $job;
return $job;
}
return null;
}
public function runAll()
{
foreach ($this->jobs2do AS $job)
{
$job->run();
}
}
}
``` | There are (at least) 4 ways to do this. There are other ways but these are the most pure. The method versions require PHP5 at a minimum.
```
class foo {
public function bar($a) { return $a; }
}
$anObject = new foo();
$ret = call_user_func(array($anObject,'bar'), 1);
$ret = call_user_func_array(array($anObject,'bar'), array(1));
$ret = call_user_method('bar', $anObject, array(1));
$ret = call_user_method_array('bar', $anObjectm, 1);
```
You can replace 'bar' with a string variable, too. | How to assign a member function to an array and call it | [
"",
"php",
"function-pointers",
""
] |
I need to know if a number compared to a set of numbers is outside of 1 stddev from the mean, etc.. | While the sum of squares algorithm works fine most of the time, it can cause big trouble if you are dealing with very large numbers. You basically may end up with a negative variance...
Plus, don't never, ever, ever, compute a^2 as pow(a,2), a \* a is almost certainly faster.
By far the best way of computing a standard deviation is [Welford's method](http://www.johndcook.com/standard_deviation.html). My C is very rusty, but it could look something like:
```
public static double StandardDeviation(List<double> valueList)
{
double M = 0.0;
double S = 0.0;
int k = 1;
foreach (double value in valueList)
{
double tmpM = M;
M += (value - tmpM) / k;
S += (value - tmpM) * (value - M);
k++;
}
return Math.Sqrt(S / (k-2));
}
```
If you have the *whole* population (as opposed to a *sample* population), then use `return Math.Sqrt(S / (k-1));`.
**EDIT:** I've updated the code according to Jason's remarks...
**EDIT:** I've also updated the code according to Alex's remarks... | **10 times faster** solution than Jaime's, but **be aware** that,
as Jaime pointed out:
> "While the sum of squares algorithm works fine most of the time, it
> can cause big trouble if you are dealing with **very large** numbers. You
> basically may end up with a negative variance"
If you think you are dealing with very large numbers or a very large quantity of numbers, you should calculate using both methods, if the results are equal, you know for sure that you can use "my" method for your case.
```
public static double StandardDeviation(double[] data)
{
double stdDev = 0;
double sumAll = 0;
double sumAllQ = 0;
//Sum of x and sum of x²
for (int i = 0; i < data.Length; i++)
{
double x = data[i];
sumAll += x;
sumAllQ += x * x;
}
//Mean (not used here)
//double mean = 0;
//mean = sumAll / (double)data.Length;
//Standard deviation
stdDev = System.Math.Sqrt(
(sumAllQ -
(sumAll * sumAll) / data.Length) *
(1.0d / (data.Length - 1))
);
return stdDev;
}
``` | How do I determine the standard deviation (stddev) of a set of values? | [
"",
"c#",
"math",
"statistics",
"numerical",
""
] |
I am looking for a javascript on the fly "Table Of Contents" generation from HTML (with anchors).
Example:
```
<h1>First level1 heading</h1>
lorem ipsum
<h2>1a heading</h2>
lorem ipsum
<h2>1b heading</h2>
lorem ipsum
<h1>Second level1 heading</h1>
lorem ipsum
```
Should return something like
```
First level1 heading
1a heading
1b heading
Second level1 heading
```
with the lines linked to the headings, and also the orignal html should be returned with anchors inserted.
Is there something included in one of the big javascript libraries or frameworks?
If none of them has, has someone seen a good JS module for this purpose? | [jQuery](http://www.jquery.org) is your friend, with this plugin: [table of contents](http://plugins.jquery.com/project/table-of-contents). Home page is <http://code.google.com/p/samaxesjs/> | Make it yourself, i wrote it :), hope it helps
add a div element as first child of body element and give an id as "tableOfContents"
and add the script below as last child of body element
```
<script>
var el = document.getElementsByTagName("*") || [];
var toc = "<ul>";
var lvl = 1;
for(var i=0;i<el.length;i++)
{
var ce = el[i];
var tag = ce.tagName + "";
var m = tag.match(/^h([1-5])$/i);
if(m)
{
var n = Number(m[1]);
if(lvl > n)
{
while(lvl-->n)toc+="</ul></li>";
}else if(lvl < n){
while(lvl++<n)toc+="<li style='list-style:none'><ul>";
}
toc += '<li><a href="#toc_' + i + '">' +
(ce.innerText || ce.text()) +
'</a></li>';
var ta = document.createElement("div");
ta.innerHTML = '<a name="toc_' + i + '" />';
ce.insertBefore(ta, ce.firstChild);
}
}
while(lvl-->1)toc+="</ul></li>";
toc+="</ul>";
document.getElementById("tableOfContents").
innerHTML = toc;
</script>
```
this script will detects each H (1 to 5) and generates your table of contents | Which javascript library or framework supports "Table Of Content" generation? | [
"",
"html",
"javascript",
"javascript-framework",
""
] |
I have below html:
```
<div class="threeimages" id="txtCss">
<a>
<img alt="Australia" src="/Images/Services%20button_tcm7-9688.gif"/>
</a>
<div class="text" id="txtLink">
<h2>
<a href="/partnerzone/downloadarea/school-information/australia/index.aspx">Australia</a>
</h2>
<p>Land of the sunshine!</p>
</div>
</div>
```
Now if you see there is href in div ID "txtLink" i.e. [Australia](/partnerzone/downloadarea/school-information/australia/index.aspx)
I want this at the runtime of page the same href values get copied into above tag of div ID "txtCss", I mean when my page gets displayed my html will be as below:
```
<div class="threeimages" id="txtCss">
<a href="/partnerzone/downloadarea/school-information/australia/index.aspx">
<img alt="Australia" src="/Images/Services%20button_tcm7-9688.gif"/>
</a>
<div class="text" id="txtLink">
<h2>
<a href="/partnerzone/downloadarea/school-information/australia/index.aspx">Australia</a>
</h2>
<p>Land of the sunshine!</p>
</div>
</div>
```
please suggest some code for above problem | **Update**
An answer without jquery here: <https://stackoverflow.com/a/887348/11333>
Back in 2009 it was perfectly acceptable to use jquery though :)
Create a js file with something like this:
```
$(document).ready(function() {
$('.threeimages').each(function(){
$(this).DupeHref();
});
});
jQuery.fn.DupeHref = function(){
var target = $(this).find(".text h2 a").attr("href");
$(this).find("a").attr("href", target);
}
```
Reference both the jquery and this javascript file in your html.
Something like this:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>
<body>
<div class="threeimages">
<a>
<img alt="Australia" src="/Images/Services%20button_tcm7-9688.gif"/>
</a>
<div class="text">
<h2>
<a href="/partnerzone/downloadarea/school-information/australia/index.aspx">Australia</a>
</h2>
<p>Land of the sunshine!</p>
</div>
</div>
<div class="threeimages">
<a>
<img alt="Belgium" src="/Images/Services%20button_tcm7-9689.gif"/>
</a>
<div class="text">
<h2>
<a href="/partnerzone/downloadarea/school-information/belgium/index.aspx">Belgium</a>
</h2>
<p>Land of beer and food!</p>
</div>
</div>
<script src="./content/js/jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="./content/js/dupetargets.js" type="text/javascript"></script>
</body>
</html>
``` | this is the shortest answer without using any library and works only thing what you want
```
var tc = document.getElementById("txtCss");
var ary = tc ? tc.getElementsByTagName("a") : [];
if(ary.length >= 2)
ary[0].href = ary[1].href;
``` | getting href value of from <a> tag | [
"",
"javascript",
"html",
"href",
""
] |
I need to set up a legacy app that uses Tomcat 4 and runs using the 1.4 JDK.
I tried to install the linux JDK 1.4 from the sun download site on Ubuntu 9.04 but it wouldnt install.
Is it possible to install JDK 1.4 on the 64 bit version of Ubuntu?
When I try and install the j2sdk-1\_4\_2\_19-linux-ia64.bin version i get the following error
`./install.sfx.22146: 1: ��: not found
./install.sfx.22146: 1: ELF2�@@H�@8@@@@@@����@�@@@��������P: not found
./install.sfx.22146: 2: Syntax error: "(" unexpected` | Are you particular about 64bit Java 1.4 ?
I have tried with 32 bit Java 1.4 and it works.
I clustered the web app to make use of more than 2GB memory. | SAP is paying extra to get just such a setup [supported](http://www.theregister.co.uk/2009/01/16/sap_sun_java_netweaver_support/), so I assume that there is no technical limitation preventing it. However, there may be licensing restrictions preventing it.
However, I'd recommend running it on a later JDK if possible. Just because the code was compiled for an earlier version doesn't mean it won't run on the more recent JRE. | Is it possible to put java 1.4 on 64 bit Ubuntu? | [
"",
"java",
"linux",
"ubuntu",
"64-bit",
"jdk1.4",
""
] |
I'm curious if there is an option to disable gcc warnings about a parameter not being valid for the language being compiled.
Ex:
```
cc1: warning: command line option "-Wno-deprecated" is valid for C++/Java/ObjC++ but not for C
```
Our build system passes the warnings we have decided on globally across a build.
We have both C/C++ code and the warnings get real annoying when trying to find actual warnings.
Any suggestions? | It seems to me that if there were such an option, there would have to be a further option to turn off warnings about that option, and so on infinitely. So I suspect there isn't.
Having the same options for builds of completely different languages seems a bit odd anyway - I would have different options defined as makefile macros and used appropriately for different targets. | To enable specific warnings in gcc *-Wxxxx* and to disable them with *-Wno-xxxx*.
From the [GCC Warning Options](http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Warning-Options.html):
> You can request many specific warnings with options beginning `-W', for example -Wimplicit to request warnings on implicit declarations. Each of these specific warning options also has a negative form beginning`-Wno-' to turn off warnings; for example, -Wno-implicit. This manual lists only one of the two forms, whichever is not the default.
However @Neil is right about separating options for different languages. If you use make you can e.g. put all C options into CFLAGS and all C++ options into CCFLAGS. | Disable gcc warning for incompatible options | [
"",
"c++",
"c",
"gcc",
"gcc-warning",
""
] |
I've seen code like the following frequently in some C++ code I'm looking at:
```
typedef class SomeClass SomeClass;
```
I'm stumped as to what this actually achieves. It seems like this wouldn't change anything. What do `typedef`s like this do? And if this does something useful, is it worth the extra effort? | See this previous answer to a related question. It's a long quote from a Dan Saks article that explains this issue as clearly as anything I've come across:
[Difference between 'struct' and 'typedef struct' in C++?](https://stackoverflow.com/questions/612328/difference-between-struct-and-typedef-struct-in-c/612476#612476)
The technique can prevent actual problems (though admittedly rare problems).
It's a cheap bit of insurance - it's zero cost at runtime or in code space (the only cost is the few bytes in the source file), but the protection you get is so small that it's uncommon to see someone use it consistently. I have a 'new class' snippet that includes the typedef, but if I actually code up a class from scratch without using the snippet, I almost never bother (or is it remember?) to add the typedef.
So I'd say I disagree with most of the opinions given here - it is worth putting those typedefs in, but not enough that I'd give anyone (including myself) grief about not putting them in.
I've been asked for an example of how not having a class name typedef'ed can result in unexpected behavior - here's an example lifted more or less from the Saks article:
```
#include <iostream>
#include <string>
using namespace std;
#if 0 // change to #if 1 to get different behavior
// imagine that this is buried in some header
// and even worse - it gets added to a header
// during maintenance...
string foo()
{
return "function foo... \n";
}
#endif
class foo
{
public:
operator string() {
return "class foo...\n";
}
};
int main()
{
string s = foo();
printf( "%s\n", s.c_str());
return 0;
}
```
When the function declaration is made visible, the behavior of the program silently changes because there is no name conflict between the function `foo` and the class `foo`.
However, if you include a "`typedef class foo foo;`" you'll get a compile time error instead of a silent difference in behavior. | It prevents code like this from compiling:
```
class SomeClass { ... };
int SomeClass;
```
This is perfectly legal C++, though it's *terrible*. If you do this, then any references to a bare `SomeClass` refer to the variable. To refer to the class, you need to explicitly say `class SomeClass` at each usage. If you create a `typedef`:
```
class SomeClass { ... };
typedef class SomeClass SomeClass;
int SomeClass;
```
Then the compiler flags the definition of `int SomeClass` as an error, as it rightly should be. | What is the purpose of typedefing a class in C++? | [
"",
"c++",
"typedef",
""
] |
I'm a newbie Java coder and I just read a variable of an integer class can be described three different ways in the API. I have the following code:
```
if (count.compareTo(0)) {
System.out.println(out_table);
count++;
}
```
This is inside a loop and just outputs `out_table`.
My goal is to figure out how to see if the value in integer `count > 0`.
I realize the `count.compare(0)` is the correct way? or is it `count.equals(0)`?
I know the `count == 0` is incorrect. Is this right? Is there a value comparison operator where its just `count=0`? | Integers are autounboxed, so you can just do
```
if (count > 0) {
....
}
``` | To figure out if an `Integer` is greater than 0, you can:
* check if `compareTo(O)` returns a positive number:
```
if (count.compareTo(0) > 0)
...
```
But that looks pretty silly, doesn't it? Better just...
* use [autoboxing](http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html)1:
```
if (count > 0)
....
```
This is equivalent to:
```
if (count.intValue() > 0)
...
```
It is important to note that "`==`" is evaluated like this, with the `Integer` operand unboxed rather than the `int` operand boxed. Otherwise, `count == 0` would return false when `count` was initialized as `new Integer(0)` (because "`==`" tests for reference equality).
1Technically, the first example uses [autoboxing](http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.7) (before Java 1.5 you couldn't pass an `int` to `compareTo`) and the second example uses [unboxing](http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.8). The combined feature is often simply called "autoboxing" for short, which is often then extended into calling both types of conversions "autoboxing". I apologize for my lax usage of terminology. | Integer value comparison | [
"",
"java",
"integer",
"int",
"equals",
"autoboxing",
""
] |
I work at a small php shop and I recently proposed that we move away from using our nas as a shared code base and start using subversion for source control.
I've figured out how to make sure our dev server gets updated with every commit to our development branch... and I know how to merge into trunk and have that update our staging server, because we have direct access to both of these, but my biggest question is how to write a script that will update the production server, which we many times only have ftp access to. I don't want to upload the entire site every time... is there any way to write a script that is smart enough to upload only what has changed to the web server when we execute it (don't want it to automatically be uploading to the production enviroment, we want to execute it manually)?
Does my question even make sense? | Basically, your issue is that you can't use subversion on the production server. What you need to do is keep, on a separate (ideally identically configured) server a copy of your production checkout, and copy that through whatever method to the production server. You could think of this as your staging server, actually, since it will also be useful for doing final tests on releases before rolling them out.
As far as the copy goes, if your provider supports [`rsync`](http://en.wikipedia.org/wiki/Rsync), you're set. If you have only FTP you'll have to find some method of doing the equivalant of rsync via FTP. This is not the first time anybody's had that need; a web search will help you out there. But if you can't find anything, drop me a note and I'll look around myself a little further.
EDIT: Hope the author doesn't mind me adding this, but I think it belongs here. To do something approximately similar to rsync with ftp, look at weex <http://weex.sourceforge.net/>. Its a wrapper around command line ftp that uses a local mirror to keep track of whats on the remote server so that it can send only changed files. Works great for me. | It [doesn't sound like](http://svn.haxx.se/users/archive-2006-12/0545.shtml) SVN plays well with FTP, but if you have http access, that may prove sufficient to push changes using [svnsync](http://svnbook.red-bean.com/en/1.4/svn.ref.svnsync.html). That's how we push changes to our production severs -- we use svnsync to keep a read-only mirror of the repository available. | PHP Subversion Setup FTP | [
"",
"php",
"svn",
"ftp",
""
] |
Is there a ready made LFU Cache available in C#? | * Java has tons of LFU cache implementations which should be easy to port to C#, for example see: <http://faq.javaranch.com/view?CachingStrategies>
* This commercial .NET library does LFU <http://www.kellermansoftware.com/pc-38-2-net-caching-library.aspx>
* This other commercial .NET library does LFU as well: <http://www.sharedcache.com/cms/>
I am sure there are others.
Here is a basic LFU implementation with aging for C# I just knocked up, its not perfect but is a good starting point:
Note: this implementation is not thread safe.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LFU {
class LFUCache<TKey,TValue> {
Dictionary<TKey, LinkedListNode<CacheNode>> cache = new Dictionary<TKey, LinkedListNode<CacheNode>>();
LinkedList<CacheNode> lfuList = new LinkedList<CacheNode>();
class CacheNode {
public TKey Key { get; set; }
public TValue Data { get; set; }
public int UseCount { get; set; }
}
int size;
int age = 0;
int agePolicy;
public LFUCache(int size) : this(size, 1000) {
}
/// <summary>
///
/// </summary>
/// <param name="size"></param>
/// <param name="agePolicy">after this number of gets the cache will take 1 off all UseCounts, forcing old stuff to expire.</param>
public LFUCache(int size, int agePolicy) {
this.agePolicy = 1000;
this.size = size;
}
public void Add(TKey key, TValue val) {
TValue existing;
if (!TryGet(key, out existing)) {
var node = new CacheNode() {Key = key, Data = val, UseCount = 1};
if (lfuList.Count == size) {
cache.Remove(lfuList.First.Value.Key);
lfuList.RemoveFirst();
}
var insertionPoint = Nodes.LastOrDefault(n => n.Value.UseCount < 2);
LinkedListNode<CacheNode> inserted;
if (insertionPoint == null) {
inserted = lfuList.AddFirst(node);
} else {
inserted = lfuList.AddAfter(insertionPoint, node);
}
cache[key] = inserted;
}
}
IEnumerable<LinkedListNode<CacheNode>> Nodes {
get {
var node = lfuList.First;
while (node != null) {
yield return node;
node = node.Next;
}
}
}
IEnumerable<LinkedListNode<CacheNode>> IterateFrom(LinkedListNode<CacheNode> node) {
while (node != null) {
yield return node;
node = node.Next;
}
}
public TValue GetOrDefault(TKey key) {
TValue val;
TryGet(key, out val);
return val;
}
public bool TryGet(TKey key, out TValue val) {
age++;
if (age > agePolicy) {
age = 0;
foreach (var node in cache.Values) {
var v = node.Value;
v.UseCount--;
}
}
LinkedListNode<CacheNode> data;
bool success = false;
if (cache.TryGetValue(key, out data)) {
var cacheNode = data.Value;
val = cacheNode.Data;
cacheNode.UseCount++;
var insertionPoint = IterateFrom(data).Last(n => n.Value.UseCount <= cacheNode.UseCount);
if (insertionPoint != data) {
lfuList.Remove(data);
lfuList.AddAfter(insertionPoint, data);
}
} else {
val = default(TValue);
}
return success;
}
}
class Program {
public static void Assert(bool condition, string message) {
if (!condition) {
Console.WriteLine("Assert failed : " + message);
throw new ApplicationException("Test Failed");
}
}
public static void RunAllTests(Program prog){
foreach (var method in prog.GetType().GetMethods()) {
if (method.Name.StartsWith("Test")) {
try {
method.Invoke(prog, null);
Console.WriteLine("Test Passed: " + method.Name);
} catch (Exception) {
Console.WriteLine("Test Failed : " + method.Name);
}
}
}
}
public void TestItemShouldBeThereOnceInserted() {
var cache = new LFUCache<string, int>(3);
cache.Add("a", 1);
cache.Add("b", 2);
cache.Add("c", 3);
cache.Add("d", 4);
Assert(cache.GetOrDefault("a") == 0, "should get 0");
Assert(cache.GetOrDefault("b") == 2, "should get 2");
Assert(cache.GetOrDefault("c") == 3, "should get 3");
Assert(cache.GetOrDefault("d") == 4, "should get 4");
}
public void TestLFUShouldWorkAsExpected() {
var cache = new LFUCache<string, int>(3);
cache.Add("a", 1);
cache.Add("b", 2);
cache.Add("c", 3);
cache.GetOrDefault("a");
cache.GetOrDefault("a");
cache.GetOrDefault("b");
cache.Add("d", 4);
cache.Add("e", 5);
Assert(cache.GetOrDefault("a") == 1, "should get 1");
Assert(cache.GetOrDefault("b") == 2, "should get 0");
Assert(cache.GetOrDefault("c") == 0, "should get 0");
Assert(cache.GetOrDefault("d") == 0, "should get 4");
Assert(cache.GetOrDefault("e") == 5, "should get 5");
}
static void Main(string[] args) {
RunAllTests(new Program());
Console.ReadKey();
}
}
}
``` | There is no such set *in the framework* as of .NET 3.5. [Ayende](http://ayende.com/) has created a [Least Recently Used](http://ayende.com/Blog/archive/2008/12/18/dropping-data-structures-into-the-pit-of-success.aspx) set. It may be a good start ([code](https://github.com/hibernating-rhinos/rhino-esb/blob/master/Rhino.ServiceBus/DataStructures/LeastRecentlyUsedSet.cs)). | LFU Cache in C#? | [
"",
"c#",
"caching",
""
] |
I have multiple NUnit tests, and I would like each test to use a specific app.config file.
Is there a way to reset the configuration to a new config file before each test? | Try:
```
/* Usage
* using(AppConfig.Change("my.config")) {
* // do something...
* }
*/
public abstract class AppConfig : IDisposable
{
public static AppConfig Change(string path)
{
return new ChangeAppConfig(path);
}
public abstract void Dispose();
private class ChangeAppConfig : AppConfig
{
private bool disposedValue = false;
private string oldConfig = Conversions.ToString(AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE"));
public ChangeAppConfig(string path)
{
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path);
typeof(ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, 0);
}
public override void Dispose()
{
if (!this.disposedValue)
{
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", this.oldConfig);
typeof(ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, 0);
this.disposedValue = true;
}
GC.SuppressFinalize(this);
}
}
}
``` | I [answered a similar question](https://stackoverflow.com/questions/835862/powershell-calling-net-assembly-that-uses-app-config/835984#835984) for Powershell. The same technique should work here, simply call the following at the start of your test:
`System.AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", configPath)`
EDIT: Actually looks like this is more complicated within a compiled exe - you need to do [something like this](http://www.codeproject.com/KB/dotnet/dllappconfig.aspx) in order to get the config reloaded. | Reload app.config with nunit | [
"",
"c#",
".net",
"nunit",
"app-config",
""
] |
I am working on a asp.net website. There are a lot of javascript plug-ins that site uses including the bookmark button(addthis), Google adsense, Admanager tags, Social Bookmarking buttons and so on.
The page loads slow and even though I have been using tools like FireBug, I haven't been able to make out why does my page load so slow.
Is there a way to find out which javascript is causing the page to load slow? Or find out the culprit and take it out?
Please be kind to me as I am just getting started with this stuff. | Using the Net tab of Firebug should show you which requests are taking the longest to load. See [this page](http://getfirebug.com/net.html) for a more detailed guide to using this information.
You could also use the [YSlow](http://developer.yahoo.com/yslow/) addon for Firebug to identify other ways you could improve the loading time of your page. | Have you tried removing scripts and complexity from your web page (one by one), sooner or later you will hit the one script that takes long time to load. If there is any.
If your web page gets consistently faster as you remove scripts and items, then that is the truth and you should look at optimizing those scripts. | Why is my page loading slow | [
"",
"asp.net",
"javascript",
"performance",
""
] |
Using jQuery, how can I:
1. Have all checkboxes on a page turned checked `on` or `off`?
2. Loop through all the checkboxes on the page which are selected. I.e something like this
```
$(sel-cboxes).each(myFunction);
```
So `myFunction` would be called on each selected checkbox.
Thanks in advance! | 1:
To check all checkboxes
```
$("input:checkbox").attr('checked', true);
```
To uncheck all
```
$("input:checkbox").attr('checked', false);
```
2:
```
$("input:checkbox:checked").each(myFunction);
``` | > 1- Have all checkboxes on a page
> turned checked on or off?
> Edited: (correction)
```
$(':checkbox').attr('checked',true);
```
> 2- Loop through all the checkboxes on
> the page which are selected. I.e
> something like this
```
$(':checkbox :checked').each(function() {
});
``` | jQuery checkboxes manipulation | [
"",
"javascript",
"jquery",
""
] |
I was thinking about the classic issue of lazy singleton initialization - the whole matter of the inefficiency of:
```
if (instance == null)
{
instance = new Foo();
}
return instance;
```
Anyone who knows what a Singleton is is familiar with the issue(you only need the if once). It's trivial but irritating.
So, I thought of an alternate solution, at least for .NET(although it should work anywhere
that has some equivalent to function pointers:
```
public class Foo
{
private delegate Foo FooReturner();
private static Foo innerFoo;
private static FooReturner fooReturnHandler = new FooReturner(InitialFooReturner);
public static Foo Instance
{
get
{
return fooReturnHandler();
}
}
private static Foo InitialFooReturner()
{
innerFoo = new Foo();
fooReturnHandler = new FooReturner(NewFooReturner);
return innerFoo;
}
private static Foo NewFooReturner()
{
return innerFoo;
}
}
```
In short - the Instance returns a delegate method. The delegate is initially set to a method
that initializes your instance, then changes the delegate to point at a simple Return method.
Now, I like to think I'm not terrible at my job, but I have no pretensions about being awesome. I have not seen an example of this code anywhere.
Ergo, I come to the conclusion that I am missing something. Something major. Either that the whole problem is too trivial to bother thinking that much about or this does something horrible that will destroy the universe. Or I fail at searching and therefore haven't seen
the hundreds of developers using this method. Something, anyway.
I was hoping the good folks here at Stack Overflow could clue me in as to what(leaving aside the controversy on whether one should use a Singleton at all).
EDIT for clarification:
This is not performance code(although if the design actively degrades performance beyond the traditional model, that would be interesting to know).
It was written purely as proof-of-concept, and I am further aware that it is not thread-safe as it properly should be. Is there any reason why it could NOT be made thread-safe by it's very nature? | [This is the canonical, thread safe, lazy Singleton pattern in C#](http://csharpindepth.com/Articles/General/Singleton.aspx):
```
public sealed class Singleton
{
Singleton(){}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested() {}
internal static readonly Singleton instance = new Singleton();
}
}
``` | To prevent from having to copy the singleton code, you could make the type generic, as such:
```
public abstract class Singleton<T>
where T: class, new()
{
public static T Instance
{
get { return Nested.instance; }
}
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested() { }
internal static readonly T instance = new T();
}
}
public sealed class MyType : Singleton<MyType>
{
}
class Program
{
static void Main()
{
// two usage pattterns are possible:
Console.WriteLine(
ReferenceEquals(
Singleton<MyType>.Instance,
MyType.Instance
)
);
Console.ReadLine();
}
}
``` | An obvious singleton implementation for .NET? | [
"",
"c#",
".net",
"singleton",
""
] |
Google has suggestion come up when you make a typo entry,how do they do it? | maybe these links can help
<http://answers.google.com/answers/threadview?id=526503>
<http://googlesystem.blogspot.com/2007/04/simplified-version-of-googles-spell.html>
<http://en.wikipedia.org/wiki/Spell_checker> | Peter Norvig (Director of Research at Google) has written a little introductory piece on [spell checking in Python](http://norvig.com/spell-correct.html) using statistical heuristics.
It's a great read, and shows how to use statistical heuristics in a very simple way. It could be ported to C# (with LINQ) quite easily (Python's list comprehensions are very close to Linq expressions).
The core part of this snippet is having all simple typos for a word (edit1 function)
the C# equivalent is the following
```
public static IEnumerable<string> Edit1(string word){
const string alphabet = "abcdefghijklmnopqrstuvwxyz";
var s = from i in Enumerable.Range (0, word.Length - 1)
select new Pair<string>(word.Substring (0, i), word.RSlice(i));
var deletes = from p in s
select p.First + p.Second.RSlice (1);
var transposes = from p in s
let b1 = p.Second
where b1.Length > 2
select p.First + b1 [1] + b1 [0] + b1.RSlice (2);
var replaces = from p in s
let b = p.Second
where b.Length > 0
from c in alphabet select p.First + c + b.RSlice (1);
var inserts = from p in s
from c in alphabet
select p.First + c + p.Second;
return deletes.Concat (transposes).Concat( replaces)
.Concat(inserts).Distinct ();}
```
where Pair is a poor man tuple (obvious code not included) and RSlice is a poor-man string-only right splicing :
```
public static class Extensions {
public static string RSlice (this string input, int i)
{
if (i > input.Length - 1)
return "";
return input.Substring (i);
}}
```
Once you got the edits for a word, you look for the word in the dictionary or the existing words of the edits (selecting the most frequent word) or the words for edits1(edits1(word)) (selecting the most frequent word). Surprisingly, this can be quite fast and quite accurate.
I'll have a link to my blog for the whole stuff ported.
Edit: oops just saw that a link in an answer above pointed to a pointer to the same Norvig's piece... | Machine learning for typos | [
"",
"c#",
"machine-learning",
""
] |
I have an array in javascript. This array has strings that contains commas (","). I want all commas to be removed from this array. Can this be done? | Yes.
```
for(var i=0; i < arr.length; i++) {
arr[i] = arr[i].replace(/,/g, '');
}
``` | The best way nowadays is to use the `map()` function in this way:
```
var resultArr = arr.map(function(x){return x.replace(/,/g, '');});
```
this is ECMA-262 standard.
If you nee it for earlier version you can add this piece of code in your project:
```
if (!Array.prototype.map)
{
Array.prototype.map = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
``` | Replace string in javascript array | [
"",
"javascript",
"arrays",
"string",
""
] |
I'm working with java.
I have a byte array (8 bits in each position of the array) and what I need to do is to put together 2 of the values of the array and get a value.
I'll try to explain myself better; I'm extracting audio data from a audio file. This data is stored in a byte array. Each audio sample has a size of 16 bits. If the array is:
byte[] audioData;
What I need is to get 1 value from samples audioData[0] and audioData[1] in order to get 1 audio sample.
Can anyone explain me how to do this?
Thanks in advance. | I'm not a Java developer so this could be completely off-base, but have you considered using a [ByteBuffer](http://java.sun.com/j2se/1.4.2/docs/api/java/nio/ByteBuffer.html)? | Assume the LSB is at data[0]
```
int val;
val = (((int)data[0]) & 0x00FF) | ((int)data[1]<<8);
``` | Convert Bytes to bits | [
"",
"java",
"types",
"byte",
"bitset",
""
] |
> When compiler need to know the size of a C (class)
> object: For example, when allocating a
> C on the stack or as a directly-held
> member of another type
From *C++ Coding Standards: 101 Rules, Guidelines, and Best Practices*
Does that mean for a heap allocated object, size is not necessary?
```
Class C;//just forward declaration
C * objc = new C();
``` | To answer your specific question:
> Does that mean for heap allocated
> object size is not necessary?
>
> ```
> Class C;//just forward declaration
> C * objc = new C();
> ```
C++ will not let you do that.
Even if it could let you perform a '`new`' on an incomplete type by magically resolving the size at a later time (I could envision this being technically possible with cooperation from the linker), the attempt will fail at compile time because of at least 2 reasons:
1. operator `new` can only be used with complete types. From the C++98 standard 5.3.4 - "[the allocated] type shall be a complete object type, but not an abstract class type or array thereof"
2. the compiler has no idea what constructors exist (and are accessible), so it would also have to fail for that reason. | No, this list is by way of example and not of exclusion. Obviously the object size must be known in heap allocation so the right amount of memory can be allocated. | Is the size of an object needed for creating object on heap? | [
"",
"c++",
"heap-memory",
"definition",
"forward-declaration",
""
] |
I have got a Visual Studio Solution containing several projects and have set up the references between the projects as project references.
When a reference to an assembly is added, the references' properties contain a setting for
`Specific Version = True|False`
This property is missing for project references. How can it be set? I'd like my solution to load any available assembly (no matter what version) in the bin folder.
I've had a problem when a workflow instance (Workflow Foundation) was deserialized and the dependencies were updated meanwhile. | I have found the solution to my problem. It's described pretty detailed [here](http://blogs.msmvps.com/theproblemsolver/2008/09/11/versioning-long-running-workflows-part-2/).
The problem is not a matter of wrong project references, but more a de/serializing of workflow instances question.
Thanks to everybody who tried to help. | I think the problem is that what you are asking is not possible directly with a project reference, I think that always implicitly turns into an 'explicit version', because of the nature of the link.
The way you **could** do this (calling the currently referenced project A, and the referencing project B):
* Have the project you want to reference in your solution, just like you do now with the project reference
* Explicitly set the dependency chain so the 'referenced' project is built first
* Build the referenced project A once first manually
* Create an assembly reference in project B to the results from the build in project A
* Set the assembly reference to 'Specific Version = false'
The build order (dependency) will guarantee that A is always built before B, and B will reference it from the binary output directory of A.
(altho, it's a little brittle and I would not recommend it since it's easy to get wrong results if the settings are not all right, or the sun aligns with the stars wrong, or some such) | How to set "Specific Version" property for project references in Visual Studio | [
"",
"c#",
"visual-studio",
"visual-studio-2008",
"assemblies",
"workflow-foundation",
""
] |
I have a requirement where I need to be able to access a list which sits in Central Administration from an Application Page which sits on my Web Front End (WFE). The issue I have is that the Application Pool User for my WFE does not have access to the SharePoint\_AdminContent database so I get access denied, they both have their own App Pools
In the logs it shows the following:
> * Reverting to process identity
> * Current user before SqlConnection.Open: Name:
> SharePointDemo\SPContentPool SID:
> S-1-5-20 ImpersonationLevel: None
> * Current user after SqlConnection.Open: Name:
> SharePointDemo\SPContentPool: S-1-5-20
> ImpersonationLevel: None
> * Insufficient SQL database permissions for user 'SPContentPool'
> in database
> 'SharePoint\_AdminContent\_53169fb3-137c-44b2-b90e-961b656e4275' on SQL Server instance 'SPNSQL'.
> Additional error information from SQL
> Server is included below. The EXECUTE
> permission was denied on the object
> 'proc\_EnumLists', database
> 'SharePoint\_AdminContent\_53169fb3-137c-44b2-b90e-961b656e4275',
> schema 'dbo'.
I have tried to runwithelevatedprivileges as well as trying Daniel Larsons method (<http://daniellarson.spaces.live.com/blog/cns!D3543C5837291E93!1919.entry>) which uses the SharePoint\System user token but it only seems to elevate as high as the Application Pool.
I am hoping there is an easy way to impersonate the Application Pool of the Admin Web Application but have been unable to find a way to do so yet... Or change the process identity to one which has access
Any thoughts, ideas or solutions are thankfully received!
Phill | The problem is that the CA Application Pool and the WFE Application pool most likely run under different accounts, which is best practice though annoying when you are a developer. There is no amount of Elevating Privileges you can do using SPSecurity.RunWithElevatedPrivileges to get around this.
Providing your security policy allows this, you can give the application pool that runs your WFE Web Application the same credentials as the Central Administration Application Pool.
This can be done using the Service Accounts screen at:
http:///\_admin/FarmCredentialManagement.aspx
If you go down the web service route, you may want to role your own web service to prevent too much 'chatting' over HTTP. | You should try to use the List web service to access the list items. And set the credentials before connecting to the web service. | SharePoint List access across Application Pools | [
"",
"c#",
"sharepoint",
"web-applications",
"application-pool",
"elevated-privileges",
""
] |
I have this piece of code:
```
<script language="javascript" type="text/jscript">
document.write("<img src='http://dm.leadgenesys.com/jpgp.lgt?en=P.........TP_Q=&ur=' + escape(document.referrer) + '' border='0' alt='no alt' />");
</script>
```
and... when I try to validate it, I'm given this error:
> document type does not allow element
> "img" here
>
> …rer) + '" border="0" alt="no alt"
> />');
>
> The element named above was found in a
> context where it is not allowed. This
> could mean that you have incorrectly
> nested elements -- such as a "style"
> element in the "body" section instead
> of inside "head" -- or two elements
> that overlap (which is not allowed).
Any idea what I can do to make this JavaScript w3c compliant? | Simple: don't try to validate your JavaScript as HTML.
You can do this in a number of ways... But the best by far is to move it out into a separate JS file, and then either call it from a short script
```
<body>
...
<script type="text/javascript" language="javascript">WriteImage();</script>
...
</body>
```
...or better yet, ditch `document.write()` entirely and manipulate the DOM after it has loaded.
### See also: [Unobtrusive JavaScript](https://stackoverflow.com/questions/tagged/unobtrusive-javascript) | Another way to silence the validator...
Put it like this:
```
<script type="text/javascript">
/* <![CDATA[ */
your_javascript_here("<" + ... ;
/* ]]> */
</script>
```
The CDATA part should be enough for the validator, the /\* style comments \*/ are for older browsers which do not recognize the CDATA tag (it would otherwise break the javascript). | Why is my script failing w3c validation? | [
"",
"javascript",
"xhtml",
"w3c-validation",
""
] |
This is with reference to this question:
[How to read output and give input to a program from c program?](https://stackoverflow.com/q/924289)
I found the answer to the above question very useful. In the same way, can I do it for windows applications? Like can I give input into a Windows form (like .net, C# applications) application's text box programmatically? Can I do the action of button click from a program?
If so, can I do it from a C program (with Tiny C compiler or any other on windows platform)? If not, how and in which language can I do it? Please don't take it as a silly question. Any example codes will be very much appreciated.
**Edit**: Can I do the same with web applications and web pages? | If your application mainly just needs to manipulate other windows, by sending keystrokes etc. i would use [AutoIt](http://www.autoitscript.com/autoit3/index.shtml). It's mainly function is exactly this job and it does it very well.
So maybe you should give it a try, cause not every problem is a nail and can be solved with a hammer (C#) ;-)) | You can [enumerate all the windows](http://msdn.microsoft.com/en-us/library/ms633497.aspx) of the system.
You can [send windows messages](http://msdn.microsoft.com/en-us/library/ms644950(VS.85).aspx) to any window.
E.g. to set the text of a textbox you have to send a [WM\_SETTEXT](http://msdn.microsoft.com/en-us/library/ms632644(VS.85).aspx) message.
FYI: [Winspector](http://www.windows-spy.com/) is a very interesting tool which makes heavy use of this as well (also to debug or otherwise first inspect the windows you're trying to programmatically access).
You might also be interested in [this](http://www.autoitscript.com/autoit3/index.shtml):
> AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way not possible or reliable with other languages (e.g. VBScript and SendKeys). AutoIt is also very small, self-contained and will run on all versions of Windows out-of-the-box with no annoying "runtimes" required! | How to give input to a windows application programmatically? | [
"",
"c#",
"c",
"automation",
""
] |
I have recently started off with LINQ and its amazing. I was wondering if LINQ would allow me to apply a function - any function - to all the elements of a collection, without using foreach. Something like python lambda functions.
For example if I have a int list, Can I add a constant to every element using LINQ
If i have a DB table, can i set a field for all records using LINQ.
I am using C# | A common way to approach this is to add your own `ForEach` generic method on `IEnumerable<T>`. Here's the one we've got in [MoreLINQ](http://code.google.com/p/morelinq/):
```
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
source.ThrowIfNull("source");
action.ThrowIfNull("action");
foreach (T element in source)
{
action(element);
}
}
```
(Where `ThrowIfNull` is an extension method on any reference type, which does the obvious thing.)
It'll be interesting to see if this is part of .NET 4.0. It goes against the functional style of LINQ, but there's no doubt that a lot of people find it useful.
Once you've got that, you can write things like:
```
people.Where(person => person.Age < 21)
.ForEach(person => person.EjectFromBar());
``` | The idiomatic way to do this with LINQ is to process the collection and return a new collection mapped in the fashion you want. For example, to add a constant to every element, you'd want something like
```
var newNumbers = oldNumbers.Select(i => i + 8);
```
Doing this in a functional way instead of mutating the state of your existing collection frequently helps you separate distinct operations in a way that's both easier to read and easier for the compiler to reason about.
If you're in a situation where you actually want to apply an action to every element of a collection (an action with side effects that are unrelated to the actual contents of the collection) that's not really what LINQ is best suited for, although you could fake it with `Select` (or write your own `IEnumerable` extension method, as many people have.) It's probably best to stick with a `foreach` loop in that case. | Apply function to all elements of collection through LINQ | [
"",
"c#",
".net",
"linq",
""
] |
While it is fairly trivial in Python to import a "child" module into another module and list its attributes, it becomes slightly more difficult when you want to import *all* child modules.
I'm building a library of tools for an existing 3D application. Each tool has its own menu item and sub menus. I'd like the tool to be responsible for creating its own menus as many of them change based on context and templates. I'd like my base module to be able to find all child modules and check for a `create_menu()` function and call it if it finds it.
What is the easiest way to discover all child modules? | using [dir()](http://docs.python.org/library/functions.html#dir) and [imp module](http://docs.python.org/library/imp.html) | I think the best way to do this sort of plugin thing is using [`entry_points`](http://pythonhosted.org/setuptools/setuptools.html#dynamic-discovery-of-services-and-plugins) and the [API for querying them](http://pythonhosted.org/setuptools/pkg_resources.html#convenience-api). | How to find all child modules in Python? | [
"",
"python",
"module",
"package",
"python-import",
""
] |
Mozilla Firefox 3.x seems to have a bug when listening to the "ondrag" event. The event object doesn't report the position of the object being dragged, `clientX`, `clientY`, and other screen offsets are all set to zero.
This is quite problematic as I wanted to make a proxy element based on the element being dragged and using of course, `clientX` and `clientY` to adjust its position.
I know that there's cool stuff around such as `setDragImage` in HTML5 but I want to provide a generic abstraction for native DD between browsers.
Faulty code:
```
document.addEventListener('drag', function(e) {
console.log(e.clientX); // always Zero
}, false);
```
Note:
This problem doesn't happen on other events (`dragstart`, `dragover`) and the `mousemove` events cannot be captured while dragging something. | I found a solution, I've placed a listener on the "dragover" event at the document level, now I get the right X and Y properties that I can expose through a globally shared object. | The drag event in HTML 5 is not fully functional in todays browsers. To simulate a drag n drop situation you should use:
1. Add a onmousedown event, setting a var true.
2. Add a onmouseup event, setting that var false.
3. Add a onmousemove event, checking if that var is true, and if it is, move your div according to the coordinates.
This always worked for me. If you face any problems, get in touch again, I can provide some examples.
good luck! | How do I get clientX and clientY to work inside my "drag" event handler on Firefox? | [
"",
"javascript",
"events",
"drag-and-drop",
"firefox-3",
""
] |
I've recently started using Magento for a client's webshop, and still need to get to grips with its systems.
The webshop should have several links to and also grab info from another domain, where the corporate website is located. I would prefer not to hardcode the domain name or URL but instead define it at some place and use that value in the phtml templates throughout the webshop. This makes it easy to adjust it when we move the site between dev, staging and production URL's.
Can anyone suggest the Magento way of doing this? Preferably we could add a field to the Store's Config GUI in the backend, similar to the way the {{base\_url}} is set. Or maybe I'm thinking the wrong way? | Magento offers (relatively) easy support for custom configuration values. The best way I've found to accomplish this is to create a single magento module that holds all your custom configuration values.
Like anything Magento, there are a lot of steps, and any one being wrong could trip you (or me!) up.
## Create an Empty Magento Module
First, you'll want to setup a magento module to hold all your custom configuration values. Creating a magento module involves
1. Create a xml file in app/etc/modules
2. Create a folder structure in app/code/local/Companyname
Companyname is a unique string that serves as a namespace, and most magento tutorials recommend you use your company name here. For the purposes of this tutorial, I'll use "Stackoverflow". Wherever you see the string Stackoverflow, replace it with your own unique string.
So, for step 1, create a file at app/etc/modules named "Stackoverflow\_Customconfig.xml", and place the following inside
```
<?xml version="1.0"?>
<config>
<modules>
<Stackoverflow_Customconfig>
<active>true</active>
<codePool>local</codePool>
</Stackoverflow_Customconfig>
</modules>
</config>
```
Random Magento Tip: There are parts of the magento system that consider whitespace significant, so it's always best to include no whitespace with your attribute values (<active>true</active> vs. <active> true </active>
Next, create the following folder
```
mkdir app/code/local/Stackoverflow/Customconfig
mkdir app/code/local/Stackoverflow/Customconfig/etc
```
And create a file at
```
app/code/local/Stackoverflow/Customconfig/etc/config.xml
```
with the following contents
```
<?xml version="1.0"?>
<config>
<modules>
<Stackoverflow_Customconfig>
<version>0.1.0</version>
</Stackoverflow_Customconfig>
</modules>
</config>
```
Congratulations, you've just setup a new Magento Module. If you clear your magento cache and go to
```
System -> Configuration -> Advanced -> Disable Modules Output
```
you should see your module listed.
## Add a System.xml file to your module
Next, we're going to add a system.xml file. This file is used to add a custom configuration value to magento, which you'll be able to grab anywhere you want during the magento request cycle. Add a file at
```
app/code/local/Stackoverflow/Customconfig/etc/system.xml
```
That contains the following
```
<config>
<sections>
<design>
<groups>
<my_or_their_group translate="label">
<label>A grouping of config values. Make your own, or us an existing group.</label>
<frontend_type>text</frontend_type>
<sort_order>50</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>0</show_in_website>
<show_in_store>0</show_in_store>
<fields>
<my_config translate="label">
<label>This will be my config's label</label>
<frontend_type>text</frontend_type>
<sort_order>50</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>0</show_in_website>
<show_in_store>0</show_in_store>
</my_config>
</fields>
</my_or_their_group>
</groups>
</design>
</sections>
</config>
```
**<design>** is the name of the section your config will be displayed in. "General, Web, Design, Currency Setup, etc." By and large, this will be a lower-case version of the title, i.e. "General" becomes "general", "Design" becomes "design". If you're not sure what this outer tag should be, search through the core magento modules. i.e., grepping for "Currency Setup" reveals a mention in
```
app/code/core/Mage/Directory/etc/system.xml
<currency translate="label" module="directory">
<label>Currency Setup</label>
```
So you'd use the tag <currency /<, and not the more intuitive <currency\_setup />
<my\_or\_their\_group translate="label"> is the name of the group your config variable will show up in. Groups are the Ajax drop downs that contain config fields. For example, the General section has a "Country options" group and a Local options" group. Again, check existing core modules if you're unsure how to place a value in an existing group.
You'll also notice a *translate attribute* here, along with a corresponding label tag. This allows you to use any string you want in the HTML interface as a group title, but internally keep the name a valid XML tag name. Our tag is named
```
<my_or_their_group />
```
but in the interface, the group will have the title
> A grouping of config values. Make your own, or us an existing group.
Finally, <my\_config translate="label"> is the name of yoru conifg value. Again, notice the *translate attribute*. The same rules as above apply.
The other xml structure is needed, and is (mostly) used to control what kind of HTML inputs will be used for your config. If you want a particular interface element, find an example in the core module and copy the XML structure.
This will allow you to set and lookup config values in the Magento GUI interface. You can retrieve your values using the static getStoreConfig method of the global Mage object and specifying the URI of your config value. The URI is created using the section/group/name of your config.
```
Mage::getStoreConfig('design/my_or_their_group/my_config');
``` | Magento provides Custom Variables from version 1.4 onwards.
Login to Admin side, System -> Custom variables -> create a new custom variable with code "my\_variable".
Enter the HTML content and Plain text for this variable
You can show the custom variable in CMS pages by putting this `{{customVar code=my_variable}}`
Or in `.phtml` pages:
```
$variableHtml = Mage::getModel('core/variable')->loadByCode('my_variable')->getValue('html');
$variablePlain = Mage::getModel('core/variable')->loadByCode('my_variable')->getValue('plain');
``` | Setting a global variable in Magento, the GUI way? | [
"",
"php",
"xml",
"configuration",
"magento",
""
] |
```
class Package:
def __init__(self):
self.files = []
# ...
def __del__(self):
for file in self.files:
os.unlink(file)
```
`__del__(self)` above fails with an AttributeError exception. I understand [Python doesn't guarantee](http://docs.python.org/reference/datamodel.html#customization) the existence of "global variables" (member data in this context?) when `__del__()` is invoked. If that is the case and this is the reason for the exception, how do I make sure the object destructs properly? | I'd recommend using Python's `with` statement for managing resources that need to be cleaned up. The problem with using an explicit `close()` statement is that you have to worry about people forgetting to call it at all or forgetting to place it in a `finally` block to prevent a resource leak when an exception occurs.
To use the `with` statement, create a class with the following methods:
```
def __enter__(self)
def __exit__(self, exc_type, exc_value, traceback)
```
In your example above, you'd use
```
class Package:
def __init__(self):
self.files = []
def __enter__(self):
return self
# ...
def __exit__(self, exc_type, exc_value, traceback):
for file in self.files:
os.unlink(file)
```
Then, when someone wanted to use your class, they'd do the following:
```
with Package() as package_obj:
# use package_obj
```
The variable package\_obj will be an instance of type Package (it's the value returned by the `__enter__` method). Its `__exit__` method will automatically be called, regardless of whether or not an exception occurs.
You could even take this approach a step further. In the example above, someone could still instantiate Package using its constructor without using the `with` clause. You don't want that to happen. You can fix this by creating a PackageResource class that defines the `__enter__` and `__exit__` methods. Then, the Package class would be defined strictly inside the `__enter__` method and returned. That way, the caller never could instantiate the Package class without using a `with` statement:
```
class PackageResource:
def __enter__(self):
class Package:
...
self.package_obj = Package()
return self.package_obj
def __exit__(self, exc_type, exc_value, traceback):
self.package_obj.cleanup()
```
You'd use this as follows:
```
with PackageResource() as package_obj:
# use package_obj
``` | The standard way is to use [`atexit.register`](https://docs.python.org/3/library/atexit.html#atexit.register):
```
# package.py
import atexit
import os
class Package:
def __init__(self):
self.files = []
atexit.register(self.cleanup)
def cleanup(self):
print("Running cleanup...")
for file in self.files:
print("Unlinking file: {}".format(file))
# os.unlink(file)
```
But you should keep in mind that this will persist all created instances of `Package` until Python is terminated.
Demo using the code above saved as *package.py*:
```
$ python
>>> from package import *
>>> p = Package()
>>> q = Package()
>>> q.files = ['a', 'b', 'c']
>>> quit()
Running cleanup...
Unlinking file: a
Unlinking file: b
Unlinking file: c
Running cleanup...
``` | How do I correctly clean up a Python object? | [
"",
"python",
"destructor",
""
] |
Recently making the switch from [Prototype](http://www.prototypejs.org/) to [jQuery](http://jquery.com/), I am struggling with some basic issues.
I use several AJAX-requests in my application; for 95% of these requests, I'd like to have some global events executed, such as showing or hiding a loading indicator. Apart from the global functionality, every request should also have some custom code executed after it has completed.
It seems like the local [Ajax events](http://docs.jquery.com/Ajax_Events) override the global ones, once they are set. For example, see the following code:
```
// global events
$('#loader').bind('ajaxStart', function() {
// in this particular example, the ajaxStart() works fine,
// as it has not been overridden
Loader.enable();
}).bind('ajaxComplete', function() {
// this section will not execute. when the local complete()
// is removed, it will execute just fine
Loader.disable();
} );
// local ajax event
$.ajax({
type: $(element).attr('method'),
url: $(element).attr('action'),
data: $(element).serialize(),
global: 'true',
complete: function(data) {
if (params.target && $('#' + params.target)) {
$('#' + params.target).html(data.responseText);
}
Behaviour.apply();
});
```
In this particular case, the local complete() event seems to stop the global ajaxComplete() event from executing.
**Is there any way to execute both the local as the global ajax events?** | First of all, thank you for the replies. Both of them at least helped me to re-evaluate my code time and time again.
**The problem and solution turned out to be quite simple:**
The `Behaviour.apply();` that was called in my local complete event triggered an error elsewhere, preventing the `complete()` function to finish correctly and effectively disabling the global `ajaxComplete()` event. Fixing this error also fixed my problem.
**This means that jQuery supports combining both *local* as *global* ajax events.** | Just tried to run your code. Added the missing }); though. Worked like a charm. Calls were made in this order:
1. ajaxStart
2. complete
3. ajaxComplete
**Here is what I did:**
```
// local ajax event
$.ajax({
...
global: 'true',
complete: function(data) {
...
}
}); // <=== This line here
``` | How to execute both the local as the global ajax events in jQuery? | [
"",
"javascript",
"jquery",
"ajax",
"jquery-events",
""
] |
Edit: I've removed the faster/more efficient from the question title as it was misleading..my intention was not optimisation but understanding arrays. Sorry for the trouble!
```
int array[10][10], i, j;
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
std::cin>>array[i][j];
}
```
Versus
```
int array[10][10], i, j;
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
std::cin>>array[j][i];
}
```
I'm pretty sure the answer has to do with how arrays are implemented on a hardware level; that the [ ][ ] syntax is just a programmer's abstraction to aid visualisation/modelling. However, I forgot which of the above code accesses the memory block sequentially from start till end...
Thanks for all the answers...
Just to confirm my understanding, does this mean the first code is equivalent to
```
int array[10][10], k;
for(k=0;k<100;k++)
{
std::cin>>*(array+k);
}
``` | Aside from the fact that waiting on getting user input will be signifficantly slower than the array access, the first one is faster.
Check out [this page on 2D array memory layout](http://www.fredosaurus.com/notes-cpp/arrayptr/23two-dim-array-memory-layout.html) if you want more background on the subject.
With the second one you are checking `A[0], A[10] ... A[1], A[11].`
The first is going sequentially `A[0], A[1], A[2] ..` | The first one has better spatial locality. Because the first subscript is the index of a subarray, and the second subscript is the element within that subarray; so when you fix `i` and vary the `j`'s, you are looking at elements that are all within a subarray and thus are close together; but when you fix `j` and vary the `i`'s, you are looking at elements that are 10 (the length of a subarray) apart, so are very spread out. | In C++, which is the way to access a 2D array sequentially (memory block wise) | [
"",
"c++",
"arrays",
""
] |
`java.math.MutableBigInteger` is only available from inside the package. It inherits from `java.lang.Object` and there is only one subclass (`SignedMutableBigInteger`) which is only available from inside the package. | ```
/**
* A class used to represent multiprecision integers that makes efficient
* use of allocated space by allowing a number to occupy only part of
* an array so that the arrays do not have to be reallocated as often.
* When performing an operation with many iterations the array used to
* hold a number is only reallocated when necessary and does not have to
* be the same size as the number it represents. A mutable number allows
* calculations to occur on the same number without having to create
* a new number for every step of the calculation as occurs with
* BigIntegers.
*
* @see BigInteger
* @version 1.12, 12/19/03
* @author Michael McCloskey
* @since 1.3
*/
```
[Source](http://www.docjar.com/docs/api/java/math/MutableBigInteger.html).
I'd guess MutableBigInteger is used internally for BigInteger heavy calculations that are slowed down by frequent reallocations. I'm not sure why its not exported as part of java.math. Perhaps some distaste for mutable value classes?
To clarify "mutable":
Standard BigInteger has one value for its entire lifetime, given two BigInteger references "a" & "b", "a+b" will always yield a new BigInteger with the same value. Let's say that value is 4.
With MutableBigInteger, "a+b" could yield 4 initially, yet yield 8, 16, 32, or any other number at some point in the future due to OTHER code changing the values (aka. mutating) of the objects referenced by "a" & "b". Accordingly, most (perhaps all) of the value types (Character, Short, Long, Integer, BigInteger, BigDecimal, Float, Double, even String) in Java are immutable. | The issue with BigInteger is that it's immutable: in other words, once you have a BigInteger object, you can't change the value of the object itself, you can only replace it with a new object.
Now this is normally a fine thing, since it prevents aliasing and so on (you don't want your "2 + 3" somewhere to suddenly turn into "2 + 5" because a user of that "3" somewhere else in your program changed it into a "5"). However, internally the BigInteger uses an array to hold the components of this value. For a large number, this array can be quite large; a BigInteger representing a bazillion might need an array of, oh, a thousand elements, say.
So what happens when I want to add one to this BigInteger? Well, we create a new BigInteger, which in turn will create a new array internal to it of a thousand elements, copy all of the elements of the old BigInteger's internal array to the new BigInteger's internal array, excepting the last one, and put in a new version of that last element incremented by one. (Or it might need to update the last two.) If you then don't need the old value, it frees up that old BigInteger, which frees up the array.
This is obviously pretty inefficient if you are just getting rid of the old values anyway. So if you have operations like this, you can instead use a MutableBigInteger, which can be incremented by simply changing the last element in the internal array of the existing MutableBigInteger. This is far faster! However, it does destroy the old value, which can be problematic, as I pointed out above. If someone gives you the int "3", you can expect that to stay the same. If someone gives you a MutableBigInteger, don't expect it to be the same number later on! | What is the purpose of java.math.MutableBigInteger? | [
"",
"java",
""
] |
I'm trying to profile the performance of a web site that I'm fairly confident is being slowed down by the loading of JavaScript files on the page.
The same JavaScript files are included several times on the page, and `<script />` tags are scattered throughout the page instead of being [included at the bottom](http://developer.yahoo.com/performance/rules.html#js_bottom).
As I suspected, when looking at FireBug's "Net" tab, most of the time (not all) when JavaScript is being loaded, no other files are requested. The browser waits for the JavaScript to complete loading.
There are a few exceptions however. There are a few occasions where JavaScript is loaded, but then at the same time, other resources appear to get loaded, such as other JavaScript files and images.
I always thought that JavaScript blocks the loading of other resources on the page. Am I incorrect in thinking this, or does this behavior vary depending on the browser or browser version?
**UPDATE:**
To those who have explained how loading a script blocks the loading of other resources, I'm already aware of this. My question is why a script **wouldn't** block the loading of other resources. Firebug is showing that some JavaScript files **do not** block loading other resources. I want to know why this would happen. | Javascript resource requests are indeed blocking, but there are ways around this (to wit: DOM injected script tags in the head, and AJAX requests) which without seeing the page myself is likely to be what's happening here.
Including multiple copies of the same JS resource is *extremely bad* but not necessarily fatal, and is typical of larger sites which might have been accreted from the work of separate teams, or just plain old bad coding, planning, or maintenance.
As far as yahoo's recommendation to place scripts at the bottom of the body, this improves *percieved* response times, and can improve actual loading times to a degree (because all the previous resources are allowed to async first), but it will never be as effective as non-blocking requests (though they come with a high barrier of technical capability).
Pretty decent discussion of non-blocking JS [here](http://yuiblog.com/blog/2008/07/22/non-blocking-scripts/). | I'm not entirly sure that Firebug offers a true reflection of what is going on within the browser. It's timing for resource loading seems to be good but I am not sure that it is acting as a true reflection of exactly what is going on. I've had better luck using HTTP sniffers/proxy applications to monitor the actual HTTP requests coming from the browser. I use Fiddler, but I know there are other tools out there as well.
In short, this many be an issue with the tool and not with how resources are actually being loaded ... at least worth ruling out. | JavaScript being loaded asynchronously in Firefox 3 (according to Firebug)? | [
"",
"javascript",
"browser",
"web-optimization",
""
] |
I am having some trouble with my ReWrite code. Please note that the .htaccess file is in the subdomain folder (...public\_html/subdomain/ )
I am simply trying to rewrite a page request:
```
http://subdomain.mysite.com/home
http://subdomain.mysite.com/index.php?page=home
```
My .htaccess file looks like this...
```
RewriteEngine On
RewriteRule ^/([A-Za-z0-9\-\_])$ /index.php?page=$1
```
Does anything jump out at you? | Your current rule probably works for urls one character long (after the slash)!
Add a `+` to signify one or more characters, or a `*` for zero or more
Try
```
RewriteEngine On
RewriteRule ^/([A-Za-z0-9\-\_]*)$ /index.php?page=$1
``` | If you want to use the rules in a .htaccess file, you need to strip the contextual per-directory path prefix from the `RewriteRule` pattern. If the .htaccess file is located in the document root `/`, you need to strip the leading `/`.
Additionally you need to quantify the character set. Otherwise it would only describe *one* character.
So try this rule:
```
RewriteRule ^([A-Za-z0-9-_]+)$ index.php?page=$1
``` | .htaccess ModReWrite help | [
"",
"php",
".htaccess",
"mod-rewrite",
"friendly-url",
""
] |
What is the best way to build a **non web browser** stand alone php app that works with some sort of database without requiring the user to install a database server. Or am i just asking too much? | If you're targeting Windows, try [WinBinder](http://winbinder.org). It allows you to develop native Windows applications using PHP.
It also supports SQLite, so you don't need a database server. | Embed the SQLite database in your app, then configure PHP to talk to the SQLite database:
<http://us.php.net/sqlite> | stand alone php app | [
"",
"php",
""
] |
I've installed the latest SVN branch from Django which includes the new forms. I'm trying to use the SelectDateWidget from django.forms.extras.widgets but the field is showing up as a normal DateInput widget.
Here is the forms.py from my application:
```
from django import forms
from jacob_forms.models import Client
class ClientForm(forms.ModelForm):
DOB = forms.DateField(widget=forms.extras.widgets.SelectDateWidget)
class Meta:
model = Client
```
What am I doing wrong? Checking the forms/extras/widgets.py I see the SelectDateWidget class exists. | The real problem was that SelectDateWidget can't be referenced this way. Changing the code to reference it differently solved my problem:
```
from django.forms import extras
...
DOB = forms.DateField(widget=extras.SelectDateWidget)
```
This seems to be a limitation that you can't reference package.package.Class from an imported package. The solution imports extras so the reference is just package.Class. | From the ticket re: the lack of documentation for SelectDateWidget here:
[Ticket #7437](http://code.djangoproject.com/attachment/ticket/7437/SelectDateWidget-doc.diff)
It looks like you need to use it like this:
```
widget=forms.extras.widgets.SelectDateWidget()
```
Note the parentheses is the example. | Django form field using SelectDateWidget | [
"",
"python",
"django",
"forms",
"widget",
"admin",
""
] |
Over the last couple of months I've been working on some implementations of sockets servers in C++ and Java. I wrote a small server in Java that would handle & process input from a flash application hosted on a website and I managed to successfully write a server that handles input from a 2D game client with multiple players in C++. I used TCP in one project & UDP in the other one. Now, I do have some questions that I couldn't really find on the net and I hope that some of the experts could help me. :)
Let's say I would like to build a server in C++ that would handle the input from thousands of standalone and/or web applications, how should I design my server then? So far, I usually create a new & unique thread for each user that connects, but I doubt this is the way to go.
Also, How does one determine the layout of packets sent over the network; is data usually sent over the network in a binary or text state? How do you handle serializated objects when you send data to different media (eg C++ server to flash application)?
And last, is there any easy to use library which is commonly used that supports portability (eg development on a windows machine & deployment on a linux box) other than boost asio.
Thank you. | Sounds like you have a couple of questions here. I'll do my best to answer what I can see.
**1. How should I handle threading in my network server?**
I would take a good look at what kind of work you're doing on the worker threads that are being spawned by your server. Spawning a new thread for each request isn't a good idea...but it might not hurt anything if the number of parallel requests is small and and tasks performed on each thread are fast running.
If you really want to do things the right way, you could have a configurable/dynamic thread pool that would recycle the worker threads as they became free. That way you could set a max thread pool size. Your server would then work up to the pool size...and then make further requests wait until a worker thread was available.
**2. How do I format the data in my packets?**
Unless you're developing an entirely new protocol...this isn't something you really need to worry about. Unless you're dealing with streaming media (or another application where packet loss/corruption is acceptable), you probably won't be using UDP for this application. TCP/IP is probably going to be your best bet...and that will dictate the packet design for you.
**3. Which format do I use for serialization?**
The way you serialize your data over the wire depends on what kind of applications are going to be consuming your service. Binary serialization is usually faster and results in a smaller amount of data that needs to be transfered over the network. The downside to using binary serialization is that the binary serialization in one language may not work in another. Therefore the clients connecting to your server are, most likely, going to have to be written in the same language you are using.
XML Serialization is another option. It will take longer and have a larger amount of data to be transmitted over the network. The upside to using something like XML serialization is that you won't be limited to the types of clients that can connect to your server and consume your service.
You have to choose what fits your needs the best.
...play around with the different options and figure out what works best for you. Hopefully you'll find something that can perform faster and more reliably than anything I've mentioned here. | As far as server design concern, I would say that you are right: although ONE-THREAD-PER-SOCKET is a simple and easy approach, it is not the way to go since it won't scale as well as other server design patterns.
I personally like the COMMUNICATION-THREADS/WORKER-THREADS approach, where a pool of a dynamic number of worker threads handle all the work generated by producer threads.
In this model, you will have a number of threads in a pool waiting for tasks that are going to be generated from another set of threads handling network I/O.
I found [UNIX Network Programming](https://rads.stackoverflow.com/amzn/click/com/0139498761) by Richard Stevens and amazing source for this kind on network programming approaches. And, despite its name, it will be very useful in windows environments as well.
Regarding the layout of the packets (you should have post a different question for this since it is a totally different question, in my opinion), there are tradeoffs when selecting TEXT vs BINARY approach.
TEXT (i.e. XML) is probably easier to parse and document, and more simple in general, while a BINARY protocol should give you better performance in terms of speed of processing and size of network packets, but you will have to deal with more complicated issues such as ENDIANNES of the words and stuff like that.
Hope it helps. | Question about server socket programming model | [
"",
"c++",
"sockets",
""
] |
I have created C# application, which creates a image file on Desktop. It works fine on XP and Vista (admin account) but it fails to create image file on Desktop in Vista (standard account).
Whether i have to include manifest file to the application to work properly?
If i add manifest, will it work on XP without any problems?
Sorry if it is lame question.
Thanks in advance. | Make sure you're using the System.Environment.SpecialFolder class to tell you where your user's Desktop really is. | Which folder are you trying to create the file in? The shared desktop folder or the user's desktop folder? Ordinary users cannot create shared desktop files.
You should be writing to the folder specified by the following Registry value:
```
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Desktop
``` | File creation fails in standard account (Vista) | [
"",
"c#",
"file",
"windows-vista",
"windows-xp",
""
] |
I am currently developing a simple application in python that connects to a server. At the moment, it's single-threaded (as multithreading is not currently required).
However I would like - for debugging, maintenance and such to also be able to have a REPL via stdin.
How do I go about that, if possible? Will I need to keep anything in mind? Will I have to make a separate thread for it? | Maybe [this](https://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application) question could help. You can modify it a bit to create a customized REPL. | You either need to go non-blocking or use a thread.
I would personally use Twisted for concurrency, which also offers a REPL-protocol which is easy to integrate. | Python REPL for a running process | [
"",
"python",
"read-eval-print-loop",
""
] |
I'm wanting to store hashed passwords in MySQL, I'm using PHP:
```
<?php
$salt = '!£$%^&*()#';
$username = 'abc';
$password = '123';
$hash = hash('sha1', $username . $salt . $password, true);
?>
```
The true parameter in hash() will return the value as raw binary data. But I don't understand what this means exactly. How should it be correctly stored in MySQL? | I found the solution.
Normal (hexed) hashes of sha1() are always CHAR(40) in length. When you return a hash as raw binary data in php, it will return a string as CHAR(20), saving 50% database space yet representing the exact same value. This is because 2 characters of hex can be compressed into 1 character, thus halving it the space needed.
So store the password as CHAR(20) and use the \*\_bin collation. | The last parameter of the hash() function indicates how the hash value is returned:
* Either as raw binary data. This way
you get the direct output of the
specific hash function you're using, in this case sha1.
* Or as a string containing a hexadecimal representation of the same raw binary data.
They are both the same and differ only in their representation. Unless you have a good reason, I would suggest that you use the hexadecimal representation and store it as a string in your database. This way it is much easier to debug problems, since you could easily print out the hexadecimal hash value. | How should 'raw binary data' hashes be stored in MySQL? | [
"",
"php",
"mysql",
"hash",
""
] |
### Background
We have a project that was started in .NET 1.1, moved to .NET 2.0, and recently moved again to .NET 3.5. The project is extremely data-driven and utilizes XML for many of its data files. Some of these XML files are quite large and I would like to take the opportunity I currently have to improve the application's interaction with them. If possible, I want to avoid having to hold them entirely in memory at all times, but on the other hand, I want to make accessing their data fast.
The current setup uses [`XmlDocument`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmldocument?redirectedfrom=MSDN&view=net-5.0) and [`XPathDocument`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xpath.xpathdocument?redirectedfrom=MSDN&view=net-5.0) (depending on when it was written and by whom). The data is looked up when first requested and cached in an internal data structure (rather than as XML, which would take up more memory in most scenarios). In the past, this was a nice model as it had fast access times and low memory footprint (or at least, satisfactory memory footprint). Now, however, there is a feature that queries a large proportion of the information in one go, rather than the nicely spread out requests we previously had. This causes the XML loading, validation, and parsing to be a visible bottleneck in performance.
### Question
Given a large XML file, what is the most efficient and responsive way to query its contents (such as, "does element A with id=B exist?") repeatedly without having the XML in memory?
Note that the data itself can be in memory, just not in its more bloated XML form if we can help it. In the worst case, we could accept a single file being loaded into memory to be parsed and then unloaded again to free resources, but I'd like to avoid that if at all possible.
Considering that we're already caching data where we can, this question could also be read as "which is faster and uses less memory; [`XmlDocument`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmldocument?redirectedfrom=MSDN&view=net-5.0), [`XPathDocument`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xpath.xpathdocument?redirectedfrom=MSDN&view=net-5.0), parsing based on [`XmlReader`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlreader?redirectedfrom=MSDN&view=net-5.0), or [`XDocument`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument?redirectedfrom=MSDN&view=net-5.0)/[LINQ-to-XML](https://learn.microsoft.com/en-us/previous-versions/bb387098(v=vs.140)?redirectedfrom=MSDN)?"
*Edit:* Even simpler, can we randomly access the XML on disk without reading in the entire file at once?
### Example
An XML file has some records:
```
<MyXml>
<Record id='1'/>
<Record id='2'/>
<Record id='3'/>
</MyXml>
```
Our user interface wants to know if a record exists with an id of 3. We want to find out without having to parse and load every record in the file, if we can. So, if it is in our cache, there's no XML interaction, if it isn't, we can just load that record into the cache and respond to the request.
### Goal
To have a scalable, fast way of querying and caching XML data files so that our user interface is responsive without resorting to multiple threads or the long-term retention of entire XML files in memory.
I realize that there may well be a blog or MSDN article on this somewhere and I will be continuing to Google after I've posted this question, but if anyone has some data that might help, or some examples of when one approach is better or faster than another, that would be great.
---
**Update**
[The XMLTeam published a blog today](https://web.archive.org/web/20160119095609/http://blogs.msdn.com/b/xmlteam/archive/2011/09/14/effective-xml-part-1-choose-the-right-api.aspx) that gives great advice on when to use the various XML APIs in .NET. It looks like something based on `XmlReader` and `IEnumerable` would be my best option for the scenario I gave here. | With XML I only know of two ways
XMLReader -> stream the large XML data in
or use the XML DOM object model and read the entire XML in at once into memory.
If the XML is big, we have XML files in 80 MB range and up, reading the XML into memory is a performance hit. There is no real way to "merge" the two ways of dealing with XML documents. Sorry. | I ran across this white paper a while ago when I was trying to stream XML: [API-based XML streaming with FLWOR power and functional updates](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.95.7182&rep=rep1&type=pdf) The paper tries to work with in memory XML but leverage LINQ accessing.
Maybe someone will find it interesting. | Optimizing XML in C# | [
"",
"c#",
"xml",
".net-3.5",
"linq-to-xml",
""
] |
Imagine the following code:
```
class foreach_convert
{
public static void method2()
{
List<IComparable> x = new List<IComparable>();
x.Add(5);
foreach (string s in x)
{
//InvalidCastException in runtime
}
}
}
```
I wonder, why is this foreach behavior so... not C#-like?
What happens here is an implicit cast to a subclass, which is error-prone and seems to be banned in every other place in the language. Or am I not right?
P.S. The reason I'm asking is that I had a bug in the similar code in my project, where I used to iterate through a custom Collection from an external library, which was called like `SomeTypeCollection`, but in fact provided a collection of base type items and could have contained items of `SomeOtherType`. My fault, but still neither the language, nor the compiler provided any explicit hints/warnings, which is quite unusual for C#... | Think back to before generics... `foreach` had to cast so that you could do sensible things like:
```
foreach (string x in names)
{
// ...
}
```
instead of:
```
foreach (object tmp in names)
{
string x = (string) tmp;
// ...
}
```
The latter is just icky, IMO. Providing an implicit cast is unlike the rest of the language, but makes it much easier to use in the vast majority of cases.
I *suspect* that if C# had had generics *and* extension methods to start with (so we could use [`OfType`](http://msdn.microsoft.com/en-us/library/bb360913.aspx) and [`Cast`](http://msdn.microsoft.com/en-us/library/bb341406.aspx)) that `foreach` wouldn't be specified in quite the same way.
Note that there's even more oddness in `foreach`: the type doesn't have to implement `IEnumerable` at all. So long as it has a `GetEnumerator` method which returns something which in turn has `MoveNext()` and `Current`, the C# compiler is happy. This meant you could implement a "strongly typed iterator" (to avoid boxing) before generics. | With C# 3 I'm using **var** - so I get the compiler warnings. | Foreach can throw an InvalidCastException? | [
"",
"c#",
"foreach",
"language-design",
""
] |
I'm not having any luck finding one. | [Apache Ki](http://incubator.apache.org/ki/) (formerly known as [JSecurity](http://www.jsecurity.org/)) could be what you're looking for if you're not afraid of doing some things yourself. I've personally created a completely transparent, annotation based, per-page web application security model (relying on both user roles/permissions and group roles) with it and it's capable of a lot more than just that. | There's [Spring Security](http://www.acegisecurity.org/) (previously known as Acegi).
Haven't used it myself, but I've heard good things about it. Most effective when used with the rest of Spring, obviously, but I think you *can* use it in a general way. | Can anyone recommend an off the shelf ACL Java lib? | [
"",
"java",
"acl",
""
] |
I'm making a Yahtzee game and I need a way to calculate a small straight (a sequence of 4 numbers in order). So valid ones would be: 1,2,3,4 | 2,3,4,5 | 3,4,5,6.
I have an array of 5 numbers and I need to figure out if one of those 3 combinations is in that array.
For those not familiar with Yahtzee, there are 5 dice (the five numbers in the array) that can be from 1-6. | ```
function isStraight($hand) {
$straights = array(range(1, 4), range(2, 5), range(3, 6));
foreach($straights as $solution) {
if(array_intersect($solution, $hand) == $solution) {
return $solution;
}
}
return false;
}
$hand = array(1,5,2,4,3);
var_dump(isStraight($hand));
```
Not sure about the rules of the game, but that should do it.
The function is going to return the first solution it finds - in this case `[1,2,3,4]`. It is going to return the boolean `false` if it doesn't find any straights in the hand. Hope this helps. | Perhaps something like this: --- warning --- air coding
```
function findSequenceLength(array $array)
{
// Filter duplicates out - and sort the array.
$sorted = array_unique($array, SORT_NUMERIC);
$lastValue = null;
$thisSeq = 0;
$longestSeq = 0;
foreach ($sorted as $value)
{
if ( ( $lastValue !== null ) && $value == $lastValue + 1)
{
// our value is exactly one above the last entry
// increase the counter
$thisSeq++;
} else {
// sequence ended - save the value
$longestSeq = max($longestSeq, $thisSeq);
$thisSeq = 1;
}
$lastValue = $value;
}
return max($longestSeq, $thisSeq);
}
$sequence = array(1,2,4,5,4,6);
echo findSequenceLength($sequence); // should return 3 [4,5,6]
```
You could then test that the "sequence length" is >= 4 to test for your "small straight" | Finding a sequence of numbers in an array | [
"",
"php",
""
] |
I have a file containing roughly all the words in English (~60k words, ~500k characters). I want to test whether a certain word I receive as input is "in English" (i.e. if this exact word is in the list).
What would be the most efficient way to do this in Python?
The trivial solution is to load the file into a list and check whether the word is in that list. The list can be sorted, which I believe will shrink the complexity to O(logn). However I'm not sure about how Python implements searching through lists, and whether there's a performance penalty if such a large list is in memory. Can I "abuse" the fact I can put a cap on the length of words? (e.g. say the longest one is 15 characters long).
Please note I run the application on a machine with lots of memory, so I care less for memory consumption than for speed and CPU utilization. | The python [Set](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset) is what you should try.
> A set object is an unordered collection of distinct hashable objects. Common uses include **membership testing**, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. | Sample Python code:
```
L = ['foo', 'bar', 'baz'] # Your list
s = set(L) # Converted to Set
print 'foo' in s # True
print 'blah' in s # False
``` | Most Efficient Way to Find Whether a Large List Contains a Specific String | [
"",
"python",
"string",
"list",
"performance",
""
] |
In C# 3.0, I'm liking this style:
```
// Write the numbers 1 thru 7
foreach (int index in Enumerable.Range( 1, 7 ))
{
Console.WriteLine(index);
}
```
over the traditional `for` loop:
```
// Write the numbers 1 thru 7
for (int index = 1; index <= 7; index++)
{
Console.WriteLine( index );
}
```
Assuming 'n' is small so performance is not an issue, does anyone object to the new style over the traditional style? | I find the latter's "minimum-to-maximum" format a lot clearer than `Range`'s "minimum-count" style for this purpose. Also, I don't think it's really a good practice to make a change like this from the norm that is not faster, not shorter, not more familiar, and not obviously clearer.
That said, I'm not against the idea in general. If you came up to me with syntax that looked something like `foreach (int x from 1 to 8)` then I'd probably agree that that would be an improvement over a `for` loop. However, `Enumerable.Range` is pretty clunky. | This is just for fun. (I'd just use the standard "`for (int i = 1; i <= 10; i++)`" loop format myself.)
```
foreach (int i in 1.To(10))
{
Console.WriteLine(i); // 1,2,3,4,5,6,7,8,9,10
}
// ...
public static IEnumerable<int> To(this int from, int to)
{
if (from < to)
{
while (from <= to)
{
yield return from++;
}
}
else
{
while (from >= to)
{
yield return from--;
}
}
}
```
You could also add a `Step` extension method too:
```
foreach (int i in 5.To(-9).Step(2))
{
Console.WriteLine(i); // 5,3,1,-1,-3,-5,-7,-9
}
// ...
public static IEnumerable<T> Step<T>(this IEnumerable<T> source, int step)
{
if (step == 0)
{
throw new ArgumentOutOfRangeException("step", "Param cannot be zero.");
}
return source.Where((x, i) => (i % step) == 0);
}
``` | Thoughts on foreach with Enumerable.Range vs traditional for loop | [
"",
"c#",
".net",
"for-loop",
"foreach",
"c#-3.0",
""
] |
I'm playing around with retrieving the MAC address from the NIC - there are a variety of ways to get it, this article covers the most common:
<http://www.codeguru.com/Cpp/I-N/network/networkinformation/article.php/c5451>
I'm currently using the GetAdaptersInfo method, which seems the most bulletproof, but if the MAC address has been set via the registry:
<http://www.mydigitallife.info/2008/06/30/how-to-change-or-spoof-mac-address-in-windows-xp-vista-server-20032008-mac-os-x-unix-and-linux/>
Then it reports the MAC address that it has been changed to. The only way I've found to actually get the true MAC is to remove the registry entry, restart the NIC, get the MAC via GetAdaptersInfo, then replace the registry entry, and restart the NIC. While it gets the job done, it's hardly transparent to the user.
Is there any other methods that anyone is familiar with, that will return the hardware MAC regardless of what the registry is set to? Ideally I'd like a solution that works on XP on up.
Thanks in advance! | My guess is that in the linked CodeGuru article, the Miniport solution is likely to overcome the problem you describe, albeit painful to implement. The reason I think this is that I have used the GetAdaptersInfo solution myself in the past, and noticed that the MAC address will change without reboot when an adapter is added, e.g. a Bluetooth adapter providing PAN services.
Perhaps rather than rebooting after changing the registry setting, you could try stopping and restarting the relevent network services. You could easily check this manually prior to looking for a programmatic solution.
(n.b. the above is all guess work. If you try it and it works, perhaps add a post for those trying to do the same in future). | You can use WMI to enumerate the [Win32\_NetworkAdapter](http://msdn.microsoft.com/en-us/library/aa394216%28v=vs.85%29.aspx) instances and look at the MACAddress property. The main issue with this technique is finding the appropriate adapter instance if you have multiple active adapters installed, e.g. on a laptop which also has a wireless connection. | How to get hardware MAC address on Windows | [
"",
"c++",
"winapi",
"networking",
"ndis",
""
] |
```
$('#global').show("explode", { number: 50}, 2000);
```
I tried this code but it doesn't seem to work properly.
It looks like it's limited i never got more than 8/10 exploding blocks.
Are there a maximum ?
Any ideas ?
the explode effect is a native effect from the jquery-ui | A jQuery [Effects Cheat sheet](http://jn.orz.hm/jquery/ui_effect.html)
shows to uses **pieces** instead of number | I think the option you need to pass in is 'pieces', not 'number'.
```
$('#global').show("explode", { pieces: 50}, 2000);
``` | Does the 'explode' effect has a maximum for the number of exploded blocks? | [
"",
"javascript",
"jquery",
"jquery-ui",
""
] |
JSLint (with the onevar flag turned on) is flagging some javascript code that I have with the following:
```
Problem at line 5 character 15: Too many var statements.
```
I am happy to fix these errors, but I'd like to know, am I doing it for performance or because it is just a bad practice and has a greater potential to introduce bugs in my javascript code. What is the reason behind the onevar flag?
I did look at the JSLint docs for the [var keyword](http://www.jslint.com/lint.html#var) but it doesn't specifically talk about why multiple var statements in the same function are bad.
Here is an attempt at an example. Explain how the code will benefit from only having 1 var statement:
```
function Test(arg) {
var x = arg + 1,
y = cache.GetItem('xyz');
if (y !== null) {
// This is what would cause the warning in JSLint
var request = ajaxPost(/* Parameters here */);
}
}
``` | Javascript does not have block scope. In other languages with it (like c), if you declare a variable in the if statement, you can not access it outside of it, but in javascript you can. The author of JSLint believes it is a bad practice, since you (or other readers) might get confused and think that you can no longer access the variable, but you actually can. Therefore, you should declare all your variables at the top of the function. | The official reason [is here](http://www.jslint.com/lint.html#scope), by Douglas Crockford.
To quote:
> In many languages, a block introduces a scope. Variables introduced in
> a block are not visible outside of the block.
>
> In JavaScript, blocks do not introduce a scope. There is only
> function-scope. A variable introduced anywhere in a function is
> visible everywhere in the function. JavaScript's blocks confuse
> experienced programmers and lead to errors because the familiar syntax
> makes a false promise.
>
> JSLint expects blocks with function, if, switch, while, for, do, and
> try statements and nowhere else.
>
> In languages with block scope, it is usually recommended that
> variables be declared at the site of first use. But because JavaScript
> does not have block scope, it is wiser to declare all of a function's
> variables at the top of the function. It is recommended that a single
> var statement be used per function. This can be declined with the vars
> option. | What is the reason behind JSLint saying there are "too many var statements" | [
"",
"javascript",
"refactoring",
"jslint",
""
] |
I'm trying to use Prism and the MVVM pattern to develop an application. In my UI, I have a previous and next button defined. For use in a calling web services, I've defined an enum that will tell me the direction I need to traverse. So, in this instance, the buttons map directly to an enum value. The enum definition is very simple and is as follows:
```
namespace CodeExpert.Book.Helpers
{
public enum BookDirection { Previous = -1, NotSet = 0, Next = 1, }
}
```
I've defined my command and delegate in my ViewModel and assigned the propery correctly. The relevant code is:
```
public DelegateCommand PreviousNextCommand { get; set; }
public IndexEntriesViewModel(GlobalVariables globalVariable, IndexEntryOperations currentOperator)
{
//a bunch of initialization code.
InitializeCommands();
}
void InitializeCommands()
{
PreviousNextCommand =
new DelegateCommand(OnPreviousNextCommandExecute);
}
private void OnPreviousNextCommandExecute(BookDirection parameter)
{
//Code to process based on BookDirection
}
```
So, based on this config, I want to pass a BookDirection enum value to the CommandParameter. I can't, however, get the XAML right for this. Here's the XAML I've tried that seems the most correct to me:
```
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="CodeExpert.Book.Views.Index"
d:DesignWidth="1024"
d:DesignHeight="768"
xmlns:helpers="clr-namespace:CodeExpert.Book.Helpers"
xmlns:command="clr-namespace:Microsoft.Practices.Composite.Presentation.Commands;assembly=Microsoft.Practices.Composite.Presentation"
xmlns:common="clr-namespace:System.Windows;assembly=System.Windows.Controls"
xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
xmlns:input="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input">
<Button x:Name="ButtonPrevious"
HorizontalAlignment="Left"
Margin="2,1,0,1"
Width="25"
Content="<"
Grid.Column="1"
Grid.Row="1"
Height="20"
command:Click.Command="{Binding Path=CurrentIndexViewModel.PreviousNextCommand}">
<command:Click.CommandParameter>
<helpers:BookDirection.Previous />
</command:Click.CommandParameter>
</Button>
</UserControl>
```
I get no intellisense for the BookDirection for the enum and get an error at design & compile time saying The type 'BookDirection' does not contain adefinition for 'Previous'. Is there no way to pass that enum, or am I simply missing something? I have it working now by setting the parameter type to `string` instead of `BookDirection`, but then I have to parse text and the code smells. I've done some Google searches and the closest thing I've come to an answer is here - [Passing an enum value as command parameter from XAML](https://stackoverflow.com/questions/359699/passing-an-enum-value-as-command-parameter-from-xaml) Unfortunately, Silverlight doesn't support the x:static binding extension, so I can't use the exact technique described in that answer.
Any help would be much appreciated. | Binding enums are really a troublesome operation, even in WPF. But there seems to be an elegant solution to it, which is available at the [`Caliburn`](http://caliburn.codeplex.com) framework.
The solution, however, is not available in the framework code, but in it's `LOB Samples`. Look for the `BindableEnum` and `BindableEnumCollection<T>` classes on the `Caliburn.Silverlight.ApplicationFramework` project.
HTH. | Just pass command parameter like simple object type. Then you can use direct cast to your enum. | Silverlight 3/Prism - Passing an enum value as a Command Parameter | [
"",
"c#",
"silverlight",
"xaml",
"enums",
"prism",
""
] |
I currently use [QtScript](http://doc.trolltech.com/4.5/qtscript.html) for scripting functionality in my C++ application, but it's rather "heavy" on the cpu. When a thread evaluates all the scripts in a loop the cpu usage increases to 90%-100%. Even when i put it to sleep for 1 msec every 5 scripts it stays above 75% cpu usage.
Are there any other, easy to implement, scripting frameworks which are much more lighter than QScript?
**edit:**
I now realize this is normal behavior and not some hogging bug in QtScript. Still it's interesting to hear what kinds of (lighweight) scripting libraries are available. | Have a look at [Lua](http://www.lua.org/about.html), it's frequently used in games so the performance must be pretty good. | Well, what do you expect? Unless the script has to wait for disk or user I/O, the CPU **should** run at 100%.
Is your problem that it runs to long?
Or that your application is unresponsive?
In that case, the problem is that your script is blocking the thread where all the UI interactions run. The general solution is to block all UI input (except the "cancel script" button :)), and move the actual processing to a separate thread.
**[edit]**
Slightly different question: is the CPU at 100% while there is no script to process?
100% CPU is good and healthy, if you are processing something.
The CPU is always busy, the current thread always consumes 100% of the core it is running on. "0% CPU activity" actually means all cycles are spent in an system idle thread (that belongs to the "system idle process" you see in task manager).
As an simplistic example: if you have one application thread active, and CPU usage is 40%, and your task manager update interval is 1s, 400ms of CPU time was spent on the application, and 600ms on the idle thread. | lightweight C++ scripting library | [
"",
"c++",
"qt",
"scripting",
""
] |
In the following setter, I can access the property backing field directly or through the getter. Is there a scenario when one would be preferred over the other?
```
public string Name {
get { return this.name; }
set {
if (value == this.name) return;
// or
// if (value == this.Name) return;
// ?
this.name = value;
NameChanged.Raise(this, this.name);
// or
// NameChanged.Raise(this, this.Name);
// ?
}
}
```
There is a related question. How would you initialize properties in the c-tor?
```
public MyClass(string name) { this.name = name; }
// or
public MyClass(string name) { Name = name; }
```
I use `this.name`, for the reason that at construction time the instance might be in an invalid/unstable/undefined state, so Name-setter validation might falsely fail. Any other opinions? | My personal opinion is to preferably use the property unless that results in the incorrect behaviour. What it comes down to is that using the property indicates a commitment to the semantics of your class and the design of your API.
Obviously sometimes there are going to be exceptions to this rule... sometimes the 'property' means something distinct to the value of the backing field (in your example, the property raises an event). If the internal use explicitly needs to avoid the semantics of the property (you don't want the event to fire), then the backing field is the correct 'second choice'.
On an unrelated note, for better or for worse, the Microsoft [StyleCop](http://code.msdn.microsoft.com/sourceanalysis) application specifically prefers the convention of accessing private fields with the 'this' prefix to differentiate access of local variables and class fields (rather than prefixing such as '`_`' or '`m_`' or variants thereof... which ironically are the convention used in legacy .NET framework code). | I would say that "Name = name" is more correct, because if you were to declare the "name" property as virtual then someone could override your property behaviour, but your constructor would still bypass their logic.
Additionally properties can encapsulate behaviour such as raising change events, which you shouldn't bypass. No user can add a handler to your event until you have constructed the object. Therefore if you make a setting in a constructor where you have external events, it won't be raised.
EDIT
See the comments below for why virtual was a bad example. | What is the proper way to access a value internally? | [
"",
"c#",
""
] |
I'm looking to tokenize Java/Javascript-like expressions in Javascript code. My input will be a string containing the expression, and the output needs to be an array of tokens.
What's the best practice for doing something like this? Do I need to iterate the string or is there a regular expression that will do this for me?
I need this to be able to support:
* Number and String literals (single and double quoted, with quote escaping)
* Basic mathematical and boolean operators and comparators (+, -, \*, /, !, and, not, <, >, etc)
* Dot and bracket notation for object access with recursion (foo.bar, foo['bar'], foo[2][prop])
* Parenthesis with nesting
* Ternary operator (foo ? bar : 'baz')
* Function calls (foo(bar))
I specifically want to avoid using `eval()` or anything of the sort for security reasons. Besides, `eval()` wouldn't tokenize the expression for me anyway. | Learn to write a recursive-descent parser. Once you understand the concepts, you can do it in any language: Java, C++, JavaScript, SystemVerilog, ... whatever. If you can handle strings then you can parse.
Recursive-descent parsing is a basic technique for parsing that can easily be coded by hand. This is useful if you don't have access to (or don't want to fool with) a parser generator.
In a recursive-descent parser, every rule in your grammar is translated to a procedure that parses the rule. If you need to refer to other rules, then you do so by calling them - they're just procedures.
A simple example: expressions involving numbers, addition and multiplication (this illustrates operator precedence). First, the grammar:
```
expr ::= term
| expr "+" term
term ::= factor
| term "*" factor
factor ::= /[0-9/+ (I'm using a regexp here)
```
Now to write the parser (which includes the lexer; with recursive-descent you can throw the two together). I've never used JavaScript, so let's try this in (my rusty) Java:
```
class Parser {
string str;
int idx; // index into string
Node parseExpr() throws ParseException
{
Node op1 = parseTerm();
Node op2;
while (idx < str.size() && str.charAt(idx) == '+') {
idx++;
op2 = parseTerm();
op1 = new AddNode(op1, op2);
}
return op1;
}
Node parseTerm() throws ParseException
{
Node op1 = parseFactor();
Node op2;
while (idx < str.size() && str.charAt(idx) == '*') {
idx++;
op2 = parseFactor();
op1 = new MultNode(op1, op2);
}
return op1;
}
Node parseFactor() throws ParseException
{
StringBuffer sb = new StringBuffer();
int old_idx = idx;
while (idx < str.size() && str.charAt(idx) >= '0' && str.charAt(idx) <= '9') {
sb.append(str.charAt(idx));
idx++;
}
if (idx == old_idx) {
throw new ParseException();
}
return new NumberNode(sb.toString());
}
}
```
You can see how each grammar rule translates into a procedure. I haven't tested this; that's an exercise for the reader.
You also need to worry about error detection. A real-world compiler needs to recover from parse errors to try to parse the remainder of its input. A one-line expression parser like this one does not need to try recovery at all, but it does need to determine that a parse error exists and flag it. The easiest way to do this if your language allows it is to throw an exception, and catch it at the entry point to the parser. I haven't detected all possible parse errors in my example above.
For more info, look up "LL parser" and "Recursive descent parser" in Wikipedia. As I said at the beginning, if you can understand the concepts (and they're simple compared to the concepts behind LALR(1) state machine configuration closures) then you are empowered to write a parser for small tasks in any language, as long as you have some rudimentary string capability. Enjoy the power. | For simple lexers where speed isn't critical, I usually write a regex for each kind of token and repeatedly attempt to match each one in turn with the start of the input. (Make sure you don't wind up with an O(n^2) algorithm!) A tool like lex will yield a more efficient lexer because it combines the regexes into one state machine. | Expression parsing: how to tokenize | [
"",
"javascript",
"regex",
"parsing",
"expression",
"lexical-analysis",
""
] |
```
float f = 5.13;
double d = 5.13;
float fp = f - (float)Math.floor(f);
double dp = d - Math.floor(d);
```
Isn't there any faster way than calling an external function every time? | You could cast f to an int which would trim the fractional part. This presumes that your doubles fall within the range of an integer.
Of course, the jitter may be smart enough to optimize Math.floor to some inlined asm that'll do the floor, which may be faster than the cast to int then cast back to float.
Have you actually measured and verified that the performance of Math.floor is affecting your program? If you haven't, you shouldn't bother with this level of micro-optimization until you know that is a problem, and then measure the performance of this alternative against the original code.
EDIT: This does appear faster. The following code takes 717ms when using Math.Floor(), and 172 ms for the int casting code on my machine, in release mode. But again, I doubt the perf improvement really matters - to get this to be measurable I had to do 100m iterations. Also, I find Math.Floor() to be much more readable and obvious what the intent is, and a future CLR could emit more optimal code for Math.Floor and beat out this approach easily.
```
private static double Floor1Test()
{
// Keep track of results in total so ops aren't optimized away.
double total = 0;
for (int i = 0; i < 100000000; i++)
{
float f = 5.13f;
double d = 5.13;
float fp = f - (float)Math.Floor(f);
double dp = d - (float)Math.Floor(d);
total = fp + dp;
}
return total;
}
private static double Floor2Test()
{
// Keep track of total so ops aren't optimized away.
double total = 0;
for (int i = 0; i < 100000000; i++)
{
float f = 5.13f;
double d = 5.13;
float fp = f - (int)(f);
double dp = d - (int)(d);
total = fp + dp;
}
return total;
}
static void Main(string[] args)
{
System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
// Unused run first, guarantee code is JIT'd.
timer.Start();
Floor1Test();
Floor2Test();
timer.Stop();
timer.Reset();
timer.Start();
Floor1Test();
timer.Stop();
long floor1time = timer.ElapsedMilliseconds;
timer.Reset();
timer.Start();
Floor2Test();
timer.Stop();
long floor2time = timer.ElapsedMilliseconds;
Console.WriteLine("Floor 1 - {0} ms", floor1time);
Console.WriteLine("Floor 2 - {0} ms", floor2time);
}
}
``` | "External function"?
System.Math is built into mscorlib!
This is actually the fastest way to do this. | What's the fastest way to get the partial value of a number in C#? | [
"",
"c#",
"floating-point",
""
] |
Is there an existing good example, or how should one approach creating a basic Template system (thinking MVC) that supports "Template Inheritance" in PHP5?
For an example of what I define as Template Inheritance, refer to the Django (a Python framework for web development) Templates documentation: <http://docs.djangoproject.com/en/dev/topics/templates/#id1>
I especially like the idea of PHP itself being the "template language", though it's not necessarily a requirement.
If listing existing solutions that implement "Template Inheritance", please try to form answers as individual systems, for the benefit of 'popular vote'. | The PHP language itself was designed for just these tasks, [unfortunately] it
became capable of more and more over time and people who had started out with
that simple syntax started implementing more and more complex tasks with that strangely evolved language.
I think what you mean with template inheritance is best expressed as dynamic
file inclusion in PHP, as simple as
```
<? require $content ?>
``` | Sorry to dig up an old thread, but I just released a library that does template inheritance in native PHP. Very inspired by Django. Please check it out and let me know what you think:
"PHP Template Inheritance"
<http://arshaw.com/phpti/> | How to implement Template Inheritance (like Django?) in PHP5 | [
"",
"php",
"model-view-controller",
"templates",
"template-inheritance",
""
] |
I have a "Tickets" table with somewhat following structure (removed unnecessary columns)
```
int | string | int |
ID | Window | Count |
------------------------
0 | Internet | 10 |
1 | Phone | 20 |
2 | Fax | 15 |
3 | Fax | 10 |
4 | Internet | 5 |
. | . | . |
. | . | . |
```
And I have mapped this table to a class "Ticket". So I can get all records like this:
```
var tickets = from t in db.Tickets
select t;
```
Now I need to get the list of unique window names in the table. For above table, list would look something like:
* Internet
* Phone
* Fax
Is there anyway to create this list without fetching all records and iterating over them?
I am using SQL Server 2008 express edition.
EDIT:
Thanks for the answers guys it solved the above problem. Just being greedy but is there any way to *also* get the total of count for each window. For example:
* Internet = 15
* Phone = 25
* Fax = 20 | How about:
```
var tickets = db.Tickets.Select(t => t.Window).Distinct();
```
I prefer to only use query expressions when I'm doing more than one operation, but if you like them the equivalent is:
```
var tickets = (from t in db.Tickets
select t.Window).Distinct();
```
To get the counts, you need to group:
```
var tickets = from t in db.Tickets
group t by t.Window into grouped
select new { Window=grouped.Key,
Total=grouped.Sum(x => x.Count) };
foreach (var entry in tickets)
{
Console.WriteLine("{0}: {1}", entry.Window, entry.Total);
}
```
Note that this should all end up being performed at the database side - examine the SQL query to check this. | ```
var query2 = from ticket in db.tickets
group window by ticket.Window into result
select new
{
Name = result.Window,
Sum = result.Sum(i => i.Count)
};
``` | List of unique strings in database table using Linq? | [
"",
"c#",
"sql-server",
"linq",
""
] |
I have an array of Castle windsor registration components of type IRegistration[]
In this case `ComponentRegistration<T> : IRegistration`
For each element in my array,
if it can be upcast to ComponentRegistration<> I would like to upcast it back to `ComponentRegistration<T>` and process it. How exactly would I do this?
I got as far as
```
foreach (var r in registrations) {
if(typeof(ComponentRegistration<>).IsAssignableFrom(r.GetType())) {
var cr = CAST r SOMEHOW
DoStuff(cr);
}
``` | Surely if you've got an `IRegistration[]` then you're *downcasting* rather than upcasting.
However, to get to your problem, what does `DoStuff()` look like? Does it need to know the type argument for `ComponentRegistration<T>`? If not, you might be best creating a non-generic base class:
```
public abstract class ComponentRegistration : IRegistration
{
// Anything in the original API which didn't use T
}
public class ComponentRegistration<T> : ComponentRegistration
{
// The bits which need T
}
```
Then you could write:
```
foreach (var r in registrations)
{
ComponentRegistration cr = r as ComponentRegistration;
if (cr != null)
{
DoStuff(cr);
}
}
```
If you really need `DoStuff` to use the generic information, you'll have to use reflection to get the appropriate type and invoke it. Avoid if possible :)
EDIT: Okay, here's an example of the reflection nastiness. It doesn't try to account for generic interfaces, as that gets even hairier.
```
using System;
using System.Reflection;
class Test
{
static void Main()
{
Delegate[] delegates = new Delegate[]
{
(Action<int>) (x => Console.WriteLine("int={0}", x)),
(Action<string>) (x => Console.WriteLine("string={0}", x)),
(Func<int, int>) (x => x + 1)
};
MethodInfo genericPerformAction = typeof(Test).GetMethod
("PerformAction");
foreach (Delegate del in delegates)
{
Type t = DiscoverTypeArgument(del, typeof(Action<>));
if (t == null)
{
// Wrong type (e.g. the Func in the array)
continue;
}
MethodInfo concreteMethod = genericPerformAction.MakeGenericMethod
(new[] { t } );
concreteMethod.Invoke(null, new object[] { del });
}
}
public static void PerformAction<T>(Action<T> action)
{
Console.WriteLine("Performing action with type {0}", typeof(T).Name);
action(default(T));
}
/// <summary>
/// Discovers the type argument for an object based on a generic
/// class which may be somewhere in its class hierarchy. The generic
/// type must have exactly one type parameter.
/// </summary>
/// <returns>
/// The type argument, or null if the object wasn't in
/// the right hierarchy.
/// </returns>
static Type DiscoverTypeArgument(object o, Type genericType)
{
if (o == null || genericType == null)
{
throw new ArgumentNullException();
}
if (genericType.IsInterface ||
!genericType.IsGenericTypeDefinition ||
genericType.GetGenericArguments().Length != 1)
{
throw new ArgumentException("Bad type");
}
Type objectType = o.GetType();
while (objectType != null)
{
if (objectType.IsGenericType &&
objectType.GetGenericTypeDefinition() == genericType)
{
return objectType.GetGenericArguments()[0];
}
objectType = objectType.BaseType;
}
return null;
}
}
```
EDIT: Note that *if* you're in a situation where *all* the members are derived from the relevant class, and *if* you're using C# 4, you can use dynamic binding:
```
using System;
using System.Reflection;
class Test
{
static void Main()
{
Delegate[] delegates = new Delegate[]
{
(Action<int>) (x => Console.WriteLine("int={0}", x)),
(Action<string>) (x => Console.WriteLine("string={0}", x)),
(Action<long>) (x => Console.WriteLine("long={0}", x)),
};
foreach (dynamic del in delegates)
{
// Yay for dynamic binding
PerformAction(del);
}
}
public static void PerformAction<T>(Action<T> action)
{
Console.WriteLine("Performing action with type {0}", typeof(T).Name);
action(default(T));
}
}
```
Unfortunately I don't know of any way of testing whether it's going to manage to bind to the method successfully without just trying it and catching the relevant exception (which would be grim). Maybe Eric will be able to tell us :) | Unfortunately you cannot do this without either
1. Having a non-generic form of ComponentRegistration
2. Knowing T
3. Using a reflection hack
**EDIT** the reflection hack
Essentially you'll need to use reflection to grab the runtime type. Inspect the type to grab the generic T in ComponentRegistration. Then use that T to instantiate an instance of method DoStuff and pass in the object as a parameter. | How to up-cast to a generic object? | [
"",
"c#",
"generics",
"casting",
""
] |
Current code only replace the spaces to dash (-)
```
$url = str_replace(' ','-',$url);
```
I want only letters, numbers and dash (-) allowed on the URL.
Let me know the tricks. | Do you want this for generating [slug](http://www.google.com/search?q=url+slug)?
Then you can do something like this:
```
$slugified = preg_replace('/[^-a-z0-9]+/i', '-', strtolower(trim($url)));
```
It will strip leading and trailing whitespace first, convert the string to lowercase, then replace all non-word characters (not a-z, 0-9 or -) with a single `-`
**A Beautiful \*# Day** will become `a-beautiful-day`
Remove `strtolower()` if you don't mind uppercase letters in the slug. | To generate slugs from any string (including strings with crazy UTF-8 characters), I use the following (taken from the WordPress source code). I realise it requires a little more code than the other answers posted here, but this is by far the most robust and complete solution to generating slugs automatically.
First, we need a `remove_accents()` function to convert all accent characters to ASCII characters, e.g. turn `á` into `a`.
```
/**
* Converts all accent characters to ASCII characters.
*
* If there are no accent characters, then the string given is just returned.
*
* @param string $string Text that might have accent characters
* @return string Filtered string with replaced "nice" characters.
*/
function remove_accents($string) {
if (!preg_match('/[\x80-\xff]/', $string))
return $string;
if (seems_utf8($string)) {
$chars = array(
// Decompositions for Latin-1 Supplement
chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
chr(195).chr(191) => 'y',
// Decompositions for Latin Extended-A
chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
// Euro Sign
chr(226).chr(130).chr(172) => 'E',
// GBP (Pound) Sign
chr(194).chr(163) => '');
$string = strtr($string, $chars);
} else {
// Assume ISO-8859-1 if not UTF-8
$chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
.chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
.chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
.chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
.chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
.chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
.chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
.chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
.chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
.chr(252).chr(253).chr(255);
$chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
$string = strtr($string, $chars['in'], $chars['out']);
$double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
$double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
$string = str_replace($double_chars['in'], $double_chars['out'], $string);
}
return $string;
}
```
The following function, `seems_utf8()`, will check if a string is UTF-8 encoded.
```
/**
* Checks to see if a string is utf8 encoded.
*
* @author bmorel at ssi dot fr
*
* @param string $Str The string to be checked
* @return bool True if $Str fits a UTF-8 model, false otherwise.
*/
function seems_utf8($Str) { # by bmorel at ssi dot fr
$length = strlen($Str);
for ($i = 0; $i < $length; $i++) {
if (ord($Str[$i]) < 0x80) continue; # 0bbbbbbb
elseif ((ord($Str[$i]) & 0xE0) == 0xC0) $n = 1; # 110bbbbb
elseif ((ord($Str[$i]) & 0xF0) == 0xE0) $n = 2; # 1110bbbb
elseif ((ord($Str[$i]) & 0xF8) == 0xF0) $n = 3; # 11110bbb
elseif ((ord($Str[$i]) & 0xFC) == 0xF8) $n = 4; # 111110bb
elseif ((ord($Str[$i]) & 0xFE) == 0xFC) $n = 5; # 1111110b
else return false; # Does not match any model
for ($j = 0; $j < $n; $j++) { # n bytes matching 10bbbbbb follow ?
if ((++$i == $length) || ((ord($Str[$i]) & 0xC0) != 0x80))
return false;
}
}
return true;
}
```
The `utf8_uri_encode()` function encodes the Unicode values to be used in the slug.
```
/**
* Encode the Unicode values to be used in the URI.
*
* @param string $utf8_string
* @param int $length Max length of the string
* @return string String with Unicode encoded for URI.
*/
function utf8_uri_encode($utf8_string, $length = 0) {
$unicode = '';
$values = array();
$num_octets = 1;
$unicode_length = 0;
$string_length = strlen($utf8_string);
for ($i = 0; $i < $string_length; $i++) {
$value = ord($utf8_string[$i]);
if ($value < 128) {
if ($length && ($unicode_length >= $length))
break;
$unicode .= chr($value);
$unicode_length++;
} else {
if (count($values) == 0) $num_octets = ($value < 224) ? 2 : 3;
$values[] = $value;
if ($length && ($unicode_length + ($num_octets * 3)) > $length)
break;
if (count( $values ) == $num_octets) {
if ($num_octets == 3) {
$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
$unicode_length += 9;
} else {
$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
$unicode_length += 6;
}
$values = array();
$num_octets = 1;
}
}
}
return $unicode;
}
```
Finally, we can declare the `slug()` function, which will generate a slug from any UTF-8 string:
```
/**
* Sanitizes title, replacing whitespace with dashes.
*
* Limits the output to alphanumeric characters, underscore (_) and dash (-).
* Whitespace becomes a dash.
*
* @param string $title The title to be sanitized.
* @return string The sanitized title.
*/
function slug($title) {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
$title = remove_accents($title);
if (seems_utf8($title)) {
if (function_exists('mb_strtolower')) {
$title = mb_strtolower($title, 'UTF-8');
}
$title = utf8_uri_encode($title, 200);
}
$title = strtolower($title);
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
}
```
After this, you can simply use the `slug()` function to *sluggify* anything.
```
<?php
// The following line of code would echo 'internationalization-is-awesome'
echo slug('Iñtërnâtiônàlizætiøn is awesome');
?>
``` | str_replace | [
"",
"php",
"regex",
"url",
"slug",
""
] |
Is it possible to write in C# method in such a way that when I write
```
String contestId = getParameter("contestId")
```
i get contestId in string, but when I write:
```
int contestId = getParameter("contestId")
```
i get contestId parsed to integer?
This is only simple example showing what i try to achieve. | Nope it's not possible to overload methods solely based on their return type. You could, however, introduce a generic parameter:
```
T getParameter<T>(string input) {
// ... do stuff based on T ...
}
```
And if you were using C# 3.0 you could use this method as:
```
var str = getParameter<string>("contestid");
var integer = getParameter<int>("contestid");
```
thus saying the actual type only once. | One thing you *could* do is return a separate object, which has implicit conversion operators to both int and string. That would get fairly close to the behavior you're asking for.
I wouldn't do that in practice though. Implicit conversions generally cause more trouble than they're worth.
Instead, add a generic parameter, like Mehrdad showed:
```
var str = getParameter<string>("contestid");
var integer = getParameter<int>("contestid");
``` | C# - method behaviour that depends on the expected type | [
"",
"c#",
"types",
""
] |
I'm removing all warnings from our compile, and came across the following:
warning: the address of `
char\* index(const char\*, int)', will always be 'true'
for the following line of code:
```
DEBUG_MSG("Data received from Device "<<(int)_nodeId << "for" << index <<(int)msgIn.index<<".");
```
DEBUG\_MSG is one of our logging macros that the preprocessor subsitutes into a statement that takes C++ style stream operations.
index does not appear to be declared, so I'm assuming that it was supposed to read:
```
DEBUG_MSG("Data received from Device "<<(int)_nodeId << "for index " <<(int)msgIn.index<<".");
```
and index would be a function\* to the "char\* index(const char\*, int)" function in the standard library, but what does the index function do? Google seems useless as it pulls up indexes of books related to C++.
Is there something I'm missing in my interpretation of this warning? | Here's a man page for index:
<http://kernel.org/doc/man-pages/online/pages/man3/index.3.html> | Presumably, the stream operators are seeing
```
<< index
```
And attempting to automatically cast it into something that can be printed:
```
<< (bool)index
```
But index is a function, and has an address that will never be NULL. So this is equivalent to:
```
<< true
```
G++ sees that this will always be true, and issues a warning.
As for what index does, see <http://www.linuxmanpages.com/man3/index.3.php> | Compile error related to "index"- is it actually a function? | [
"",
"c++",
"gcc-warning",
""
] |
How can I make an SSH connection in Python 3.0? I want to save a file on a remote computer where I have password-less SSH set up. | I recommend calling ssh as a subprocess. It's reliable and portable.
```
import subprocess
proc = subprocess.Popen(['ssh', 'user@host', 'cat > %s' % filename],
stdin=subprocess.PIPE)
proc.communicate(file_contents)
if proc.retcode != 0:
...
```
You'd have to worry about quoting the destination filename. If you want more flexibility, you could even do this:
```
import subprocess
import tarfile
import io
tardata = io.BytesIO()
tar = tarfile.open(mode='w:gz', fileobj=tardata)
... put stuff in tar ...
proc = subprocess.Popen(['ssh', 'user@host', 'tar xz'],
stdin=subprocess.PIPE)
proc.communicate(tardata.getvalue())
if proc.retcode != 0:
...
``` | You want all of the ssh-functionality implemented as a python library? Have a look at paramiko, although I think it's not ported to Python 3.0 (yet?).
If you can use an existing ssh installation you can use the `subprocess` way Dietrich described, or (another way) you could also use `pexpect` ([website here](https://pexpect.readthedocs.io/en/stable/)). | SSH Connection with Python 3.0 | [
"",
"python",
"file",
"ssh",
""
] |
I have a Sql Query which returns me over half million rows to process... The process doesn't take really long, but I would like to speed it up a little bit with some multiprocessing. Considering the code below, is it possible to multithread something like that easily?
```
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// ...process row
}
}
```
It would be perfect if I could simply get a cursor at the beginning and in the middle of the list of results. That way, I could have two thread processing the records. However the SqlDataReader doesn't allow me to do that...
Any idea how I could achieve that? | Set up a producer/consumer queue, with one producer process to pull from the reader and queue records as fast as it can, but do no "processing". Then some other number of processes (how many you want depends on your system) to dequeue and process each queued record. | You shouldn't read that many rows on the client.
That being said, you can partition your query into multiple queries and execute them in parallel. That means launch multiple SqlCommands in separate threads and have them each churn a partition of the result. The A+ question is how to partition the result, and this depends largely o your data and your query:
1. You can use a range of keys (eg. `ID betweem 1 and 10000`, `ID between 10001 and 20000` etc)
2. You can use an attribute (eg. `RecordTypeID IN (1,2)`, `RecordTypeID IN (3,4)` etc)
3. You can use a synthetic range (ie. `ROW_NUMBER() BETWEEN 1 and 1000` etC), but this is very problematic to pull of right
4. You can use a hash (eg. `BINARY_CHECKSUM(*)%10 == 0`, `BINARY_CHECKSUM(*)%10==1` etc)
You just have to be very careful that the partition queries do no overlap and **block** during execution (ie. scan the same records and acquire X locks), thus serializing each other. | Is there a way to multithread a SqlDataReader? | [
"",
"sql",
"sql-server",
"performance",
"multithreading",
"c#-3.0",
""
] |
I'm not quite sure what I'm attempting to do is called, so I'm struggling to find any clues from google.
I have a couple of methods with the same logic in them, the only thing that differs is the property they are using on an object.
```
class Foo
{
public int A(Bar bar)
{
return bar.A * 2;
}
public int B(Bar bar)
{
return bar.B * 2;
}
public int C(Bar bar)
{
return bar.C * 2;
}
}
class Bar
{
public int A;
public int B;
public int C;
}
```
Instead of the three separate methods in `Foo` I want one, with a signature that looks more like
```
public int X(Bar bar, ??? x)
{
return bar.x * 2;
}
```
Is this possible? | ```
internal class Program {
private static void Main(string[] args) {
var bar = new Bar {A = 1, B = 2, C = 3};
Console.WriteLine(new Foo().X(bar, it => it.A));
Console.WriteLine(new Foo().X(bar, it => it.B));
// or introduce a "constant" somewhere
Func<Bar, int> cFieldSelector = it => it.C;
Console.WriteLine(new Foo().X(bar, cFieldSelector));
}
}
internal class Foo {
// Instead of using a field by name, give it a method to select field you want.
public int X(Bar bar, Func<Bar, int> fieldSelector) {
return fieldSelector(bar) * 2;
}
public int A(Bar bar) {
return bar.A * 2;
}
public int B(Bar bar) {
return bar.B * 2;
}
public int C(Bar bar) {
return bar.C * 2;
}
}
internal class Bar {
public int A;
public int B;
public int C;
}
``` | I misread the question the first time, my bad.
You can do this with Reflection:
```
public int Method(Bar bar, string propertyName)
{
var prop = typeof(Bar).GetProperty(propertyName);
int value = (int)prop.GetValue(bar,null);
return value * 2;
}
```
Then, you call it like this:
```
Method(bar,"A");
```
Just noticed that in your example, the 3 variables in Bar are public instance variables. I'm assuming that you just did this for your sample, but if this is in fact the case in your real class, use Rex M's approach. | Pass FieldName as a Parameter | [
"",
"c#",
"reflection",
"anonymous-function",
""
] |
I am trying to figure out the best way to name my HTML form fields so that they can be easily parsed into a set of PHP opbjects.
For example I have the following table of elements: (let's assume it is inside a form)
```
<table>
<tr id='payment0'>
<td><input type='text' name='paymentType0'></td>
<td><input type='text' name='paymentAmount0'></td>
<td><input type='text' name='paymentAccount0'></td>
</tr>
<tr id='payment1'>
<td><input type='text' name='paymentType1'></td>
<td><input type='text' name='paymentAmount1'></td>
<td><input type='text' name='paymentAccount1'></td>
</tr>
</table>
```
Obviously I can write a bunch of code to search through the $\_POST array to find all the paymentType/Amount/Account etc. values and put them into objects. However this feels a bit smelly and I am wondering if there is a better way to name these form elements?
On a side note, I had attempted to name the fields as control arrays (at least that's what I call them) so instead of paymentType0 it would be paymentType[0] and PHP would see them as an array that I could iterate though. The problem with this approach is that referencing these fields with jQuery becomes very difficult due to the square brackets.
What's the 'best of both' worlds solution for this? | You can use array without any problems, but don't call the fields `paymentType[0]`, `paymentAmount[0]`, ...
Instead, call them `payment[0][type]`, `payment[0][amount]`, etc.
Then the records will be conveniently grouped into associative arrays, which are much easier to manipulate:
```
foreach ($_POST["payment"] as $payment) {
echo "The type was $payment[type] and the amount was $payment[amount]";
}
```
As for the jQuery: follow David's suggestion. Objects in JavaScript are really just associative arrays with syntactic sugar and you can access their members as follows:
```
myForm["payment[0][amount]"].value = 300
``` | You could consider preprocessing the submitted values with jQuery. Instead of submitting the raw form data you could structure them on the client-side and pass them to the server using JSON, which can easily be transformed into a PHP object. | How to structure HTML form elements so they can be easily translated into a PHP object? | [
"",
"php",
"jquery",
"html",
"oop",
"webforms",
""
] |
After spending a lot of time and code on programming in Swing, I thought this can't be state-of-the-art Java GUI building. After not finding a user-friendly visual gui bilder for eclipse I stumbled upon declarative GUI building with XML UI toolkits... and I thought: This must be it! I think it's the right way to go, easy and also close to web-programming.
But after looking around in the web and on SO, I got the impression that it is not very common! Although there are many implementations and APIs, it seems like most of them are kind of dead and had no updates in the last 5 years..
So I wonder: Is my feeling right, that XML is not very widespread for java GUIs? And if so - what are the reasons? Maybe it couldn't become accepted or it has some major drawbacks or people are doing everything in the web instead with fatclients or there are better alternatives, maybe javafx?
I just need to know if it is worth spending time in that area or better look for alternate ways. As I dont read developer magazines I just don't know what the trends in gui building are and which technologies are believed to have a future. But I can't imagine that people still spend so much time on writing nasty swing (or swt) apps. | Sun's answer to that seems to be [JavaFX](http://javafx.com).
It has a declarative language for specifying the GUI and there will be builder apps as well. | There new fresh and interesting approach - it uses **YAML**. Check it out at <http://code.google.com/p/javabuilders/> | Is XML or XUL the future of Java GUI building? | [
"",
"java",
"xml",
"user-interface",
"swing",
"xul",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.