Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm curious about the underlying implementation of static variables within a function.
If I declare a static variable of a fundamental type (char, int, double, etc.), and give it an initial value, I imagine that the compiler simply sets the value of that variable at the very beginning of the program before `main()` is called:
```
void SomeFunction();
int main(int argCount, char ** argList)
{
// at this point, the memory reserved for 'answer'
// already contains the value of 42
SomeFunction();
}
void SomeFunction()
{
static int answer = 42;
}
```
However, if the static variable is an instance of a class:
```
class MyClass
{
//...
};
void SomeFunction();
int main(int argCount, char ** argList)
{
SomeFunction();
}
void SomeFunction()
{
static MyClass myVar;
}
```
I know that it will not be initialized until the first time that the function is called. Since the compiler has no way of knowing when the function will be called for the first time, how does it produce this behavior? Does it essentially introduce an if-block into the function body?
```
static bool initialized = 0;
if (!initialized)
{
// construct myVar
initialized = 1;
}
``` | In the compiler output I have seen, function local static variables are initialized exactly as you imagine.
(Caveat: This paragraph applies to C++ versions older than C++11. See the comments for changes since C++11.) Note that in general this is *not* done in a thread-safe manner. So if you have functions with static locals like that that might be called from multiple threads, you should take this into account. Calling the function once in the main thread before any others are called will usually do the trick.
I should add that if the initialization of the local static is by a simple constant like in your example, the compiler doesn't need to go through these gyrations - it can just initialize the variable in the image or before `main()` like a regular static initialization (because your program wouldn't be able to tell the difference). But if you initialize it with a function's return value, then the compiler pretty much has to test a flag indicating if the initialization has been done or something equivalent. | [This question](https://stackoverflow.com/questions/838917/how-does-the-compiler-resolve-infinite-reference-loops/838932#838932) covered similar ground, but thread safety wasn't mentioned. For what it's worth, C++0x will make function static initialisation thread safe.
(see the [C++0x FCD](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3092.pdf), 6.7/4 on function statics: "If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for
completion of the initialization.")
One other thing that hasn't been mentioned is that function statics are destructed in reverse order of their construction, so the compiler maintains a list of destructors to call on shutdown (this may or may not be the same list that atexit uses). | How is static variable initialization implemented by the compiler? | [
"",
"c++",
"compiler-construction",
"static",
"initialization",
""
] |
Consider:
```
var object = {
foo: {},
bar: {},
baz: {}
}
```
How would I do this:
```
var first = object[0];
console.log(first);
```
Obviously, that doesn’t work because the first index is named `foo`,
not `0`.
```
console.log(object['foo']);
```
works, but I don’t know it’s named foo. It could be named anything. I just want the first. | If the order of the objects is significant, you should revise your JSON schema to store the objects in an array:
```
[
{"name":"foo", ...},
{"name":"bar", ...},
{"name":"baz", ...}
]
```
or maybe:
```
[
["foo", {}],
["bar", {}],
["baz", {}]
]
```
As Ben Alpert points out, properties of Javascript objects are unordered, and your code is broken if you expect them to enumerate in the same order that they are specified in the object literal—there is no "first" property. | Just for fun this works in JS 1.8.5
```
var obj = {a: 1, b: 2, c: 3};
Object.keys(obj)[0]; // "a"
```
This matches the same order that you would see doing
```
for (o in obj) { ... }
``` | Getting the first index of an object | [
"",
"javascript",
"javascript-objects",
""
] |
I need to change RichEditor and TextEditor modes with JavaScript, now I need to convert Html to Text which is actually still in Html editor mode, so I need just p tags, but other Html can be stripped off. | Regex replace (globally, case-insensitively):
```
</?(?:(?!p\b)[^>])*>
```
with the empty string.
Explanation:
```
< # "<"
/? # optional "/"
(?: # non-capture group
(?! # negative look-ahead: a position not followed by...
p\b # "p" and a word bounday
) # end lock-ahead
[^>]* # any char but ">", as often as possible
) # end non-capture group
> # ">"
```
This is one of the few situations where applying regex to HTML can actually work.
Some might object and say that the use of a literal "<" within an attribute value was actually not forbidden, and therefore would potentially break the above regex. They would be right.
The regex would break in *this* situation, replacing the underlined part:
```
<p class="foo" title="unusual < title">
---------
```
If such a thing is possible with your input, then you might have to use a more advanced tool to do the job - a parser. | This should help
```
var html = '<img src=""><p>content</p><span style="color: red">content</span>';
html.replace(/<(?!\s*\/?\s*p\b)[^>]*>/gi,'')
```
explanation for my regex:
replace all parts
1. beginning with "<",
2. not followed by (?!
* any number of white-space characters "\s\*"
* optional "/" character
* and tag name followed by a word boundary (here "p\b")
3. containing any characters not equal ">" - [^>]\*
4. and ending with ">" character | Strip Html from Text in JavaScript except p tags? | [
"",
"javascript",
""
] |
I run a Java code with the following command:
```
$ java -Xms4G -Xmx4G myjavacode
```
My cpu's RAM capacity is 6GB.
However it always fail to execute giving me this
error message:
```
Invalid initial heap size: -Xms5G
The specified size exceeds the maximum representable size.
Could not create the Java virtual machine
```
Is there any way to set up Java option so that we can
execute the code? | You've exceeded the maximum heap size of your JVM. This is both JVM and OS dependent. In most 32-bit systems the maximum value will be 2Gb, regardless of the physical memory available. | By default Java will run in 32 bit mode. Be sure to give it the -d64 option to put it into 64 bit mode. Once in 64-bit mode, you shouldn't have any trouble allocating a 6GB JVM. | Avoiding Initial Memory Heap Size Error | [
"",
"java",
"memory-management",
""
] |
I have a XML file with the following data format:
```
<net NetName="abc" attr1="123" attr2="234" attr3="345".../>
<net NetName="cde" attr1="456" attr2="567" attr3="678".../>
....
```
Can anyone tell me how could I data mine the XML file using an awk one-liner? For example, I would like to know attr3 of abc. It will return 345 to me. | In general, [you don't](https://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-rege). XML/HTML parsing is hard enough without trying to do it concisely, and while you may be able to hack together a solution that succeeds with a limited subset of XML, eventually it will break.
Besides, [there are many great languages with great XML parsers already written](https://stackoverflow.com/questions/773340/can-you-provide-an-example-of-parsing-html-with-your-favorite-parser), so why not use one of them and make your life easier?
I don't know whether or not there's an XML parser built for awk, but I'm afraid that if you want to parse XML with awk you're going to get a lot of "hammers are for nails, screwdrivers are for screws" answers. I'm sure it can be done, but it's probably going to be easier for you to write something quick in Perl that uses XML::Simple (my personal favorite) or some other XML parsing module.
Just for completeness, I'd like to note that if your snippet is an example of the entire file, it is not valid XML. Valid XML should have start and end tags, like so:
```
<netlist>
<net NetName="abc" attr1="123" attr2="234" attr3="345".../>
<net NetName="cde" attr1="456" attr2="567" attr3="678".../>
....
</netlist>
```
I'm sure invalid XML has its uses, but some XML parsers may whine about it, so unless you're dead set on using an awk one-liner to try to half-ass "parse" your "XML," you may want to consider making your XML valid.
In response to your edits, I still won't do it as a one-liner, but here's a Perl script that you can use:
```
#!/usr/bin/perl
use strict;
use warnings;
use XML::Simple;
sub usage {
die "Usage: $0 [NetName] ([attr])\n";
}
my $file = XMLin("file.xml", KeyAttr => { net => 'NetName' });
usage() if @ARGV == 0;
exists $file->{net}{$ARGV[0]}
or die "$ARGV[0] does not exist.\n";
if(@ARGV == 2) {
exists $file->{net}{$ARGV[0]}{$ARGV[1]}
or die "NetName $ARGV[0] does not have attribute $ARGV[1].\n";
print "$file->{net}{$ARGV[0]}{$ARGV[1]}.\n";
} elsif(@ARGV == 1) {
print "$ARGV[0]:\n";
print " $_ = $file->{net}{$ARGV[0]}{$_}\n"
for keys %{ $file->{net}{$ARGV[0]} };
} else {
usage();
}
```
Run this script from the command line with 1 or 2 arguments. The first argument is the `'NetName'` you want to look up, and the second is the attribute you want to look up. If no attribute is given, it should just list all the attributes for that `'NetName'`. | I have written a tool called `xml_grep2`, based on [XML::LibXML](http://search.cpan.org/dist/XML-LibXML), the perl interface to [libxml2](http://xmlsoft.org).
You would find the value you're looking for by doing this:
```
xml_grep2 -t '//net[@NetName="abc"]/@attr3' to_grep.xml
```
The tool can be found at <http://xmltwig.com/tool/> | How can I mine an XML document with awk, Perl, or Python? | [
"",
"python",
"xml",
"perl",
"awk",
""
] |
Let's say that I have this string:
```
s = '<p>Hello!</p>'
```
When I pass this variable to a template, I want it to be rendered as raw html. Looking at the docs I see that I can either use the safe filter:
```
{{s|safe}}
```
or disable autoescape:
```
{%autoescape off}
{{s}}
{%endautoescape%}
```
or inside the python code declare it safe:
```
from django.utils.safestring import mark_safe
s = mark_safe(s)
```
None of these options are working for me. Whatever I do, the string is displayed as:
```
<p>Hello!</p>
```
I must be missing something, just couldn't figure out what. Is there some security setting somewhere that disallows escaping?
EDIT: Bizarre, the problem seems to be gone after I have restarted the computer. | You pretty much covered it, those are indeed all the ways to disable autoescaping.
Are you sure the value you are talking about is actually `s = '<p>Hello!</p>'`?
My hunch is that you have additional escaping somewhere in that string... | I think you should write as follows
```
{{s|escape|safe}}
```
it is ok for me | escape problem in django templates | [
"",
"python",
"html",
"django",
"django-templates",
"rendering",
""
] |
I was just pleasantly surprised to came across the documentation of [Python's compiler package](http://docs.python.org/library/compiler), but noticed that it's gone in Python 3.0, without any clear replacement or explanation.
I can't seem to find any discussion on python-dev about how this decision was made - does anyone have any insight inot this decision? | I believe the functionality is now built in:
* [compile](http://docs.python.org/3/library/functions.html#compile)
* [ast](http://docs.python.org/3.3/library/ast.html) | To provide specific references to the decision trail:
* <https://mail.python.org/pipermail/python-3000/2007-May/007577.html>
* [PEP 3108](https://www.python.org/dev/peps/pep-3108/)
And, for what it's worth, I started Python3 port of the compiler package, to be maintained outside of the stdlib:
* <https://github.com/pfalcon/python-compiler>
* <https://pypi.org/project/python-compiler/> | Why is the compiler package discontinued in Python 3? | [
"",
"python",
"compiler-construction",
"python-3.x",
""
] |
I'd like to show some visual progress to a user during an ajax request. E.g when he clicks a 'process' button which makes an AJAX request to a server-side script, he will see a 'loading...' message and a graphic, but I also want to show him some progress of how much processing is done. E.g `5/10 processed, 6/10 processed...` and so on.
Is there anyway to do this? | Yep, there is, but it is kind of complicated. The only way I've found is using an iframe on the client, and response.writeing on the server to send blocks of javascript back to the client, that javascript calls on the parent window to process the status messages.
Here's some sample code. There may be problems with it, I'm snipping it out of a much bigger app.
html:
```
<button id="doStuff">
<div id="status"></div>
<div id="iframeHolder"></div>
```
javascript:
```
//This one will be called from the HTML the javascript is streaming back
function updateStatus(message) {
$('#status').html(message);
}
$('#doStuff').click(function(event) {
event.preventDefault();
var url="your.page.html";
$('#iframeHolder').html('<iframe src="' + url + '"></iframe>');
}
```
server side (this is vb asp.net, but you should be able to do it in your language of choice):
```
dim message as string = "hello world"
dim script = String.Format("<script type='text/javascript'>parent.updateStatus('{0}');</script>",message)
Response.Write(script)
Response.Flush()
```
Some observations
* Querystring will be your friend here. I'm not sure if you can programatically postback to an iframe
* You will probably have to add some cachebusting garbage to the querystring, otherwise the browser will more than likely cache the contents. It'll be very very quick, but wrong :-)
* You might need to send "some" html before the browser starts processing the iframe stuff. I've found that sending a HTML comment of about 1k of garbage helps
* To avoid refresh problems in FF, and "forever loading" problems in chrome and safari, set the iframe's src to about:blank once you're done (`$('#iframeHolder iframe').attr('src','about:blank')`)
* the jQuery UI progress bar looks pretty swanky for displaying the percent processed
Hope that helps. I tore my head out with this a couple of months ago :-) | I don't know what your server side process actually is, but would it make any sense to break it up into a series of Ajax calls, each doing a part of the process? Then you could increment you display at each step. | Forcing page content to change through Javascript | [
"",
"javascript",
"jquery",
"ajax",
""
] |
The title speaks for itself. I'm building a **winforms** C# 2.0 app.
Any tutorials or inspiring ideas? | ADO.NET is a big topic - but the keywords to search for here are `SqlConnection`, `SqlCommand`, `SqlDataReader`, etc. If you like `DataSet` (I'm not a fan, but some people love them), then the dataset designer will do a lot for you.
Another option is to use a .NET 2.0 web-service (asmx) for data access via a central app-server - making it a "smart client".
With later .NET versions, WCF (.NET 3.0), LINQ-to-SQL (.NET 3.5), Entity Framework (.NET 3.5 SP1) and ADO.NET Data Services (.NET 3.5 SP1) become options. | There's not much difference between a local SQL Server instance and a distant one. You just set something like `Server=sqlserver.remote-machine.com` in your connection string. | How do I connect to a distant sql server database in a winforms app? | [
"",
"c#",
"sql-server",
"winforms",
""
] |
I have a table with sets of settings for users, it has the following columns:
```
UserID INT
Set VARCHAR(50)
Key VARCHAR(50)
Value NVARCHAR(MAX)
TimeStamp DATETIME
```
UserID together with Set and Key are unique. So a specific user cannot have two of the same keys in a particular set of settings. The settings are retrieved by set, so if a user requests a certain key from a certain set, the whole set is downloaded, so that the next time a key from the same set is needed, it doesn't have to go to the database.
Should I create a primary key on all three columns (userid, set, and key) or should I create an extra field that has a primary key (for example an autoincrement integer called SettingID, bad idea i guess), or not create a primary key, and just create a unique index?
----- UPDATE -----
Just to clear things up: This is an end of the line table, it is not joined in anyway. UserID is a FK to the Users table. Set is not a FK. It is pretty much a helper table for my GUI.
Just as an example: users get the first time they visit parts of the website, a help balloon, which they can close if they want. Once they click it away, I will add some setting to the "GettingStarted" set that will state they helpballoon X has been disabled. Next time when the user comes to the same page, the setting will state that help balloon X should not be shown anymore. | > Should I create a primary key on all three columns `(userid, set, and key)`
Make this one.
Using surrogate primary key will result in an extra column which is not used for other purposes.
Creating a `UNIQUE INDEX` along with surrogate primary key is same as creating a non-clustered `PRIMARY KEY`, and will result in an extra `KEY lookup` which is worse for performance.
Creating a `UNIQUE INDEX` without a `PRIMARY KEY` will result in a `HEAP-organized` table which will need an extra `RID lookup` to access the values: also not very good. | Having composite unique keys is mostly not a good idea.
Having any business relevant data as primary key can also make you troubles. For instance, if you need to change the value. If it is not possible in the application to change the value, it could be in the future, or it must be changed in an upgrade script.
It's best to create a surrogate key, a automatic number which does not have any business meaning.
**Edit** after your update:
In this case, you can think of having **conceptually no primary key**, and make this three columns either the primary key of a composite unique key (to make it changeable). | SQL: To primary key or not to primary key? | [
"",
"sql",
"indexing",
"primary-key",
""
] |
I have a class with two constructors, one that takes no arguments and one that takes one argument.
Creating objects using the constructor that takes one argument works as expected. However, if I create objects using the constructor that takes no arguments, I get an error.
For instance, if I compile this code (using g++ 4.0.1)...
```
class Foo
{
public:
Foo() {};
Foo(int a) {};
void bar() {};
};
int main()
{
// this works...
Foo foo1(1);
foo1.bar();
// this does not...
Foo foo2();
foo2.bar();
return 0;
}
```
... I get the following error:
```
nonclass.cpp: In function ‘int main(int, const char**)’:
nonclass.cpp:17: error: request for member ‘bar’ in ‘foo2’, which is of non-class type ‘Foo ()()’
```
Why is this, and how do I make it work? | ```
Foo foo2();
```
change to
```
Foo foo2;
```
You get the error because compiler thinks of
```
Foo foo2()
```
as of function declaration with name 'foo2' and the return type 'Foo'.
But in that case If we change to `Foo foo2` , the compiler might show the error `" call of overloaded ‘Foo()’ is ambiguous"`. | Just for the record..
It is actually not a solution to your code, but I had the same error message when incorrectly accessing the method of a class instance pointed to by `myPointerToClass`, e.g.
```
MyClass* myPointerToClass = new MyClass();
myPointerToClass.aMethodOfThatClass();
```
where
```
myPointerToClass->aMethodOfThatClass();
```
would obviously be correct. | error: request for member '..' in '..' which is of non-class type | [
"",
"c++",
""
] |
I just installed Apache 2.2.11 and downloaded the zip for PHP5.2.9-2
I uncommented
> extension=php\_pdo\_pgsql.dll
and
> extension=php\_pgsql.dll
But when I call the phpinfo() function, postgresql is not showing up. What am I forgetting?
Also, on the PHP site, I found this:
> In order to enable PostgreSQL support,
> --with-pgsql[=DIR] is required when you compile PHP. DIR is the PostgreSQL
> base install directory, defaults to
> /usr/local/pgsql. If shared object
> module is available, PostgreSQL module
> may be loaded using extension
> directive in php.ini or dl()
> function.
> I recognise that this is ment for Linux, but is there something written here, telling me to do something I've forgotten? | In your `php.ini` make sure that the `extension_dir` directive is pointing to the folder that contains the php\_pgsql.dll file.
Also check your HTTP error log for errors. | Did you restart Apache after making changes to your php.ini? The PHP module in Apache wont pickup changes until a restart is performed. | PostgreSQL not showing up on phpconfig() function(on windows) | [
"",
"php",
"postgresql",
""
] |
I updated my python interpreter, but I think the old one is still called. When I check for the version I get:
```
$ python -V
Python 3.0.1
```
But I believe the old interpreter is still being called. When I run the command:
```
python myProg.py
```
The script runs properly. But when I invoke it with the command
```
./myProg.py
```
I get the error message:
```
AttributeError: 'str' object has no attribute 'format'
```
Which apparently is due to the old interpreter being called. How can I fix this? I run Mac OS X 10.5. Has it something to do with the first line:
```
#!/usr/bin/python
```
I just started out with python and am not very familiar with interpreted languages, so I am not too sure what is going on. | According to the first line of the script, `#!/usr/bin/python`, you are calling the Python interpreter at `/usr/bin/python` (which is most likely the one that ships with Mac OS X). You have to change that path to the path where you installed your Python 3 interpreter (likely `/usr/local/bin/python` or `/opt/local/bin/python`); *or* you can just change that line to read `#!/usr/bin/env python`, which will call the `python` listed first in your `PATH` variable (which seems to be the newer version you installed). | Firstly, the recommended shebang line is:
```
#!/usr/bin/env python
```
This will make sure the python interpreter that is invoked when you `./foo.py` is the same interpreter that is invoked when you invoke python from the command line.
From your description, I suspect that if you did:
```
which python
```
It would not give you `/usr/bin/python`. It would give you something else, which is where the python 3 interpreter lives. You can either modify your shebang line to the above, or replace the path to the python interpreter with the path returned by `which`. | The wrong python interpreter is called | [
"",
"python",
"python-3.x",
""
] |
I am wondering why this framework (QCodo) is almost forgotten and totally unpopular.
I've started using it a few years ago and it is the **only** thing that keeps me with PHP. Yeah ... its development is stuck (that's why there is now more active branch [Qcubed](http://qcu.be)) but it is still very good piece of software.
Its main advantages:
* Event driven (something like asp.net) **no spaghetti code**
* Powerful code generation
* good ORM
* follows DRY
* very simple AJAX support
* is fun to write
Since then I wanted to be trendy and checked Django but I cannot write normal request-based web application (it just doesn't feel right).
Don't believe? chess.com is written with it and surely there are plenty others.
My 2 questions are:
1. Have you heard of it (PHP people)?
2. If you are using it what is your opinion about it (show us examples of your work)
Thanks | 1. The creator(s) of Qcodo never really promoted the framework, and thus, didn't generate a large following. I believe they created it mostly for their own use, but also offered it up to others. It is awesome if you are looking for a code-generating framework. It does have a learning curve. So to get the most use of it, it's best to spend time studying the examples.
2. Qcodo has really had no active development for well over a year and there doesn't appear to be much chance that development will continue on Qcodo anytime soon. Qcodo appears to be dying a slow death.
3. Qcubed, a branch of Qcodo, is under active development and has been since Nov 2008. It was created by users of Qcodo who got frustrated with the lack of Qcodo progress. If you are just getting started, start here and not with Qcodo. But use Qcodo forums to search for problems/questions you may have.
Qcodo and Qcubed are fantastic frameworks. Don't discount or underestimate them just because you've not heard of them. | I've used PHP a lot for many years and never heard of it. | Why a very good PHP framework - Qcodo (or Qcubed - its branch) - is so unpopular? | [
"",
"php",
"orm",
"frameworks",
"event-handling",
"code-generation",
""
] |
My question is simple: are `std::vector` elements guaranteed to be contiguous? In other words, can I use the pointer to the first element of a `std::vector` as a C-array?
If my memory serves me well, the C++ standard did not make such guarantee. However, the `std::vector` requirements were such that it was virtually impossible to meet them if the elements were not contiguous.
Can somebody clarify this?
Example:
```
std::vector<int> values;
// ... fill up values
if( !values.empty() )
{
int *array = &values[0];
for( int i = 0; i < values.size(); ++i )
{
int v = array[i];
// do something with 'v'
}
}
``` | This was missed from C++98 standard proper but later added as part of a TR. The forthcoming C++0x standard will of course contain this as a requirement.
From n2798 (draft of C++0x):
> **23.2.6 Class template vector [vector]**
>
> 1 A vector is a sequence container that supports random access iterators. In addition, it supports (amortized)
> constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage
> management is handled automatically, though hints can be given to improve efficiency. The elements of a
> vector are stored contiguously, meaning that if v is a vector where T is some type other
> than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size(). | As other answers have pointed out, the contents of a vector is guaranteed to be continuous (excepting bool's weirdness).
The comment that I wanted to add, is that if you do an insertion or a deletion on the vector, which could cause the vector to reallocate it's memory, then you will cause all of your saved pointers and iterators to be invalidated. | Are std::vector elements guaranteed to be contiguous? | [
"",
"c++",
"vector",
"language-lawyer",
"stdvector",
""
] |
I know that one can define an **'expected'** exception in JUnit, doing:
```
@Test(expect=MyException.class)
public void someMethod() { ... }
```
But what if there is always same exception thrown, but with different 'nested'
**causes**.
Any suggestions? | You could wrap the testing code in a try / catch block, catch the thrown exception, check the internal cause, log / assert / whatever, and then rethrow the exception (if desired). | As of JUnit 4.11 you can use the `ExpectedException` rule's [`expectCause()`](http://junit.czweb.org/apidocs/org/junit/rules/ExpectedException.html#expectCause(org.hamcrest.Matcher)) method:
```
import static org.hamcrest.CoreMatchers.*;
// ...
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void throwsNestedException() throws Exception {
expectedException.expectCause(isA(SomeNestedException.class));
throw new ParentException("foo", new SomeNestedException("bar"));
}
``` | JUnit: Possible to 'expect' a wrapped exception? | [
"",
"java",
"exception",
"junit",
""
] |
i need Enumarable value from below class but give error
```
public static Enumerable LoadDataByName(string name)
{
List<StuffDepartman> Stuff = (List<StuffDepartman>)HttpContext.Current.Session["Stuffs"];
var stuffs = from s in Stuff select s;
stuffs = from s in Stuff where s.Name = name select s.Name;
return stuffs.AsEnumerable();
}
```
But Give me error: **System.Linq.Enumerable': static types cannot be used as return types** | In .NET 3.5, there exists a static `Enumerable` existing in `System.Linq`, which contains extension methods for manipulating `IEnumerable`s - this is not what you want to (or clearly *can*) return. Change it to `IEnumerable`, which is the non-generic enumerable class (and what I think you intend), and all should work fine.
Even better, use the generic version of `IEnumerable`, as such:
```
public static IEnumerable<StuffDepartman> LoadDataByName(string name)
{
var stuffs = (List<StuffDepartman>)HttpContext.Current.Session["Stuffs"];
return (from s in stuffs where s.Name == name select s.Name);
}
```
Also, note that you don't need the call to `AsEnumerable` before returning, since `List<T>` implements `IEnumerable<T>`, and the former can be implicitly casted to the latter. The `=` needed to be changed to `==`, since you want to use the equality rather than assigment operator here. The other changes are just tidying up. | `System.Linq.Enumerable` is a static class with a bunch of extension methods defined on it. You perhaps meant to return `IEnumerable<string>` instead. | Return Enumerable value from Class in linq? | [
"",
"c#",
".net",
"asp.net",
"linq",
""
] |
I have two results from a data set. I want to add both results in one gridview column. I do not want to merge in the code behind. Is there another way to do that?
```
<asp:TemplateField HeaderText="Entered Date" SortExpression="Date">
<ItemTemplate>
<div style="text-align: center;">
<asp:Label ID="Label3" runat="server" Text='<%# formatDisplayDate(Eval("Date").ToString()) %>'></asp:Label>
</div>
</ItemTemplate>
</asp:TemplateField>
```
Now i would return "04/04/2009". I would like to return "04/04/2009-PASSED" | Have you tried:
```
formatDisplayDate(Eval("Date").ToString()) & "-" & Eval("OtherField").ToString()
```
If that doesn't work you should be able to set up a TemplateField for the combined rows like this:
```
<asp:TemplateField HeaderText="CombinedFieldName" SortExpression="CombinedFieldName">
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# DataBinder.Eval(Container,"DataItem.FirstField") %>' >
</asp:Label>
-
<asp:Label ID="Label2" runat="server"
Text='<%# DataBinder.Eval(Container,"DataItem.SecondField") %>' >
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
```
That said - it is usually much more efficient to do the field concatenation in the database operation if possible. I haven't tested, but I would assume that concatenating in the SELECT would be fastest, followed by concatenating in the data set in the codebehind, and combining them on the ASP.Net page would be slowest. | My first question is why don't you want to merge in the code behind? The more content you bind to a control the more data that gets put into that controls view state.
@Gary.Ray has a really good solution, but something you might find better is to use linq to build a single data object from your existing data sets that way you only include what you need and the data is a lot easier to isolate, think single responsibility pattern here, if you can move the code that deals with getting your data to somewhere that only deals with getting data your application will be MUCH easy to maintain in the future. | How do i put 2 DataSet Table Results in one GridView Column? | [
"",
"c#",
".net",
"asp.net",
"html",
""
] |
How do you make a Java desktop application modular? How should the modules be classified? | As a design goal, modularity means that you want to have an application composed of separate parts (modules) where each part has its area of responsibility and contains all classes concerned with that area (high [cohesion](http://en.wikipedia.org/wiki/Cohesion_(computer_science))), and communication between those parts happens through narrow, well-defined and -documented interfaces ([loose coupling](http://en.wikipedia.org/wiki/Loose_coupling)).
You achieve this by planning your design beforehand and adjusting those planse and refactoring the code constantly during implementation.
It's useful to make a difference between technical modules such as GUI, network communication or DB access (which often form layers, though these may be sub-divided into several modules), and domain modules that contain the application-specific logic and often don't form layers. | Have a look at OSGi technologies. Each module of your application (called a bundle) is a separate jar, and OSGi takes care of dependency resolution and dynamically loading bundle classpaths etc.
For desktop applications I would strongly recommend looking at DA-Launcher from [www.dynamicjava.org](http://www.dynamicjava.org). It makes deploying your app SOOO much easier. They also have a few things like dynamic JPA that are useful for any OSGi app. | How to make a desktop application modular? | [
"",
"java",
"desktop",
"desktop-application",
"modularity",
""
] |
I'm going to refactor certain parts in a huge code base (18000+ Java classes). Goal is to be able to extract lower layers as independent libraries to be reused in other projects that currently use duplicate of this code base. Especially one part is of interest to be refactored into a framework independent of business logic. Ultimately I would like the code to have a clean architectural layering.
I've looked at the code with a tool called Structure 101 for java and found lots (!) of architectural layering issues where lower layers are referencing upper layers.
I don't want to simply start messing with the code but try to come up with a reasonable strategy to go about this problem. What things should I keep in mind?
I'm thinking about at least taking small steps. I'm also thinking about have unit tests in place, but that requires creating them, since there are none.
Any thoughts on this? | You should also take a look at Working with legacy code by Michael Feathers:
[http://www.amazon.com/Working-Effectively-Legacy-Robert-Martin/dp/0131177052/ref=sr\_1\_1?ie=UTF8&s=books&qid=1242430219&sr=8-1](https://rads.stackoverflow.com/amzn/click/com/0131177052)
I think one of the most important things you can put in place to facilitate this are tests to ensure that everything still works post refactoring/pulling out into separate modules. Add to this by introducing a continuous integration system that runs your tests when you check something in. | 18,000 classes is really heading towards the "enormous" end of things. This is going to give you distinct problems, including build / compile time and having smoke come out of the computer when you fire up the ide.
My first assumption is that with that many classes, there's a lot of duplication of common functionality and possibly unused classes or possibly even subsystems. I'd expect this because when something gets that large it becomes more and more likely that a developer doesn't know the whole system, or doesn't know where those Util functions are, and finds it just easier to write a new one. Looking for redundancies to remove will help simplify.
Another possible source of redundancy is uselessly deep class hierarchies, or piles of pointless interfaces (an example - Where I work there's a directory of about 50 or so classes, most > 1000 lines (not mine, not mine!). Each of these implements an interface, which is nothing more than its own method skeleton. There are no other implementations of those interfaces. All 50 could be deleted without issue). There are also those developers who've just discovered OO and are really keen on it - you know the ones, the single concrete implementation that extends a chain of 5 abstract classes and 3 interfaces.
Along with that I'd try to take a subsection of code (a few hundred classes at the absolute most) and move them to a subproject, which I'd then link in to the main as a jar. You could then work on that in a bit of peace with a reasonable hope of being able to understand the whole thing - there's a psychological aspect to this as well - there's less of an incentive to do good work if you feel like you're working on something that's an enormous, incomprehensible mess, than if you're working on your own clean subproject that you understand completely. | What should I keep in mind in order to refactor huge code base? | [
"",
"java",
"architecture",
"refactoring",
"layer",
""
] |
I wish to run Eclipse for C++ on Vista but I absolutely do not want to run the JRE installation. Is there any place where I can get a JRE in a zip that I can just dump in the Eclipse folder and have it work? | Download the JRE offline installer, right click on it, and have 7zip/winrar/whatever unzip it.
You'll get a folder with a fully funcional JRE, but no install required :)
You might want to read [this](http://wiki.eclipse.org/FAQ_How_do_I_run_Eclipse%3F) to run Eclipse with that JRE. | You can run Eclipse by copying the JRE into the `eclipse/jre` directory ([wiki documentation](http://wiki.eclipse.org/FAQ_How_do_I_run_Eclipse%3F)).
The JRE is distributed with the [Java JDK](http://java.sun.com/javase/downloads/index.jsp) (*/path/jdk1.6xxx/jre*). The JDK uses an installer, but you can just copy this directory from another machine, install and uninstall the JDK or whatever. | How to run Eclipse without running JRE installation? | [
"",
"eclipse",
"java",
""
] |
I am trying to create an array of class objects taking an integer argument. I cannot see what is wrong with this simple little code. Could someone help?
```
#include <fstream>
#include <iostream>
using namespace std;
typedef class Object
{
int var;
public:
Object(const int& varin) : var(varin) {}
} Object;
int main (int argc, char * const argv[])
{
for(int i = 0; i < 10; i++)
{
Object o(i)[100];
}
return 0;
}
``` | In C++ you don't need `typedef`s for `class`es and `struct`s. So:
```
class Object
{
int var;
public:
Object(const int& varin) : var(varin) {}
};
```
Also, descriptive names are always preferrable, `Object` is much abused.
```
int main (int argc, char * const argv[])
{
int var = 1;
Object obj_array[10]; // would work if Object has a trivial ctor
return 0;
}
```
Otherwise, in your case:
```
int main (int argc, char * const argv[])
{
int var = 1;
Object init(var);
Object obj_array[10] = { var, ..., var }; // initialize manually
return 0;
}
```
Though, really you should look for `vector`
```
#include <vector>
int main (int argc, char * const argv[])
{
int var = 1;
vector<Object> obj_vector(10, var); // initialize 10 objects with var value
return 0;
}
``` | dirkgently's rundown is fairly accurate representation of arrays of items in C++, but where he is initializing all the items in the array with the same value it looks like you are trying to initialize each with a distinct value.
To answer your question, creating an array of objects that take an int constructor parameter. You can't, objects are created when the array is allocated and in the absence of a trivial constructor your compiler will complain. You can however initialize an array of pointers to your object but you really get a lot more flexibility with a vector so my following examples will use std::vector.
You will need to initialize each of the object separately if you want each Object to have a distinct value, you can do this one of two ways; on the stack, or on the heap. Lets look at on-the-stack first.
Any constructor that take a single argument and is not marked as `explicit` can be used as an implicit constructor. This means that any place where an object of that type is expected you can instead use an instance of the single parameter type. In this example we create a vector of your Object class and add 100 Objects to it (push\_back adds items to a vector), we pass an integer into push\_back which implicitly creates an Object passing in the integer.
```
#include <vector>
int main() {
std::vector<Object> v;
for(int i = 0; i < 100; i++) {
v.push_back(i);
}
}
```
Or to be explicit about it:
```
#include <vector>
int main() {
std::vector<Object> v;
for(int i = 0; i < 100; i++) {
v.push_back(Object(i));
}
}
```
In these examples, all of the Object objects are allocated on the stack in the scope of the for loop, so a copy happens when the object is pushed into the vector. Copying a large number of objects can cause some performance issues especially if your object is expensive to copy.
One way to get around this performance issue is to allocate the objects on the heap and store pointers to the objects in your vector:
```
#include <vector>
int main() {
std::vector<Object*> v;
for(int i = 0; i < 100; i++) {
v.push_back(new Object(i));
}
for(int i = 0; i < 100; i++) {
delete v[i];
}
}
```
Since our objects were created on the heap we need to make sure that we delete them to call their deconstructor and, free their memory, this code does that in the second loop.
Manually calling `delete` has it's own caveats, if you pass these pointers to other code you can quickly loose track of who owns the pointers and who should delete them. An easier way to solve this problem is to use a smart pointer to track the lifetime of the pointer, see either `boost::shared_ptr` or `tr1::shared_ptr` which are reference-counted pointers :
```
#include <vector>
int main() {
std::vector<shared_ptr<Object> > v;
for(int i = 0; i < 100; i++) {
Object* o = new Object(i);
v.push_back(shared_ptr<Object>(o));
}
}
```
You'll notice that the shared\_ptr constructor is explicit, this is done intentionally to make sure that the developer is intentionally stuffing their pointer into the shared pointer. When all references to an object are released the object will automatically be deleted by the shared\_ptr, freeing us of the need to worry about it's lifetime. | Need help creating an array of objects | [
"",
"c++",
""
] |
From what I've found in C#, the Control.Invoke method requires that you use a delegate with no input parameters. Is there any way around this? I would like to invoke a method to update the UI from another thread and pass to string parameters to it. | Which version of C# are you using? If you are using C#3.5 you can use closures to avoid passing in parameters.
With C#3.5
```
public static class ControlExtensions
{
public static TResult InvokeEx<TControl, TResult>(this TControl control,
Func<TControl, TResult> func)
where TControl : Control
{
return control.InvokeRequired
? (TResult)control.Invoke(func, control)
: func(control);
}
public static void InvokeEx<TControl>(this TControl control,
Action<TControl> func)
where TControl : Control
{
control.InvokeEx(c => { func(c); return c; });
}
public static void InvokeEx<TControl>(this TControl control, Action action)
where TControl : Control
{
control.InvokeEx(c => action());
}
}
```
Safely invoking code now becomes trivial.
```
this.InvokeEx(f => f.label1.Text = "Hello World");
this.InvokeEx(f => this.label1.Text = GetLabelText("HELLO_WORLD", var1));
this.InvokeEx(() => this.label1.Text = DateTime.Now.ToString());
```
---
With C#2.0 it becomes less trivial
```
public class MyForm : Form
{
private delegate void UpdateControlTextCallback(Control control, string text);
public void UpdateControlText(Control control, string text)
{
if (control.InvokeRequired)
{
control.Invoke(new UpdateControlTextCallback(UpdateControlText), control, text);
}
else
{
control.Text = text;
}
}
}
```
Using it simple, but you have to define more callbacks for more parameters.
```
this.UpdateControlText(label1, "Hello world");
``` | Some more possibilities:
```
this.Invoke(new MethodInvoker(() => this.DoSomething(param1, param2)));
```
or
```
this.Invoke(new Action(() => this.DoSomething(param1, param2)));
```
or even
```
this.Invoke(new Func<YourType>(() => this.DoSomething(param1, param2)));
```
where the first option is the best one, because MethodInvoker is concepted for that purposes and has a better performance. | Control.Invoke with input Parameters | [
"",
"c#",
"winforms",
"multithreading",
""
] |
There are six tabs in the NUnit Test runner:
```
Errors and Failures
Tests Not Run
Console.Out
Console.Error
Trace
Log
```
I know what *Errors and Failures* are for but the purpose of the remaining tabs is confusing. Both *Console.Out* and *Trace* appear to serve a similar purpose.
As a comment has pointed out, I have written a similar question asking *how* does one write to all of the tabs. In this question, I am asking *why* does one write to each of the tabs? *Why* does one write to the *Console.Out* vs the *Trace* vs the *Log* tab? *What* is the intended purpose of each tab? | The Tests Not Run tab displays tests which were skipped. These are tests which have the Ignore() attribute defined. This is useful if you want to temporarily disable a test that is known to be temporarily invalid, or that is too time consuming to run on a regular basis.
The remaining tabs are all covered in your other question:
* Console.Out -> Console.WriteLine()
* Console.Error -> Console.Error.WriteLine()
* Trace -> System.Diagnostics.Trace.WriteLine()
* Log -> log4net output
Console.Out writes data to stdout.
Console.Error writes data to stderr.
Trace writes data to the [Trace Ojbect](http://www.asp101.com/articles/robert/tracing/default.asp) .
[Log4Net](http://logging.apache.org/log4net/index.html) writes to a "variety of log targets."
The purpose of all of these is the same: to obtain insight into what your code is doing as it runs, without using breakpoints and a debugger. Which one you use depends on your requirements: The Console methods produce user-visible output. Trace is easy to show/hide (and includes quite a lot of extra information), but doesn't appear to have any kind of persistence backing it. Logging can be permanent, but requires the overhead of maintaining the log file. | I would expect Console.Out to be used when writing or debugging your tests, whereas Trace would be used to display trace output from the code under test. Trace output in your code can be conditional using Trace.WriteIf etc and turned on by switch definitions in your config file. | What is each tab in the NUnit Gui Runner supposed to be for? | [
"",
"c#",
".net",
"winforms",
"nunit",
"nunit-2.5",
""
] |
Hi anyone sees why my alert won't work?
```
<script type="text/javascript">
function SubmitForm(method) {
var login = document.form.login.value;
var password = document.form.password.value;
$.post("backend.php", {
login: login,
password: password,
method: method},
function(data){
alert(data.message);
console.log(data.refresh);
}, "json");
}
</script>
```
Response from backend.php is
```
backend{"message":"Log in credentials are not correct","refresh":"false"}
``` | Why is 'backend' at the start of your response? I would start by removing that. Everything from { to } looks good. | While I dont think its your problem, the callback function does take a 2nd parameter (the jQuery docs call it "textStatus") which is a textual representation of the HTTP status. Specify a 2nd argument to your callback.
```
function(data, textStatus) { ...
``` | jQuery ignores response | [
"",
"javascript",
"jquery",
"html",
"ajax",
""
] |
I have a simple object that allows you to assign three properties (x,y,z) (lets call this object a "point", because that is what it is). I then have a second object with a method that accepts two instances of the first object, and returns the distance between the two "points" in three dimensional space. I also need a method that will accept two "points"
and a double, representing distance traveled (from the first "point" parameter used) that returns a "point" object with its x,y,z coordinates.
I'm ok with everything except the calculation of the point coordinates that are on the original line between the two points supplied, that is at a certain distance from the first point.
"point" object:
```
public class POR
{
private double PORX;
private double PORY;
private double PORZ;
public double X
{
get { return PORX; }
set { PORX = value; }
}
public double Y
{
get { return PORY; }
set { PORY = value; }
}
public double Z
{
get { return PORZ; }
set { PORZ = value; }
}
public POR(double X, double Y, double Z)
{
PORX = X;
PORY = Y;
PORZ = Z;
}
```
I'm then using :
```
public double PorDistance(POR por1, POR por2)
{
return Math.Round(Math.Sqrt( Math.Pow((por1.X - por2.X),2) + Math.Pow((por1.Y - por2.Y),2) + Math.Pow((por1.Z - por2.Z),2)),2);
}
```
to return the distance between those two points I need something like
```
public POR IntersectPOR (POR por1, POR por2, double distance)
{
}
```
where distance is the distance traveled from por1 towards por2. | This can be done with a bit of help from vectors.
Let's say your starting point is called P, and the other point is Q, and the distance is d. You want to find the point on the line PQ at a distance d from P towards Q.
1. First you need to find the direction of travel. That's done by finding Q - P
```
v = Point(Q.x - P.x, Q.y - P.y, Q.z - P.z)
```
2. Now you need to find the unit vector in that direction, so
```
scale = sqrt(v.x*v.x + v.y*v.y + v.z*v.z)
unit = Point(v.x/scale, v.y/scale, v.z/scale)
```
3. Now you need to find the vector representing the distance traveled:
```
t = Point(unit.x*d, unit.y*d, unit.z*d)
```
4. To find the final position, add your traveled vector to your starting point:
```
final = Point(P.x + t.x, P.y + t.y, P.z + t.z)
``` | It looks like you want something similar to:
```
public class Point
{
public double x, y, z;
// ctors, Add(), Subtract() omitted
public Point Normalize()
{
double m = Magnitude;
if (m != 0.0) return ScaleTo(1.0/m);
return new Point();
}
public double Magnitude
{
get { return Math.Sqrt(x * x + y * y + z * z); }
}
public Point ScaleTo(double s)
{
return new Point(x * s, y * s, z * s);
}
}
public Point PointOnLine(Point from, Point to, double dist)
{
return from.Add(to.Subtract(from).Normalize().ScaleTo(dist));
}
``` | Intersection of a line and a Sphere? | [
"",
"c#",
"math",
"3d",
""
] |
What is returned if $('#id') doesn't match anything? I figured it would be null or false or something similar so I tried checking like so:
```
var item = $('#item');
if (!item){
...
}
```
But that didn't work. | You can find how many elements were matched using:
```
$('selector').length
```
To check whether no elements were matched, use:
```
var item = $('#item');
if (item.length == 0) {
// ...
}
``` | While `$('selector').length` is great for finding out how many objects your selector matches, its actually completely unnecesary. The thing about jQuery is that all selector based functions use length internally, so you could just do `$(selector).hide()` (or whatever) and it takes no action for an empty set. | jQuery: What is returned if $('#id') doesn't match anything? | [
"",
"javascript",
"jquery",
"css",
"jquery-selectors",
""
] |
I recently read the following overflow post:
[Hidden Features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
One of the features pointed out was the arglist. Why would one choose this or the alternatives as a means of using a variable length argument list to a method? Also, note that I would probably not use this kind of construct in my code unless a corner case warranted doing so. This is more of a question of semantics than whether it is even practical or prudent to even use variable length arguments. So does anyone know which is better and why?
```
[Test]
public void CanHandleVariableLengthArgs()
{
TakeVariableLengthArgs(__arglist(new StringBuilder(), 12));
object[] arr = { new StringBuilder() };
TakeVariableLengthArgs2(arr);
TakeVariableLengthArgs3(
new Dictionary<string, object>
{ { "key", new StringBuilder() } });
}
public void TakeVariableLengthArgs(__arglist)
{
var args = new ArgIterator(__arglist);
var a = (StringBuilder)TypedReference.ToObject(args.GetNextArg());
a.Append(1);
}
public void TakeVariableLengthArgs2(params object[] args)
{
var a = (StringBuilder)args[0];
a.Append(1);
}
public void TakeVariableLengthArgs3(Dictionary<string, object> args)
{
var a = (StringBuilder)args["StringBuilder"];
a.Append(1);
}
``` | I would certainly never use \_\_arglist, since it's undocumented and nobody knows what it means in any case.
I'd also avoid variable-length argument lists for as long as possible, and instead rework my design to understand what is truly variable, and to model that variability in a less platform-dependant manner. | It depends on the case. I've used params in cases where I have a variable number of arguments and it significantly adds to the readability of the calling code.
For example, I have a class that represents a TIFF document and allows access to a collection of pages which can be reordered and interspersed with other TIFF documents. Since one of the most common tasks our customers want is the ability to easily combine multiple TIFF documents into a single, we also provide the following two utility methods:
```
public static void Combine(Stream output, params Stream[] sources) { /* ... */ }
public static void Combine(Stream output, params string[] sourceFiles) { /* ... */ }
```
which in usage make the client code feel really nice:
```
using (FileStream output = new FileStream(outputPath, FileMode.Create)) {
TiffDocument.Combine(output, tpsCoverSheetPath, mainDocumentPath, tpsTrailerPath);
}
``` | C# variable length args, which is better and why: __arglist, params array or Dictionary<T,K>? | [
"",
"c#",
"c#-3.0",
"c#-2.0",
""
] |
I have some tables with data:
**Category**
```
CategoryID CategoryName
1 Home
2 Contact
3 About
```
**Position**
```
PositionID PositionName
1 Main menu
2 Left menu
3 Right menu
```
...(new row can be added later)
**CategoryPosition**
```
CPID CID PID COrder
1 1 1 1
2 1 2 2
3 1 3 3
4 2 1 4
5 2 3 5
```
How can I make a table like this:
```
CID CName MainMenu LeftMenu RightMenu
1 Home 1 2 3
2 Contact 4 0 5
3 About 0 0 0
```
And if a new Category or Position row is added later, the query should reflect the change automatically, e.g:
```
CID CName MainMenu LeftMenu RightMenu BottomMenu
1 Home 1 2 3 0
2 Contact 4 0 5 0
3 About 0 0 0 0
4 News 0 0 0 0
``` | The following dynamic query seems to work:
```
declare @columnlist nvarchar(4000)
select @columnlist = IsNull(@columnlist + ', ', '') + '[' + PositionName + ']'
from #Position
declare @query nvarchar(4000)
select @query = '
select *
from (
select CategoryId, CategoryName, PositionName,
IsNull(COrder,0) as COrder
from #Position p
cross join #Category c
left join #CategoryPosition cp
on cp.pid = p.PositionId
and cp.cid = c.CategoryId
) pv
PIVOT (max(COrder) FOR PositionName in (' + @columnlist + ')) as Y
ORDER BY CategoryId, CategoryName
'
exec sp_executesql @query
```
Some clarification:
* The @columnlist contains the dymamic field list, built from the Positions table
* The cross join creates a list of all categories and all positions
* The left join seeks the corresponding COrder
* max() selects the highest COrder per category+position, if there is more than one
* PIVOT() turns the various PositionNames into separate columns
P.S. My table names begin with #, because I created them as temporary tables. Remove the # to refer to a permanent table.
P.S.2. If anyone wants to try his hands at this, here is a script to create the tables in this question:
```
set nocount on
if object_id('tempdb..#Category') is not null drop table #Category
create table #Category (
CategoryId int identity,
CategoryName varchar(50)
)
insert into #Category (CategoryName) values ('Home')
insert into #Category (CategoryName) values ('Contact')
insert into #Category (CategoryName) values ('About')
--insert into #Category (CategoryName) values ('News')
if object_id('tempdb..#Position') is not null drop table #Position
create table #Position (
PositionID int identity,
PositionName varchar(50)
)
insert into #Position (PositionName) values ('Main menu')
insert into #Position (PositionName) values ('Left menu')
insert into #Position (PositionName) values ('Right menu')
--insert into #Position (PositionName) values ('Bottom menu')
if object_id('tempdb..#CategoryPosition') is not null
drop table #CategoryPosition
create table #CategoryPosition (
CPID int identity,
CID int,
PID int,
COrder int
)
insert into #CategoryPosition (CID, PID, COrder) values (1,1,1)
insert into #CategoryPosition (CID, PID, COrder) values (1,2,2)
insert into #CategoryPosition (CID, PID, COrder) values (1,3,3)
insert into #CategoryPosition (CID, PID, COrder) values (2,1,4)
insert into #CategoryPosition (CID, PID, COrder) values (2,3,5)
``` | Since PIVOT requires a static list of columns, I think a dynamic-sql-based approach is really all that you can do: <http://www.simple-talk.com/community/blogs/andras/archive/2007/09/14/37265.aspx> | Join with dynamic pivot (version 2) | [
"",
"sql",
"sql-server",
"sql-server-2008",
"join",
""
] |
I have an ASPX page with two RequiredFieldValidator and a button to go to another page. This button must do a postback to know where to go. This button can be clicked it any time.
The problem is that the RequiredFieldValidators are not disabled and show their message asking for a value.
Is there any way to avoid validation when the user click this special button?
Thank you! | Set CausesValidation to false on the special button, or put the RequiredFieldValidators in a ValidationGroup with whatever should cause the validation. (The button that should cause validation and the validators should all be in the same validation group) The first option should work and be the quickest. | CausesValidation="false" | ASP.NET: avoid RequiredFieldValidator on navigate button postback | [
"",
"c#",
"asp.net",
"requiredfieldvalidator",
""
] |
I've been working on a really large project for almost 2 years and the client requirements keep changing. These changes, of course, effect everything and I would like to find a way to work with the CSS in a more dynamic fashion.
I assume I could get one of the ruby or python CSS DSLs running under ironRuby/Python but this client is very very particular about what software/frameworks are installed.
I have not found a CSS DSL where the base programming language is vb or c#.
reference:
<http://sandbox.pocoo.org/clevercss/> and <http://nubyonrails.com/articles/dynamic-css> | Less CSS for .NET was recently released.
<http://www.dotlesscss.org/> | I am not sure about any publicly available products, but I have written an ASP.NET HttpHandler for .css files a few times. Its a pretty simple task, and I usually add things like variable and basic expression support, realtime minification, comment stripping, etc. Is this what your looking for? If so, I think each time its taken maybe 10 hours of work max to write, debug, and implement the handler...not too bad given all the benefits. | Is there a .NET based CSS abstraction library? | [
"",
"c#",
".net",
"css",
"vb.net",
"dsl",
""
] |
I'm trying to write an extension method to insert data into a dictionary of dictionaries defined as follows:
```
items=Dictionary<long,Dictionary<int,SomeType>>()
```
What I have so far is:
```
public static void LeafDictionaryAdd<TKEY1,TKEY2,TVALUE>(this IDictionary<TKEY1,IDictionary<TKEY2,TVALUE>> dict,TKEY1 key1,TKEY2 key2,TVALUE value)
{
var leafDictionary =
dict.ContainsKey(key1)
? dict[key1]
: (dict[key1] = new Dictionary<TKEY2, TVALUE>());
leafDictionary.Add(key2,value);
}
```
but the compiler doesn't like it. The statement:
```
items.LeafDictionaryAdd(longKey, intKey, someTypeValue);
```
gives me a type inference error.
For the statement:
```
items.LeafDictionaryAdd<long, int, SomeType>(longKey, intKey, someTypeValue);
```
I get "...does not contain a definition for... and the best extension method overload has some invalid arguments.
What am I doing wrong? | Some inventive generic usage ;-p
```
class SomeType { }
static void Main()
{
var items = new Dictionary<long, Dictionary<int, SomeType>>();
items.Add(12345, 123, new SomeType());
}
public static void Add<TOuterKey, TDictionary, TInnerKey, TValue>(
this IDictionary<TOuterKey,TDictionary> data,
TOuterKey outerKey, TInnerKey innerKey, TValue value)
where TDictionary : class, IDictionary<TInnerKey, TValue>, new()
{
TDictionary innerData;
if(!data.TryGetValue(outerKey, out innerData)) {
innerData = new TDictionary();
data.Add(outerKey, innerData);
}
innerData.Add(innerKey, value);
}
``` | Try to use a concrete type:
```
public static void LeafDictionaryAdd<TKEY1,TKEY2,TVALUE>(this IDictionary<TKEY1, Dictionary<TKEY2,TVALUE>> dict,TKEY1 key1,TKEY2 key2,TVALUE value)
```
see the **`Dictionary<TKEY2,TVALUE>`** instead of `IDictionary<TKEY2,TVALUE>` | Extension method for Dictionary of Dictionaries | [
"",
"c#",
"dictionary",
"extension-methods",
""
] |
I've just added yet another 3rd-party component to my .net project that contains a class called `Client` and it got me thinking about common class names.
Do you name your public classes something as common as `Client`, or do you try to make the name more specific?
In the past I would have said `Client` was fine, since it can always be accessed explicitly via its namespace (`Company.Product.Client`) but MS seem to stick to more descriptive class names in the .net framework, such as `WebClient`, `TcpClient` and `SmtpClient`.
I think names like `MessagePub.Client` look quite neat, and `MessagePub.MessagePubClient` much less so, but then having lots of `Client`s floating about also feels quite messy.
All of these 3rd-party components I'm using are actually open source, so is it recommended to refactor and change their class names to something more descriptive to make my code more readable or is accessing via their namespace a better idea? Or does it just not matter? :-) | I think a more descriptive name almost always is better. Its not just a technical issue, but certainly also a semantic one : for one thing it obliges you to think what kind of class you're dealing with exactly and helps you to set the boundaries. | Don't forget about the [**namespace alias quantifier**](http://msdn.microsoft.com/en-us/library/c3ay4x3d.aspx) when you have to deal with third-party libraries using similar/identical names:
```
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
```
Like that you can distinguish easily between the different classes:
```
Excel.Application excelApp = new Excel.Application();
Word.Application wordApp = new Word.Application();
``` | What should I do when a class name is very common? | [
"",
"c#",
".net",
"naming-conventions",
"class-design",
""
] |
I'm working on writing a Pong game and I've run across a problem.
I'm trying to figure out how to bounce a point off of a line.
The best method I can figure out to do this with is
* Calculate the current and future position of the Ball.
+ Line Segment: {Ball.location, Ball.location + Ball.direction} (Ball.location and Ball.direction use a custom vector/coordinate class)
* Calculate if the generated line segment intersects with any of the walls or paddles.
+ ??? Don't know how to do this yet (Will ask in a separate question)
* At the first intersection found
+ Bounce the ball off of the line
- Create a triangle formed with
* a = Ball's current position
* b = Intersection point of the line.
* c = Closest point to the Ball's current position on the line.
- Find the angle that the ball hits the line
* angle = cos(distance(b, c) / distance(a, b))
- Find the angle to rotate the ball's direction
* (90 - angle)\*2
- Rotate Ball's direction and move it to it's new position
* ignoring distance traveled to hit the line for now, doesn't need to be exactly on the line
* Else if there is no intersection
+ Move the ball to it's new position.
Is this an acceptable method or am I missing something? | You just need to check if the center of the ball is within its radius of the paddle to tell whether or not its time to bounce. There was an older question asked that has several answers on [calculating bounce angle](https://stackoverflow.com/questions/573084/how-to-calculate-bounce-angle). | If you want the authentic Pong feel, then computing the new vector is much easier than doing real reflections. Pong just reverses the sign of either dx or dy. If the ball hits a horizontal barrier, then negate dy. Vertical, then negate dx. | How do I bounce a point off of a line? | [
"",
"c++",
"graphics",
"physics",
""
] |
What is the best way to generate a unique hardware ID on Microsoft Windows with C++ that is not easily spoofable (with for example changing the MAC Address)? | Windows stores a unique Guid per machine in the registry at:
```
HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\MachineGuid
``` | There are a variety of "tricks", but the only real "physical answer" is "no, there is no solution".
A "machine" is nothing more than a passive bus with some hardware around.
Although each piece of iron can provide a somehow usable identifier, every piece of iron can be replaced by a user for whatever bad or good reason you can never be fully aware of (so if you base your functionality on this, you create problems to your user, and hence -as a consequence- to yourself every time an hardware have to be replaced / reinitialized / reconfigured etc. etc.).
Now, if your problem is identify a machine in a context where many machines have to inter-operate together, this is a role well played by MAC or IP addresses or Hostnames. But be prepared to the idea that they are not necessarily constant on long time-period (so avoid to hard-code them - instead "discover then" upon any of your start-up)
If your problem is -instead- identify a software instance or a licence, you have probably better to concentrate on another kind of solution: you sell licences to "users" (it is the user that has the money, not his computer!), not to their "machines" (that users must be free to change whenever they need/like without your permission, since you din't licence the hardware or the OS...), hence your problem is not to identify a machine, but a USER (consider that a same machine can be a host for many user and that a same user can work on a variety of machines ..., you cannot assume/impose a 1:1 relation, without running into some kind of problems sooner or later, when this idiom ifs found to no more fit).
The idea should be to register the users in a somewhat reachable site, give them keys you generate, and check that a same user/key pair is not con-temporarily used more than an agreed number of times under a given time period. When violations exceed, or keys becomes old, just block and wait for the user to renew.
As you can see, the answer mostly depends on the reason behind your question, more than from the question itself. | Generating a Hardware-ID on Windows | [
"",
"c++",
"windows",
"unique",
"uuid",
"copy-protection",
""
] |
I have a web application and two class files,
First class is **MyClass.class** which is inside the abc.jar file (WEB-INF/lib/abc.jar) and
Second class is **YourClass.class** which is inside classes folder (WEB-INF/classes/ YourClass.class).
My question is which class would load first when the Application starts? And Why ? | In my experience you can't predict the order in which the classes are loaded by the JVM.
Once I made a test runner (kinda Maven's Surefire) and with the same JVM and OS it loaded classes in different order when run in different machines. The lesson learnt:
> You shouldn't build your applications
> to depend on class loading order | Classes are loaded as needed, for some definition of "needed". Exactly when a class is loaded is dependent upon the JRE implementation, javac implementation, exactly what thread are up to, server code and, of course, application code. It's a bad idea to make assumptions in this area. If you want to see what happens for a particular run, you can use [`-verbose:class`](http://java.sun.com/javase/6/docs/technotes/tools/windows/java.html#options) | Which class would load first when Web application starts? | [
"",
"java",
"servlets",
"classloader",
""
] |
does FastCGI work well with PHP? It seems that some people running Ruby on Rails have problems with FastCGI, but is it fine with PHP? | [Does PHP work with FastCGI?](http://www.fastcgi.com/docs/faq.html#PHP) [FastCGI official FAQ] | I use FastCGI (through php-cgi) with [Cherokee](http://www.cherokee-project.org) for PHP and it's just grand. No issues.
I would definitely recommend installing xcache at the same time. The performance boost will blow your socks into next week.
I've just seen you asking about Apache in one of the comments. I don't know why you'd choose FastCGI over mod\_php. The performance difference would be almost invisible but I'm certain mod\_php would be slightly faster (and a ton more simple to set up).
Well I genuinely thought that was the case. And then I read this: <http://www.gnegg.ch/2006/08/mod_php-lighttpd-fastcgi-whats-fastest/>
And it looks like Apache+FastCGI is faster than Apache+mod\_php. Odd. | does FastCGI work well with PHP? | [
"",
"php",
"fastcgi",
""
] |
I have a problem with a javascript error: `$("#slider") is undefined`
How can i solve this problem?
```
<script type="text/javascript">
$(document).ready(function() {
$("#slider").easySlider({
controlsBefore: '<p id="controls">',
controlsAfter: '</p>',
prevId: 'prevBtn',
nextId: 'nextBtn'
});
});
</script>
```
This is my html
```
<div id='slider'>
<table>
<tr>
<td width='325'>hello</td>
<td width='325'>hello</td>
</table>
</div>
``` | ```
jQuery(document).ready(function() {
jQuery("#slider").easySlider({
controlsBefore: '<p id="controls">',
controlsAfter: '</p>',
prevId: 'prevBtn',
nextId: 'nextBtn'
});
});
```
Probebly you got more then 1 jQuery script try this script if it work you have to change the order of script use | I doubt there's a problem in the code you've pasted here -- even if you wrote something like this:
```
$('bladkhadlhadkjha').easySlider({ ... });
```
You wouldn't be getting the "undefined" error, since jQuery would handle that gracefully. Make sure that jQuery is being included properly, your plugin is being included properly and that the code you've pasted is exactly the code you're having the problem with. | Javascript undefined variable | [
"",
"javascript",
"jquery",
"undefined",
""
] |
I am using NUnit 2.5, and I want to test a method that recieves several parameters.
Is it reasonable to try to test them using one Test method, with several different TestCases, or will it be harder to maintain (Or just pin point the exact failure) in the long run?
My general idea is to try something like
```
[TestCase("valid", Result="validasd",
Description = "Valid string test, expecting valid answer")]
[TestCase(null, ExpectedException = typeof(ArgumentNullException),
Description = "Calling with null, expecting exception")]
[TestCase("", ExpectedException = typeof(ArgumentException),
Description = "Calling with an empty string, expecting exception")]
public string TestSubString(string value)
{
return MethodUnderTest(value);
}
```
Is it also a recommended usage - without an explicit assert, just checking on the return value? Or should I stick to the normal way or asserting the value inside the method? | I have found the TestCase attribute to be useful when testing methods that primarily accept some simple values, compute with them, and then return a result. In these cases, it takes substantially less overhead and duplication to write such tests.
This approach does not work when the method requires complex object parameters, because the TestCase attribute can only accept primitive types as input parameters to pass to the method.
You may also want to consider writing a more typical unit test if:
1. other developers on your team are not familiar with this technique
2. the signature of the method likely to change or accommodate more parameters
3. if there are more than a handful of test cases or combinations of values to test
4. you need the tests to execute in a particular order
5. you want to run your tests using [ReSharper](http://www.jetbrains.com/resharper/index.html) for Visual Studio (it currently does not recognize the TestCase attribute) | I would avoid that. It would be extremely hard to maintain. I would have one test method for each case. | Unit testing several different results in one method | [
"",
"c#",
"unit-testing",
"nunit",
""
] |
So, I started to build a small test application to test lambda expressions. I found several examples here and elsewhere but I just don't get them.
Can anybody explain my how to build an expression by using textboxes or any other variables?
My Test List
```
List<People> lPeople = new List<People>
{
new People { Name= "Jean", LastName = "Borrow", Age= 21 } ,
new People { Name= "Dean", LastName = "Torrow", Age= 20 }
};
```
Working lambda Expression
```
IEnumerable<People> result = lPeople.Where(p => p.Age < 21);
dgv_1.DataSource = result.ToList();
dgv_1.Update();
```
How can I build the expressions dynamically?
Something like `lPeople.Where(p => p.LastName == Textbox.Text);` (which of course doesn't work)
Thanks!
Edit: Added some code to the solution below
```
Int32 iAge;
Boolean bSuc = Int32.TryParse(tb_filter_age.Text, out iAge);
if (!bSuc)
{
iAge = 0;
}
``` | "which of course doesn't work"
What happens when you try it? By the look of it, that's the kind of thing I do all the time.
To switch operations based on a ComboBox specifying the operator:
```
int age = int.Parse(textBoxAge.Text);
IEnumerable<People> result;
if (comboBoxOperator.Text == "=")
result = lPeople.Where(p => p.Age == age);
else if (comboBoxOperator.Text == "<")
result = lPeople.Where(p => p.Age < age);
else
result = lPeople.Where(p => p.Age > age);
dgv_1.DataSource = result.ToList();
dgv_1.Update();
```
The code that converts the age string into an `int` will throw if the user enters something that can't be converted. Look up `TryParse` to avoid exceptions. | Try the Predicate Builder at <http://www.albahari.com/nutshell/predicatebuilder.aspx>
I used it to make an advanced search where the user could keep adding optional search criteria. | Dynamic build lambda expressions | [
"",
"c#",
"lambda",
""
] |
I'm trying to declare a method in main.h like this:
```
void buildGraph(int gNum, Graph** gArray);
```
Where Graph is a class and I'm trying to pass a pointer to an array of pointers to Graph objects.
I get the error message: "Graph has not been declared".
Even though I have #include "graph.h" at the top of the page and I've been using the
graph class plenty until now, so I know it works.
Any ideas? | Maybe the name Graph is in a namespace? What does that graph.h file say -- is Graph at top-level, or inside a namespace statement? | It's likely that you have more than one graph.h file in the filesystem and the wrong one is included. If it's because of accidential copying remove the unneeded copies, if it's because of collision with C++ standart library or other libraries headers you should rename you header files to prevent such collisions in future. | Passing a **Class as an argument | [
"",
"c++",
"class",
""
] |
For example DbVisualizer can be used to connect to a DB and create nice diagram out of existing tables and their relations. But in this specific case I do not have a live database but I have bunch of create table and alter statements.
Is there any tool to generate similar diagrams out of SQL DDL? | I believe that Embarcadero's ERStudio can import a SQL script into a diagram, but it's a pricey tool to use just for something like this. You could always just create an empty database and run the scripts then point to that. | I found the MySQL tool MySQL Workbench to do a great job. There is a Mac OS X version. More information can be found at <http://dev.mysql.com/doc/index-gui.html>. | How to generate Entity-Relation diagram from SQL DDL? | [
"",
"sql",
"database-design",
"ddl",
"erd",
""
] |
I have a somewhat obscure question here.
What I need: To determine if the permissions (or, strictly speaking, a specific ACE of a DACL) of a file/folder was inherited.
How I tried to solve this: using winapi bindings for python (win32security module, to be precise). Here is the stripped down version, that does just that, - it simply takes a path to a file as an argument and prints out ACEs one by one, indicating which flags are set.
```
#!/usr/bin/env python
from win32security import *
import sys
def decode_flags(flags):
_flags = {
SE_DACL_PROTECTED:"SE_DACL_PROTECTED",
SE_DACL_AUTO_INHERITED:"SE_DACL_AUTO_INHERITED",
OBJECT_INHERIT_ACE:"OBJECT_INHERIT_ACE",
CONTAINER_INHERIT_ACE:"CONTAINER_INHERIT_ACE",
INHERIT_ONLY_ACE:"INHERIT_ONLY_ACE",
NO_INHERITANCE:"NO_INHERITANCE",
NO_PROPAGATE_INHERIT_ACE:"NO_PROPAGATE_INHERIT_ACE",
INHERITED_ACE:"INHERITED_ACE"
}
for key in _flags.keys():
if (flags & key):
print '\t','\t',_flags[key],"is set!"
def main(argv):
target = argv[0]
print target
security_descriptor = GetFileSecurity(target,DACL_SECURITY_INFORMATION)
dacl = security_descriptor.GetSecurityDescriptorDacl()
for ace_index in range(dacl.GetAceCount()):
(ace_type,ace_flags),access_mask,sid = dacl.GetAce(ace_index)
name,domain,account_type = LookupAccountSid(None,sid)
print '\t',domain+'\\'+name,hex(ace_flags)
decode_flags(ace_flags)
if __name__ == '__main__':
main(sys.argv[1:])
```
Simple enough - get a security descriptor, get a DACL from it then iterate through the ACEs in the DACL. The really important bit here is INHERITED\_ACE access flag. It should be set when the ACE is inherited and not set explicitly.
When you create a folder/file, its ACL gets populated with ACEs according to the ACEs of the parent object (folder), that are set to propagate to children. However, unless you do any change to the access list, the INHERITED\_ACE flag will NOT be set! But the inherited permissions are there and they DO work.
If you do any slight change (say, add an entry to the access list, apply changes and delete it), the flag magically appears (the behaviour does not change in any way, though, it worked before and it works afterwards)! What I want is to find the source of this behaviour of the INHERITED\_ACE flag and, maybe find another *reliable* way to determine if the ACE was inherited or not.
How to reproduce:
1. Create an object (file or folder)
2. Check permissions in windows explorer, see that they have been propagated from the parent object (using, say, security tab of file properties dialog of windows explorer).
3. Check the flags using, for example, the script I was using (INHERITED\_ACE will NOT be set on any ACEs).
4. Change permissions of an object (apply changes), change them back even.
5. Check the flags (INHERITED\_ACE *will* be there)
6. ..shake your head in disbelief (I know I did)
Sorry for a somewhat lengthy post, hope this makes at least a little sense. | On my Win XP Home Edition this code doesn't seem to work at all :-)
I get this stack trace:
> Traceback (most recent call last):
> File "C:\1.py", line 37, in
> main(sys.argv[1:])
> File "C:\1.py", line 29, in main
> for ace\_index in range(dacl.GetAceCount()):
>
> AttributeError: 'NoneType' object has no attribute 'GetAceCount'
Can you just try to "nudge" the DACL to be filled?
I mean, if you know it's going to work after you make a slight change in it... do a slight change programmatically, add a stub ACE and remove it. Can you?
**UPDATE.** I made an experiment with a C# program on my work machine (with Win XP Prof) and I must tell you that the .net way of getting this security information actually works. So, when I create a new file, my C# program detects that the ACEs were inherited, while your python code doesn't.
Here is the sample output of my runs:
> C:>csharp\_tricks.exe 2.txt
>
> FullControl --> IsInherited: True
>
> FullControl --> IsInherited: True
>
> ReadAndExecute, Synchronize --> IsInherited: True
>
> ---
>
> C:>1.py 2.txt
>
> 2.txt
>
> BUILTIN\Administrators 0x0
>
> NT AUTHORITY\SYSTEM 0x0
>
> BUILTIN\Users 0x0
My C# class:
```
public class InheritedAce
{
public static string GetDACLReport(string path)
{
StringBuilder result = new StringBuilder();
FileSecurity fs = new FileSecurity(path, AccessControlSections.Access);
foreach (var rule in fs.GetAccessRules(true, true, typeof(SecurityIdentifier)).OfType<FileSystemAccessRule>())
{
result.AppendFormat("{0} --> IsInherited: {1}", rule.FileSystemRights, rule.IsInherited);
result.AppendLine();
}
return result.ToString();
}
}
```
So, it seems to be a bug in the python pywin32 security library. Maybe they aren't doing all the necessary system calls... | You can use the .Net framework
```
System.Security.AccessControl
```
This covers ACL and DACL and SACL. | A reliable way to determine if ntfs permissions were inherited | [
"",
"python",
"winapi",
"acl",
"ntfs",
"file-permissions",
""
] |
I'm in the process of creating a double-linked list, and have overloaded the operator= to make on list equal another:
```
template<class T>
void operator=(const list<T>& lst)
{
clear();
copy(lst);
return;
}
```
but I get this error when I try to compile:
```
container_def.h(74) : error C2801: 'operator =' must be a non-static member
```
Also, if it helps, line 74 is the last line of the definition, with the "}". | Exactly what it says: operator overloads must be member functions. (declared inside the class)
```
template<class T>
void list<T>::operator=(const list<T>& rhs)
{
...
}
```
Also, it's probably a good idea to return the LHS from = so you can chain it (like `a = b = c`) - so make it
`list<T>& list<T>::operator=....` | Put that operator inside your class definition. It must be a member because `operator=` is special and you would not gain something by writing it as a non-member anyway. A non-member operator has two important main benefits:
* Implicit conversions of the right *and* the left side of the operator invocation
* No need to know about internals of the class. Function can be realized as non-member non-friend.
For `operator=`, both is not usable. Assigning to a temporary result of a conversion does not make sense, and `operator=` will need access to internals in most cases. In addition, a special `operator=` is automatically provided by C++ if you don't provide one (the so-called copy-assignment operator). Making it possible to overload `operator=` as a non-member would have introduced additional complexity for apparently no practical gain, and so that isn't allowed.
So change your code so that it looks like this (this assumes the `operator=` is *not* a copy-assignment operator, but assigning from a `list<T>` to something else. This isn't clear from your question):
```
class MyClass {
...
template<class T>
MyClass& operator=(const list<T>& lst)
{
clear();
copy(lst);
return *this;
}
...
};
```
It's pretty standard that a `operator=` returns a reference to itself again. I recommend you to adhere to that practice. It will look familiar to programmers and could cause surprises if it would return `void` all of a sudden. | What does "operator = must be a non-static member" mean? | [
"",
"c++",
"class",
"operator-overloading",
"non-static",
""
] |
How do I reference a constant string in my .designer.cs file?
A straight forward answer is to create a private string variable in my .cs file, then edit the designer.cs file to use this variable instead of hardcoding the string. But the designer doesn't like this throws an error. I understand why this can't work, but I'm not sure of what the best alternative is.
Should each of my UI controls just have text as a place holder, then I need to override all text properties only at runtime? This way I loose the benefit of seeing everything in the designer.
I'm just trying to figure how to cause the least disruption when things change in the future. Thanks. | The `*.designer.*` files are generated by Visual Studio. You don't want to modify them by hand at all unless you really have to, because Visual Studio may at times *re*-generate them and erase your changes.
What you really need to do is think of your constant string a resource that you want to be available to the forms designer, so that when it generates the code it uses that resource.
There are several ways to accomplish this in Visual Studio. The easiest is probably via databindings for the controls. To demonstrate, put a label control on a form and look at the properties for the control. If you sort the properties by name there will be two properties at the top of the list enclosed in parentheses: `ApplicationSettings` and `DataBindings`. If you pull those down, you will see they both have options to bind to the `Text` property of your label. Using these, you can put your "constant string" in either your app's settings file and bind it via the `ApplicationSettings` property or in any datasource and bind it via the `DataBindings` property. Then the forms designer will generate the appropriate code for you. | It's not entirely clear to me what you're trying to achieve, but normally if you want to avoid the strings all being hard-coded into the designer .cs file, you use a resource file which the strings will be loaded from on startup.
If you set the "localizable" property of the form to be "true" I believe everything will end up in resources automatically. On the other hand, I'm far from expert at Windows Forms, so take all this with a pinch of salt until you've got it working :) | How to use constant strings in C# designer.cs code? | [
"",
"c#",
"constants",
"designer",
""
] |
I am trying to loop from 100 to 0. How do I do this in Python?
`for i in range (100,0)` doesn't work.
---
For discussion of **why** `range` works the way it does, see [Why are slice and range upper-bound exclusive?](https://stackoverflow.com/questions/11364533). | Try `range(100,-1,-1)`, the 3rd argument being the increment to use (documented [here](https://docs.python.org/library/functions.html#range)).
("range" options, start, stop, step are documented [here](https://docs.python.org/3/library/stdtypes.html?highlight=range#range)) | In my opinion, this is the most readable:
```
for i in reversed(range(101)):
print(i)
``` | Loop backwards using indices | [
"",
"python",
"loops",
""
] |
I'm trying to send a byte[] (using PUT) with Restlet but I can't find any info on how to do it. My code looks like this:
```
Request request = new Request(Method.PUT, url);
request.setEntity( WHAT DO I PUT HERE?, MediaType.APPLICATION_OCTET_STREAM);
```
I had expected to find something along the lines of ByteArrayRepresentation, just like there's a JsonRepresentation and a a StringRepresentation but I couldn't find anything. | I believe you want to use an [InputRepresentation](http://www.restlet.org/documentation/1.1/api/org/restlet/resource/InputRepresentation.html), like so:
```
Representation representation = new InputRepresentation(new ByteArrayInputStream(bytes), MediaType.APPLICATION_OCTET_STREAM);
request.setEntity(representation);
``` | I'm not familiar with restlet, but one way to do it would be to base64 encode the data. Then you could handle it like a regular string. | Sending binary data with the Restlet client | [
"",
"java",
"http",
"rest",
"restlet",
"put",
""
] |
In regards to: [Find Hyperlinks in Text using Python (twitter related)](https://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related)
How can I extract just the url so I can put it into a list/array?
---
## Edit
Let me clarify, I don't want to parse the URL into pieces. I want to extract the URL from the text of the string to put it into an array. Thanks! | In response to the OP's edit I hijacked [Find Hyperlinks in Text using Python (twitter related)](https://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related) and came up with this:
```
import re
myString = "This is my tweet check it out http://example.com/blah"
print(re.search("(?P<url>https?://[^\s]+)", myString).group("url"))
``` | Misunderstood question:
```
>>> from urllib.parse import urlparse
>>> urlparse('http://www.ggogle.com/test?t')
ParseResult(scheme='http', netloc='www.ggogle.com', path='/test',
params='', query='t', fragment='')
```
[or py2.\* version](http://docs.python.org/library/urlparse.html?#urlparse.urlparse):
```
>>> from urlparse import urlparse
>>> urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
params='', query='', fragment='')
```
**ETA**: regex are indeed are the best option here:
```
>>> s = 'This is my tweet check it out http://tinyurl.com/blah and http://blabla.com'
>>> re.findall(r'(https?://\S+)', s)
['http://tinyurl.com/blah', 'http://blabla.com']
``` | Extracting a URL in Python | [
"",
"python",
"url",
"parsing",
""
] |
Very straightforward:
**Is it possible to prevent the browser from scrolling when a user pressed arrow keys?** | Very straightforward: Yes, but don't do it.
Changing fundamental operation of how a browser operates just confuses or angers users, and makes the whole experience less user-friendly. The user should have ultimate control of the way his or her browser functions, not you. This is similar to blocking menu items from being accessed, or removing context menus etc. | yes.
use something like:
document.getElementById('yourID').onkeypress = HandleKeyPress;
```
function HandleKeyPress(e) {
var e = e || window.event;
switch (e.keyCode) {
case e.DOM_VK_LEFT:
case e.DOM_VK_RIGHT:
case e.DOM_VK_UP:
case e.DOM_VK_DOWN:
if (e.preventDefault)
e.preventDefault();
else e.returnValue = false;
}
}
```
Though it may not be a good idea to do so. just be sure that you're not overlooking a better approach. | Is it possible to prevent document scrolling when arrow keys are pressed? | [
"",
"javascript",
"html",
"browser",
"dom-events",
""
] |
I'm using Microsoft Visual C# 2008 Express.
In my main form, there's that X button to close the form at the top right. How do I add code to this button? In my menu, I have an "Exit" item and it has code that cleans up and closes my databases. How do I add the same code to this button if the user chooses that as a way to exit?
Thanks!
-Adeena | Using the FormClosing Event should catch any way of closing the form. | In the Design view for your form, within the Properties window, select the Events button and scroll down to the "FormClosed" and "FormClosing" events.
FormClosed is called after the form is closed.
FormClosing is called before the form is closed and also allows you to cancel the close, keeping the form open:
```
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
}
``` | How do I add code to the exit button in a c# form? | [
"",
"c#",
"button",
"exit",
""
] |
If I start python from the command line and type:
```
import random
print "Random: " + str(random.random())
```
It prints me a random number (Expected, excellent).
If I include the above-two lines in my django application's models.py and start my django app with runserver I get the output on the command line showing me a random number (Great!)
If I take a custom tag which works perfectly fine otherwise, but I include
```
import random
print "Random: " + str(random.random())
```
as the first 2 lines of the custom tag's .py file, I get an error whenever I try to open up a template which uses that custom tag:
```
TypeError at /help/
'module' object is not callable
```
Please keep in mind that if I get rid of these two lines, my custom tag behaves as otherwise expected and no error is thrown. Unfortunately, I need some random behavior inside of my template tag.
The problem is if in a custom tag I do:
```
import random
```
on a custom template tag, it imports
```
<module 'django.templatetags.random' from '[snip path]'>
```
and not
```
<module 'random' from 'C:\\Program Files\\Python26\\lib\\random.pyc'>
```
as is normally imported from everywhere else
Django template library has a filter called random, and somehow it is getting priority above the system's random.
Can anyone recommend how to explicitly import the proper python random? | The answer is ... strange.
When I originally wrote my custom tag, I called it `random.py`. I quickly realized that this name may not be good and renamed it `randomchoice.py` and deleted my `random.py` file. Python kept the compiled `random.pyc` file around, and it was getting loaded whenever I did `import random`. I removed my random.pyc file, and the problem went away. | Yes, this kind of error is pretty easy. Basically don't name any of your filenames or anything you create with the same names as any likely python modules you are going to use. | python random.random() causes "'module' object is not callable" when used in custom template tag | [
"",
"python",
"django",
"random",
"templatetags",
""
] |
The .NET security model throws security errors whenever a .NET exe is run from a file share. The error does not appear when ran from a local drive. Does anyone know of a way around this without requiring the code to be signed? | [Using CasPol to Fully Trust a Share](http://blogs.msdn.com/shawnfa/archive/2004/12/30/344554.aspx)
more answers here:
[Why does my .NET application crash when run from a network drive?](https://stackoverflow.com/questions/148879/why-does-my-net-application-crash-when-run-from-a-network-drive) | Use [caspol.exe](http://msdn.microsoft.com/en-us/library/cb6t8dtz(VS.80).aspx) to assign that file share enough permissions to run your program. | Running a .NET application from a file share without code signing | [
"",
"c#",
".net",
"vb.net",
"security",
"clr",
""
] |
Why does this attempt at creating a list of curried functions not work?
```
def p(x, num):
print x, num
def test():
a = []
for i in range(10):
a.append(lambda x: p (i, x))
return a
>>> myList = test()
>>> test[0]('test')
9 test
>>> test[5]('test')
9 test
>>> test[9]('test')
9 test
```
What's going on here?
A function that actually does what I expect the above function to do is:
```
import functools
def test2():
a = []
for i in range (10):
a.append(functools.partial(p, i))
return a
>>> a[0]('test')
0 test
>>> a[5]('test')
5 test
>>> a[9]('test')
9 test
``` | In Python, variables created in loops and branches aren't scoped. All of the functions you're creating with `lambda` have a reference to the same `i` variable, which is set to `9` on the last iteration of the loop.
The solution is to create a function which returns a function, thus scoping the iterator variable. This is why the `functools.partial()` approach works. For example:
```
def test():
def makefunc(i):
return lambda x: p(i, x)
a = []
for i in range(10):
a.append(makefunc(i))
return a
``` | Well you can also bind the i to an outer lambda for the lazy.
```
def p(x, num):
print x, num
def test():
a = []
for i in range(10):
a.append((lambda i :lambda x: p (i, x))(i))
return a
``` | What's going on with the lambda expression in this python function? | [
"",
"python",
"lambda",
""
] |
Sometimes I see and have used the following variation for a fast divide in C++ with floating point numbers.
```
// orig loop
double y = 44100.0;
for(int i=0; i<10000; ++i) {
double z = x / y;
}
// alternative
double y = 44100;
double y_div = 1.0 / y;
for(int i=0; i<10000; ++i) {
double z = x * y_div;
}
```
But someone hinted recently that this might not be the most accurate way.
Any thoughts? | On just about every CPU, a floating point divide is several times as expensive as a floating point multiply, so multiplying by the inverse of your divisor is a good optimization. The downside is that there is a possibility that you will lose a *very* small portion of accuracy on certain processors - eg, on modern x86 processors, 64-bit float operations are actually internally computed using 80 bits when using the default FPU mode, and storing it off in a variable will cause those extra precision bits to be truncated according to your FPU rounding mode (which defaults to nearest). This only really matters if you are concatenating many float operations and have to worry about the error accumulation. | [Wikipedia](http://en.wikipedia.org/wiki/Division_(digital)) agrees that this can be faster. The linked article also contains several other fast division algorithms that might be of interest.
I would guess that any industrial-strength modern compiler will make that optimization for you if it is going to profit you at all. | A good way to do a fast divide in C++? | [
"",
"c++",
"performance",
"math",
""
] |
I'm experimenting with MVVM for the first time and really like the separation of responsibilities. Of course any design pattern only solves many problems - not all. So I'm trying to figure out where to store application state and where to store application wide commands.
Lets say my application connects to a specific URL. I have a ConnectionWindow and a ConnectionViewModel that support gathering this information from the user and invoking commands to connect to the address. The next time the application starts, I want to reconnect to this same address without prompting the user.
My solution so far is to create an ApplicationViewModel that provides a command to connect to a specific address and to save that address to some persistent storage (where it's actually saved is irrelevant for this question). Below is an abbreviated class model.
The application view model:
```
public class ApplicationViewModel : INotifyPropertyChanged
{
public Uri Address{ get; set; }
public void ConnectTo( Uri address )
{
// Connect to the address
// Save the addres in persistent storage for later re-use
Address = address;
}
...
}
```
The connection view model:
```
public class ConnectionViewModel : INotifyPropertyChanged
{
private ApplicationViewModel _appModel;
public ConnectionViewModel( ApplicationViewModel model )
{
_appModel = model;
}
public ICommand ConnectCmd
{
get
{
if( _connectCmd == null )
{
_connectCmd = new LambdaCommand(
p => _appModel.ConnectTo( Address ),
p => Address != null
);
}
return _connectCmd;
}
}
public Uri Address{ get; set; }
...
}
```
So the question is this: Is an ApplicationViewModel the right way to handle this? How else might you store application state?
**EDIT:** I'd like to know also how this affects testability. One of the primary reasons for using MVVM is the ability to test the models without a host application. Specifically I'm interested in insight on how centralized app settings affect testability and the ability to mock out the dependent models. | If you weren't using M-V-VM, the solution is simple: you put this data and functionality in your Application derived type. Application.Current then gives you access to it. The problem here, as you're aware, is that Application.Current causes problems when unit testing the ViewModel. That's what needs to be fixed. The first step is to decouple ourselves from a concrete Application instance. Do this by defining an interface and implementing it on your concrete Application type.
```
public interface IApplication
{
Uri Address{ get; set; }
void ConnectTo(Uri address);
}
public class App : Application, IApplication
{
// code removed for brevity
}
```
Now the next step is to eliminate the call to Application.Current within the ViewModel by using Inversion of Control or Service Locator.
```
public class ConnectionViewModel : INotifyPropertyChanged
{
public ConnectionViewModel(IApplication application)
{
//...
}
//...
}
```
All of the "global" functionality is now provided through a mockable service interface, IApplication. You're still left with how to construct the ViewModel with the correct service instance, but it sounds like you're already handling that? If you're looking for a solution there, Onyx (disclaimer, I'm the author) can provide a solution there. Your Application would subscribe to the View.Created event and add itself as a service and the framework would deal with the rest. | I generally get a bad feeling about code that has one view model directly communicating with another. I like the idea that the VVM part of the pattern should be basically pluggable and nothing inside that area of the code should depend of the existence of anything else within that section. The reasoning behind this is that without centralising the logic it can become difficult to define responsibility.
On the other hand, based on your actual code, it may just be that the ApplicationViewModel is badly named, it doesn't make a model accessible to a view, so this may simply be a poor choice of name.
Either way, the solution comes down to a break down of responsibility. The way I see it you have three things to achieve:
1. Allow the user to request to connect to an address
2. Use that address to connect to a server
3. Persist that address.
I'd suggest that you need three classes instead of your two.
```
public class ServiceProvider
{
public void Connect(Uri address)
{
//connect to the server
}
}
public class SettingsProvider
{
public void SaveAddress(Uri address)
{
//Persist address
}
public Uri LoadAddress()
{
//Get address from storage
}
}
public class ConnectionViewModel
{
private ServiceProvider serviceProvider;
public ConnectionViewModel(ServiceProvider provider)
{
this.serviceProvider = serviceProvider;
}
public void ExecuteConnectCommand()
{
serviceProvider.Connect(Address);
}
}
```
The next thing to decide is how the address gets to the SettingsProvider. You could pass it in from the ConnectionViewModel as you do currently, but I'm not keen on that because it increases the coupling of the view model and it isn't the responsibility of the ViewModel to know that it needs persisting. Another option is to make the call from the ServiceProvider, but it doesn't really feel to me like it should be the ServiceProvider's responsibility either. In fact it doesn't feel like anyone's responsibility other than the SettingsProvider. Which leads me to believe that the setting provider should listen out for changes to the connected address and persist them without intervention. In other words an event:
```
public class ServiceProvider
{
public event EventHandler<ConnectedEventArgs> Connected;
public void Connect(Uri address)
{
//connect to the server
if (Connected != null)
{
Connected(this, new ConnectedEventArgs(address));
}
}
}
public class SettingsProvider
{
public SettingsProvider(ServiceProvider serviceProvider)
{
serviceProvider.Connected += serviceProvider_Connected;
}
protected virtual void serviceProvider_Connected(object sender, ConnectedEventArgs e)
{
SaveAddress(e.Address);
}
public void SaveAddress(Uri address)
{
//Persist address
}
public Uri LoadAddress()
{
//Get address from storage
}
}
```
This introduces tight coupling between the ServiceProvider and the SettingsProvider, which you want to avoid if possible and I'd use an EventAggregator here, which I've discussed in an answer to [this question](https://stackoverflow.com/questions/798964/wpf-mvvm-correct-way-to-fire-event-on-view-from-viewmodel/799079#799079)
To address the issues of testability, you now have a very defined expectancy for what each method will do. The ConnectionViewModel will call connect, The ServiceProvider will connect and the SettingsProvider will persist. To test the ConnectionViewModel you probably want to convert the coupling to the ServiceProvider from a class to an interface:
```
public class ServiceProvider : IServiceProvider
{
...
}
public class ConnectionViewModel
{
private IServiceProvider serviceProvider;
public ConnectionViewModel(IServiceProvider provider)
{
this.serviceProvider = serviceProvider;
}
...
}
```
Then you can use a mocking framework to introduce a mocked IServiceProvider that you can check to ensure that the connect method was called with the expected parameters.
Testing the other two classes is more challenging since they will rely on having a real server and real persistent storage device. You can add more layers of indirection to delay this (for example a PersistenceProvider that the SettingsProvider uses) but eventually you leave the world of unit testing and enter integration testing. Generally when I code with the patterns above the models and view models can get good unit test coverage, but the providers require more complicated testing methodologies.
Of course, once you are using a EventAggregator to break coupling and IOC to facilitate testing it is probably worth looking into one of the dependency injection frameworks such as Microsoft's Prism, but even if you are too late along in development to re-architect a lot of the rules and patterns can be applied to existing code in a simpler way. | Where to store application settings/state in a MVVM application | [
"",
"c#",
".net",
"wpf",
"unit-testing",
"mvvm",
""
] |
I'm reading out lots of texts from various RSS feeds and inserting them into my database.
Of course, there are several different character encodings used in the feeds, e.g. UTF-8 and ISO 8859-1.
Unfortunately, there are sometimes problems with the encodings of the texts. Example:
1. The "ß" in "Fußball" should look like this in my database: "Ÿ". If it is a "Ÿ", it is displayed correctly.
2. Sometimes, the "ß" in "Fußball" looks like this in my database: "ß". Then it is displayed wrongly, of course.
3. In other cases, the "ß" is saved as a "ß" - so without any change. Then it is also displayed wrongly.
What can I do to avoid the cases 2 and 3?
How can I make everything the same encoding, preferably UTF-8? When must I use `utf8_encode()`, when must I use `utf8_decode()` (it's clear what the effect is but when must I use the functions?) and when must I do nothing with the input?
How do I make everything the same encoding? Perhaps with the function `mb_detect_encoding()`? Can I write a function for this? So my problems are:
1. How do I find out what encoding the text uses?
2. How do I convert it to UTF-8 - whatever the old encoding is?
Would a function like this work?
```
function correct_encoding($text) {
$current_encoding = mb_detect_encoding($text, 'auto');
$text = iconv($current_encoding, 'UTF-8', $text);
return $text;
}
```
I've tested it, but it doesn't work. What's wrong with it? | If you apply `utf8_encode()` to an already UTF-8 string, it will return garbled UTF-8 output.
I made a function that addresses all this issues. It´s called `Encoding::toUTF8()`.
You don't need to know what the encoding of your strings is. It can be Latin1 ([ISO 8859-1)](https://en.wikipedia.org/wiki/ISO/IEC_8859-1), [Windows-1252](https://en.wikipedia.org/wiki/Windows-1252) or UTF-8, or the string can have a mix of them. `Encoding::toUTF8()` will convert everything to UTF-8.
I did it because a service was giving me a feed of data all messed up, mixing UTF-8 and Latin1 in the same string.
Usage:
```
require_once('Encoding.php');
use \ForceUTF8\Encoding; // It's namespaced now.
$utf8_string = Encoding::toUTF8($utf8_or_latin1_or_mixed_string);
$latin1_string = Encoding::toLatin1($utf8_or_latin1_or_mixed_string);
```
Download:
<https://github.com/neitanod/forceutf8>
I've included another function, `Encoding::fixUFT8()`, which will fix every UTF-8 string that looks garbled.
Usage:
```
require_once('Encoding.php');
use \ForceUTF8\Encoding; // It's namespaced now.
$utf8_string = Encoding::fixUTF8($garbled_utf8_string);
```
Examples:
```
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("FÃÂédÃÂération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
```
will output:
```
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football
```
I've transformed the function (`forceUTF8`) into a family of static functions on a class called `Encoding`. The new function is `Encoding::toUTF8()`. | You first have to detect what encoding has been used. As you’re parsing RSS feeds (probably via HTTP), you should read the encoding from the `charset` parameter of the [`Content-Type` HTTP header field](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17). If it is not present, read the encoding from the `encoding` attribute of the [XML processing instruction](http://www.w3.org/TR/REC-xml/#dt-xmldecl). If that’s missing too, [use UTF-8 as defined in the specification](http://www.w3.org/TR/REC-xml/#charencoding).
---
Here is what I probably would do:
I’d use [cURL](http://docs.php.net/curl) to send and fetch the response. That allows you to set specific header fields and fetch the response header as well. After fetching the response, you have to parse the HTTP response and split it into header and body. The header should then contain the `Content-Type` header field that contains the MIME type and (hopefully) the `charset` parameter with the encoding/charset too. If not, we’ll analyse the XML PI for the presence of the `encoding` attribute and get the encoding from there. If that’s also missing, the XML specs define to use UTF-8 as encoding.
```
$url = 'http://www.lr-online.de/storage/rss/rss/sport.xml';
$accept = array(
'type' => array('application/rss+xml', 'application/xml', 'application/rdf+xml', 'text/xml'),
'charset' => array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'byte2be', 'byte2le', 'byte4be', 'byte4le', 'BASE64', 'UUENCODE', 'HTML-ENTITIES', 'Quoted-Printable', '7bit', '8bit'))
);
$header = array(
'Accept: '.implode(', ', $accept['type']),
'Accept-Charset: '.implode(', ', $accept['charset']),
);
$encoding = null;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
$response = curl_exec($curl);
if (!$response) {
// error fetching the response
} else {
$offset = strpos($response, "\r\n\r\n");
$header = substr($response, 0, $offset);
if (!$header || !preg_match('/^Content-Type:\s+([^;]+)(?:;\s*charset=(.*))?/im', $header, $match)) {
// error parsing the response
} else {
if (!in_array(strtolower($match[1]), array_map('strtolower', $accept['type']))) {
// type not accepted
}
$encoding = trim($match[2], '"\'');
}
if (!$encoding) {
$body = substr($response, $offset + 4);
if (preg_match('/^<\?xml\s+version=(?:"[^"]*"|\'[^\']*\')\s+encoding=("[^"]*"|\'[^\']*\')/s', $body, $match)) {
$encoding = trim($match[1], '"\'');
}
}
if (!$encoding) {
$encoding = 'utf-8';
} else {
if (!in_array($encoding, array_map('strtolower', $accept['charset']))) {
// encoding not accepted
}
if ($encoding != 'utf-8') {
$body = mb_convert_encoding($body, 'utf-8', $encoding);
}
}
$simpleXML = simplexml_load_string($body, null, LIBXML_NOERROR);
if (!$simpleXML) {
// parse error
} else {
echo $simpleXML->asXML();
}
}
``` | Detect encoding and make everything UTF-8 | [
"",
"php",
"encoding",
"utf-8",
"character-encoding",
""
] |
Rather than hard-wiring some paths in my php.ini configuration, I'd like to configure them using system variables that are shared in some other places such as my Apache configuration. I've done some searching and couldn't find the right mix of keywords to discover if there's a way to do this.
Does anyone know if this can be done?
```
upload_tmp_dir = $SCRATCH_HOME/uploads
```
Now SCRATCH\_HOME can be exported in the environment as /tmp or /var/scratch or whatever I want it to be. | Documented officially: <https://www.php.net/manual/en/configuration.file.php#example-36>
Before I begin, I just want to specify my configurations:
I'm using Windows 7-64bit, PHP 5.4.3, Apache HTTP Server 2.2.x, I've set my environmental variable `PHP_HOME=C:\tools\php-5.4.3` (PHP installation directory).
I use the variable in my `httpd.conf` and `php.ini` file
Note: I will be omitting some text for brevity.
In the `httpd.conf` file
```
# For PHP 5 do something like this:
LoadModule php5_module "${PHP_HOME}/php5apache2_2.dll"
AddType application/x-httpd-php .php
# configure the path to php.ini
PHPIniDir "${PHP_HOME}"
```
In the `php.ini` file
```
; Directory in which the loadable extensions (modules) reside.
; http://php.net/extension-dir
; extension_dir = "./"
; On windows:
extension_dir = "${PHP_HOME}/ext"
``` | According to the [PHP docs](http://php.net/manual/en/configuration.file.php), environment-variables can indeed be used in the configuration file.

It doesn’t say anything about what syntax to use, but it is the same as with Apache’s configuration file which uses \*nix syntax. So for example, if you want PHP to use the system temp-directory, you would use this:
```
upload_tmp_dir = ${Temp}
```
You can confirm that it is active with the following script:
```
<?php
echo "ini: " . ini_get('upload_tmp_dir') . "\n";
echo "env: " . sys_get_temp_dir() . "\n";
echo "temp: " . getenv('temp') . "\n";
echo "tmp: " . getenv('tmp') . "\n";
?>
``` | Is it possible to use environment variables in php.ini? | [
"",
"php",
"configuration",
"environment-variables",
""
] |
I've got a python GUI app in the workings, which I intend to use on both Windows and Mac. The documentation on Tkinter isn't the greatest, and google-fu has failed me.
In short, I'm doing:
```
c = Canvas(
master=frame,
width=settings.WINDOW_SIZE[0],
height=settings.WINDOW_SIZE[1],
background=settings.CANVAS_COLOUR
)
file = PhotoImage(file=os.path.join('path', 'to', 'gif'))
c.create_bitmap(position, image=file)
c.pack()
root.mainloop()
```
If I comment out the create\_bitmap line, the app draws fine. If I comment it back in, I get the following error:
`_tkinter.TclError: unknown option "-image"`
Which is odd. Tkinter is fine, according to the python tests (ie, importing \_tkinter, Tkinter, and doing `Tk()`). I've since installed PIL against my windows setup (XP SP3, Python 2.6) imagining that it was doing some of the heavy lifting at a low level. It doesn't seem to be; I still get the aforementioned error.
The full stacktrace, excluding the code I've already pasted, is:
```
File "C:\Python26\lib\lib-tk\Tkinter.py", line 2153, in create_bitmap
return self._create('bitmap', args, kw)
File "C:\Python26\lib\lib-tk\Tkinter.py", line 2147, in _create
*(args + self._options(cnf, kw))))
```
Anyone able to shed any light? | Tk has two types of graphics, bitmap and image. Images come in two flavours, bitmap and photo. Bitmaps and Images of type bitmap are not the same thing, which leads to confusion in docs.
PhotoImage creates an image of type photo, and needs an image object in the canvas, so the solution is, as you already concluded, to use create\_image. | Short answer:
Don't use create\_bitmap when you mean to use create\_image. | Why in the world does Tkinter break using canvas.create_image? | [
"",
"python",
"python-imaging-library",
"tkinter",
"tk-toolkit",
""
] |
```
int main(void)
{
std::string foo("foo");
}
```
My understanding is that the above code uses the default allocator to call new. So even though the std::string foo is allocated on the stack the internal buffer inside of foo is allocated on the heap.
How can I create a string that is allocated entirely on the stack? | I wanted to do just this myself recently and found the following code illuminating:
[Chronium's stack\_container.h](http://src.chromium.org/viewvc/chrome/trunk/src/base/containers/stack_container.h?view=markup)
It defines a new `std::allocator` which can provide stack-based allocation for the initial allocation of storage for STL containers. I wound up finding a different way to solve my particular problem, so I didn't actually use the code myself, but perhaps it will be useful to you. Do be sure to read the comments in the code regarding usage and caveats.
To those who have questioned the utility and sanity of doing this, consider:
* Oftentimes you know a priori that your string has a reasonable maximum size. For example, if the string is going to store a decimal-formatted 32-bit integer,you know that you do not need more than 11 characters to do so. There is no need for a string that can dynamically grow to unlimited size in that case.
* Allocating from the stack is faster in many cases than allocating from the heap.
* If the string is created and destroyed frequently (suppose it is a local variable in a commonly used utility function), allocating from the stack instead of the heap will avoid fragmentation-inducing churn in the heap allocator. For applications that use a lot of memory, this could be a game changer.
Some people have commented that a string that uses stack-based allocation will not be a `std::string` as if this somehow diminishes its utility. True, you can't use the two interchangeably, so you won't be able to pass your `stackstring` to functions expecting a `std::string`. But (if you do it right), you will be able to use all the same member functions on your `stackstring` that you use now on `std::string`, like `find_first_of()`, `append()`, etc. `begin()` and `end()` will still work fine, so you'll be able to use many of the STL algorithms. Sure, it won't be `std::string` in the strictest sense, but it will still be a "string" in the practical sense, and it will still be quite useful. | The problem is that `std::basic_string` has a template parameter for the allocator. But `std::string` is not a template and has no parameters.
So, you could in principle use an instantiation of `std::basic_string` with an allocator that uses memory on the stack, but it wouldn't be a `std::string`. In particular, you wouldn't get runtime polymorphism, and you couldn't pass the resulting objects into functions expecting a `std::string`. | How do I allocate a std::string on the stack using glibc's string implementation? | [
"",
"c++",
"memory",
"heap-memory",
"stdstring",
"stack-memory",
""
] |
Can someone give me an example of how I would delete a row in mysql with Zend framework when I have two conditions?
i.e: (trying to do this)
```
"DELETE FROM messages WHERE message_id = 1 AND user_id = 2"
```
My code (that is failing miserably looks like this)
```
// is this our message?
$condition = array(
'message_id = ' => $messageId,
'profile_id = ' => $userId
);
$n = $db->delete('messages', $condition);
``` | Instead of an associative array, you should just be passing in an array of criteria expressions, ala:
```
$condition = array(
'message_id = ' . $messageId,
'profile_id = ' . $userId
);
```
(and make sure you escape those values appropriately if they're coming from user input) | Better to use this:
```
$condition = array(
'message_id = ?' => $messageId,
'profile_id = ?' => $userId
);
```
The placeholder symbols (?) get substituted with the values, escapes special characters, and applies quotes around it. | Example of a Multi Condition Delete with Zend framework | [
"",
"php",
"mysql",
"zend-framework",
"zend-db",
""
] |
I'm using the Python Shell in this way:
```
>>> s = 'Ã'
>>> s
'\xc3'
```
How can I print s variable to show the character Ã??? This is the first and easiest question. Really, I'm getting the content from a web page that has non ascii characters like the previous and others with tilde like á, é, í, ñ, etc. Also, I'm trying to execute a regex with these characters in the pattern expression against the content of the web page.
How can solve this problem??
This is an example of one regex:
```
u'<td[^>]*>\s*Definición\s*</td><td class="value"[^>]*>\s*(?P<data>[\w ,-:\.\(\)]+)\s*</td>'
```
If I use Expresson application works fine.
EDIT[05/26/2009 16:38]:
Sorry, about my explanation. I'll try to explain better.
I have to get some text from a page. I have the url of that page and I have the regex to get that text. The first thing I thought was the regex was wrong. I checked it with Expresso and works fine, I got the text I wanted. So, the second thing I thought was to print the content of the page and that was when I saw that the content was not what I see in the source code of the web page. The differences are the non ascii characters like á, é, í, etc. Now, I don't know what I have to do and if the problem is in the encoding of the page content or in the pattern text of the regex. One of the regex I've defined is the previous one.
The question wolud be: is there any problem using regex which pattern text has non ascii characters??? | Suppose you want to print it as utf-8. Before python 3, the best is to specifically encode it
```
print u'Ã'.encode('utf-8')
```
if you get the text externally then you have to specifically decode('utf-8) such as
```
f = open(my_file)
a = f.next().decode('utf-8') # you have a unicode line in a
print a.encode('utf-8')
``` | **How can I print s variable to show the character Ã???**
use `print`:
```
>>> s = 'Ã'
>>> s
'\xc3'
>>> print s
Ã
``` | How to show characters non ascii in python? | [
"",
"python",
"urllib2",
""
] |
First some background: I'm working on an application and I'm trying to follow MVVM conventions writing it. One thing I'd like to do is to be able to give the application different "skins" to my application. The same application, but show one "skin" for one client and a different "skin" for another.
And so my questions are:
1. Is it possible to load a xaml file at run time and "assign" it to my app?
2. Can the xaml file be an external file residing in a different folder?
3. Can the application switch to another xaml file easily, or only at startup time?
So where should I start looking at for information on this? Which WPF methods, if they exist, handle this functionality?
Thanks!
Edit: the type of "skinning" I'm wanting to do is more than just changing the look of my controls. The idea is having a completely different UI. Different buttons, different layouts. Kinda like how one version of the app would be fully featured for experts and another version would be simplified for beginners. | I think this is fairly simple with the XamlReader, give this a shot, didn't try it myself, but I think it should work.
<https://learn.microsoft.com/en-us/archive/blogs/ashish/dynamically-loading-xaml> | As Jakob Christensen noted, you can load any XAML you want using `XamlReader.Load`. This doesn't apply only for styles, but `UIElement`s as well. You just load the XAML like:
```
UIElement rootElement;
FileStream s = new FileStream(fileName, FileMode.Open);
rootElement = (UIElement)XamlReader.Load(s);
s.Close();
```
Then you can set it as the contents of the suitable element, e.g. for
```
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Foo Bar">
<Grid x:Name="layoutGrid">
<!-- any static elements you might have -->
</Grid>
</Window>
```
you could add the `rootElement` in the `grid` with:
```
layoutGrid.Children.Add(rootElement);
layoutGrid.SetColumn(rootElement, COLUMN);
layoutGrid.SetRow(rootElement, ROW);
```
You'll naturally also have to connect any events for elements inside the `rootElement` manually in the code-behind. As an example, assuming your `rootElement` contains a `Canvas` with a bunch of `Path`s, you can assign the `Path`s' `MouseLeftButtonDown` event like this:
```
Canvas canvas = (Canvas)LogicalTreeHelper.FindLogicalNode(rootElement, "canvas1");
foreach (UIElement ui in LogicalTreeHelper.GetChildren(canvas)) {
System.Windows.Shapes.Path path = ui as System.Windows.Shapes.Path;
if (path != null) {
path.MouseLeftButtonDown += this.LeftButtonDown;
}
}
```
I've not tried switching XAML files on the fly, so I cannot say if that'll really work or not. | Loading XAML at runtime? | [
"",
"c#",
"wpf",
"xaml",
""
] |
Well, I have a class Customer (no base class).
I need to cast from LinkedList to List. Is there any clean way to do this?
Just so you know, I need to cast it to List. No other type will do. (I'm developing a test fixture using Slim and FitNesse).
---
EDIT: Okay, I think I need to give code examples here.
```
import java.util.*;
public class CustomerCollection
{
protected LinkedList<Customer> theList;
public CustomerCollection()
{
theList = new LinkedList<Customer>();
}
public void addCustomer(Customer c){ theList.add(c); }
public List<Object> getList()
{
return (List<? extends Object>) theList;
}
}
```
So in accordance with Yuval A's remarks, I've finally written the code this way. But I get this error:
```
CustomerCollection.java:31: incompatible types
found : java.util.List<capture#824 of ? extends java.lang.Object>
required: java.util.List<java.lang.Object>
return (List<? extends Object>)theList;
^
1 error
```
So, what's the correct way to do this cast? | You do not need to cast. `LinkedList` implements `List` so you have no casting to do here.
Even when you want to down-cast to a `List` of `Object`s you can do it with generics like in the following code:
```
LinkedList<E> ll = someList;
List<? extends Object> l = ll; // perfectly fine, no casting needed
```
Now, after your edit I understand what you are trying to do, and it is something that is not possible, without creating a new `List` like so:
```
LinkedList<E> ll = someList;
List<Object> l = new LinkedList<Object>();
for (E e : ll) {
l.add((Object) e); // need to cast each object specifically
}
```
and I'll explain why this is not possible otherwise. Consider this:
```
LinkedList<String> ll = new LinkedList<String>();
List<Object> l = ll; // ERROR, but suppose this was possible
l.add((Object) new Integer(5)); // now what? How is an int a String???
```
For more info, see the [Sun Java generics tutorial](http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf). Hope this clarifies. | Here's my horrible solution for doing casting. I know, I know, I shouldn't be releasing something like this into the wild, but it has come in handy for casting any object to any type:
```
public class UnsafeCastUtil {
private UnsafeCastUtil(){ /* not instatiable */}
/**
* Warning! Using this method is a sin against the gods of programming!
*/
@SuppressWarnings("unchecked")
public static <T> T cast(Object o){
return (T)o;
}
}
```
Usage:
```
Cat c = new Cat();
Dog d = UnsafeCastUtil.cast(c);
```
Now I'm going to pray to the gods of programming for my sins... | How to cast generic List types in java? | [
"",
"java",
"generics",
"casting",
""
] |
I'm trying to build code from the nVidia 9.5 SDK but I get the following linker errors:
```
>1>NV_D3DCommonDX9U.lib(NV_StringFuncs.obj) : error LNK2005: "class std::basic_istream<char,struct std::char_traits<char> > & __cdecl std::getline<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_istream<char,struct std::char_traits<char> > &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &)" (??$getline@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@YAAAV?$basic_istream@DU?$char_traits@D@std@@@0@AAV10@AAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@0@@Z) already defined in msvcprtd.lib(MSVCP90D.dll)
1>FogTombScene.obj : error LNK2019: unresolved external symbol "public: struct IDirect3DTexture9 * * __thiscall TextureFactory::CreateTextureFromFile(struct IDirect3DDevice9 *,wchar_t const *,bool)" (?CreateTextureFromFile@TextureFactory@@QAEPAPAUIDirect3DTexture9@@PAUIDirect3DDevice9@@PB_W_N@Z) referenced in function "public: virtual long __thiscall FogTombScene::RestoreDeviceObjects(void)" (?RestoreDeviceObjects@FogTombScene@@UAEJXZ)
1>FogTombScene.obj : error LNK2019: unresolved external symbol "public: long __thiscall LoadXFile::LoadFile(wchar_t const *,bool)" (?LoadFile@LoadXFile@@QAEJPB_W_N@Z) referenced in function "public: virtual long __thiscall FogTombScene::RestoreDeviceObjects(void)" (?RestoreDeviceObjects@FogTombScene@@UAEJXZ)
1>FogTombScene.obj : error LNK2019: unresolved external symbol "public: long __thiscall LoadXFile::Initialize(struct IDirect3DDevice9 *,class std::basic_string<wchar_t,struct std::char_traits<wchar_t>,class std::allocator<wchar_t> > (__cdecl*)(class std::basic_string<wchar_t,struct std::char_traits<wchar_t>,class std::allocator<wchar_t> > const &,bool),class TextureFactory * *)" (?Initialize@LoadXFile@@QAEJPAUIDirect3DDevice9@@P6A?AV?$basic_string@_WU?$char_traits@_W@std@@V?$allocator@_W@2@@std@@ABV34@_N@ZPAPAVTextureFactory@@@Z) referenced in function "public: virtual long __thiscall FogTombScene::RestoreDeviceObjects(void)" (?RestoreDeviceObjects@FogTombScene@@UAEJXZ)
1>NV_D3DCommonDX9U.lib(NV_StringFuncs.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: void __thiscall std::locale::facet::_Register(void)" (__imp_?_Register@facet@locale@std@@QAEXXZ) referenced in function "class std::ctype<char> const & __cdecl std::use_facet<class std::ctype<char> >(class std::locale const &)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z)
1>NV_D3DCommonDX9U.lib(NV_StringFuncs.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static unsigned int __cdecl std::ctype<char>::_Getcat(class std::locale::facet const * *)" (__imp_?_Getcat@?$ctype@D@std@@SAIPAPBVfacet@locale@2@@Z) referenced in function "class std::ctype<char> const & __cdecl std::use_facet<class std::ctype<char> >(class std::locale const &)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z)
1>NV_D3DCommonDX9U.lib(NV_StringFuncs.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static unsigned int __cdecl std::ctype<unsigned short>::_Getcat(class std::locale::facet const * *)" (__imp_?_Getcat@?$ctype@G@std@@SAIPAPBVfacet@locale@2@@Z) referenced in function "class std::ctype<unsigned short> const & __cdecl std::use_facet<class std::ctype<unsigned short> >(class std::locale const &)" (??$use_facet@V?$ctype@G@std@@@std@@YAABV?$ctype@G@0@ABVlocale@0@@Z)
```
I have no idea why I'm gettin gthese terrors because I'm 99% sure I've setup my directories correctly.
For example one of the functions it can't find is TextureFactory::CreateTextureFromFile yet I have the directory in which that function is declared and defined already added to the include/source directory in the Visual C++ settings.
Top of the file looks like this:
```
#include "nvafx.h"
//#include "NV_D3DCommon\NV_D3DCommonDX9.h" // include library sub-headers
// and add .lib to linker inputs
//#include "NV_D3DMesh\NV_D3DMesh.h"
//#include "shared\NV_Common.h"
//#include "shared\NV_Error.h"
#include "FogTombScene.h"
#include "ThicknessRenderProperties.h"
#include "ThicknessRenderProperties8BPC.h"
#include "../camera.h"
// When the following two lines are added I get more LNK2005 (understandable)
// but I also still get the same LNK2019 errors as above
#include "texturefactory.h"
#include "texturefactory.cpp"
```
More to the point if I say #include "TextureFactory.h" and #include "texturefactory.cpp" at the top of the file in which I'm getting these errors then there can be no room for ambiguity, the functions are defined and basically copy+pasted into the same source file generating the linker error, yet I still get the linker error.
Am I overlooking something? | That happend because:
1 The source of .lib is missing like said tomzx or Daniel,
or
2 The .lib it was compiled in another version of Visual C
Try to create your file like a .c (NOT a .cpp) in notepad, then you add to your project the file .c (project...add to project...file)
Sorry I'm Mexican, I don't speak english.
Saludos. | You have added the files in the include/source folder, but what about the libraries? Looks more like a library problem to me (missing .lib).
Maybe you also need to list your dependencies in Linker - Input.
LNK2005 generally means that additionnal libraries aren't correctly linked. | Linker errors in Visual C++ LNK2005, LNK2019 - not sure why | [
"",
"c++",
"visual-c++",
"linker",
"lnk2019",
"lnk2005",
""
] |
I'm using the following code to write data through a named pipe from one application to another. The thread where the writing is taken place should never be exited. But if r\_write() returns less than it should, the thread/program stops for some reason. How can I make the thread continue once write has returned less than it should?
```
ssize_t r_write(int fd, char *buf, size_t size)
{
char *bufp;
size_t bytestowrite;
ssize_t byteswritten;
size_t totalbytes;
for (bufp = buf, bytestowrite = size, totalbytes = 0;
bytestowrite > 0;
bufp += byteswritten, bytestowrite -= byteswritten) {
byteswritten = write(fd, bufp, bytestowrite);
if ((byteswritten) == -1 && (errno != EINTR))
return -1;
if (byteswritten == -1)
byteswritten = 0;
totalbytes += byteswritten;
}
return totalbytes;
}
void* sendData(void *thread_arg)
{
int fd, ret_val, count, numread;
string word;
char bufpipe[5];
ret_val = mkfifo(pipe, 0777); //make the sprout pipe
if (( ret_val == -1) && (errno != EEXIST))
{
perror("Error creating named pipe");
exit(1);
}
while(1)
{
if(!sproutFeed.empty())
{
string s;
s.clear();
s = sproutFeed.front();
int sizeOfData = s.length();
snprintf(bufpipe, 5, "%04d", sizeOfData);
char stringToSend[strlen(bufpipe) + sizeOfData +1];
bzero(stringToSend, sizeof(stringToSend));
strncpy(stringToSend,bufpipe, strlen(bufpipe));
strncat(stringToSend,s.c_str(),strlen(s.c_str()));
strncat(stringToSend, "\0", strlen("\0"));
int fullSize = strlen(stringToSend);
cout << "sending string" << stringToSend << endl;
fd = open(pipe,O_WRONLY);
int numWrite = r_write(fd, stringToSend, strlen(stringToSend) );
if(numWrite != fullSize)
{
bzero(bufpipe, strlen(bufpipe));
bzero(stringToSend, strlen(stringToSend));
cout << "NOT FULL SIZE WRITE " << endl; //program ends here??
}
else
{
sproutFeed.pop();
bzero(bufpipe, strlen(bufpipe));
bzero(stringToSend, strlen(stringToSend));
}
}
else
{
sleep(1);
}
}
}
``` | The write to the FIFO failed. Investigate the value of `errno` to find out why. Look in `errno.h` on your system to decipher the value of errno. If the program is ending upon trying to write to the console, the reason may be related.
Also, your loop doesn't appear to be closing the file descriptor for the FIFO (`close(fd)`).
Finally, you mention multithreading. The standard library stream `cout` on your system may not (and probably isn't) thread-safe. In that case, writing to the console concurrently from multiple threads will cause unpredictable errors. | If the `write()` returns a positive (non-zero, non-negative) value for the number of bytes written, it was successful, but there wasn't room for all the data. Try again, writing the remainder of the data from the buffer (and repeat as necessary). Don't forget, a FIFO has a limited capacity - and writers will be held up if necessary.
If the `write()` returns a negative value, the write failed. The chances are that you won't be able to recover, but check `errno` for the reason why.
I think the only circumstance where `write()` can return zero is if you have the file descriptor open with `O_NONBLOCK` and the attempt to write would block. You might need to scrutinize the manual page for `write()` to check for any other possibilities.
What your thread does then depends on why it experienced a short write, and what you want to do about it. | How to get a thread to continue after write() has written less bytes than requested? | [
"",
"c++",
"c",
"multithreading",
"named-pipes",
""
] |
We're looking at developing a Web Service to function as a basis for a browser display/gui for a networked security prototype written in C++. My experience with web services has been limited to Java. I prefer Web Services in Java because it's on the "beaten path".
One sure was to do this would be to simply code a Java client which invokes the web service, and call it as a command line with parameters from the C++ code.
It's not ideal, since generally speaking an API is preferable, but in this case it would work and be a pretty safe solution.
A resource which does handles web service development in C++ is called gSOAP, at this url: <http://gsoap2.sourceforge.net>
Any thought on which is a better approach? Has anyone used gSOAP, and if so, what did you think? | My colleague ended up using a combination of Axis2 / java (for the service) and gsoap for the client. He created the wsdl from the Java service by generating it from a C++ header (using c2wsdl (?) or something like that. He said it was better than using a Java interface because that generated two sets of wsdl, for seperate versions of soap.
Then he used wsdl2java to generate the webservice and a test web client. Once we got that working, he used gsoap to create the web client (in C++), and it worked fine.
thanks for all the answers! I ended using a combination of them. | I'd done things with gSOAP, it's not awful. I'm increasingly opposed to the RPC model for web services, though; it forces you into a lot of connection and session state that adds complexity. A REST interface is simpler and more robust. | What is a good platform for devoloping web services in C++? | [
"",
"c++",
"web-services",
""
] |
I have a form which you can post a file over to my server.
Is there a way, without using a custom HTTP handler, to intercept the start of the post and prevent it before the file is uploaded and bandwidth used up.
So for example, I could check an IP address and if it's blocked in my system I could stop the request before I waste 10MB of uploading.
Thanks!
EDIT:
I'm using ASP.NET MVC | This is really a job for a HttpModule, not a HttpHandler. Just check remote IP against a blacklist in the BeginRequest event and null route or what have you. | As far as I am aware, this isn't possible with stock .NET code, unless you spend time to recreate the file handling and parsing ASP.NET does. | Can I intercept a file upload over HTTP to IIS7 and deny the upload based on a validation criteria? | [
"",
"c#",
".net",
"validation",
"post",
"file-upload",
""
] |
How can you compress inline script and style tags?
YSlow says [In addition to minifying external scripts and styles, inlined script and style blocks can and should also be minified](http://developer.yahoo.com/performance/rules.html#minify). | You might look into [MBCompression](http://www.codeplex.com/MbCompression) It allows you to compress pretty much everything coming out of a .net app (including those lovely webresource.axd files).
This has a similiar effect as regular javascript compression. Beyond that, i'd still look into pulling out the inline scripts into separate files in order to remove duplication and allow the browser to cache that data. | Don't forget that there's a [.NET port of YUI Compressor](http://yuicompressor.codeplex.com/). :)
You can use it for post-build events or in a TFS build or just use the dll's in your own project(s). | Can YUI compressor minify ASP.NET inline script? | [
"",
"javascript",
"minify",
"yui-compressor",
""
] |
I have a table (`SQL Sever`) which references paths (`UNC` or otherwise), but now the path is going to change.
In the path column, I have many records and I need to change just a portion of the path, but not the entire path. And I need to change the same string to the new one, in every record.
How can I do this with a simple `update`? | It's this easy:
```
update my_table
set path = replace(path, 'oldstring', 'newstring')
``` | ```
UPDATE [table]
SET [column] = REPLACE([column], '/foo/', '/bar/')
``` | How to replace a string in a SQL Server Table Column | [
"",
"sql",
"sql-server",
"database",
"database-administration",
""
] |
I've seen some samples of using 'T' to make a method reuseable for generic collections of different classes, but I've never really gotten into it or understood the samples.
I wonder if it would be possible to put the 2 methods below into one and what the downsides of doing this would be (performance-wise).
Anyone?
```
[NonAction]
public List<SelectListItem> ToSelectList(IEnumerable<Department> departments, string defaultOption)
{
var items = departments.Select(d => new SelectListItem() { Text = d.Code + " - " + d.Description, Value = d.Id.ToString() }).ToList();
items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" });
return items;
}
[NonAction]
public List<SelectListItem> ToSelectList(IEnumerable<Function> functions, string defaultOption)
{
var items = functions.Select(f => new SelectListItem() { Text = f.Description, Value = f.Id.ToString() }).ToList();
items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" });
return items;
}
```
---
**SOLUTION**
The solution that I used:
*usage*
```
var departmentItems = departments.ToSelectList(d => d.Code + " - " + d.Description, d => d.Id.ToString(), " - ");
var functionItems = customerFunctions.ToSelectList(f => f.Description, f => f.Id.ToString(), " - ");
```
*with*
```
public static class MCVExtentions
{
public static List<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, string> text, Func<T, string> value, string defaultOption)
{
var items = enumerable.Select(f => new SelectListItem() { Text = text(f), Value = value(f) }).ToList();
items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" });
return items;
}
}
``` | Without implementiong a common interface like @Grzenio suggested, you could use a generic method like this:
```
public List<SelectListItem> ToSelectList<T>(IEnumerable<T> enumerable, Func<T, string> text, Func<T, string> value, string defaultOption)
{
var items = enumerable.Select(f => new SelectListItem() { Text = text(f), Value = value(f) }).ToList();
items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" });
return items;
}
// use like
t.ToSelectList(departments, d => d.Code + " - " + d.Description, d => d.Id.ToString(), "default");
t.ToSelectList(functions, f => f.Description, f => f.Id.ToString(), "default");
``` | The old school way would be to create a common interface for both Department and Function:
```
interface A
{
int ID{get;}
string Description{get;}
}
```
You implement Description on Department to return `d.Code + " - " + d.Description`.
and write the function to use this interface instead of concrete classes:
```
[NonAction]
public List<SelectListItem> ToSelectList(IEnumerable<A> as, string defaultOption)
{
var items = as.Select(a => new SelectListItem() { Text = a.Description, Value = a.Id.ToString() }).ToList();
items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" });
return items;
}
```
EDIT: Regarding using generics, its not going to help much in this case, because
* the objects you are passing needs to implement Id and Description
* you are not returning these objects, so in this respect you don't have to care about type safety of generics | How to refactor these 2 similar methods into one? | [
"",
"c#",
"generics",
"refactoring",
""
] |
I have a list of items on a page with a set of controls to MoveUp, MoveDown and Delete.
The controls sit at the top of list hidden by default. As you mouseover an item row, I select the controls with jquery
```
//doc ready function:
..
var tools = $('#tools');
$('#moveup').click(MoveUp);
$('#movedn').click(MoveDn);
$('#delete').click(Delete);
..
$('li.item').mouseover(function(){
$(this).prepend(tools);
});
```
This works great in Firefox .. the tools move into the current row, and the click events call the ajax functions. However, in IE6 and IE7 .. no click occurs. I tried unbinding on mouseout and rebinding on each mouseover .. to no avail.
I also looked into various reasons outside of javascript (e.g. transparent png conflicts, z-index, position:absolute) .. also no solution found.
I eventually needed to add a tools row to each item and show/hide on mouse over/out. Works just as well -- the only downer is that I have much more 'tools' markup on my page.
Does anyone know why IE ignores/drops/kills the mouse events once the objects are moved (using prepend)? And why rebinding the event afterwards also has no effect? Kept me annoyed for almost 2 hours before I gave up. | IE will lose events depending on how you are adding things to the DOM.
```
var ele = $("#itemtocopy");
$("#someotheritem").append( ele ); // Will not work and will lose events
$("#someotheritem").append( ele.clone(true) );
```
I would also recommend using .live() on the click events to simplify your code a little. Mouseover/out is not supported by live yet. <http://docs.jquery.com/Events/live> | I just spent the whole day troubleshooting events not triggering on items appended to the DOM, (IE7, jQuery 1.4.1) and it wasn't because I needed to use live() (though, good to know, Chad), nor was it because I needed to clone the items.
It was because I was selecting anchor tags that had a "#" in them like so:
```
var myitem = $('a[href=#top]');
```
My solution was to use the "Attribute Contains Selector" like so:
```
var myitem = $('a[href*=top]');
```
Fortunately I have enough control over everything that it won't likely break in the future. This isn't technically related to appended objects, but hopefully it saves someone some time. | jQuery event handlers not firing in IE | [
"",
"javascript",
"jquery",
"jquery-events",
"jquery-1.3",
""
] |
I've begun writing a game using XNA Framework and have hit some simple problem I do not know how to solve correctly.
I'm displaying a menu using Texture2D and using the keyboard (or gamepad) I change the menu item that is selected. My problem is that the current function used to toggle between menu items is way too fast. I might click the down button and it will go down 5 or 6 menu items (due to the fact that Update() is called many time thus updating the selected item).
```
ex.
(> indicate selected)
> MenuItem1
MenuItem2
MenuItem3
MenuItem4
MenuItem5
I press the down key for just a second), then I have this state:
MenuItem1
MenuItem2
MenuItem3
> MenuItem4
MenuItem5
What I want is (until I press the key again)
MenuItem1
> MenuItem2
MenuItem3
MenuItem4
MenuItem5
```
What I am looking for is a way to either have the player click the up/down key many time in order to go from one menu item to the other, or to have some sort of minimum wait time before going to the next menu item. | I've built a (large) class that helps a lot with any and all XNA input related tasks, it makes what you're asking for easy.
```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
namespace YourNamespaceHere
{
/// <summary>
/// an enum of all available mouse buttons.
/// </summary>
public enum MouseButtons
{
LeftButton,
MiddleButton,
RightButton,
ExtraButton1,
ExtraButton2
}
public class InputHelper
{
private GamePadState _lastGamepadState;
private GamePadState _currentGamepadState;
#if (!XBOX)
private KeyboardState _lastKeyboardState;
private KeyboardState _currentKeyboardState;
private MouseState _lastMouseState;
private MouseState _currentMouseState;
#endif
private PlayerIndex _index = PlayerIndex.One;
private bool refreshData = false;
/// <summary>
/// Fetches the latest input states.
/// </summary>
public void Update()
{
if (!refreshData)
refreshData = true;
if (_lastGamepadState == null && _currentGamepadState == null)
{
_lastGamepadState = _currentGamepadState = GamePad.GetState(_index);
}
else
{
_lastGamepadState = _currentGamepadState;
_currentGamepadState = GamePad.GetState(_index);
}
#if (!XBOX)
if (_lastKeyboardState == null && _currentKeyboardState == null)
{
_lastKeyboardState = _currentKeyboardState = Keyboard.GetState();
}
else
{
_lastKeyboardState = _currentKeyboardState;
_currentKeyboardState = Keyboard.GetState();
}
if (_lastMouseState == null && _currentMouseState == null)
{
_lastMouseState = _currentMouseState = Mouse.GetState();
}
else
{
_lastMouseState = _currentMouseState;
_currentMouseState = Mouse.GetState();
}
#endif
}
/// <summary>
/// The previous state of the gamepad.
/// Exposed only for convenience.
/// </summary>
public GamePadState LastGamepadState
{
get { return _lastGamepadState; }
}
/// <summary>
/// the current state of the gamepad.
/// Exposed only for convenience.
/// </summary>
public GamePadState CurrentGamepadState
{
get { return _currentGamepadState; }
}
/// <summary>
/// the index that is used to poll the gamepad.
/// </summary>
public PlayerIndex Index
{
get { return _index; }
set {
_index = value;
if (refreshData)
{
Update();
Update();
}
}
}
#if (!XBOX)
/// <summary>
/// The previous keyboard state.
/// Exposed only for convenience.
/// </summary>
public KeyboardState LastKeyboardState
{
get { return _lastKeyboardState; }
}
/// <summary>
/// The current state of the keyboard.
/// Exposed only for convenience.
/// </summary>
public KeyboardState CurrentKeyboardState
{
get { return _currentKeyboardState; }
}
/// <summary>
/// The previous mouse state.
/// Exposed only for convenience.
/// </summary>
public MouseState LastMouseState
{
get { return _lastMouseState; }
}
/// <summary>
/// The current state of the mouse.
/// Exposed only for convenience.
/// </summary>
public MouseState CurrentMouseState
{
get { return _currentMouseState; }
}
#endif
/// <summary>
/// The current position of the left stick.
/// Y is automatically reversed for you.
/// </summary>
public Vector2 LeftStickPosition
{
get
{
return new Vector2(
_currentGamepadState.ThumbSticks.Left.X,
-CurrentGamepadState.ThumbSticks.Left.Y);
}
}
/// <summary>
/// The current position of the right stick.
/// Y is automatically reversed for you.
/// </summary>
public Vector2 RightStickPosition
{
get
{
return new Vector2(
_currentGamepadState.ThumbSticks.Right.X,
-_currentGamepadState.ThumbSticks.Right.Y);
}
}
/// <summary>
/// The current velocity of the left stick.
/// Y is automatically reversed for you.
/// expressed as:
/// current stick position - last stick position.
/// </summary>
public Vector2 LeftStickVelocity
{
get
{
Vector2 temp =
_currentGamepadState.ThumbSticks.Left -
_lastGamepadState.ThumbSticks.Left;
return new Vector2(temp.X, -temp.Y);
}
}
/// <summary>
/// The current velocity of the right stick.
/// Y is automatically reversed for you.
/// expressed as:
/// current stick position - last stick position.
/// </summary>
public Vector2 RightStickVelocity
{
get
{
Vector2 temp =
_currentGamepadState.ThumbSticks.Right -
_lastGamepadState.ThumbSticks.Right;
return new Vector2(temp.X, -temp.Y);
}
}
/// <summary>
/// the current position of the left trigger.
/// </summary>
public float LeftTriggerPosition
{
get { return _currentGamepadState.Triggers.Left; }
}
/// <summary>
/// the current position of the right trigger.
/// </summary>
public float RightTriggerPosition
{
get { return _currentGamepadState.Triggers.Right; }
}
/// <summary>
/// the velocity of the left trigger.
/// expressed as:
/// current trigger position - last trigger position.
/// </summary>
public float LeftTriggerVelocity
{
get
{
return
_currentGamepadState.Triggers.Left -
_lastGamepadState.Triggers.Left;
}
}
/// <summary>
/// the velocity of the right trigger.
/// expressed as:
/// current trigger position - last trigger position.
/// </summary>
public float RightTriggerVelocity
{
get
{
return _currentGamepadState.Triggers.Right -
_lastGamepadState.Triggers.Right;
}
}
#if (!XBOX)
/// <summary>
/// the current mouse position.
/// </summary>
public Vector2 MousePosition
{
get { return new Vector2(_currentMouseState.X, _currentMouseState.Y); }
}
/// <summary>
/// the current mouse velocity.
/// Expressed as:
/// current mouse position - last mouse position.
/// </summary>
public Vector2 MouseVelocity
{
get
{
return (
new Vector2(_currentMouseState.X, _currentMouseState.Y) -
new Vector2(_lastMouseState.X, _lastMouseState.Y)
);
}
}
/// <summary>
/// the current mouse scroll wheel position.
/// See the Mouse's ScrollWheel property for details.
/// </summary>
public float MouseScrollWheelPosition
{
get
{
return _currentMouseState.ScrollWheelValue;
}
}
/// <summary>
/// the mouse scroll wheel velocity.
/// Expressed as:
/// current scroll wheel position -
/// the last scroll wheel position.
/// </summary>
public float MouseScrollWheelVelocity
{
get
{
return (_currentMouseState.ScrollWheelValue - _lastMouseState.ScrollWheelValue);
}
}
#endif
/// <summary>
/// Used for debug purposes.
/// Indicates if the user wants to exit immediately.
/// </summary>
public bool ExitRequested
{
#if (!XBOX)
get
{
return (
(IsCurPress(Buttons.Start) &&
IsCurPress(Buttons.Back)) ||
IsCurPress(Keys.Escape));
}
#else
get { return (IsCurPress(Buttons.Start) && IsCurPress(Buttons.Back)); }
#endif
}
/// <summary>
/// Checks if the requested button is a new press.
/// </summary>
/// <param name="button">
/// The button to check.
/// </param>
/// <returns>
/// a bool indicating whether the selected button is being
/// pressed in the current state but not the last state.
/// </returns>
public bool IsNewPress(Buttons button)
{
return (
_lastGamepadState.IsButtonUp(button) &&
_currentGamepadState.IsButtonDown(button));
}
/// <summary>
/// Checks if the requested button is a current press.
/// </summary>
/// <param name="button">
/// the button to check.
/// </param>
/// <returns>
/// a bool indicating whether the selected button is being
/// pressed in the current state and in the last state.
/// </returns>
public bool IsCurPress(Buttons button)
{
return (
_lastGamepadState.IsButtonDown(button) &&
_currentGamepadState.IsButtonDown(button));
}
/// <summary>
/// Checks if the requested button is an old press.
/// </summary>
/// <param name="button">
/// the button to check.
/// </param>
/// <returns>
/// a bool indicating whether the selected button is not being
/// pressed in the current state and is being pressed in the last state.
/// </returns>
public bool IsOldPress(Buttons button)
{
return (
_lastGamepadState.IsButtonDown(button) &&
_currentGamepadState.IsButtonUp(button));
}
#if (!XBOX)
/// <summary>
/// Checks if the requested key is a new press.
/// </summary>
/// <param name="key">
/// the key to check.
/// </param>
/// <returns>
/// a bool that indicates whether the selected key is being
/// pressed in the current state and not in the last state.
/// </returns>
public bool IsNewPress(Keys key)
{
return (
_lastKeyboardState.IsKeyUp(key) &&
_currentKeyboardState.IsKeyDown(key));
}
/// <summary>
/// Checks if the requested key is a current press.
/// </summary>
/// <param name="key">
/// the key to check.
/// </param>
/// <returns>
/// a bool that indicates whether the selected key is being
/// pressed in the current state and in the last state.
/// </returns>
public bool IsCurPress(Keys key)
{
return (
_lastKeyboardState.IsKeyDown(key) &&
_currentKeyboardState.IsKeyDown(key));
}
/// <summary>
/// Checks if the requested button is an old press.
/// </summary>
/// <param name="key">
/// the key to check.
/// </param>
/// <returns>
/// a bool indicating whether the selectde button is not being
/// pressed in the current state and being pressed in the last state.
/// </returns>
public bool IsOldPress(Keys key)
{
return (
_lastKeyboardState.IsKeyDown(key) &&
_currentKeyboardState.IsKeyUp(key));
}
/// <summary>
/// Checks if the requested mosue button is a new press.
/// </summary>
/// <param name="button">
/// teh mouse button to check.
/// </param>
/// <returns>
/// a bool indicating whether the selected mouse button is being
/// pressed in the current state but not in the last state.
/// </returns>
public bool IsNewPress(MouseButtons button)
{
switch (button)
{
case MouseButtons.LeftButton:
return (
_lastMouseState.LeftButton == ButtonState.Released &&
_currentMouseState.LeftButton == ButtonState.Pressed);
case MouseButtons.MiddleButton:
return (
_lastMouseState.MiddleButton == ButtonState.Released &&
_currentMouseState.MiddleButton == ButtonState.Pressed);
case MouseButtons.RightButton:
return (
_lastMouseState.RightButton == ButtonState.Released &&
_currentMouseState.RightButton == ButtonState.Pressed);
case MouseButtons.ExtraButton1:
return (
_lastMouseState.XButton1 == ButtonState.Released &&
_currentMouseState.XButton1 == ButtonState.Pressed);
case MouseButtons.ExtraButton2:
return (
_lastMouseState.XButton2 == ButtonState.Released &&
_currentMouseState.XButton2 == ButtonState.Pressed);
default:
return false;
}
}
/// <summary>
/// Checks if the requested mosue button is a current press.
/// </summary>
/// <param name="button">
/// the mouse button to be checked.
/// </param>
/// <returns>
/// a bool indicating whether the selected mouse button is being
/// pressed in the current state and in the last state.
/// </returns>
public bool IsCurPress(MouseButtons button)
{
switch (button)
{
case MouseButtons.LeftButton:
return (
_lastMouseState.LeftButton == ButtonState.Pressed &&
_currentMouseState.LeftButton == ButtonState.Pressed);
case MouseButtons.MiddleButton:
return (
_lastMouseState.MiddleButton == ButtonState.Pressed &&
_currentMouseState.MiddleButton == ButtonState.Pressed);
case MouseButtons.RightButton:
return (
_lastMouseState.RightButton == ButtonState.Pressed &&
_currentMouseState.RightButton == ButtonState.Pressed);
case MouseButtons.ExtraButton1:
return (
_lastMouseState.XButton1 == ButtonState.Pressed &&
_currentMouseState.XButton1 == ButtonState.Pressed);
case MouseButtons.ExtraButton2:
return (
_lastMouseState.XButton2 == ButtonState.Pressed &&
_currentMouseState.XButton2 == ButtonState.Pressed);
default:
return false;
}
}
/// <summary>
/// Checks if the requested mosue button is an old press.
/// </summary>
/// <param name="button">
/// the mouse button to check.
/// </param>
/// <returns>
/// a bool indicating whether the selected mouse button is not being
/// pressed in the current state and is being pressed in the old state.
/// </returns>
public bool IsOldPress(MouseButtons button)
{
switch (button)
{
case MouseButtons.LeftButton:
return (
_lastMouseState.LeftButton == ButtonState.Pressed &&
_currentMouseState.LeftButton == ButtonState.Released);
case MouseButtons.MiddleButton:
return (
_lastMouseState.MiddleButton == ButtonState.Pressed &&
_currentMouseState.MiddleButton == ButtonState.Released);
case MouseButtons.RightButton:
return (
_lastMouseState.RightButton == ButtonState.Pressed &&
_currentMouseState.RightButton == ButtonState.Released);
case MouseButtons.ExtraButton1:
return (
_lastMouseState.XButton1 == ButtonState.Pressed &&
_currentMouseState.XButton1 == ButtonState.Released);
case MouseButtons.ExtraButton2:
return (
_lastMouseState.XButton2 == ButtonState.Pressed &&
_currentMouseState.XButton2 == ButtonState.Released);
default:
return false;
}
}
#endif
}
}
```
Just copy it into a separate class fie and move it to your namespace, then declare one (inputHelper variable), initialize it in the initialiaze portion, and call inputHelper.Update() in your update loop before the update logic. Then whenever you need something related to input, just use the InputHelper! for instance, in your situation, you would use InputHelper.IsNewPress([type of input button/key here]) to check if you want to move the menu item down or up. For this example: inputHelper.IsNewPress(Keys.Down) | the best way to implement this is to cache the keyboard/gamepad state from the update statement that just passed.
```
KeyboardState oldState;
...
var newState = Keyboard.GetState();
if (newState.IsKeyDown(Keys.Down) && !oldState.IsKeyDown(Keys.Down))
{
// the player just pressed down
}
else if (newState.IsKeyDown(Keys.Down) && oldState.IsKeyDown(Keys.Down))
{
// the player is holding the key down
}
else if (!newState.IsKeyDown(Keys.Down) && oldState.IsKeyDown(Keys.Down))
{
// the player was holding the key down, but has just let it go
}
oldState = newState;
```
In your case, you probably only want to move "down" in the first case above, when the key was just pressed. | How to slow down or stop key presses in XNA | [
"",
"c#",
"xna",
""
] |
Here's the deal: I'm trying, as a learning experience, to convert a C program to C++. [This program](http://www.zompist.com/sounds.htm) takes a text file and applies modifications to it according to user-inputted rules. Specifically, it applies sounds changes to a set of words, using rules formatted like "s1/s2/env". s1 represents the characters to be changed, s2 represents what to change it into, and env is the context in which the change should be applied.
I'm sorry that I don't describe this in more depth, but the question would be too long, and the author's site already explains it.
The function I'm having trouble is TryRule. I understand that it's supposed to see if a given rule applies to a given string, but I'm having trouble understanding exactly how it does it. The poor explanation of the parameters confuses me: for example, I don't understand why the strings "s1" and "s2" have to be passed back, or what does "i" represent.
This is the code:
```
/*
** TryRule
**
** See if a rule s1->s2/env applies at position i in the given word.
**
** If it does, we pass back the index where s1 was found in the
** word, as well as s1 and s2, and return TRUE.
**
** Otherwise, we return FALSE, and pass garbage in the output variables.
*/
int TryRule( char *word, int i, char *Rule, int *n, char **s1, char **s2, char *varRep )
{
int j, m, cont = 0;
int catLoc;
char *env;
int optional = FALSE;
*varRep = '\0';
if (!Divide( Rule, s1, s2, &env ) || !strchr( env, '_' ))
return(FALSE);
for (j = 0, cont = TRUE; cont && j < strlen(env); j++)
{
switch( env[j] )
{
case '(':
optional = TRUE;
break;
case ')':
optional = FALSE;
break;
case '#':
cont = j ? (i == strlen(word)) : (i == 0);
break;
case '_':
cont = !strncmp( &word[i], *s1, strlen(*s1) );
if (cont)
{
*n = i;
i += strlen(*s1);
}
else
{
cont = TryCat( *s1, &word[i], &m, &catLoc );
if (cont && m)
{
int c;
*n = i;
i += m;
for (c = 0; c < nCat; c++)
if ((*s2)[0] == Cat[c][0] && catLoc < strlen(Cat[c]))
*varRep = Cat[c][catLoc];
}
else if (cont)
cont = FALSE;
}
break;
default:
cont = TryCat( &env[j], &word[i], &m, &catLoc );
if (cont && !m)
{
/* no category applied */
cont = i < strlen(word) && word[i] == env[j];
m = 1;
}
if (cont)
i += m;
if (!cont && optional)
cont = TRUE;
}
}
if (cont && printRules)
printf( " %s->%s /%s applies to %s at %i\n",
*s1, *s2, env, word, *n );
return(cont);
}
``` | This code is... tough to read. I looked at the original file, and it could really use some better variable names. I especially love this part from one of the function comments:
```
/*
** (Stuff I removed)
**
** Warning: For now, we don't have a way to handle digraphs.
**
** We also return TRUE if (<- It really just stops here!)
*/
```
I can see the challenge. I agree with wmeyer about the variables. I think I understand things, so I'm going to attempt to translate the function into pseudo code.
Word: The string we are looking at
i: The index in the string we're looking at
Rule: The text of the rule (i.e. "v/b/\_")
n: A variable to return the index into the string we found the match for the \_, I think
s1: Returns the first part of the rule, decoded out of Rule
s2: Returns the second part of the rule, decoded out of Rule
varRep: Returns the character matched in the category, if a category matched, I think
```
int TryRule( char *word, int i, char *Rule,
int *n, char **s1, char **s2, char *varRep ) {
Prepare a bunch of variables we''ll use later
Mark that we''re not working on an optional term
Set varRep''s first char to null, so it''s an empty string
if (We can parse the rule into it''s parts
OR there is no _ in the environment (which is required))
return FALSE // Error, we can't run, the rule is screwy
for (each character, j, in env (the third part of the rule)) {
if (cont is TRUE) {
switch (the character we''re looking at, j) {
if the character is opening paren:
set optional to TRUE, marking it''s an optional character
if the character is closing paren:
set optional to FALSE, since we''re done with optional stuff
if the character is a hash mark (#):
// This is rather complicated looking, but it's not bad
// This uses a ? b : c, which means IF a THEN b ELSE c
// Remember i is the position in the word we are looking at
// Hash marks match the start or end of a word
// J is the character in the word
if (j >= 0) {
// We're not working on the first character in the rule
// so the # mark we found is to find the end of a word
if (i == the length of the word we''re looking at) {
// We've found the end of the word, so the rule matches
continue = true; // Keep going
} else {
// We're not at the end of a word, but we found a hash
// Rule doesn't match, so break out of the main loop by setting
// continue to false
continue = false;
}
} else {
// OK, the hash mark is the first part of env,
// so it signifies the start of a word
continue = (i == 0); // Continue holds if we
// are matching the first
// character in *word or not
}
if the character is an _ (the match character):
// This gets complicated
continue = if word starting at character i ISN''T s1, the search string;
if (continue == TRUE) {
// There was no match, so we'll go look at the next word
n = the index of the word start that didn''t match // Not sure why
i = i (start index to look) + length of s1 (word we just matched)
// This means i now holds the index of the start of the next word
} else {
// TryCat sees if the character we're trying to match is a category
continue = s1 is a category in the program
&& the category contains the character at word[i]
// If continue holds false, s1 was a category and we found no match
// If continue holds true, s1 either wasn't a category (so m = 0)
// or s1 WAS a category, m contains 1, and catLoc holds which
// character in the category definition was matched
if (we found a match of some sort
&& s1 was a category (indicated by m == 1)) {
n = index of the character in the word we found a match
i = the index of the next character (m is always 1, so this is ugly)
for (each category defined) {
if (first character of s2
== the category''s name
&& where in the category definition we matched
is less than the length of the category we''re on) {
varRep = the character matched in the category
}
}
// Now the above seems EXACTLY like the TryCat function. You'd
// think varRep would always hold the same value as catLoc. I
// believe this loop is so that later rules also get applied?
} else {
continue = FALSE; // Because we didn't match a letter or category
}
}
Any other character:
continue = the character we''re looking at is a category in the program
&& the category contains the character at word[i]
if (there was a match AND it wasn''t a category (m == 0, just a letter)) {
m = 1;
continue if and only if there are characters left in the word
(i < strlen()) && the current character is at word[i]
(we matched a literal character, instead of a category)
}
if (continue)
i = i + m // Remember, M is always 1 or 0
// So this is basically IF continue THEN i++ END IF
if ((continue == FALSE) && (optional == TRUE))
// We didn't find a match, but we're working on an optional part
// So continue anyway
continue = TRUE;
end switch
end if continue == true
}
}
if (continue && printRules)
print out a little debug statement showing what we matched
return continue; // At this point, if continue is false we can't keep matching
}
```
I hope this helps. You may need to read it a few times. It took me over 45 minutes to write this, almost entirely because of trying to decipher exactly what's going on in some of the cases around TryCat. Add in about 5 minutes for constantly trying to hit the Tab key and getting my cursor send to the next field (stupid HTML text box).
Sorry this is so big, you'll probably have to do a bunch of horizontal scrolling. | Given that you are converting from C to C++ you should be refactoring the code to become more readable as well.
One major problem with this code is that the variables have terrible names and I'd wager even the original writer of the routine would need to spend some time analysing it.
Just renaming the variables to be more precise would give you a greater hand in understanding what the code does.
Take a look at some [questions tagged under refactoring](https://stackoverflow.com/questions/tagged/refactoring) for some help. There is also [Refactoring by Martin Fowler](https://rads.stackoverflow.com/amzn/click/com/0201485672) | Need help understanding a C function | [
"",
"c++",
"c",
""
] |
In my web application I've to keep audit of the user actions. So whenever user takes an action I update the object on which action is taken and keep audit trail of that action.
Now If I first modify the object and then update audit trail but the audit trail fails then what?
Obviously I need to roll-back changes to modified object. I can use Sql-Transactions in simple application, but I'm using Subsonic to talk to db. How I can handle the situation? | Something like:
```
Using ts As New System.Transactions.TransactionScope()
Using sharedConnectionScope As New SubSonic.SharedDbConnectionScope()
' Do your individual saves here
' If all OK
ts.Complete()
End Using
End Using
``` | The [answer](https://stackoverflow.com/questions/910863/using-transactions-with-subsonic/911069#911069) given by [@Kevinw](https://stackoverflow.com/users/108853/kevinw) is perfectly okay. I'm posting this just as translation of his answer to C# code. I'm not using comments as it will not format code :) Also I'm using try/catch to know if transaction should complete or be rolled back.
```
using (System.Transactions.TransactionScope ts = new TransactionScope())
{
using (SharedDbConnectionScope scs = new SharedDbConnectionScope())
{
try
{
//do your stuff like saving multiple objects etc. here
//everything should be completed nicely before you reach this
//line if not throw exception and don't reach to line below
ts.Complete();
}
catch (Exception ex)
{
//ts.Dispose(); //Don't need this as using will take care of it.
//Do stuff with exception or throw it to caller
}
}
}
``` | Using transactions with subsonic | [
"",
"c#",
"asp.net",
"web-applications",
"subsonic",
"transactions",
""
] |
Why does the following code give me an error (g++ 4.1.2)?
```
template<class A>
class Foo {
public:
typedef std::vector<A> AVec;
AVec* foo();
};
template<class A>
Foo<A>::AVec* Foo<A>::foo() { // error on this line
return NULL;
}
```
The error is:
```
error: expected constructor, destructor, or type conversion before '*' token
```
How am I supposed to define the `Foo<A>::foo()` function otherwise (with the correct return type)? | This is an issue called "[two-stage lookup](http://gcc.gnu.org/onlinedocs/gcc/Name-lookup.html)". Basically, since `A` is a template parameter in `foo()`'s definition, the compiler can't know when parsing the template for the first time, whether `Foo<A>::AVec` is a type or even exists (since, for instance, there may exist a specialization of `Foo<Bar>` which doesn't contain the typedef at all). It will only know what it is during template **instantiation**, which happens later - and it's too late for this stage.
The correct way would be to use the `typename` keyword to indicate that this is a type:
```
template<class A>
class Foo {
public:
typedef std::vector<A> AVec;
AVec* foo();
};
template<class A>
typename Foo<A>::AVec* Foo<A>::foo() {
return NULL;
}
``` | The usual `typename` issue:
```
template<class A>
typename Foo<A>::AVec* Foo<A>::foo() { // error on this line
return NULL;
}
```
Remember: As a general rule, all qualified names that depend on a template parameter need `typename` before them. | Templated member function with typedef return value | [
"",
"c++",
"templates",
""
] |
I need to determine in 80% if a file is binary or text, is there any way to do it even quick and dirty/ugly in c#? | I would probably look for an abundance of control characters which would typically be present in a binary file but rarely in an text file. Binary files tend to use 0 enough that just testing for many 0 bytes would probably be sufficient to catch most files. If you care about localization you'd need to test multi-byte patterns as well.
As stated though, you can always be unlucky and get a binary file that looks like text or vice versa. | There's a method called Markov Chains. Scan a few model files of both kinds and for each byte value from 0 to 255 gather stats (basically probability) of a subsequent value. This will give you a 64Kb (256x256) profile you can compare your runtime files against (within a % threshold).
Supposedly, this is how browsers' Auto-Detect Encoding feature works. | How can I determine if a file is binary or text in c#? | [
"",
"c#",
"text",
"file-io",
"binary",
""
] |
How do I, using a *regular expression*, split this **string**:
```
string = "a[a=d b&c[e[100&2=34]]] e[cheese=blue and white] x[a=a b]"
```
into this **array**:
```
string.split( regexp ) =>
[ "a[a=d b&c[e[100&2=34]]]", "e[cheese=blue and white]", "x[a=a b]" ]
```
The basic rule is that **string** should be split at **whitespace ( \s )**, unless **whitespace** exists inside **brackets( [ ] )**; | If the rule is this simple, I would suggest just doing it manually. Step through each character and keep track of your nesting level by increasing by 1 for each [ and decreasing by 1 for each ]. If you reach a space with nesting == 0 then split.
Edit:
I was thinking that I might also mention that there are other pattern matching facilities in some languages that do natively support this sort of thing. For example, in Lua you can use '%b[]' to match balanced nested []'s. (Of course, Lua doesn't have a built in split function....) | You can't; regular expressions are based on state machines which don't have a "stack" so you can remember the number of nesting levels.
But maybe you can use a trick: Try to convert the string into a valid [JSON string](http://en.wikipedia.org/wiki/JSON). Then you can use `eval()` to parse it into a JavaScript object. | Splitting a complex string with Regular Expressions | [
"",
"javascript",
"regex",
""
] |
I asked "[How can I tell if a point belongs to a certain line?](https://stackoverflow.com/questions/907390/how-can-i-tell-if-a-point-belongs-to-a-certain-line)" before and I found a suitable answer so thank you very much.
**Now, I would like to know how to tell if a certain point is *close* to my line.** | You need to [calculate the right angle distance](http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html) to the line. Then you have to define what "close" is and test if it is within that distance.

The equation you want is:
 | [@Alan Jackson](https://stackoverflow.com/users/72995/alan-jackson)'s answer is almost perfect - but his first (and most up-voted) comment suggests that endpoints are not correctly handled. To ensure the point is on the segment, simply create a box where the segment is a diagonal, then check if the point is contained within. Here is the *pseudo-code*:
Given Line ab, comprised of points a and b, and Point p, in question:
```
int buffer = 25;//this is the distance that you would still consider the point nearby
Point topLeft = new Point(minimum(a.x, b.x), minimum(a.y, b.y));
Point bottomRight = new Point(maximum(a.x, b.x), maximum(a.y, b.y));
Rect box = new Rect(topLeft.x - buffer, topLeft.y - buffer, bottomRight.x + buffer, bottomRight.y + buffer);
if (box.contains(p))
{
//now run the test provided by Alan
if (test)
return true;
}
return false;
``` | How can I tell if a point is nearby a certain line? | [
"",
"c#",
"algorithm",
"geometry",
"gdi+",
"drawing",
""
] |
I'm trying to catch a double-click event in a TreeView's empty area to create a new node. Unfortunately standard way doesn't work. I've tried attaching ButtonPressEvent to both TreeView and the ScrolledWindow in which T.V. is hosted. I don't get any callbacks to my function.
How can I solve this? | You'll need to use the GLib.ConnectBeforeAttribute on your handler to handle TreeView.ButtonPressEvent, otherwise the widget will handle the event internally and your handler won't be called.
example:
```
[GLib.ConnectBefore]
void OnTreeViewButtonPressEvent(object sender, ButtonPressEventArgs e)
{
if (e.Type == Gdk.EventType.TwoButtonPress)
{
// double click
}
}
``` | <http://old.nabble.com/CellRenderer-editable-on-double-click-td24975510.html>
```
self.treeview.connect("button-press-event",self.cell_clicked)
def cell_clicked(self, widget, event):
if event.button == 1 and event.type == gtk.gdk.BUTTON_PRESS:
print "Double clicked on cell"
``` | How to catch clicks in a Gtk.TreeView? | [
"",
"c#",
"gtk",
"gtk#",
"gtktreeview",
""
] |
I've been using Microsoft.Jet.OLEDB.4.0 and Microsoft.ACE.OLEDB.12.0 to read in .csv, .xls, and .xlsx files.
I just found out that neither of these technologies are supported in native 64bit mode!
I have 2 questions:
1. What is the supported way to
programatically read .csv, .xls, and
.xlsx files in 64 bit mode. I just
can't find answers to this anywhere.
2. If I can't read in all three file
types, what is the best way to read
in .csv files in a 64 bit
environment?
Notes:
* I'm using .NET (3.5p1)
* This is a shrink wrap app; redistribution is a
key factor.
**Update:**
I can use CorFlags to force the application to run in 32bit mode, which works, but is not desirable. | Here is a discussion of what to do [about deprecated MDAC](http://msdn.microsoft.com/en-us/library/ms810810.aspx). I am afraid the answer is not very satisfying ...
> These new or converted Jet
> applications can continue to use Jet
> with the intention of using Microsoft
> Office 2003 and earlier files (.mdb
> and .xls) for non-primary data
> storage. However, for these
> applications, you should plan to
> migrate from Jet to the 2007 Office
> System Driver. You can download the
> 2007 Office System Driver, which
> allows you to read from and write to
> pre-existing files in either Office
> 2003 (.mdb and .xls) or the Office
> 2007 (\*.accdb, \*.xlsm, \*.xlsx and
> \*.xlsb) file formats. IMPORTANT Please read the 2007 Office System End User
> License Agreement for specific usage
> limitations.
>
> Note: SQL Server applications can also
> access the 2007 Office System, and
> earlier, files from SQL Server
> heterogeneous data connectivity and
> Integrations Services capabilities as
> well, via the 2007 Office System
> Driver. Additionally, 64-bit SQL
> Server applications can access to
> 32-bit Jet and 2007 Office System
> files by using 32-bit SQL Server
> Integration Services (SSIS) on 64-bit
> Windows. | The main problem is that the Jet DBMS is a 32bit library that gets loaded into the calling process, so you will never be able to use Jet directly from within your app in 64bit mode. As Tim mentioned you could write your own csv parser, but since this is a shrink-wrap app you want something that will handle a wider range of formats. Luckily, there are a number of ways to talk 32-bit apps, so you can still use Jet with a trick.
I would write a little exe that was marked to run only in 32-bit mode. This exe would take a command line argument of the name of the file to read and the name of a temp file to write to. I would use Jet to load the csv/xls, then put the data into an array of arrays, and use the xml serializer to write the data to the temp file.
Then when I need to load/convert a csv/xls file, I would do the following:
```
object[][] ConvertFile(string csvOrXlsFile)
{
var output = System.IO.Path.GetTempFileName();
try
{
var startinfo = new System.Diagnostics.ProcessStartInfo("convert.exe",
string.Format("\"{0}\" \"{1}\"", csvOrXlsFile, output));
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = startinfo;
proc.Start();
proc.WaitForExit();
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(object[][]));
using (var reader = System.IO.File.OpenText(output))
return (object[][])serializer.Deserialize(reader);
}
finally
{
if (System.IO.File.Exists(output))
System.IO.File.Delete(output);
}
}
``` | OleDB not supported in 64bit mode? | [
"",
"c#",
".net",
"csv",
"64-bit",
"oledb",
""
] |
I am fairly new to C++ and I have seen a bunch of code that has method definitions in the header files and they do not declare the header file as a class. Can someone explain to me why and when you would do something like this. Is this a bad practice?
Thanks in advance! | > Is this a bad practice?
Not in general. There are a lot of libraries that are `header only`, meaning they only ship header files. This *can* be seen as a lightweight alternative to compiled libraries.
More importantly, though, there is a case where you *cannot* use separate precompiled compilation units: templates must be specialized in the same compilation unit in which they get declared. This may sound arcane but it has a simple consequence:
Function (and class) templates cannot be defined inside cpp files and used elsewhere; instead, they *have* to be defined inside header files directly (with a few notable exceptions).
Additionally, classes in C++ are purely optional – while you *can* program object oriented in C++, a lot of good code doesn't. Classes supplement algorithms in C++, not the other way round. | It's not bad practice. The great thing about C++ is that it lets you program in many styles. This gives the language great flexibility and utility, but possibly makes it trickier to learn than other languages that force you to write code in a particular style.
If you had a small program, you could write it in one function - possibly using a couple of goto's for code flow.
When you get bigger, splitting the code into functions helps organize things.
Bigger still, and classes are generally a good way of grouping related functions that work on a certain set of data.
Bigger still, namespaces help out.
Sometimes though, it's just easiest to write a function to do something. This is often the case where you write a function that only works on primitive types (like int). int doesn't have a class, so if you wanted to write a printInt() function, you might make it standalone. Also, if a function works on objects from multiple classes, but doesn't really belong to one class and not the other, that might make sense as a standalone function. This happens a lot when you write operators such as define less than so that it can compare objects of two different classes. Or, if a function can be written in terms of a classes public methods, and doesn't need to access data of the class directly, some people prefer to write that as a standalone function.
But, really, the choice is yours. Whatever is the most simple thing to do to solve your problem is best.
You might start a program off as just a few functions, and then later decide some are related and refactor them into a class. But, if the other standalone functions don't naturally fit into a class, you don't have to force them into one. | When to use Header files that do not declare a class but have function definitions | [
"",
"c++",
"file",
"header",
""
] |
I'm writing some code (just for fun so far) in Python that will store some data on every point in a 3d space. I'm basically after a 3d matrix object that stores arbitary objects that will allow me to do some advanced selections, like:
* Get the point where x=1,y=2,z=3.
* Getting all points where y=2.
* Getting all points within 3 units of position x=1,y=2,z=3.
* Getting all points where point.getType() == "Foo"
In all of the above, I'd need to end up with some sort of output that would give me the original position in the space, and the data stored at that point.
Apparently numpy can do what I want, but it seems highly optimised for scientific computing and working out how to get the data like I want above has so far eluded me.
Is there a better alternative or should I return to banging my head on the numpy wall? :)
EDIT: some more info the first three answers made me realise I should include: I'm not worried about performance, this is purely a proof-of-concept where I'd prefer clean code to good performance. I will also have data for every point in the given 3d space, so I guess a Spare Matrix is bad? | Here's another common approach
```
class Point( object ):
def __init__( self, x, y, z, data ):
self.x, self.y, self.z = x, y, z
self.data = data
def distFrom( self, x, y, z )
return math.sqrt( (self.x-x)**2 + (self.y-y)**2 + (self.z-z)**2 )
database = [ Point(x,y,z,data), Point(x,y,z,data), ... ]
```
Let's look at your use cases.
Get the point where x=1,y=2,z=3.
```
[ p for p in database if (p.x, p.y, p.z) == ( 1, 2, 3 ) ]
```
Getting all points where y=2.
```
[ p for p in database if p.y == 2 ]
```
Getting all points within 3 units of position x=1,y=2,z=3.
```
[ p for p in database if p.distFrom( 1, 2, 3 ) <= 3.0 ]
```
Getting all points where point.getType() == "Foo"
```
[ p for p in database if type(p.data) == Foo ]
``` | Well ... If you expect to really *fill* that space, then you're probably best off with a densely packed matrix-like structure, basically [voxels](http://en.wikipedia.org/wiki/Voxel).
If you don't expect to fill it, look into something a bit more optimized. I would start by looking at [octrees](http://en.wikipedia.org/wiki/Octree), which are often used for things like this. | Storing information on points in a 3d space | [
"",
"python",
"data-structures",
"3d",
"matrix",
"numpy",
""
] |
The Database Engine Tuning Advisor has finally given up the ghost and can't help me any more, so I'm having to learn a little bit more about indexes (shouldn't it be indices?).
I think I'm more or less there. I know when to use composite indexes, what to include with my indexes, the difference between clustered and non-clustered indexes etc.
However... One thing still confuses me. When creating an index, there is a sort order to the index. I understand what this means, but I am struggling to think of a scenario where a reverse order index might be useful. My best guess is to speed up queries that retrieve rows that occur at the end of the forward sorted index, such as the most chronologically recent rows, but frankly, I'm more or less clueless.
Can anyone enlighten me? | The sort order of an index matters only for a multi-column index. For a single column, Sql Sever can just use the index in reverse order, if it wants DESC where the index is ASC.
For a multi-column search, the index sorting does matter. Say you have an index on:
```
field1, field2 desc
```
This would be useful for this query:
```
select field1, field2 from table order by field1, field2 desc
```
And for this query, where the index can be used in reverse:
```
select field1, field2 from table order by field1 desc, field2
```
But for this query, Sql Server would need an additional in-memory sort:
```
select field1, field2 from table order by field1, field2
``` | Defining the right sort order can ***potentially*** eliminate the need for a sort step in the query plan when you define an *order by* in the select statement.
[Msdn article](http://msdn.microsoft.com/en-us/library/ms181154(SQL.90).aspx "Index Sort Order") | Descending sort order indexes | [
"",
"sql",
"sql-server",
"indexing",
"performance",
""
] |
The following code continues to be displayed even if there are entries in my database and I don't understand why. Am I missing something? I'm not sure if this makes sense, but help would be great. :)
```
if($numrows==0)
{
echo"<h3>Results</h3>";
echo"<p>Sorry, your search: "".$escaped."" returned zero results</p>";
}
``` | If the code you're having a problem with is the same as quoted in [your previous question](https://stackoverflow.com/questions/826439/help-with-search-coding-please)... then the problem is here:
```
$numresults=mysql_query($query);
$numrows=mysql_num_rows(numresults);
```
You're missing a $ before numresults on the second line. | how do you get $numrows? It can be the mistake.
What I usually do is:
```
if($numrows > 0 ){
// Code
}else{
echo"<h3>Results</h3>";
echo"<p>Sorry, your search: "".$escaped."" returned zero results</p>";
}
``` | Code is displayed even with entries in the database | [
"",
"php",
"database",
"search",
""
] |
I have to build a C# program that makes CSV files and puts long numbers (as string in my program). The problem is, when I open this CSV file in Excel the numbers appear like this:
1234E+ or 1234560000000 (the end of the number is 0)
How I retain the formatting of the numbers? If I open the file as a text file, the numbers are formatted correctly.
Thanks in advance. | Format those long numbers as strings by putting a ' (apostrophe) in front or making a formula out of it: ="1234567890123" | As others have mentioned, you can force the data to be a string. The best way for that was ="1234567890123". The = makes the cell a formula, and the quotation marks make the enclosed value an Excel string literal. This will display all the digits, even beyond Excel's numeric precision limit, but the cell (generally) won't be able to be used directly in numeric calculations.
If you need the data to remain numeric, the best way is probably to create a native Excel file (.xls or .xlsx). Various approaches for that can be found in the solutions to [this related Stack Overflow question](https://stackoverflow.com/questions/151005/create-excel-xls-and-xlsx-file-from-c).
If you don't mind having thousands separators, there is one other trick you can use, which is to make your C# program insert the thousands separators and surround the value in quotes: "1,234,567,890,123". Do not include a leading = (as that will force it to be a string). Note that in this case, the quotation marks are for protecting the commas in the CSV, not for specifying an Excel string literal. | How to show long numbers in Excel? | [
"",
"c#",
"excel",
""
] |
How do I cast a parameter passed into a function at runtime?
```
private object PopulateObject(object dataObj, System.Data.DataRow dataRow, string query)
{
object = DataAccess.Retriever.RetrieveArray<dataObj.GetType()>(query);
```
i'd like to know how to get dataObj.GetType() inside the type declaration at runtime. | Try something like this:
```
private T PopulateObject<T>(T dataObj, System.Data.DataRow dataRow, string query)
{
dataObj = DataAccess.Retriever.RetrieveArray<T>(query);
}
```
This will allow you to avoid any reflection in this method as the type argument supplied to `PopulateObject` will also be the type argument for `RetrieveArray`. By calling this method the compiler will be able to infer the type of `T`, allowing you to avoid writing runtime type checking. | You cannot do this, because variable declaration happens at compile time, not runtime. You should create a generic method.
```
private T PopulateObject<T>(T dataObj, DataRow dataRow, String query)
{
return DataAccess.Retriever.RetrieveArray<T>(query);
}
``` | dynamic casting | [
"",
"c#",
"casting",
""
] |
I am new in Java so please be patient.
It is common to map (convert) lists to lists. Some languages have a `map` method, some (C#) `Select`. How is this done with Java? Is a `for` loop the only option?
I expect to be able to do something like this:
```
List<Customer> customers = new ArrayList<Customer>();
...
List<CustomerDto> dtos = customers.convert(new Converter(){
public convert(c) {
return new CustomerDto();
}
})
```
I have missed something? Please give me a starting point. | I implemented something on the fly. See if this helps you. If not, use Google Collections as suggested.
```
public interface Func<E, T> {
T apply(E e);
}
public class CollectionUtils {
public static <T, E> List<T> transform(List<E> list, Func<E, T> f) {
if (null == list)
throw new IllegalArgumentException("null list");
if (null == f)
throw new IllegalArgumentException("null f");
List<T> transformed = new ArrayList<T>();
for (E e : list) {
transformed.add(f.apply(e));
}
return transformed;
}
}
List<CustomerDto> transformed = CollectionUtils.transform(l, new Func<Customer, CustomerDto>() {
@Override
public CustomerDto apply(Customer e) {
// return whatever !!!
}
});
``` | There is no built-in way of doing this in Java - you have to write or use a helper class. [Google Collections](http://google-collections.googlecode.com) includes
```
public static <F,T> List<T> transform(List<F> fromList,
Function<? super F,? extends T> function)
```
This works well, but it's a bit clumsy to use, as you have to use a one-method anonymous class and a static method. This is no fault of Google Collections, it is just the nature of doing this type of task in Java.
Note that this lazily transforms items in the source list as needed. | What is the most elegant way to map one list to another in Java? | [
"",
"java",
""
] |
What i'd like to generate into method bodies:
```
private void SomeMethod()
{
Logger.Log("Entering SomeMethod.");
// do stuff here
Logger.Log("Exiting SomeMethod.")
}
```
Is there a tool which can generate that for me?
If there isn't, and I'd like to implement one myself, then where do I start, which library should I look into for recognizing methods in c# source code? Simple regexes should be enough? | check out postsharp
<http://www.postsharp.org/>
this is an Aspect-orientated-programming framework. It will allow you to paint your methods with attributes that will run loggers, security checks etc. | You're definitely looking for [PostSharp](http://www.postsharp.org/) here - Aspect Oriented Programming (AOP) for .NET. It will allow you to add handlers that get executed before the start and after the end of arbitrary methods, so that you effectively only need define your logging code in one place. | How to auto-generate logger calls into source code in C#? | [
"",
"c#",
"logging",
"code-generation",
""
] |
Is this a possible function?
I need to check if a variable is existent in a list of ones I need to check against and also that cond2 is true
eg
```
if($row['name'] == ("1" || "2" || "3") && $Cond2){
doThis();
}
```
It's not working for me and all I changed in the copy paste was my list and the variable names | ```
if(in_array($row['name'], array('1', '2', '3')) && $Cond2) {
doThis();
}
```
PHP's `in_array()` docs: <http://us.php.net/manual/en/function.in-array.php> | You're lookin for the function [`in_array()`](http://us.php.net/manual/en/function.in-array.php).
```
if (in_array($row['name'], array(1, 2, 3)) && $cond2) {
#...
``` | Simple PHP Condition help: if($Var1 = in list($List) and $Cond2) - Is this posslbe? | [
"",
"php",
"list",
"conditional-statements",
""
] |
Is it possible in the Windows environment to detect if a file is being opened with with .NET
I would like to place a handler on the file system to detect if a file or any file is being opened, is this possible? | The simplest solution would be to use a [`FileSystemWatcher`](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx) and set the filter to [`NotifyFilters.LastAccess`](http://msdn.microsoft.com/en-us/library/system.io.notifyfilters.asp), which will tell it to watch for a change in the last access date/time. | Check out the FileSystemWatcher class
<http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx>
I'm not 100% sure that you can determine if a file is opened, but you can determine if a file is changed, created, deleted. | Detecting a file opening | [
"",
"c#",
"filesystems",
".net",
""
] |
Which one is faster? Which one uses less memory?
```
Console.WriteLine("string1")
Console.WriteLine("string2")
Console.WriteLine("string3")
Console.WriteLine("stringNth")
```
or
```
StringBuilder output = new StringBuilder();
output.AppendLine("string1");
output.AppendLine("string2");
output.AppendLine("string3");
output.AppendLine("stringNth");
Console.WriteLine(output);
```
thanks, | The first.
The console class is going to buffer this to the standard output stream.
With the second option, you're trying to create your own buffer, then buffer that again.
Take it to an extreme - do this 10,000,000 times. Your StringBuilder would eventually eat up all of your memory, where the Console would just be spitting out output. | Since this is a 7 year old question and answers here needed some more clarity adding my answer.
Console.WriteLine will be slower. But it will consume less memory.
Second one will take more memory but it will be much much faster.
Some statistics:
Writing 100,000 using Console.Writeline takes approx 30 seconds.
Using String builder it takes less than a second.
If strings are small then memory won't be an issue and using second approach will be better. | Which is better,using console.writeline() many times or saving the output on a stringbuilder and calling console.writeline once? | [
"",
"c#",
""
] |
How can I work around the Oracle's limitation of not allowing subqueries in triggers.
Here's an example trigger I'm trying to create, but am unable to because I can't use a subquery.
```
CREATE OR REPLACE TRIGGER trigger_w_subquery
AFTER UPDATE OR INSERT ON project_archiving
FOR EACH ROW WHEN (old.archiving_status <> new.archiving_status
AND new.archiving_status = 1
AND (SELECT offer FROM projects WHERE projnum = :new.projnum) IS NULL
)
BEGIN
INSERT INTO offer_log (offer, status, date)
VALUES (null, 9, sysdate);
END;
``` | This trigger would do it:
```
CREATE OR REPLACE TRIGGER trigger_w_subquery
AFTER UPDATE OR INSERT ON project_archiving
FOR EACH ROW WHEN (old.archiving_status <> new.archiving_status
AND new.archiving_status = 1
)
DECLARE
l_offer projects.offer%TYPE;
BEGIN
SELECT offer INTO l_offer
FROM projects
WHERE projnum = :new.projnum;
IF l_offer IS NULL THEN
INSERT INTO offer_log (offer, status, date)
VALUES (null, 9, sysdate);
END IF;
END;
```
I have assumed that the select from projects will always find a row; if not it will raise a NO\_DATA\_FOUND exception that you may need to handle. | I expect that you want something like
```
CREATE OR REPLACE TRIGGER trigger_w_subquery
AFTER UPDATE OR INSERT ON project_archiving
FOR EACH ROW
WHEN (old.archiving_status <> new.archiving_status
AND new.archiving_status = 1)
DECLARE
l_offer projects.offer%TYPE;
BEGIN
SELECT offer
INTO l_offer
FROM projects
WHERE projnum = :new.projnum;
IF( l_offer IS NULL )
THEN
INSERT INTO offer_log (offer, status, date)
VALUES (null, 9, sysdate);
END IF;
END;
``` | Oracle: Using subquery in a trigger | [
"",
"sql",
"oracle",
"triggers",
"subquery",
""
] |
I have a class I'm unit testing that requires fairly extensive database setup before the individual test methods can run. This setup takes a long time: for reasons hopefully not relevant to the question at hand, I need to populate the DB programatically instead of from an SQL dump.
The issue I have is with the tear-down. How can I easily rollback all the changes made in the db setup phase?
I'm currently using Hibernate + Spring Transactional Testing support, such that my individual test methods are wrapped in transactions.
One solution would be to do the db setup within each test method, such that the db setup would be rolled back automatically. However, the test methods would take forever to run since each method would need to re-prep the database.
Any other ideas? Basically, I'm looking for a way to run my db setup, run my individual tests (each wrapped in a transaction which gets rolled-back after execution), and then roll-back the initial db setup. Any ideas on making this working in a Hibernate / Spring / Junit fashion? Is there a Hibernate "drop all tables" equivalent command? | Are you stuck with a specific database vendor? If not, you could use an in-memory database, such as [HSQLDB](http://hsqldb.org/). When you are done with the tests you just throw away the state. This is only appropriate if the tables can be empty at the start of the test suite (before your programmatic setup, that is).
You still need to create tables, but if everything is neatly mapped using Hibernate you can use the hbm2ddl to generate your tables. All you have to do is add the following to your *test* session factory definition:
```
<session-factory>
...
<property name="hibernate.hbm2ddl.auto">create</property>
...
</session-factory>
```
If this solution seems applicable I can elaborate on it. | Is there a reason that you have to have a connection to the database to run your unit tests? It sounds like it might be easier to refactor your class so that you can mock the interaction with the database. You can mock classes (with some exceptions) as well as interfaces with EasyMock (www.easymock.org).
If your class relies on a complex pre-existing state in a connected database, it would probably be easier to write faster executing tests using mocks. We don't know what the size of your project is or how often your tests are run, but execution time might be something to think about, especially in a large project. | Setup and Tear Down of Complex Database State With Hibernate / Spring / JUnit | [
"",
"java",
"hibernate",
"spring",
"junit",
""
] |
I apologize for the subjectiveness of this question, but I am a little stuck and I would appreciate some guidance and advice from anyone who's had to deal with this issue before:
I have (what's become) a very large RESTful API project written in C# 2.0 and some of my classes have become monstrous. My main API class is an example of this -- with several dozen members and methods (probably approaching hundreds). As you can imagine, it's becoming a small nightmare, not only to maintain this code but even just **navigating** the code has become a chore.
I am reasonably new to the SOLID principles, and I am massive fan of design patterns (but I am still at that stage where I can **implement** them, but not quite enough to know when to **use** them - in situations where its not so obvious).
I need to break my classes down in size, but I am at a loss of how best to go about doing it. Can my fellow StackOverflow'ers please suggest ways that they have taken existing code monoliths and cut them down to size? | **Single Responsibility Principle** - A class should have only one reason to change. If you have a monolithic class, then it probably has more than one reason to change. Simply define your one reason to change, and be as granular *as reasonable*. I would suggest to start "large". Refactor one third of the code out into another class. Once you have that, then start over with your new class. Going straight from one class to 20 is too daunting.
**Open/Closed Principle** - A class should be open for extension, but closed for change. Where reasonable, mark your members and methods as virtual or abstract. Each item should be relatively small in nature, and give you some base functionality or definition of behavior. However, if you need to change the functionality later, you will be able to *add* code, rather than *change* code to introduce new/different functionality.
**Liskov Substitution Principle** - A class should be substitutable for its base class. The key here, in my opinion, is do to inheritance correctly. If you have a huge case statement, or two pages of if statements that check the derived type of the object, then your violating this principle and need to rethink your approach.
**Interface Segregation Principle** - In my mind, this principle closely resembles the Single Responsibility principle. It just applies specifically to a high level (or mature) class/interface. One way to use this principle in a large class is to make your class implement an *empty* interface. Next, change all of the types that use your class to be the type of the interface. This will break your code. However, it will point out exactly how you are consuming your class. If you have three instances that each use their own subset of methods and properties, then you now know that you need three different interfaces. Each interface represents a collective set of functionality, and one reason to change.
**Dependency Inversion Principle** - The parent / child allegory made me understand this. Think of a parent class. It defines behavior, but isn't concerned with the dirty details. It's dependable. A child class, however, is all about the details, and can't be depended upon because it changes often. You always want to depend upon the parent, responsible classes, and never the other way around. If you have a parent class depending upon a child class, you'll get unexpected behavior when you change something. In my mind, this is the same mindset of SOA. A service contract defines inputs, outputs, and behavior, with no details.
Of course, my opinions and understandings may be incomplete or wrong. I would suggest learning from people who have mastered these principles, like Uncle Bob. A good starting point for me was his book, [Agile Principles, Patterns, and Practices in C#](https://rads.stackoverflow.com/amzn/click/com/0131857258). Another good resource was [Uncle Bob on Hanselminutes](http://www.hanselman.com/blog/HanselminutesPodcast145SOLIDPrinciplesWithUncleBobRobertCMartin.aspx).
Of course, as [Joel and Jeff pointed out](https://blog.stackoverflow.com/2009/02/podcast-41/), these are principles, not rules. They are to be tools to help guide you, not the law of the land.
**EDIT:**
I just found these [SOLID screencasts](http://www.dimecasts.net/Casts/ByTag/SOLID%20Principle) which look really interesting. Each one is approximately 10-15 minutes long. | There's a classic book by [Martin Fowler - Refactoring: Improving the Design of Existing Code.](https://rads.stackoverflow.com/amzn/click/com/0201485672)
There he provides a set of design techniques and example of decisions to make your existing codebase more manageable and maintainable (and that what SOLID principals are all about). Even though there are some standard routines in refactoring it is a very custom process and one solution couldn't be applied to all project.
Unit testing is one of the corner pillars for this process to succeed. You do need to cover your existing codebase with enough code coverage so that you'd be sure you don't break stuff while changing it. Actually using modern unit testing framework with mocking support will lead encourage you to better design.
There are tools like ReSharper (my favorite) and CodeRush to assist with tedious code changes. But those are usually trivial mechanical stuff, making design decisions is much more complex process and there's no so much tool support. Using class diagrams and UML helps. That what I would start from, actually. Try to make sense of what is already there and bring some structure to it. Then from there you can make decisions about decomposition and relations between different components and change your code accordingly.
Hope this helps and happy refactoring! | How to implement SOLID principles into an existing project | [
"",
"c#",
"design-patterns",
"solid-principles",
""
] |
It's my first time dealing with cookies in JavaScript and the below script works fine on my local PC but when I upload it here: [example](http://www.keithdonegan.com/jquery/stylesheet-switcher-with-cookies/) it fails.
```
$(document).ready(function(){
// Get Cookie
var getCookie = document.cookie;
if(getCookie == "stylesheet=blue")
{
$("[rel=stylesheet]").attr({href : "blue.css"});
}
else if(getCookie == "stylesheet=main")
{
$("[rel=stylesheet]").attr({href : "main.css"});
}
// Set Stylsheet back to Main
$('#reset').click(function()
{
$("[rel=stylesheet]").attr({href : "main.css"});
var setCookie = document.cookie = "stylesheet=main";
});
// Set Stylsheet Blue
$('#blue').click(function()
{
$("[rel=stylesheet]").attr({href : "blue.css"});
var setCookie = document.cookie = "stylesheet=blue";
});
});
```
Any ideas? | The problem is, you are using google analytics, which also sets its own cookies. So, when reading document.cookie property, it will never have the value eg. "stylesheet=blue", because it will contain information on other cookies. Call
```
alert(document.cookie);
```
and check the value for yourself.
You should use a function for getting cookie value, for example
```
function getCookie(N){
if(N=(new RegExp(';\\s*'+N+'=([^;]*)')).exec(';'+document.cookie+';'))
return N[1]
}
```
or use [jQuery cookie plugin](http://plugins.jquery.com/project/Cookie) | When you get the cookie back, it isn't just the string "stylesheet=blue" but has other information in it as well.
For me the string I get back looks like this:
```
"stylesheet=blue; __utma=168444603.22445052401845424.1242318397.1242318397.1242318397.1; __utmb=168444603.5.10.1242318397; __utmc=168444603; __utmz=168444603.1242318397.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/questions/864324/cookie-sets-on-localhost-but-not-on-live-server"
```
check that the string contains "stylesheet=blue" instead of checking equivalance.
**Edit**: See what @Rafael said. I like the JQuery cookie plugin | Cookie sets on Localhost but not on live server? | [
"",
"javascript",
"cookies",
""
] |
I have already read [Using Java to encrypt integers](https://stackoverflow.com/questions/321787/using-java-to-encrypt-integers) and [Encrypting with DES Using a Pass Phrase](http://www.exampledepot.com/egs/javax.crypto/PassKey.html).
All I need is a simple Encrypter which transforms a 12 digit number to a 12 digit number with the following constraints:
1. The encryption must depend on a password (which will be constant throughout the life time of an application) and nothing else.
2. The mapping must be 1-1 (No hashing and multiple inputs giving same output and vice versa).
3. The mapping must not change between different VMs or when VM is started (like when you restart Java, the utility should give you same mappings which means that it must be purely dependent on the password that is supplied).
4. Numbers starting with 0 is not a valid 12 digit number (also input numbers won't start with 0).
5. The key/password should never be guessable. For example running the utility with multiple inputs and analysing the outputs should not allow one to guess the key/pwd/hash or whatever.
6. All inputs will be exactly 12 digits and less than a 12 digit prime number (which means we could use modulo arithmetic).
Having trawled through the literature I have this code with me
```
public void mytestSimple(long code, String password) throws Exception {
SecretKey key = new SecretKeySpec(password.getBytes(), "DES");
Cipher ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
System.out.println(ecipher.getOutputSize(8));
byte[] encrypted = ecipher.doFinal(numberToBytes(code));
System.out.println(encrypted + "--" + encrypted.length);
Cipher dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = dcipher.doFinal(encrypted);
System.out.println(bytesToNumber(decrypted) + "--" + decrypted.length);
}
public void testSimple() throws Exception {
mytestSimple(981762654986L, "password");
}
```
I am running into problems as to
1. How to convert the 16 bytes into a 12 digit number.
2. Maintain 1-1 mapping.
3. Keep the encryption/decryption same across multiple VM invocations.
\*\*\*\* Answer added by me below\*\*\*\*
I have added one answer which is a 40bit RSA pulled out of standard Java RSA keypair gen logic. I still have to work on the edge cases. I am going to accept the answer and upvote "Tadmas" who I think kinda lead me to the answer. Can someone tell me if my algorithm is going to be weak/attackable? | Me thinks the answer given below by Tadmas was very helpful and I want you guys to hack/bully my implementation below. As Tadmas points out all my numbers are 40 bits (12 digit number is 10^12 which is 2^40 approx).
I copied the sun.security.rsa.RSAKeyPairGenerator (link) and created my own generator for a 40 bit RSA algorithm. The standard one needs between 512-1024 bits so I removed the input check around it. Once I create a suitable n, e, d values (e seems to be 65537 as per the alog). The following code served fine,
```
public void testSimple() throws NoSuchAlgorithmException {
MyKeyPairGenerator x = new MyKeyPairGenerator();
x.initialize(40, new SecureRandom("password".getBytes()));
MyPublicPrivateKey keypair = x.generateKeyPair();
System.out.println(keypair);
BigInteger message = new BigInteger("167890871234");
BigInteger encoded = message.modPow(keypair.e, keypair.n);
System.out.println(encoded); //gives some encoded value
BigInteger decoded = encoded.modPow(keypair.d, keypair.n);
System.out.println(decoded); //gives back original value
}
```
Disadvantages
1. The encoded may not always be 12 digits (sometimes it may start with 0 which means only 11 digits). I am thinking always pad 0 zeroes in the front and add some CHECKSUM digit at the start which might alleviate this problem. So a 13 digit always...
2. A 40 bits RSA is weaker than 512 bit (not just 512/40 times but an exponential factor of times). Can you experts point me to links as to how secure is a 40bit RSA compared to 512 bit RSA (I can see some stuff in wiki but cannot concretely confirm possibility of attacks)? Any links (wiki?) on probabilities/number of attempts required to hack RSA as a function of N where n is the number of bits used will be great ! | You're not going to be able to convert 16 bytes into a 12 digit number without losing information. 256 ^ 16 > 10^12. (Not that you even have 10^12 options, as you've only got the range [100000000000, 999999999999].
I doubt that you'll be able to use any traditional encryption libraries, as your requirements are somewhat odd. | How can I encrypt/decrypt 12-digit decimal numbers to other ones, using a password and Java? | [
"",
"java",
"encryption",
""
] |
I have two Collection objects, I want to associate each object of these two in a readable way (HashMap, Object created on purpose, you choose).
I was thinking of two loops one nested into the other, but maybe it's a well known problem and has a commonly understandable solution...
What if the number of Collection objects raises above two?
EDIT after Joseph Daigle comment: The items of the Collection objects are all of the same type, they are rooms of hotels found to be bookable under certain conditions.
```
Collection<Room> roomsFromA = getRoomsFromA();
Collection<Room> roomsFromB = getRoomsFromB();
for(Room roomA : roomsFromA){
for(Room roomB : roomsFromB){
//add roomA and roomB to something, this is not important for what I need
//the important part is how you handle the part before
//especially if Collection objects number grows beyond two
}
}
```
EDIT 2: I'll try to explain better, sorry for the question being unclear.
Follows an example:
A user requests for a double and a single room.
The hotel has 3 double and 4 single rooms available.
I need to associate every "double room" to every "single room", this is because each Room has its own peculiarity say internet, a more pleasant view, and so on. So i need to give the user all the combinations to let him choose.
This is the simple case, in which only two Collection of Room objects are involved, how do you manage the problem when say both hotel and user can offer / request more Room types? | What you are trying to do here is to get all possible permutations of choosing X from a set of Y. This is a well known problem in discrete mathematics and I think it is just called Combinatorial Mathematics.
To solve your problem you need to create a super collection containing all your Room types. If this is an array or a List you can then use [this example](http://docs.google.com/Doc?id=ddd8c4hm_5fkdr3b) to calculate all possible ways of choosing X from the set of Y. The example will give you the indices from the list/array. | Do the collections line up exactly?
```
HashMap map = new HashMap();
for (int i=0; i<c1.Size(); i++) {
map.put(c1[i], c2[i]);
}
``` | How do you associate each Collection's item to another one's? | [
"",
"java",
"collections",
"permutation",
""
] |
We have system here that uses Java JNI to call a function in a C library. Everything running on Solaris.
I have a problem somewhere with string encoding. An arabic character is returned by the function written in C, but the JNI methods receives a string with another encoding. I already tried setting $NLS\_LANG, and the vm parameter for encoding the same way, but nothing has worked. So I need to be able to debug the C code and the Java JNI together.
what is the best way to debug it? | The dbx debugger (part of Sun Studio) can attach to a JVM process and let you single step between Java code and native code. The functionality went by the code name "jdbx", although it's all part of dbx. It hasn't been heavily promoted, so it might have bugs. There were issues when the IDE had two debug engines both handling Java, but using the command line dbx avoids those issues.
Of course, there are probably lots of more conventional ways to debug your specific problem without necessarily using source level debugging that can mix the Java and C code. | Eclipse Juno release with latest Android Plugins supports the debugging.
[How to Use Eclipse to Debug JNI code (Java & C/C++)](https://stackoverflow.com/questions/2762916/how-to-use-eclipse-to-debug-jni-code-java-c-c) | How to debug JNI/C library? | [
"",
"java",
"c",
"debugging",
"solaris",
"java-native-interface",
""
] |
I'm quite new to c++, but I've got the hang of the fundamentals. I've come across the use of "Uint32" (in various capitalizations) and similar data types when reading other's code, but I can't find any documentation mentioning them. I understand that "Uint32" is an unsigned int with 32 bits, but my compiler doesn't. I'm using visual c++ express, and it doesn't recognize any form of it from what I can tell.
Is there some compilers that reads those data types by default, or have these programmers declared them themselves as classes or #define constants?
I can see a point in using them to know exactly how long your integer will be, since the normal declaration seems to vary depending on the system. Is there any other pros or cons using them? | Visual c++ doesn't support the fixed-width integer types, because it doesn't include support for C99. Check out the answers to [my question on this subject](https://stackoverflow.com/questions/734802/fixed-width-integers-in-c) for various options you have for using them. | Unix platforms define these types in **stdint.h**, this is the preferred method of ensuring type sizing when writing portable code.
Microsoft's platforms do not define this header, which is a problem when going cross-platform. If you're not using [Boost Integer Library](http://www.boost.org/doc/libs/1_38_0/libs/integer/index.html) already, I recommend getting Paul Hsieh's [portable stdint.h](http://www.azillionmonkeys.com/qed/pstdint.h) implementation of this header for use on Microsoft platforms.
**Update:** Visual Studio 2010 and later do define this header. | "Uint32", "int16" and the like; are they standard c++? | [
"",
"c++",
""
] |
I've got some JavaScript in an ASP.NET page that looks like this:
```
var list = $get('<%=Topics.ClientID %>');
```
I have many functions written now where this syntax is used, and I would like to centralize my JavaScript and move this into an external JavaScript file. This breaks however, since 'Topics' cannot be found.
What is the best strategy for getting this to work? I assume I should pass the control/control information as a parameter to the function, but I can't seem to get the syntax to work. Any suggestions? | It's a common problem for ASP.NET JS development. As for me, I'm using same approach each time and it looks fine.
I'm used to OOP in Javascript, so most my JS external files look like:
```
function CouponManager()
{
}
```
And in .aspx code i do:
```
<script language="javascript">
var couponManager = new CouponManager();
</script>
```
If I need to pass some parameters I change the declaration of class to:
```
function CouponManager(params)
{
// .. stuff here
this.initialize = function(initParams)
{
// .. accessing initParams variable for server control IDs
};
this.initialize(params);
}
```
And from .aspx code I do the following:
```
<script language="javascript">
var couponManager = new CouponManager
({
txtCouponNameId = '<%= txtCouponName.ClientID %>',
txtCouponDescriptionId = '<%= txtCouponDescription.ClientID %>'
});
</script>
```
This approach allows me to separate JS from .aspx page and have all server control dependencies in a single tag. | You should create a javascript method from inside the usercontol which returns the client side element. Then in your other page/control, just access that method
In User Control
```
<script language="javascript">
function GetTopics() {
return = $get('<%=Topics.ClientID %>');
}
</script>
```
In other page/control
```
<script language="javascript">
var list = GetTopics();
</script>
```
Edit - The problem you are facing is you need Topics.ClientID where it doesn't exist. So the only real way to bridge that gap is to put it in a common place. If you really don't want to do that, you can try and select your element by some other criteria. If you are using jQuery, you could mark an element with a class of Topics then find it with $(".Topics"). | AJAX & ASP.net, Referencing server controls in external file | [
"",
"javascript",
"ajax",
"asp.net-ajax",
"parameters",
"clientid",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.