Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
```
array(1) {
[0]=>
string(8) "outgoing"
}
bool(false)
array(1) {
[0]=>
string(8) "outgoing"
}
bool(false)
```
Is currently being produced by
```
$connect = ftp_connect('example.com');
$result = ftp_login($connect, 'username', 'password');
echo '<pre>';
var_dump(ftp_nlist($connect, ''));
var_dump(ftp_nlist($connect, '/outgoing/'));
var_dump(ftp_nlist($connect, '/2689312/'));
var_dump(ftp_nlist($connect, '/2689312/outgoing/'));
```
But why isn't it letting me list lower than the top directory? This is really stumping me. I can't even get into a sub folder let alone the full folder scheme I need to open.
Any ideas? | To get the list of the CWD, instead of:
`var_dump(ftp_nlist($connect, ''));`
you need to do:
`var_dump(ftp_nlist($connect, '.'));`
I believe if you want to deeper from there the directory must be:
`./subdirectory` | Most FTP services do not let the FTP client who is connecting go further down than the home directory. So check the home directory of the user that is connecting.
It could also be that you are calling the directory wrong.
If `/2689312/` is below your starting directory. Try doing `../2689312/` | PHP FTP directory listing error | [
"",
"php",
"ftp",
""
] |
I have a set of time stamped values I'd like to place in a sorted set.
```
public class TimedValue {
public Date time;
public double value;
public TimedValue(Date time, double value) {
this.time = time;
this.value = value;
}
}
```
The business logic for sorting this set says that values must be ordered in descending value order, *unless it's more than 7 days older than the newest value*.
So as a test, I came up with the following code...
```
DateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");
TreeSet<TimedValue> mySet = new TreeSet<TimedValue>(new DateAwareComparator());
mySet.add(new TimedValue(dateFormatter.parse("01/01/2009"), 4.0 )); // too old
mySet.add(new TimedValue(dateFormatter.parse("01/03/2009"), 3.0)); // Most relevant
mySet.add(new TimedValue(dateFormatter.parse("01/09/2009"), 2.0));
```
As you can see, initially the first value is more relevant than the second, but once the final value is added to the set, the first value has expired and should be the least relevant.
My initial tests say that this should work... that the TreeSet will dynamically reorder the entire list as more values are added.
But even though I see it, I'm not sure I believe it.
Will a sorted collection reorder the entire set as each element is added? Are there any gotchas to using a sorted collection in this manner (i.e performance)? Would it be better to manually sort the list after all values have been added (I'm guessing it would be)?
**Follow-up:**
As many (and even I to a certain extent) suspected, the sorted collection does not support this manner of "dynamic reordering". I believe my initial test was "working" quite by accident. As I added more elements to the set, the "order" broke down quite rapidly. Thanks for all the great responses, I refactored my code to use approaches suggested by many of you. | I don't see how your comparator can even detect the change, unless it remembers the newest value it's currently seen - and that sounds like an approach which is bound to end in tears.
I suggest you do something along the following lines:
* Collect your data in an unordered set (or list)
* Find the newest value
* Create a comparator *based on that value*, such that all comparisons using that comparator will be fixed (i.e. it will never return a different result based on the same input values; the comparator itself is immutable although it depends on the value originally provided in the constructor)
* Create a sorted collection using that comparator (in whatever way seems best depending on what you then want to do with it) | I would advise against this for a few reasons:
1. Since it's basically a red-black tree behind the scenes (which doesn't necessarily have to be rebuilt from scratch on every insertion), you might easily end up with values in the wrong part of the tree (invalidating most of the TreeSet API).
2. The behavior is not defined in the spec, and thus may change later even if it's working now.
3. In the future, when anything goes strangely wrong in anything remotely touching this code, you'll spend time suspecting that this is the cause.
I would recommend either recreating/resorting the TreeSet before searching it or (my preference) iterating through the set before the search and removing any of the objects that are too old. You could even, if you wanted to trade some memory for speed, keep a second list ordered by date and backed by the same objects so that you all you would have to do to filter your TreeSet is remove objects from the TreeSet based on the time-sorted list. | Is it OK to have a Java Comparator where order can change dynamically? | [
"",
"java",
"collections",
"comparator",
""
] |
I have an application in C# .NET which has a `MainForm` and a few classes.
One of these classes receives incoming data messages from a network. I need to get these message's text appended into a multi-line textbox on the `MainForm`.
I can send the message to a method in the `MainForm` by making the method static, but then the static method cannot access the `MainForm`'s controls.
**TheIncomingDataClass.cs**
```
namespace TheApplicationName
{
class TheIncomingDataClass
{
public void IncomingMessage(IncomingMessageType message)
{
TheApplicationName.MainForm.ReceiveMSG(message);
}
```
**MainForm.cs**
```
public static void ReceiveMSG(string message)
{
txtDisplayMessages.AppendText(message); //This line causes compile error
}
```
The compile error:
> An object reference is required for the nonstatic field, method, or
> property 'TheApplicationName.MainForm.txtDisplayMessages' | A static method doesn't have access to members like txtDisplayMessages because it is not a part of that instance. I suggest you do some reading on the concepts of static methods and whatnot, because that is a fairly language agnostic concept. That method would best be served by removing the static modifier, because it doesn't need to be static - it appears that it would need to be called by that particular instance of that object. | To continue the way you've been doing it, your "`TheIncomingDataClass`" should have a reference to the `MainForm` object with which it should interface. When you create an instance of this class (presumably from an instance method of `MainForm`), you will need to pass in a reference to this `MainForm` object.
```
class TheIncomingDataClass{
MainForm form;
public TheIncomingDataClass(MainForm form){
this.form = form;
}
}
class MainForm : Form{
MainForm(){
new TheIncomingDataClass(this);
}
}
```
However, as suggested by [Bugs](https://stackoverflow.com/questions/952023/in-c-net-how-does-one-access-a-control-from-a-static-method/952049#952049), you probably would be better off making this an event on `TheIncomingDataClass` and subscribing to it from `MainForm`.
```
class IncomingMessageEventArgs : EventArgs{
IncomingMessageType message;
public IncomingMessageType Message{get{return message;}}
public IncomingMessageEventArgs(IncomingMessageType message){
this.message = message;
}
}
class TheIncomingDataClass{
public event EventHandler<IncomingMessageEventArgs> MessageReceived;
protected virtual void OnMessageReceived(IncomingMessageEventArgs e){
if(MessageReceived != null)
MessageReceived(this, e);
}
public void IncomingMessage(IncomingMessageType message){
OnMessageReceived(new IncomingMessageEventArgs(message));
}
}
class MainForm : Form{
MainForm(){
new TheIncomingDataClass().MessageReceived +=
(s, e)=>txtDisplayMessages.AppendText(e.Message.ToString());
}
}
``` | How does one access a control from a static method? | [
"",
"c#",
".net",
"winforms",
""
] |
I am relatively new to C++. Recent assignments have required that I convert a multitude of char buffers (from structures/sockets, etc.) to strings. I have been using variations on the following but they seem awkward. Is there a better way to do this kind of thing?
```
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
char* bufferToCString(char *buff, int buffSize, char *str)
{
memset(str, '\0', buffSize + 1);
return(strncpy(str, buff, buffSize));
}
string& bufferToString(char* buffer, int bufflen, string& str)
{
char temp[bufflen];
memset(temp, '\0', bufflen + 1);
strncpy(temp, buffer, bufflen);
return(str.assign(temp));
}
int main(int argc, char *argv[])
{
char buff[4] = {'a', 'b', 'c', 'd'};
char str[5];
string str2;
cout << bufferToCString(buff, sizeof(buff), str) << endl;
cout << bufferToString(buff, sizeof(buff), str2) << endl;
}
``` | Given your input strings are not null terminated, you shouldn't use str... functions. You also can't use the popularly used [`std::string` constructors](http://en.cppreference.com/w/cpp/string/basic_string/basic_string). However, you can use this constructor:
`std::string str(buffer, buflen)`: it takes a `char*` and a length. (actually `const char*` and length)
I would avoid the C string version. This would give:
```
std::string bufferToString(char* buffer, int bufflen)
{
std::string ret(buffer, bufflen);
return ret;
}
```
If you really must use the `C-string` version, either drop a `0` at the `bufflen` position (if you can) or create a buffer of `bufflen+1`, then `memcpy` the buffer into it, and drop a `0` at the end (`bufflen` position). | If the data buffer may have null ('\0') characters in it, you don't want to use the null-terminated operations.
You can either use the constructor that takes char\*, length.
```
char buff[4] = {'a', 'b', 'c', 'd'};
cout << std::string(&buff[0], 4);
```
Or you can use the constructor that takes a range:
```
cout << std::string(&buff[0], &buff[4]); // end is last plus one
```
Do NOT use the std::string(buff) constructor with the buff[] array above, because it is not null-terminated. | Good methods for converting char array buffers to strings? | [
"",
"c++",
""
] |
I am using the FileInfo class. However, the file info cannot find the file.
The file is called log4Net.config and I have added it to my project. I have set the properties to build action = 'Content' and copy output = 'copy always'
When I run the following code:
```
FileInfo logfileInfo = new FileInfo("Log4Net.config");
if (!logfileInfo.Exists)
{
Console.WriteLine("Cannot find file: " + logfileInfo.FullName);
return;
}
else
{
XmlConfigurator.Configure(logfileInfo);
}
```
Exists is always false. The exception is: Could not find file 'Log4Net.config'.
I have checked on my PDA and the Log4Net.config has been copied the PDA and is in the same directory as the executable. So not sure why it cannot find it.
Just some extra info the configure method expects a FileInfo as a parameter.
Am I doing something wrong.
Many thanks for any advice,
Steve | You have to point to the root of your project. FileInfo points to the root of the OS not the root of the exe. So you should change the code like this :
```
FileInfo logfileInfo = new FileInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + @"\Log4Net.config");
``` | A file not found exception is also thrown when the program does not have the security permission to access the file, so perhaps that's the case?
btw, there's a contradiction in your Post: First you say the file is called "logPDA.config", then it's suddenly called "Log4Net.config". Just to make sure, is the file always named the same? | FileInfo compact framework 3.5 - cannot find file | [
"",
"c#",
"compact-framework",
"fileinfo",
""
] |
I'm writing a simple CMS based on Django. Most content management systems rely on having a fixed page, on a fixed URL, using a template that has one or many editable regions. To have an editable region, you require a Page. For the system to work out which page, you require the URL.
The problem comes when you're no longer dealing with "pages" (be those FlatPages pages, or something else), but rather instances from another Model. For example if I have a Model of products, I may wish to create a detail page that has multiple editable regions within.
I *could* build those regions into the Model but in my case, there are several Models and is a lot of variance in how much data I want to show.
Therefore, I want to build the CMS at template level and specify what a block (an editable region) is based on the instance of "page" or the model it uses.
I've had the idea that perhaps I could dump custom template tags on the page like this:
```
{% block unique_object "unique placeholder name" %}
```
And that would find a "block" based on the two arguments passed in. An example:
```
<h1>{{ product_instance.name }}</h1>
{% block product_instance "detail: product short description" %}
{% block product_instance "detail: product video" %}
{% block product_instance "detail: product long description" %}
```
Sounds spiffy, right? Well the problem I'm running into is how do I create a "key" for a zone so I can pull the correct block out? I'll be dealing with a completely unknown object (it could be a "page" object, a URL, a model instance, anything - it could even be a boat`</fg>`).
Other Django micro-applications must do this. You can tag anything with django-tagging, right? I've tried to understand how that works but I'm drawing blanks.
So, firstly, am I mad? And assuming I not, and this looks like a relatively sane idea to persue, how should I go about linking an object+string to a block/editable-region?
Note: Editing will be done *on-the-page* so there's no real issue in letting the users edit the zones. I won't have to do any reverse-mumbo-jumbo in the admin. My eventual dream is to allow a third argument to specify what sort of content area this is (text, image, video, etc). If you have any comments on any of this, I'm happy to read them! | django-tagging uses Django's [contenttypes](http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/) framework. The docs do a much better job of explaining it than I can, but the simplest description of it would be "generic foreign key that can point to any other model."
This may be what you are looking for, but from your description it also sounds like you want to do something very similar to some other existing projects:
* **[django-flatblocks](http://pypi.python.org/pypi/django-flatblocks/0.3.1)** ("... acts like django.contrib.flatpages but for parts of a page; like an editable help box you want show alongside the main content.")
* **[django-better-chunks](http://bitbucket.org/hakanw/django-better-chunks/wiki/Home)** ("Think of it as flatpages for small bits of reusable content you might want to insert into your templates and manage from the admin interface.")
and so on. If these are similar then they'll make a good starting point for you. | It's pretty straightforward to use the [contenttypes](http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#ref-contrib-contenttypes) framework to implement the lookup strategy you are describing:
```
class Block(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
object = generic.GenericForeignKey() # not actually used here, but may be handy
key = models.CharField(max_length=255)
... other fields ...
class Meta:
unique_together = ('content_type', 'object_id', 'key')
def lookup_block(object, key):
return Block.objects.get(content_type=ContentType.objects.get_for_model(object),
object_id=object.pk,
key=key)
@register.simple_tag
def block(object, key)
block = lookup_block(object, key)
... generate template content using 'block' ...
```
One gotcha to be aware of is that you can't use the `object` field in the `Block.objects.get` call, because it's not a real database field. You must use `content_type` and `object_id`.
I called the model `Block`, but if you have some cases where more than one unique `(object, key)` tuple maps to the same block, it may in fact be an intermediate model that itself has a `ForeignKey` to your actual `Block` model or to the appropriate model in a helper app like the ones Van Gale has mentioned. | How to agnostically link any object/Model from another Django Model? | [
"",
"python",
"django",
"django-models",
"content-management-system",
""
] |
I'm going to extend the existing std::map class and add a new function to it:
```
template<typename key_type, typename value_type>
class CleanableMap : public Cleanable, public std::map<key_type, value_type>
{
CleanableMap(const CleanableMap& in); //not implemented
CleanableMap& operator=(const CleanableMap& in); //not implemented
public:
CleanableMap() {}
CleanableMap(const std::map<key_type, value_type>& in) { *this = in; }
virtual ~CleanableMap() {}
std::map<key_type, value_type>& operator=(const std::map<key_type, value_type>& in)
{
*((std::map<key_type, value_type>*)this) = in;
return *this;
}
};
```
I've got a copy constructor and assignment operator such that I can simply assign an existing std::map of the same type to my new map:
```
CleanableMap<DWORD, DWORD> cm;
std::map<DWORD, DWORD> stdm;
cm = stdm;
```
The problem is, the compiler is complaining with an error that doesn't make sense -- I've explicitly coded for what it's complaining about:
```
1>c:\dev\proj\commonfunc.cpp(399) : error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::map<_Kty,_Ty>' (or there is no acceptable conversion)
1> with
1> [
1> _Kty=DWORD,
1> _Ty=DWORD
1> ]
1> c:\dev\proj\templates.h(245): could be 'CleanableMap<key_type,value_type> &CleanableMap<key_type,value_type>::operator =(const CleanableMap<key_type,value_type> &)'
1> with
1> [
1> key_type=DWORD,
1> value_type=DWORD
1> ]
1> c:\dev\proj\templates.h(250): or 'std::map<_Kty,_Ty> &CleanableMap<key_type,value_type>::operator =(const std::map<_Kty,_Ty> &)'
1> with
1> [
1> _Kty=unsigned long, <--- where did it come up with that?
1> _Ty=std::pair<const DWORD,DWORD>, <--- where did it come up with that?
1> key_type=DWORD,
1> value_type=DWORD
1> ]
1> while trying to match the argument list '(CleanableMap<key_type,value_type>, std::map<_Kty,_Ty>)'
1> with
1> [
1> key_type=DWORD,
1> value_type=DWORD
1> ]
1> and
1> [
1> _Kty=DWORD,
1> _Ty=DWORD
1> ]
```
There 'could be' it mentions on line 245 doesn't make sense -- there is no assignment operator like that (well, it's private. Removing it completely doesn't change anything).
The 'could be' it mentions on line 250 is the assignment operator that I defined, but it was somehow deduced some other non-matching template types. Where did it get those??
Help!!! :) | Adding onto Neil's answer.
One concrete reason you should not be deriving from std::map is that it does not have a virtual destructor. This means you simply cannot guarantee any resources you allocate as a part of your map will be freed during the destruction of your implementation via a std::map pointer.
```
std::map<int,int>* pMap = GetCleanableMap();
...
delete pMap; // does not call your destructor
``` | `std::map` is not intended to be extended by derivation. If you want to add new functionality, do it with stand-alone functions. | Stuck on C++ template - deriving from std::map | [
"",
"c++",
"visual-c++",
"templates",
"stl",
""
] |
I hope this question isn’t too “right field” and I'll be upfront in saying I'm a newb compared to many people on stackflow...
I want to compare object representations of images, audio and text for an AI project I am working on. I'd like to convert all three inputs into a single data type and use a central comparison algorithm to determine statically probable matches.
What are the “fastest” native .Net and SQL data types for making comparisons like this? In .Net what data type requires the least amount of conversions in the CLR? For SQL, what type can be “CRUD-ed” the fastest?
I was thinking bytes for .Net and integers for SQL but integers pose a problem of being a one dimensional concept. Do you think the images and audio should be handled within the file system rather than SQL…I’m guessing so…
FWIW I'm building a robot from parts I bought at TrossenRobotics.com | Personally, if you need to do frequent comparisons between large binary objects, I would hash the objects and compare the hashes.
If the hashes don't match, then you can be sure the objects don't match (which should be the majority of the cases).
If the hashes do match, you can then start a more lengthy routine to compare the actual objects.
This method alone should boost your performance quite a bit if you're comparing these objects frequently. | Speed of data types is a bit hard to measure. It makes a big difference if you're using a 32-bits operating system or a 64-bits. Why? Because it determines the speed at which this data can be processed.
In general, on a 32-bits system, all data types that fit inside 32 bits (int16, int32, char, byte, pointers) will be processed as the same speed. If you need lots of data to be processed, it's best to divide it in blocks of four bytes each for your CPU to process them.
However, when you're writing data to disk, data speed tends to depend on a lot more factors. If your disk device is on some USB port, all data gets serialized, thus it would be byte after byte. In that case, size doesn't matter much, although the smallest datablocks would leave the smallest gaps. (In languages like Pascal you'd use a packed record for this kind of data to optimize streaming performance, while having your fields in your records aligned at multiples of 4 bytes for CPU performance.)
Regular disks will store data in bigger blocks. To increase reading/writing speed, you'd prefer to make your data structures as compact as possible. But for processing performance, having them aligned on 4 bytes boundaries is more effective.
Which reminds me that I once had a discussion with someone about using compression on an NTFS disk. I managed to prove that compressing an NTFS partition could actually improve the performance of a computer since it had to read a lot less data blocks, even though it meant it had to do more processing to decompress the same data blocks.
To improve performance, you just have to find the weakest (slowest) link and start there. Once it's optimized, there will be another weak link... | Fastest .Net and SQL data types | [
"",
".net",
"sql",
"types",
"robotics",
""
] |
While playing with implementing a virtual assignment operator I have ended with a funny behavior. It is not a compiler glitch, since g++ 4.1, 4.3 and VS 2005 share the same behavior.
Basically, the virtual operator= behaves differently than any other virtual function with respect to the code that is actually being executed.
```
struct Base {
virtual Base& f( Base const & ) {
std::cout << "Base::f(Base const &)" << std::endl;
return *this;
}
virtual Base& operator=( Base const & ) {
std::cout << "Base::operator=(Base const &)" << std::endl;
return *this;
}
};
struct Derived : public Base {
virtual Base& f( Base const & ) {
std::cout << "Derived::f(Base const &)" << std::endl;
return *this;
}
virtual Base& operator=( Base const & ) {
std::cout << "Derived::operator=( Base const & )" << std::endl;
return *this;
}
};
int main() {
Derived a, b;
a.f( b ); // [0] outputs: Derived::f(Base const &) (expected result)
a = b; // [1] outputs: Base::operator=(Base const &)
Base & ba = a;
Base & bb = b;
ba = bb; // [2] outputs: Derived::operator=(Base const &)
Derived & da = a;
Derived & db = b;
da = db; // [3] outputs: Base::operator=(Base const &)
ba = da; // [4] outputs: Derived::operator=(Base const &)
da = ba; // [5] outputs: Derived::operator=(Base const &)
}
```
The effect is that the virtual operator= has a different behavior than any other virtual function with the same signature ([0] compared to [1]), by calling the Base version of the operator when called through real Derived objects ([1]) or Derived references ([3]) while it does perform as a regular virtual function when called through Base references ([2]), or when either the lvalue or rvalue are Base references and the other a Derived reference ([4],[5]).
Is there any sensible explanation to this odd behavior? | Here's how it goes:
If I change [1] to
```
a = *((Base*)&b);
```
then things work the way you expect. There's an automatically generated assignment operator in `Derived` that looks like this:
```
Derived& operator=(Derived const & that) {
Base::operator=(that);
// rewrite all Derived members by using their assignment operator, for example
foo = that.foo;
bar = that.bar;
return *this;
}
```
In your example compilers have enough info to guess that `a` and `b` are of type `Derived` and so they choose to use the automatically generated operator above that calls yours. That's how you got [1]. My pointer casting forces compilers to do it your way, because I tell compiler to "forget" that `b` is of type `Derived` and so it uses `Base`.
Other results can be explained the same way. | There are three operator= in this case:
```
Base::operator=(Base const&) // virtual
Derived::operator=(Base const&) // virtual
Derived::operator=(Derived const&) // Compiler generated, calls Base::operator=(Base const&) directly
```
This explains why it looks like Base::operator=(Base const&) is called "virtually" in case [1]. It's called from the compiler-generated version. The same applies to case [3]. In case 2, the right-hand side argument 'bb' has type Base&, so Derived::operator=(Derived&) cannot be called. | Why does virtual assignment behave differently than other virtual functions of the same signature? | [
"",
"c++",
"inheritance",
"virtual-functions",
"assignment-operator",
""
] |
Can anyone tell me what I am doing wrong? my comparePasswords() is not working...
```
<script>
function comparePasswords()
{
if (post-form.password.value != post-form.password2.value)
{
$('passwordShow').innerHTML = '';
}
else
{
$('passwordShow').innerHTML = 'Passwords do not match';
}
}
</script>
<form id="post-form" action="signup.php" method="post" >
<input type="password" id="password" name="password" onkeyup="testPassword(this.value);" maxlength="50" size="25" tabindex="102" value="">
<input type="password" id="password2" name="password2" onkeyup="comparePasswords();" maxlength="50" size="25" tabindex="104" value="">
</form>
``` | you need to use
```
document.getElementById('password').value
```
and
```
document.getElementById('password2').value
```
Also, your logic is wrong. The first conditional block will fire if the passwords do not match.
**EDIT**
seems you are using jQuery, so simply use
```
$('#password').val()
```
to get the field's value.
You should also set the innerHTML using jQuery (may as well) with the `html()` method | The problem is with how you're accessing the form object.
```
post-form.password
```
To the javascript engine, this is the same as this:
```
post - (form.password)
```
Also, you'd have to give your form a `name` attribute (not just an id) to access it that way. If you wanted to access it by name, you'd use something like this:
```
document['post-form'].password
```
Or by id:
```
document.getElementById("post-form");
``` | Comparing two fields in a form in Javascript - Not working | [
"",
"javascript",
"jquery",
"html",
""
] |
i'm not sure why i cant get diff values for my variables here, help!
```
int main()
{
srand(time(NULL));
srand48(time(NULL));
Packet* firstPacket = new Packet();
firstPacket->packetSize = randSize();
firstPacket->dest = randDest();
firstPacket->arrivalTime = myExp(lamb);
Host[firstPacket->dest].Frame.push_back(firstPacket); // adding first packet
Host[firstPacket->dest].numOfPack++;
calcFrameSize(Host[firstPacket->dest]);
cout << Host[token].frameTVTime << " " << Host[token].frameSize
<< " " << token << " " << curTime << endl;
}
``` | Are your statements:
```
srand(time(NULL));
srand48(time(NULL));
```
calling your:
```
inline float time(int size) { return (10.0*(float)size/12500); }
```
rather than the system time?
That would explain why you are not getting random numbers.
As pointed out time() is a bad name for that function. | What is in randSize() and randDest()? Make sure that those functions don't call srand() inside. | c++ not randomizing | [
"",
"c++",
"random",
""
] |
I'm trying to make a modem call in one end, and in the other end the program answers the call. It doesn't seem to detect the carrier. Am I doing anything wrong? Am I missing something?
```
int main(int argc, char** argv)
{
ParseArgs(argc,argv);
SerialPort* port = SerialPort::New();
if(!port)
Error(ErrorNoMemory,"Can't create port");
int error = port->Open(PortNum, SendFlag);
if(error)
Error(error,"Can't open port");
error = port->Initialise(PortBaud);
if(error)
Error(error,"Can't initialise port");
if(ReceiveFlag)
{
port->Listen();
Receive(port); //after the call is stablished I send a file
}
else
{
port->Dial(PhoneNumber);
Send(port);
}
port->Close();
delete port;
return 0;
}
```
The part of opening the port:
```
int Open(unsigned port, bool SendFlag)
{
// make name for port...
char name[] = "\\\\.\\com???.???";
char* nameNumber = name+sizeof(name)-8;
char* nameEnd = nameNumber;
if(port>999){
return ErrorInvalidPort;
}
if(port>99)
{
*nameEnd++ = '0'+port/100;
port %= 100;
}
if(port>9)
{
*nameEnd++ = '0'+port/10;
port %= 10;
}
*nameEnd++ = '0'+port;
*nameEnd = 0;
// open port...
hSerial = CreateFile(name, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if(hSerial==INVALID_HANDLE_VALUE)
{
switch(GetLastError())
{
case ERROR_FILE_NOT_FOUND:
return ErrorInvalidPort;
case ERROR_ACCESS_DENIED:
return ErrorPortInUse;
default:
return Error();
}
}
SetupComm( hSerial, 1024, 1024 );
if (!SendFlag)
{
if (!SetCommMask(hSerial, EV_RING |EV_RLSD))
// Error setting communications mask
printf("error mascara");
}
else
{
if (!SetCommMask(hSerial, EV_RLSD))
{
// Error setting communications mask
printf("error mascara");
}
}
return 0;
}
```
The initialise part:
```
int Initialise(unsigned baud)
{
// flush port...
if(!FlushFileBuffers(hSerial))
return Error();
if(!PurgeComm(hSerial, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR))
return Error();
// configure port...
DCB dcb ;
if(!GetCommState(hSerial, &dcb))
return Error();
dcb.BaudRate = CBR_115200;
dcb.ByteSize = 8;
dcb.StopBits = ONESTOPBIT;
dcb.Parity = NOPARITY;
if(!SetCommState(hSerial, &dcb))
{
if(GetLastError()==ERROR_INVALID_PARAMETER)
return ErrorInvalidSettings;
return Error();
}
// set timeouts to zero so read/writes return immediately...
COMMTIMEOUTS timeouts = {0};
timeouts.ReadIntervalTimeout = MAXDWORD;
timeouts.ReadTotalTimeoutConstant = 0;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.WriteTotalTimeoutConstant = 0;
timeouts.WriteTotalTimeoutMultiplier= 0;
if(!SetCommTimeouts(hSerial, &timeouts))
return Error();
// flush port again...
if(!PurgeComm(hSerial, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR))
return Error();
return 0;
}
```
The dial part:
```
int Dial(char *telefono)
{
unsigned long int n = 0;
DWORD dwCommEvent;
DWORD bytes;
DWORD dwRead;
char cadena[15];
char chRead;
sprintf(cadena, "ATDT%s\r", telefono);
if (!WriteFile( hSerial, "ATH1\r", strlen("ATH1\r"), (&(n)), 0 ))
{
printf("error");
}
FlushFileBuffers( hSerial );
Sleep(1000);
if (!WriteFile( hSerial, cadena, strlen(cadena), (&(n)), 0))
{
printf("error");
}
FlushFileBuffers( hSerial );
Sleep(10000);
printf("Marcamos");
do
{
printf("Espero eventos");
if(WaitCommEvent(hSerial, &dwCommEvent, NULL))
{
if(dwCommEvent & EV_RLSD)
{
printf("rlsd");
break;
}
else
{
printf("otro");
}
}
printf("fin del bucle");
} while(true);
return 0;
}
```
The listening part:
```
int Listen()
{
DWORD dwCommEvent;
unsigned long int n = 0;
do
{
printf("ESpero eventos");
if(WaitCommEvent(hSerial, &dwCommEvent, NULL))
{
if(dwCommEvent & EV_RING)
{
printf("RING");
if (!WriteFile( hSerial, "ATA\r", strlen("ATA\r"), (&(n)), 0 ))
{
printf("error");
}
FlushFileBuffers( hSerial );
break;
}
else if (dwCommEvent & EV_RLSD )
{
break;
}
}
printf("fin del bucle");
} while(true);
return 0;
}
``` | You may want to try issuing an ATS0=1 on the receiving side and let the modem autoanswer (substitute the number of rings you want instead of 1 if you wish).
You may discover that smart modems don't always pass through the ring (EV\_RING) signal.
**EDIT:** Don't forget to 'ATS0=0' when you don't want the modem to auto-answer any more. | You might have an easier time of it using Microsoft's [Telephony API](http://msdn.microsoft.com/en-us/library/ms734273(VS.85).aspx) (TAPI) rather than trying to talk to the modem directly. | modem call in c++ | [
"",
"c++",
"windows",
"events",
"modem",
"dial-up",
""
] |
I would like a PHP script to read the contents from a CSV file in the following format
```
id, sku
1,104101
2,105213
```
there are a total of 1486 entries, I believe that it's better to use a for loop instead of while !EOF.
After that, I would like to perform SQL query on a database named m118, table catalog\_product\_entity.
The query would be like UPDATE sku=$csvSku WHERE id=$csvId
Being a novice at both PHP and MySQL, I do not know where to start coding. | fgetcsv can be used to parse CSV files. mysql\_query method could be used to perform MySQL queries.
The complete code is as follows:
```
<?php
$fin = fopen('catalog_product_entity.csv','r') or die('cant open file');
$link = mysql_connect('localhost', 'm118', 'pw');
If (!$link) {
die ('Could not connect: ' . mysql_error());
}
@mysql_select_db('m118') or die ('Unable to select database');
echo "Connection succeeded <br />\n";
while (($data=fgetcsv($fin,1000,","))!==FALSE) {
$query = "UPDATE catalog_product_entity SET sku='$data[1]' WHERE entity_id='$data[0]'";
mysql_query($query);
echo "Record updated <br />\n";
}
fclose($fin);
mysql_close();
?>
``` | You will need to do something like:
```
$filename = "file_name_on_server.csv"
$fp = fopen( $filename ,"r");
while ($line = fgets ($fp))
{
```
now use [Split](https://www.php.net/split) to get an array of the comma delimited values
```
$arr = split (",", $line);
```
Now you have an array for the comma delimited values on $line. You can do simple string formatting to stick those values into an SQL query.
```
$query = "INSERT INTO `TableBlah` (Field1, Field2) VALUES (" . $arr[0] . "," . $arr[1] . ")";
```
Use the [mysql api](http://au.php.net/manual/en/book.mysql.php) to send those queries to the database
```
}
fclose($fp);
``` | Writing a PHP file to read from CSV and execute SQL Query | [
"",
"php",
"mysql",
"csv",
""
] |
I am trying to create colored headers and footers when printing a JTable. Specifically, I am looking at getPrintable() in javax.swing.JTable, but MessageFormat does not give me the option to specify the color of the header or footer.
How can I do it?
*clarification*
I am interested in setting the header/footers while printing. For example, notepad appends the filename as a header to what you print.
*update*
Seems like there is no standard way of doing this, can someone give me some workarounds? The only answer posted so far has nothing to do with printing(as in send to a printer, not displaying to screen) header/footers.
Copied from my comment: I am interested in the printing header/footer. For example, when you are printing a document from notepad, it appends the filename as a header (or perhaps its the footer, I do not remember exactly) | One solution I can think of is to use your own printable:
```
public class CustomTablePrintable implements Printable {
Printable tablePrintable;
public void setTablePrintable(Printable printable) {
tablePrintable = printable;
}
public int print(Graphics graphics, PageFormat pageFormat,
int pageIndex) throws PrinterException {
if (pageIndex > 0) {
return NO_SUCH_PAGE;
}
tablePrintable.print(graphics, pageFormat, pageIndex);
Graphics2D g2d = (Graphics2D)graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
// Draw header/footer here
graphics.drawString(header, posx, posy);
return PAGE_EXISTS;
}
}
```
When you call getPrintable from your JTable, inject it to a new instance to the custom printable and then use this with the PrinterJob.
You can now draw the header and footer as you wish, but you also lose some stuff:
* You can't use MessageFormat to format the messages. I believe that you could easily add this functionality to your printable.
* Header and footer aren't automatically positioned. You could have rough estimates for these though.
**EDIT:** I've looked at the Java Sources and there is the private class TablePrintable that does all the job. You can peak at the source code to see how the header and footer are printed. Then you can move this functionality to your Printable class. | This code is mainly from www.java2s.com with changes to show how to change the color. It is not the prettiest solution but hopefully will help you.
```
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public class MainClass {
public static void main(String args[]) {
String rows[][] = { { "A", "a" }, { "B", "b" }, { "E", "e" } };
String headers[] = { "Upper", "Lower" };
JFrame frame = new JFrame("Label Header");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable table = new JTable(rows, headers);
JScrollPane scrollPane = new JScrollPane(table);
Border headerBorder = UIManager.getBorder("TableHeader.cellBorder");
JLabel headerLabel1 = new JLabel(headers[0], JLabel.CENTER);
headerLabel1.setBorder(headerBorder);
// Here is where the color is changed.
headerLabel1.setBackground(new Color(255, 0, 0));
headerLabel1.setForeground(new Color(0, 0, 255));
// End of color change.
JLabel headerLabel2 = new JLabel(headers[1], JLabel.CENTER);
headerLabel2.setBorder(headerBorder);
TableCellRenderer renderer = new JComponentTableCellRenderer();
TableColumnModel columnModel = table.getColumnModel();
TableColumn column0 = columnModel.getColumn(0);
TableColumn column1 = columnModel.getColumn(1);
column0.setHeaderRenderer(renderer);
column0.setHeaderValue(headerLabel1);
column1.setHeaderRenderer(renderer);
column1.setHeaderValue(headerLabel2);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
class JComponentTableCellRenderer implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
return (JComponent)value;
}
}
```
The most important bit is:
```
// Here is where the color is changed.
headerLabel1.setBackground(new Color(255, 0, 0));
headerLabel1.setForeground(new Color(0, 0, 255));
// End of color change.
```
HTH let me know how you got on with it :) | Printing headers and footers in color? | [
"",
"java",
"swing",
"printing",
"jtable",
"awt",
""
] |
`XDocument.Load` throws an exception when using an XML file with version 1.1 instead of 1.0:
```
Unhandled Exception: System.Xml.XmlException: Version number '1.1' is invalid. Line 1, position 16.
```
Any clean solutions to resolve the error (without regex) and load the document? | Initial reaction, just to confirm that I can reproduce this:
```
using System;
using System.Xml.Linq;
class Test
{
static void Main(string[] args)
{
string xml = "<?xml version=\"1.1\" ?><root><sub /></root>";
XDocument doc = XDocument.Parse(xml);
Console.WriteLine(doc);
}
}
```
Results in this exception:
```
Unhandled Exception: System.Xml.XmlException: Version number '1.1' is invalid. Line 1, position 16.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.ParseXmlDeclaration(Boolean isTextDecl)
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
at System.Xml.Linq.XDocument.Parse(String text, LoadOptions options)
at System.Xml.Linq.XDocument.Parse(String text)
at Test.Main(String[] args)
```
It's still failing as of .NET 4.6. | "Version 1.0" is hardcoded in various places in the standard .NET XML libraries. For example, your code seems to be falling foul of this line in System.Xml.XmlTextReaderImpl.ParseXmlDeclaration(bool):
```
if (!XmlConvert.StrEqual(this.ps.chars, this.ps.charPos, charPos - this.ps.charPos, "1.0"))
```
I had a similar issue with XDocument.Save refusing to retain 1.1. It was the same type of thing - a hardcoded "1.0" in a System.Xml method.
I couldn't find anyway round it that still used the standard libraries. | XDocument can't load xml with version 1.1 in C# LINQ? | [
"",
"c#",
"xml",
"linq",
"linq-to-xml",
""
] |
I have a full path as given below.
```
C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd
```
How can the DTDs "part" to be fetched from this whole part?
Desired output:
```
C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk.DTDs
```
Can I use `String`'s methods for this?
If yes, then how to fetch it? | Edit: Please read the OP’s question and all of her comments carefully before downvotiong this. The OP’s title question isn’t EXACTLY what she wanted. My answer gave her what she needed to solve her problem. Which is why she voted it the answer. Yes, Joel’s answer is correct if specifically answering the title question. But after reading her comments, you’ll see that not exactly what she was looking for. Thanks.
Use this ...
```
string strFullPath = @"C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd";
string strDirName;
int intLocation, intLength;
intLength = strFullPath.Length;
intLocation = strFullPath.IndexOf("DTDs");
strDirName = strFullPath.Substring(0, intLocation);
textBox2.Text = strDirName;
``` | Use `System.IO.Path.GetDirectoryName()` for the entire path, or `new DirectoryInfo(path).Parent.Name` for just the name of that one folder.
---
**There is no directory named "DTDs" in the path you posted.** IT looks like there's a *file* named `"DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd"`, but the periods (.) in that path are not valid directory separator characters. Did you mean `"DannyGoXuk\DTDs\xhtml-math-svg-flat.dtd"`?
If that's the case, *given that entire new path*, you want something like this to return a list of files in the `DTDs` folder:
```
string path = @"C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk\DTDs\xhtml-math-svg-flat.dtd";
string[] files = new DirectoryInfo(path).Parent.GetFiles();
```
---
> in properties window i choose Build Type as Embedded resource.
And now we finally get to it. When you choose "Embedded Resource", the item is bundled into your executable program file. *There is no direct path anymore*. Instead, set your Build Type to "Content" and set "Copy to Output Directory" to "Copy Always" or "Copy if Newer". | How to get a part from the full path in C#? | [
"",
"c#",
"string",
"directory",
""
] |
I don't get this:
<http://localhost/index.php/articles/edit/1/my-first-article>
This URL is mentioned as an example in the [Kohana framework documentation](http://docs.kohanaphp.com/general/urls). I poked around in the files of my installation, and there is no .htaccess besides my own one that has nothing to do with that.
So, how can it be that an index.php is called but then, as parameters, the stuff looks like added directories to the URL? That doesn't look "real".
Or is this just how native PHP/Apache/HTTP stuff actually works? As I understand it, / is always telling "hey, a directory!". Makes really zero sense to me... how's that possible? Or do they have somewhere an .htaccess that I just can't see / find? | In PHP you can get the data after the filename with the [`$_SERVER["PATH_INFO"]`](https://stackoverflow.com/questions/2261951/what-exactly-is-path-info-in-php) variable. This allows you to basically GET information without having to use GET variables, which means Google and co will think you're using static pages. This is basically an alternative to `mod_rewrite` which is often enabled while `mod_rewrite` is more often not enabled.
This may be obvious to you, but it wasn't immediately to me, this doesn't work correctly on index pages unless you use the filename. For instance, `http://example.com/test/my/get/params` will not work, while `http://example.com/test/index.php/my/get/params` will. | From the [Apache docs](http://httpd.apache.org/docs/2.0/mod/core.html):
> **AcceptPathInfo Directive**
>
> This directive controls whether
> requests that contain trailing
> pathname information that follows an
> actual filename (or non-existent file
> in an existing directory) will be
> accepted or rejected. The trailing
> pathname information can be made
> available to scripts in the PATH\_INFO
> environment variable.
>
> For example, assume the location
> /test/ points to a directory that
> contains only the single file
> here.html. Then requests for
> /test/here.html/more and
> /test/nothere.html/more both collect
> /more as PATH\_INFO.
So I assume this setting is enabled somewhere like in httpd.conf. Note that this, like mod\_rewrite, can be enabled/configured in a number of places - [see here](http://httpd.apache.org/docs/2.0/mod/directive-dict.html#Context). | How can a URL like http://localhost/index.php/articles/edit/1/my-first-article work without an .htaccess? | [
"",
"php",
".htaccess",
"kohana",
"pathinfo",
""
] |
I'm getting a datetime string in a format like "2009-05-28T16:15:00" (this is ISO 8601, I believe). One hackish option seems to be to parse the string using `time.strptime` and passing the first six elements of the tuple into the datetime constructor, like:
```
datetime.datetime(*time.strptime("2007-03-04T21:08:12", "%Y-%m-%dT%H:%M:%S")[:6])
```
I haven't been able to find a "cleaner" way of doing this. Is there one? | I prefer using the [dateutil](https://pypi.org/project/python-dateutil/) library for timezone handling and generally solid date parsing. If you were to get an `ISO 8601` string like: `2010-05-08T23:41:54.000Z` you'd have a fun time parsing that with strptime, especially if you didn't know up front whether or not the timezone was included. `pyiso8601` has a couple of issues (check their tracker) that I ran into during my usage and it hasn't been updated in a few years. dateutil, by contrast, has been active and worked for me:
```
from dateutil import parser
yourdate = parser.parse(datestring)
``` | Since Python 3.7 and no external libraries, you can use the [`fromisoformat`](https://docs.python.org/3.7/library/datetime.html#datetime.datetime.fromisoformat) function from the [`datetime`](https://docs.python.org/3.7/library/datetime.html) module:
```
datetime.datetime.fromisoformat('2019-01-04T16:41:24+02:00')
```
Python 2 doesn't support the `%z` format specifier, so it's best to explicitly use Zulu time everywhere if possible:
```
datetime.datetime.strptime("2007-03-04T21:08:12Z", "%Y-%m-%dT%H:%M:%SZ")
``` | How do I translate an ISO 8601 datetime string into a Python datetime object? | [
"",
"python",
"datetime",
"iso8601",
"datetime-parsing",
""
] |
What is the most exact way of seeing how long something, for example a method call, took in code?
The easiest and quickest I would guess is this:
```
DateTime start = DateTime.Now;
{
// Do some work
}
TimeSpan timeItTook = DateTime.Now - start;
```
But how exact is this? Are there better ways? | A better way is to use the Stopwatch class:
```
using System.Diagnostics;
// ...
Stopwatch sw = new Stopwatch();
sw.Start();
// ...
sw.Stop();
Console.WriteLine("Elapsed={0}",sw.Elapsed);
``` | As others have said, `Stopwatch` is a good class to use here. You can wrap it in a helpful method:
```
public static TimeSpan Time(Action action)
{
Stopwatch stopwatch = Stopwatch.StartNew();
action();
stopwatch.Stop();
return stopwatch.Elapsed;
}
```
(Note the use of `Stopwatch.StartNew()`. I prefer this to creating a Stopwatch and then calling `Start()` in terms of simplicity.) Obviously this incurs the hit of invoking a delegate, but in the vast majority of cases that won't be relevant. You'd then write:
```
TimeSpan time = StopwatchUtil.Time(() =>
{
// Do some work
});
```
You could even make an `ITimer` interface for this, with implementations of `StopwatchTimer,` `CpuTimer` etc where available. | Exact time measurement for performance testing | [
"",
"c#",
".net",
"performance",
"testing",
""
] |
I've just started playing with the REST starter kit, and I've hit a road block trying to build my own service. I'm trying to create a service for account management, and I can't get the service to serialize my objects, throwing the following error:
> Unable to deserialize XML body with root name 'CreateAccount' and root namespace '' (for operation 'CreateAccount' and contract ('Service', '<http://tempuri.org/>')) using DataContractSerializer. Ensure that the type corresponding to the XML is added to the known types collection of the service.
Here's the actual code for the service (based off of the 'DoWork' method that came with the project):
```
[WebHelp(Comment = "Creates a Membership account")]
[WebInvoke(UriTemplate = "CreateAccount", RequestFormat = WebMessageFormat.Xml)]
[OperationContract]
public ServiceResponse CreateAccount(CreateAccount request)
{
try
{
// do stuff
return new ServiceResponse()
{
Status = "SUCCESS",
ErrorMessage = ""
};
}
catch (Exception ex)
{
return new ServiceResponse()
{
Status = "ERROR",
ErrorMessage = ex.Message + "\n\n" + ex.StackTrace
};
}
}
```
And last, but not least, here's the object that's causing all the trouble:
```
public class CreateAccount
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public bool SignUpForNewsletter { get; set; }
public string Password { get; set; }
}
```
Am I missing anything stupid?
Thanks in advance! | It appears the problem is a namespace clash between your method name "CreateAccount" and your input type "CreateAccount".
Also, you have to mark your CreateAccount type as a DataContract like so:
```
[DataContract]
public CreateAccount
{
[DataMember]
public string LastName { get; set; }
...
}
```
If you want to keep the same name, you can specify a namespace for the CreateAccount class.
I noticed you have a return type as well. Ensure the return type is marked with the DataContract attribute as well. Also, specify the return format like so:
```
ResponseFormat = WebMessageFormat.Xml
``` | It turns out I was missing an extra value in the `[DataContract]` attribute on the business object.
Should be `[DataContract(Namespace = "")]` | Can't deserialize XML in WCF REST service | [
"",
"c#",
"xml",
"wcf",
"rest",
"xml-serialization",
""
] |
We have a really old legacy code base that uses globals like they're going out of fashion - nearly all of the inter-page communication is done via globals and sessions or both. This *could* be changed as a last resort but ideally I don't want to touch any of it as everything I touch could introduce more bugs :-p.
Anyway, We're incorporating a new "module" into the application which was written completely in zend and is really nice and modular. My aim is to get zend running as the backbone and the old legacy code to run as a sort of module/controller within zend and once it has control just execute normally and do whatever it wants.
The 2 issues I have:
* I need to get Zend to see that I'm using legacy URL's (login.php, show.php, etc) and pass execution to a specific controller;
* I'm embedding an entire application inside a function of another and this breaks the default behavuour of variables appearing in the global scope as globals - i.e. they're now just local variables of this method and thus can't be seen without first specifying that they are globals.
If there's another way this could be done I'd be happy to hear it :-p
Cheers,
Chris | For the first issue I think you can use the Zend\_Router class.
But nevertheles I dont think is a good idea to port a procedural application to the ZF concept which is a object oriented one.
I would either rewrite the application or just use separate classes as loose components, thing that is recommended by ZF creators as well. | For legacy codebases my recommendation is to utilise your [APACHE rewrite rules](https://httpd.apache.org/docs/current/mod/mod_rewrite.html). Normally zend framework has rewrite along the lines of:
```
<Location />
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ /index.php [NC,L]
</Location>
```
Instead change "index.php" to something not currently used, like "ZendFramework.php". Put the normal content (Define APPLICATION\_ENV, APPLICATION\_PATH, bootstrap etc..) into this ZendFramework.php file.
Now your server will still serve up all existing legacy code as before, but you route non-existing paths (such as /module/controller/action) to Zend. Depending on your legacy codebase you may have some collisions in paths, you'll have to deal with that as you name your modules/controllers/actoions and custom routes. Over time you can move legacy code into ZendFramework modules.
```
RewriteRule ^.*$ /ZendFramework.php [NC,L]
``` | Mixing Zend and Old Procedural code | [
"",
"php",
"zend-framework",
"routes",
"global-variables",
""
] |
I know the '`-fPIC`' option has something to do with resolving addresses and independence between individual modules, but I'm not sure what it really means. Can you explain? | PIC stands for Position Independent Code.
To quote `man gcc`:
> If supported for the target machine, emit position-independent code, suitable for dynamic linking and avoiding any limit on the size of the global offset table. This option makes a difference on AArch64, m68k, PowerPC and SPARC.
Use this when building shared objects (\*.so) on those mentioned architectures. | The `f` is the gcc prefix for options that "control the interface conventions used
in code generation"
The `PIC` stands for "Position Independent Code", it is a specialization of the `fpic` for m68K and SPARC.
Edit: After reading page 11 of the [document referenced by 0x6adb015](http://people.redhat.com/drepper/dsohowto.pdf), and the comment by coryan, I made a few changes:
This option only makes sense for shared libraries and you're telling the OS you're using a Global Offset Table, GOT. This means all your address references are relative to the GOT, and the code can be shared accross multiple processes.
Otherwise, without this option, the loader would have to modify all the offsets itself.
Needless to say, we almost always use -fpic/PIC. | What does -fPIC mean when building a shared library? | [
"",
"c++",
"c",
"gcc",
"fpic",
""
] |
```
a=[]
a.append(3)
a.append(7)
for j in range(2,23480):
a[j]=a[j-2]+(j+2)*(j+3)/2
```
When I write this code, it gives an error like this:
```
Traceback (most recent call last):
File "C:/Python26/tcount2.py", line 6, in <module>
a[j]=a[j-2]+(j+2)*(j+3)/2
IndexError: list assignment index out of range
```
May I know why and how to debug it? | Change this line of code:
```
a[j]=a[j-2]+(j+2)*(j+3)/2
```
to this:
```
a.append(a[j-2] + (j+2)*(j+3)/2)
``` | You're adding new elements, elements that do not exist yet. Hence you need to use `append`: since the items do not exist yet, you cannot reference them by index. [Overview of operations on mutable sequence types](http://docs.python.org/3.0/library/stdtypes.html#mutable-sequence-types).
```
for j in range(2, 23480):
a.append(a[j - 2] + (j + 2) * (j + 3) / 2)
``` | Python error: IndexError: list assignment index out of range | [
"",
"python",
""
] |
I've tried to create a login widget that can be included at will in any action that is outside the content of the application that requires login. My thought here was that I wanted a DRY-approach for rendering the login box with any error messages from a previous login attempt. To enable this I utilized the [FlashMessenger](http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.flashmessenger) for saving the result of a failed login-attempt. The widget also uses the [Post/Redirect/Get-pattern](http://www.theserverside.com/patterns/thread.tss?thread_id=20936) to avoid the problem of posting data multiple times when using the browser back-button.
Now, the problem is that I would rather not use the [Zend\_View\_Helper\_Action](http://framework.zend.com/manual/en/zend.view.helpers.html#zend.view.helpers.initial.action) since that helper clones the request and creates another run of the dispatch-loop, which is pretty resource intensive. So, by looking at the code below, could you give me some advice on how to refactor the code such that:
1. **The widget can be included in an arbitrary view script**
2. **Results from a previous login attempt is rendered**
3. **The widget does not invoke a run in the dispatch-loop**
Currently, the login widget is rendered by calling, in the view scripts:
```
echo $this->action('auth', 'login-widget');
```
AuthController.php:
```
class AuthController extends Zend_Controller_Action {
// This method is invoked by Zend_View_Helper_Action to render the
// login widget
public function loginWidgetAction () {
$flashMessenger = $this->_helper->flashMessenger->setNamespace('login');
$this->view->messages = $flashMessenger->getMessages();
}
public function loginAction () {
if($this->getRequest()->isPost()) {
$result = Auth::doLogin($this->getRequest()->getPost());
if($result->isValid()) {
$this->_redirect('user');
}
else {
$flashMessenger = $this->_helper->flashMessenger->
setNamespace('login');
foreach($result->getMessages() as $message) {
$flashMessenger->addMessage($message);
}
}
}
// This will be changed to redirect either to the index page,
// or the page the request originated from if available.
$this->_redirect('');
}
[...]
}
```
/models/Auth.php:
```
/**
* Model for encapsulating the actions that deals with authentication,
* such as registering and activating users, as well as logging in and
* logging out.
* @todo: Refactor this to remove static methods
*/
class Auth {
/**
*
* @return Zend_Auth_Result
*/
public static function doLogin ($credentials) {
$authAdapter = new Auth_Adapter_DbTable(
Zend_Db_Table::getDefaultAdapter(),
'Users',
'username',
'pwdHash',
'SHA1(CONCAT(?, salt))'
);
$authAdapter->setIdentity($credentials['username']);
$authAdapter->setCredential($credentials['password']);
$auth = Zend_Auth::getInstance();
return $auth->authenticate($authAdapter);
}
[...]
}
```
/models/Auth/Adapter/DbTable.php:
```
class Auth_Adapter_DbTable extends Zend_Auth_Adapter_DbTable {
/**
* authenticate() - defined by Zend_Auth_Adapter_Interface. This method
* is called to attempt an authenication. Previous to this call, this
* adapter would have already been configured with all necessary
* information to successfully connect to a database table and attempt
* to find a record matching the provided identity.
*
* @throws Zend_Auth_Adapter_Exception if answering the authentication
* query is impossible
* @see library/Zend/Auth/Adapter/Zend_Auth_Adapter_DbTable#authenticate()
* @return MedU_Auth_Result
*/
public function authenticate() {
return parent::authenticate();
}
/**
* _authenticateValidateResult() - This method attempts to validate that
* the record in the result set is indeed a record that matched the
* identity provided to this adapter.
*
* Additionally it checks that the user account is activated.
*
* @param array $resultIdentity
* @return MedU_Auth_Result
*/
protected function _authenticateValidateResult($resultIdentity)
{
$result = parent::_authenticateValidateResult($resultIdentity);
if(!$result->isValid()) { return $result; }
$this->_checkAccountIsActivated($resultIdentity);
$this->_checkAccountIsSuspended($resultIdentity);
// Overwrite the username supplied by the user and instead
// use the name supplied upon registration, i.e if the
// user signs in as uSERNAME and registered as Username,
// the identity is Username
$this->_authenticateResultInfo['identity'] =
$resultIdentity[$this->_identityColumn];
return $this->_authenticateCreateAuthResult();
}
protected function _checkAccountIsActivated ($resultIdentity) {
if(!$resultIdentity['activated']) {
$this->_authenticateResultInfo['code'] =
MedU_Auth_Result::FAILURE_NOT_ACTIVATED;
$this->_authenticateResultInfo['messages'] =
array('The account has not yet been activated.
Please click on the link provided in the
activation email.');
}
}
protected function _checkAccountIsSuspended ($resultIdentity) {
if($resultIdentity['suspended']) {
$this->_authenticateResultInfo['code'] =
MedU_Auth_Result::FAILURE_SUSPENDED;
$this->_authenticateResultInfo['messages'] =
array('The account has been suspended.
If you feel this is a mistake,
please contact our support: support@meduniverse.com');
}
}
/**
* _authenticateCreateAuthResult() - This method creates a
* MedU_Auth_Result object from the information that has
* been collected during the authenticate() attempt.
*
* @return MedU_Auth_Result
*/
protected function _authenticateCreateAuthResult()
{
return new MedU_Auth_Result(
$this->_authenticateResultInfo['code'],
$this->_authenticateResultInfo['identity'],
$this->_authenticateResultInfo['messages']
);
}
}
```
/views/scripts/auth/partials/login-widget.phtml
```
// The fetchForm-view helper returns a Zend_Form object.
// The form definition (xml) is attached below in the
// code box below this one.
<div class="box">
<h3>Login</h3>
<?php if($this->messages) : ?>
<ul class="errors">
<?php foreach($this->messages as $message) : ?>
<li><?php echo $message ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<div>
<?php echo $this->fetchForm('user', 'login') ?>
</div>
</div>
```
/application/configs/forms.xml
```
// Configuration of the Login form. 'user' and 'login' are
// just keys for the view helper to return the correct form
<forms>
<user>
<login>
<action value="/auth/login" />
<method value="post" />
<elements>
<username>
<type value="text"></type>
<options>
<label value="Username" />
<required value="true" />
<validators>
<alnum validator="alnum" />
<strlen validator="StringLength">
<options min="6" max="45" />
</strlen>
</validators>
</options>
</username>
<password>
<type value="password" />
<options>
<label value="Password" />
<required value="true" />
<validators>
<strlen validator="StringLength">
<options min="6" max="20" />
</strlen>
</validators>
</options>
</password>
<submit>
<type value="submit" />
<options>
<label value="Log in" />
</options>
</submit>
</elements>
</login>
``` | As far as I understood your solution, your current call to the `Zend_View_Helper_Action` helper does nothing more than rendering the login form. Why don't you write your on view helper that retrieves the login-related messages from the flash-messenger and renders the login form?
**EDIT:**
1. You can retrieve the flash-messenger from its static broker:
```
$flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
$flashMessenger->setNamespace('login');
$messages = $flashMessenger->getMessages();
```
2. You don't need to instatiate a new flash-messenger in your view helper, you just can retrieve the current instance of it (see 1.). From a design point of view I'd say that it's absolutely feasible to retrieve application components within your view helpers (the `Zend_View_Helper_Url` for example retrieves the router from the static front-controller). To reduce coupling and to implement a setter-dependency-injection-pattern I'd suggest the following (`Zend_View_Helper_Translate` uses a similar pattern to retrieve the translator):
```
class My_View_Helper_Login extends Zend_View_Helper_Abstract
{
// [...]
/**
* @var Zend_Controller_Action_Helper_FlashMessenger
*/
protected $_flash;
/**
* @param Zend_Controller_Action_Helper_FlashMessenger $flash
* @return My_View_Helper_Login Provides a fluent interface
*/
public function setFlashMessenger(Zend_Controller_Action_Helper_FlashMessenger $flash)
{
$this->_flash = $flash;
return $this;
}
/**
* @return Zend_Controller_Action_Helper_FlashMessenger
*/
public function getFlashMessenger()
{
if ($this->_flash === null) {
$this->_flash = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
}
return $this->_flash;
}
/**
*
*/
public function login()
{
$flashMessenger = $this->getFlashMessenger();
$flashMessenger->setNamespace('login');
$messages = $flashMessenger->getMessages();
// [...]
}
}
```
3. Not when the flash-messenger provides the functionality you need. If you need to distinguish between error, informational and success messages for example a home-grown solution would perhaps be the better way. | Another addition is that you can use FlashMessenger to store *ANY* data. So you can do
```
$flash->addMessage(array('status'=>'error','message'=> 'oops'));
```
and then in foreach use
```
foreach($messages as $message){
echo '<div class="message '. $message['status'] .'">' . $message['message'] . '</div>'
}
``` | Refactoring a Zend_View_Helper_Action widget, utilizing Zend_Controller_Action_Helper_FlashMessenger, into a model | [
"",
"php",
"zend-framework",
"zend-form",
"zend-db-table",
""
] |
This is my first time working with regular expressions and I've been trying to get a regular expression working that would match the following:
* apple
* apple inc.
* apple co.
* apple corp.
but would not match:
* inc. apple
* co. apple
* apple co. inc.
* apple corp. inc.
* apple inc. corp.
* and so on...
This is what I got so far (apple)\s(inc|corp|co).$
Think you could help :)
EDIT: It needs to work in Java. Does java have it's own syntax for Regular Expressions? | You're almost there:
```
^apple(?:\s(?:inc|co|corp)\.)?$
```
Note that if you want your regexp to be case insensitive, you either have to pass the `CASE_INSENSITIVE` flag when constructing the pattern or add `(?i)` to the pattern. | Try something like this:
```
^apple\s?(inc|corp|co)?\.?$
```
Be careful with periods (.) as they are wildcards ( put a backslash in front of them).
? means not required
^ means beginning of the line
$ means end of the line
Look here for a more complete explanation: <http://www.anaesthetist.com/mnm/perl/Findex.htm> | co. corp. inc. regular expression | [
"",
"java",
"regex",
""
] |
I need to make sure none of the lines in my code exceeds a a certain length.
Normally I separate lines where there's a comma or another suitable break.
How can I separate this line into 2?
```
cout<<"Error:This is a really long error message that exceeds the maximum permitted length.\n";
```
If I just press enter somewhere in the middle it doesn't work. | Two options:
```
cout << "Error:This is a really long "
<< "error message that exceeds "
<< "the maximum permitted length.\n";
```
Or:
```
cout << "Error:This is a really long "
"error message that exceeds "
"the maximum permitted length.\n";
```
The second one is more efficient. | ```
cout<<"Error:This is a really long error "
"message that exceeds the maximum permitted length.\n";
```
or
```
cout<<"Error:This is a really long error \
message that exceeds the maximum permitted length.\n";
```
or
```
c\
o\
u\
t<<"Error:This is a really long error \
message that exceeds the maximum permitted length.\n";
``` | How to split long lines of code in c++? | [
"",
"c++",
"split",
""
] |
I have been coding my PHP applications in Notepad. I want to take it a step up and do it professional, and as far as I can tell using the Zend Framework is where to start. I have been reading the documentation and quick start and a few tutorials but I am still completely lost.
* Is Zend on your local machine or on the remote server?
* Is the "MVC" model different files? A file for the GUI, A File for the Functions used to get data and the database?
* Is there a tutorial that REALLY goes into detail about how you can accomplish things with Zend Framework, and how to get started?
The reason I am asking this is because the tutorials I have been reading still leave me confused and I am very anxious to start doing this professionally. I would like to utilize this new set of tools! Please help :) | We've all been there before!
Zend Framework is a pretty powerful MVC framework for PHP. There are scads of tutorials all over the net. The quickstart tutorial is good to get a general skeleton of an application, but I found [Akrabat's Zend Framework tutorial](http://akrabat.com/zend-framework-tutorial/) to be a better real world example.
ZF is fantastic when you're at the point where you need to develop robust applications and need a whole suite of libraries to accompany this - ZF's library is huge and all the components play quite nicely with each other (although, you can rip them out individually and add them to any project). The downside to ZF is that because it is so flexible, there can be quite a bit of complexity in setting it up.
To be honest, if starting to get your feet wet with MVC applications, you might try something a little bit more straight forward. I find [CodeIgniter](http://codeigniter.com/) to have a very short learning curve while maintaining the fundamentals of MVC design. [CakePHP](http://cakephp.org/) also walks you through the steps quite deliberately. | The quickstart tutorial is a great way to begin, maybe read it again? There's also this one:
<http://www.cyberciti.biz/tips/zend-framework-php-tutorial.html>
From the above link:
> This tutorial is intended to give a
> very basic introduction to using the
> Zend Framework to write a very basic
> database driven application.
And here's a list of ZF tutorials for beginners:
**Introduction and database
Tutorial:** <http://akrabat.com/zend-framework-tutorial/>
Source Files [here](http://akrabat.com/wp-content/uploads/zf-tutorial-174.zip)
**Authentication
Tutorial:**
<http://akrabat.com/zend-auth-tutorial/>
Source Files [here](http://akrabat.com/wp-content/uploads/zf-auth-tutorial-200.zip)
**Forms
Tutorial:** <http://akrabat.com/zend-framework/simple-zend_form-example/>
Source Files [here](http://akrabat.com/wp-content/uploads/Zend_Form_Example.zip)
**File Upload
Tutorial**: <http://akrabat.com/zend-framework/simple-zend_form-file-upload-example-revisited/>
Source Files [here](http://akrabat.com/wp-content/uploads/Zend_Form_FileUpload_Example.zip)
**Layout
Tutorial:** <http://akrabat.com/zend-framework/simple-zend_layout-example/>
Source Files [here](http://akrabat.com/wp-content/uploads/Zend_Layout_Example.zip)
I would make sure they're not for much earlier versions of the ZF before diving in. | Where do I start with Zend Framework? | [
"",
"php",
"zend-framework",
""
] |
How do I set up module imports so that each module can access the objects of all the others?
I have a medium size Python application with modules files in various subdirectories. I have created modules that append these subdirectories to `sys.path` and imports a group of modules, using `import thisModule as tm`. Module objects are referred to with that qualification. I then import that module into the others with `from moduleImports import *`. The code is sloppy right now and has several of these things, which are often duplicative.
First, the application is failing because some module references aren't assigned. This same code does run when unit tested.
Second, I'm worried that I'm causing a problem with recursive module imports. Importing moduleImports imports thisModule, which imports moduleImports . . . .
What is the right way to do this? | **"I have a medium size Python application with modules files in various subdirectories."**
Good. Make absolutely sure that each directory include a `__init__.py` file, so that it's a package.
**"I have created modules that append these subdirectories to `sys.path`"**
Bad. Use `PYTHONPATH` or install the whole structure `Lib/site-packages`. Don't update `sys.path` dynamically. It's a bad thing. Hard to manage and maintain.
**"imports a group of modules, using `import thisModule as tm`."**
Doesn't make sense. Perhaps you have one `import thisModule as tm` for each module in your structure. This is typical, standard practice: import just the modules you need, no others.
**"I then import that module into the others with `from moduleImports import *`"**
Bad. Don't blanket import a bunch of random stuff.
Each module should have a longish list of the specific things it needs.
```
import this
import that
import package.module
```
Explicit list. No magic. No dynamic change to `sys.path`.
My current project has 100's of modules, a dozen or so packages. Each module imports just what it needs. No magic. | Few pointers
1. You may have already split
functionality in various module. If
correctly done most of the time you
will not fall into circular import
problems (e.g. if module a depends
on b and b on a you can make a third
module c to remove such circular
dependency). As last resort, in a
import b but in b import a at the
point where a is needed e.g. inside
function.
2. Once functionality is properly in
modules group them in packages under
a subdir and add a `__init__.py` file
to it so that you can import the
package. Keep such pakages in a
folder e.g. lib and then either add
to sys.path or set PYTHONPATH env
variable
3. from module import \* may not
be good idea. Instead, import whatever
is needed. It may be fully qualified. It
doesn't hurt to be verbose. e.g.
from pakageA.moduleB import
CoolClass. | Properly importing modules in Python | [
"",
"python",
"python-import",
""
] |
I need that some html in the area in the asp.net page that i am coding, is changed according to a string variable.
I was thinking about creating a label, and then change the text on it.
But the string variable contains something like:
```
<h2><p>Notify:</p> alert</h2>
```
So, I don't feel that give this to a label text is a good idea
How i can do?
Using response.write?
If I use response.write, my added code will be at the beginning of the html source, how i can tell him to add it in a specific ?
Thank you | why don't you give **LiteralControl** a try?
```
myLitCtrl.Text="<h2><p>Notify:</p> Alert</h2>";
``` | If you really don't want to use any server controls, you should put the `Response.Write` in the place you want the string to be written:
```
<body>
<% Response.Write(stringVariable); %>
</body>
```
A shorthand for this syntax is:
```
<body>
<%= stringVariable %>
</body>
``` | ASP.NET - How to write some html in the page? With Response.Write? | [
"",
"c#",
"asp.net",
""
] |
I'm using a `HashSet<T>` to store a collection of objects. These objects already have a unique ID of `System.Guid`, so I'd rather the `HashSet<>` just use that existing ID rather then trying to figure out itself how to hash the object. How do I override the build in hashing and force my program to use the build in ID value as the hash value?
Also say I know the `Guid` of an object in my `HashSet<>`, is there a way to get an object from a `HashSet<T>` based on this `Guid` alone? Or should I use a dictionary instead. | A `HashSet<>` is not based a key/value pair, and provides no "by key" access - it is just a set of unique values, using the hash to check containment very quickly.
To use a key/value pair (to fetch out by `Guid` later) the simplest option would be a `Dictionary<Guid,SomeType>`. The existing hash-code on `Guid` should be fine (although **if you needed** (you don't here) you can provide an `IEqualityComparer<T>` to use for hashing. | Override the [`GetHashCode()`](http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx) method for your object.
Of course, there's a slight wrinkle here... GUIDs are larger than int32s, which .NET uses for hashcodes. | How do I control how an object is hashed by a hashset | [
"",
"c#",
"hash",
"hashset",
""
] |
In C# and Vb.net,is any way without iterating by loop a bitarray to check contins any true or false value (Dotnet 2.0) ? | I doubt there's any way you could do it without a loop under the hood (as a `BitArray` can be arbitrarily long, unlike `BitVector32`), but if you just don't want to write it yourself:
```
var hasAnyTrue = input.Cast<bool>().Contains(true);
var hasAnyFalse = input.Cast<bool>().Contains(false);
``` | If you are using the BitArray class from System.Collections you can use the following code to determine if anything is true.
C# version
```
var anyTrue = myArray.Cast<bool>().Any(x => x);
```
VB.Net Version
```
Dim anyTrue = myArray.Cast(Of Boolean)().Any(Function(x) x)
``` | How check bitArray contains any true or any false value? | [
"",
"c#",
"vb.net",
""
] |
Suppose a HTML element's `id` is known, so the element can be refereced using:
```
document.getElementById(element_id);
```
Does a native Javascript function exist that can be used to append a CSS class to that element? | ```
var element = document.getElementById(element_id);
element.className += " " + newClassName;
```
Voilà. This will work on pretty much every browser ever. The leading space is important, because the `className` property treats the css classes like a single string, which ought to match the `class` attribute on HTML elements (where multiple classes must be separated by spaces).
Incidentally, you're going to be better off using a Javascript library like [prototype](http://www.prototypejs.org/) or [jQuery](http://jquery.com/), which have methods to do this, as well as functions that can first check if an element already has a class assigned.
In prototype, for instance:
```
// Prototype automatically checks that the element doesn't already have the class
$(element_id).addClassName(newClassName);
```
See how much nicer that is?! | Adding class using element's [classList](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) property:
```
element.classList.add('my-class-name');
```
Removing:
```
element.classList.remove('my-class-name');
``` | how to append a css class to an element by javascript? | [
"",
"javascript",
"css",
""
] |
> **Duplicate of**
> [Dynamic SQL Comma Delimited Value Query](https://stackoverflow.com/questions/517028/dynamic-sql-comma-delimited-value-query)
> [Parameterized Queries with Like and In](https://stackoverflow.com/questions/303149/parameterized-queries-with-like-and-in-conditions)
I have a SQL Server Stored Procedure where I would like to pass a `varchar` full of comma delimited values to an `IN` function. For example:
```
DECLARE @Ids varchar(50);
SET @Ids = '1,2,3,5,4,6,7,98,234';
SELECT *
FROM sometable
WHERE tableid IN (@Ids);
```
This does not work of course. I get the error:
> Conversion failed when converting the varchar value '1,2,3,5,4,6,7,98,234' to data type int.
How can I accomplish this (or something relatively similar) without resorting to building dynamic SQL? | **Don't use a function that loops to split a string!**, my function below will split a string very fast, with no looping!
Before you use my function, you need to set up a "helper" table, you only need to do this one time per database:
```
CREATE TABLE Numbers
(Number int NOT NULL,
CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
DECLARE @x int
SET @x=0
WHILE @x<8000
BEGIN
SET @x=@x+1
INSERT INTO Numbers VALUES (@x)
END
```
use this function to split your string, which does not loop and is very fast:
```
CREATE FUNCTION [dbo].[FN_ListToTable]
(
@SplitOn char(1) --REQUIRED, the character to split the @List string on
,@List varchar(8000) --REQUIRED, the list to split apart
)
RETURNS
@ParsedList table
(
ListValue varchar(500)
)
AS
BEGIN
/**
Takes the given @List string and splits it apart based on the given @SplitOn character.
A table is returned, one row per split item, with a column name "ListValue".
This function workes for fixed or variable lenght items.
Empty and null items will not be included in the results set.
Returns a table, one row per item in the list, with a column name "ListValue"
EXAMPLE:
----------
SELECT * FROM dbo.FN_ListToTable(',','1,12,123,1234,54321,6,A,*,|||,,,,B')
returns:
ListValue
-----------
1
12
123
1234
54321
6
A
*
|||
B
(10 row(s) affected)
**/
----------------
--SINGLE QUERY-- --this will not return empty rows
----------------
INSERT INTO @ParsedList
(ListValue)
SELECT
ListValue
FROM (SELECT
LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(@SplitOn, List2, number+1)-number - 1))) AS ListValue
FROM (
SELECT @SplitOn + @List + @SplitOn AS List2
) AS dt
INNER JOIN Numbers n ON n.Number < LEN(dt.List2)
WHERE SUBSTRING(List2, number, 1) = @SplitOn
) dt2
WHERE ListValue IS NOT NULL AND ListValue!=''
RETURN
END --Function FN_ListToTable
```
you can use this function as a table in a join:
```
SELECT
Col1, COl2, Col3...
FROM YourTable
INNER JOIN FN_ListToTable(',',@YourString) s ON YourTable.ID = s.ListValue
```
Here is your example:
```
Select * from sometable where tableid in(SELECT ListValue FROM dbo.FN_ListToTable(',',@Ids) s)
``` | Of course if you're lazy like me, you could just do this:
```
Declare @Ids varchar(50) Set @Ids = ',1,2,3,5,4,6,7,98,234,'
Select * from sometable
where Charindex(','+cast(tableid as varchar(8000))+',', @Ids) > 0
``` | Passing a varchar full of comma delimited values to a SQL Server IN function | [
"",
"sql",
"sql-server",
"t-sql",
"sql-in",
""
] |
I have a dynamic client to a service. How can i change the ReaderQuotas property of it's endpoint binding?
I tried like this but it doesn't work ...
```
DynamicProxyFactory factory = new DynamicProxyFactory(m_serviceWsdlUri);
foreach (ServiceEndpoint endpoint in factory.Endpoints)
{
Binding binding = endpoint.Binding;
binding.GetProperty<XmlDictionaryReaderQuotas>(new BindingParameterCollection()).MaxArrayLength = 2147483647
binding.GetProperty<XmlDictionaryReaderQuotas>(new BindingParameterCollection()).MaxBytesPerRead =2147483647;
binding.GetProperty<XmlDictionaryReaderQuotas>(new BindingParameterCollection()).MaxDepth = 2147483647;
binding.GetProperty<XmlDictionaryReaderQuotas>(new BindingParameterCollection()).MaxNameTableCharCount = 2147483647;
binding.GetProperty<XmlDictionaryReaderQuotas>(new BindingParameterCollection()).MaxStringContentLength = 2147483647;
}
```
Even after doing this the ReaderQuotas values remain the default ones.
I also tried like this and still doesn't work:
```
DynamicProxyFactory factory = new DynamicProxyFactory(m_serviceWsdlUri);
foreach (ServiceEndpoint endpoint in factory.Endpoints)
{
System.ServiceModel.Channels.BindingElementCollection bec = endpoint.Binding.CreateBindingElements();
System.ServiceModel.Channels.TransportBindingElement tbe = bec.Find<System.ServiceModel.Channels.TransportBindingElement>();
tbe.MaxReceivedMessageSize = 2147483647;
tbe.MaxBufferPoolSize = 2147483647;
TextMessageEncodingBindingElement textBE = bec.Find<TextMessageEncodingBindingElement>();
if (textBE != null)
{
textBE.ReaderQuotas.MaxStringContentLength = 2147483647;
textBE.ReaderQuotas.MaxArrayLength = 2147483647;
textBE.ReaderQuotas.MaxBytesPerRead = 2147483647;
textBE.ReaderQuotas.MaxDepth = 2147483647;
textBE.ReaderQuotas.MaxNameTableCharCount = 2147483647;
}
}
```
I need this so I can send more than 8kb to the service. | Setting quotas on a BindingElement after the binding is created has no effect on that binding.
Edit (since you don't know what binding is used):
You can use reflection to set the property. Note you should make sure the Binding actually has the property before setting it. Not all bindings have this property. If you try to set it on a binding that doesn't support it, the example will throw an exception.
```
Binding binding = endpoint.Binding;
XmlDictionaryReaderQuotas myReaderQuotas = new XmlDictionaryReaderQuotas();
myReaderQuotas.MaxStringContentLength = _sanebutusablelimit_;
myReaderQuotas.MaxArrayLength = _sanebutusablelimit_;
myReaderQuotas.MaxBytesPerRead = _sanebutusablelimit_;
myReaderQuotas.MaxDepth = _sanebutusablelimit_;
myReaderQuotas.MaxNameTableCharCount = _sanebutusablelimit_;
binding.GetType().GetProperty("ReaderQuotas").SetValue(binding, myReaderQuotas, null);
```
Hope this helps you a bit. | Why are you solving that in a such complex way, just alter the ReaderQuotas directly:
ie:
WSHttpBinding WebBinding = new WSHttpBinding();
**WebBinding.ReaderQuotas.MaxArrayLength = int.MaxValue;
WebBinding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
WebBinding.ReaderQuotas.MaxBytesPerRead = int.MaxValue;**
This will work without that weird reflection sample.
Cheers | Modify endpoint ReaderQuotas programmatically | [
"",
"c#",
"wcf",
"readerquotas",
""
] |
In windows when you click on an icon on your desktop, the icon darkens with a shade that is based on your windows theme that is currently used.
I have a custom control that displays an image. I would like to have the same functionality as the windows icon click. How do I obtain the same result in WinForms by selecting my custom control? | Right now I'm using the following code... if anyone has something better, I'll be glad to change it!
```
private void drawAndShadeTheImage(Graphics g)
{
//if the image is null then there is nothing to do.
if (Image != null)
{
Bitmap bitMap = new Bitmap(Image);
//if this control is selected, shade the image to allow the user to
//visual identify what is selected.
if (ContainsFocus)
{
//The delta is the percentage of change in color shading of
//the image.
int delta = 70;
//zero is the lowest value (0 - 255) that can be represented by
//a color component.
int zero = 0;
//Get each pixel in the image and shade it.
for (int y = 0; y < bitMap.Height; y++)
{
for (int x = 0; x < bitMap.Width; x++)
{
Color oColor = bitMap.GetPixel(x, y);
//Lime is the background color on the image and should
//always be transparent, if this check is removed the
//background will be displayed.
if (oColor.ToArgb() != Color.Lime.ToArgb())
{
int oR = oColor.R - delta < zero ? zero :
oColor.R - delta;
int oG = oColor.G - delta < zero ? zero :
oColor.G - delta;
int oB = oColor.B - delta < zero ? zero :
oColor.B - delta;
int oA = oColor.A - delta < zero ? zero :
oColor.A - delta;
Color nColor = Color.FromArgb(oA, oR, oG, oB);
bitMap.SetPixel(x, y, nColor);
}
}
}
}
//Make the background of the image transparent.
bitMap.MakeTransparent();
g.DrawImage(bitMap, this.ClientRectangle);
}
}
``` | Windows implements alpha-blending for selected icons since Windows XP. If you want to achieve similar look you must draw your image with alpha blending:
```
public static void DrawBlendImage(Graphics canvas, Image source, Color blendColor, float blendLevel, int x, int y)
{
Rectangle SourceBounds = new Rectangle(x, y, source.Width, source.Height);
ColorMatrix MaskMatrix = new ColorMatrix();
MaskMatrix.Matrix00 = 0f;
MaskMatrix.Matrix11 = 0f;
MaskMatrix.Matrix22 = 0f;
MaskMatrix.Matrix40 = (float)blendColor.R / byte.MaxValue;
MaskMatrix.Matrix41 = (float)blendColor.G / byte.MaxValue;
MaskMatrix.Matrix42 = (float)blendColor.B / byte.MaxValue;
ImageAttributes MaskAttributes = new ImageAttributes();
MaskAttributes.SetColorMatrix(MaskMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
ColorMatrix TransparentMatrix = new ColorMatrix();
TransparentMatrix.Matrix33 = blendLevel;
ImageAttributes TransparentAttributes = new ImageAttributes();
TransparentAttributes.SetColorMatrix(TransparentMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
canvas.DrawImage(source, SourceBounds, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, MaskAttributes);
canvas.DrawImage(source, SourceBounds, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, TransparentAttributes);
}
```
In your case you can use **SystemColors.Highlight** as blendColor. | Clicking a control and causing it to shade | [
"",
"c#",
".net",
"winforms",
"windows-themes",
""
] |
In C# I need to be able to define a method but have it return one or two return types. The compiler gives me an error when I try to do it, but why isn't it smart enough to know which method I need to call?
```
int x = FunctionReturnsIntOrString();
```
Why would the compiler prevent me from having two functions with different return types? | While it may be obvious in this particular scenario, there are many scenarios where this is in fact not obvious. Lets take the following API for an example
```
class Bar {
public static int Foo();
public static string Foo();
}
```
It's simply not possible for the compiler to know which Foo to call in the following scenarios
```
void Ambiguous() {
Bar.Foo();
object o = Bar.Foo();
Dog d = (Dog)(Bar.Foo());
var x = Bar.Foo();
Console.WriteLine(Bar.Foo());
}
```
These are just a few quick samples. More contrived and evil problems surely exist. | From the last paragraph of section 1.6.6 of the [C# 3.0 language specification](http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx):
> The signature of a method must be unique in the class in which the method is declared. The signature of a method consists of the name of the method, the number of type parameters and the number, modifiers, and types of its parameters. The signature of a method does not include the return type.
In IL two methods can differ by return type alone, but outside of reflection there is no means to call a method that differs only be return type. | Method overloading return values | [
"",
"c#",
"overloading",
""
] |
I have a BOOST\_FOREACH loop to iterate over a list. Unfortunately, I also need to cache an iterator to a particular item.
```
typedef List::iterator savedIterator;
BOOST_FOREACH(Item &item, list)
{
// stuff...
if (condition)
savedIterator = &item; // this won't work
// do more stuff...
}
```
Obviously I can do this using a list.begin()..list.end() for loop, but I've grown to like BOOST\_FOREACH. Is there a way round this? | This is not possible, as you do not have access to an iterator pointing to the current item inside the loop.
You could fetch an iterator from the list somehow using the current items data but I don't know if this is a good idea to follow, also performance-wise.
I'd suggest you use the solution you already proposed yourself with list.begin() .. list.end(), this is in my opinion the easiest to implement and recognize. | With Boost.Foreach, you're pretty much stuck with the reference to the dereferenced iterator since this is what Boost.Foreach was designed to do: simplify access to the elements in a range. However, if you're just looking for a single element that fits a criteria you might want to try `std::find_if()`:
```
struct criteria {
template <class T>
bool operator()(T const & element) const {
return (element /* apply criteria... */)? true : false;
}
};
// somewhere else
List::iterator savedIterator =
std::find_if(list.begin(), list.end(), criteria());
```
It also looks like you want to apply operations on the whole list -- in which case I'll suggest using something like `std::min_element()` or `std::max_element()` along with Boost.Iterators like `boost::transform_iterator`.
```
struct transformation {
typedef int result_type;
template <class T>
int operator()(T const & element) const {
// stuff
int result = 1;
if (condition) result = 0;
// more stuff
return result;
}
};
// somewhere else
List::iterator savedIterator =
std::min_element(
boost::make_transform_iterator(list.begin(), transformation()),
boost::make_transform_iterator(list.end(), transformation()),
).base();
``` | Access Iterator in BOOST_FOREACH loop | [
"",
"c++",
"boost",
"iterator",
"foreach",
""
] |
I have the following 3 tables as part of a simple "item tagging" schema:
==Items==
* ItemId int
* Brand varchar
* Name varchar
* Price money
* Condition varchar
* Description varchar
* Active bit
==Tags==
* TagId int
* Name varchar
* Active bit
==TagMap==
* TagMapId int
* TagId int (fk)
* ItemId int (fk)
* Active bit
I want to write a LINQ query to bring back Items that match a list of tags (e.g. TagId = 2,3,4,7). In my application context, examples of items would be "Computer Monitor", "Dress Shirt", "Guitar", etc. and examples of tags would be "electronics", "clothing", etc. I would normally accomplish this with a SQL IN Statement. | Something like
```
var TagIds = new int[] {12, 32, 42};
var q = from map in Context.TagMaps
where TagIds.Contains(map.TagId)
select map.Items;
```
should do what you need. This will generate an In ( 12, 32, 42 ) clause (or more specifically a parameterized IN clause if I'm not mistaken). | given array of items:
```
var list = new int[] {2,3,4}
```
use:
```
where list.Contains(tm.TagId)
``` | Linq version of SQL "IN" statement | [
"",
"sql",
"linq",
"linq-to-sql",
""
] |
Is there any way for me to avoid the additional cast when I cast a `List<T>` to my own collection, which is nothing but a derivate of `List<T>`?
---
### Example:
```
ScreenCollection screens = screenRepository.GetAll().ToList();
// fails because ScreenCollection != return of ToList() which is List<Screen>
// However,
public class ScreenCollection : List<Screen>
```
I know I could do the following, simple enough:
```
ScreenCollection screens = (ScreenCollection)screenRepository.GetAll().ToList();
```
I would like to avoid that additional casting, if possible. | This isn't possible and in fact, your cast is wrong too. Just because `ScreenCollection` derives from `List<Screen>` doesn't mean every `List<Screen>` instance also implements `ScreenCollection`.
.NET 4.0 and C#4 will provide contravariance and covariance on interface types, which would go some way to mitigating the situation you face, but it doesn't provide variance for lists.
One way to address your issue would be to have an extension method or constructor for `ScreenCollection` (depending on whether you own the code or not) that could create a new instance based on a given `IEnumerable<Screen>` or `IList<Screen>`. You could also consider refactoring your `ScreenCollection` type (if it is yours to refactor) so that it encapsulates a `List<Screen>` rather than inherits from it, and then just wrap the new `List<Screen>` instance from `ToList()`. | Subclassing `List<T>` is rarely useful - except to give it a name; `Collection<T>` at least gives you the option to override some things...
In your example, I'm assuming that `.ToList()` is the LINQ extension method - in which case, it really is returning a `List<T>`, not a `ScreenColleciton`. ~~You could add an implicit conversion operator, but I don't think that is a good idea~~ (turns out that not only is it not a good idea: it isn't possible ;-p credit: Aistina - comments).
If it *isn't* the LINQ extension method - then simply type it to return the right thing... | Is there a way to avoid the additional cast List<T> into MyOwnCollection : List<T> in C#? | [
"",
"c#",
""
] |
What characters are allowed and what is not allowed in a C# class name? Could you please help?
EDIT: To specify. What special characters are allowed? Please be specific, because links to 50 pages specs in high-technical language is not an answer that will help me a lot.
EXPLANATION: What I try to accomplish is to divide class name into distinguishable parts for example:
> class Person@WorkOffice@Helper@Class
>
> {
>
> }
And I think about a way of using some kind of character or something else to be able to get parts Person, WorkOffice, Helper and Class from this class name.
And yes, I know it's crazy, but I need it that way. I know that I can use attributes and reflection to store this data in class meta but this is not the case, so please don't suggest this solution. | The spec details are [here](https://ecma-international.org/wp-content/uploads/ECMA-334_7th_edition_december_2023.pdf) (§6.4.3, p.639). Essentially, any unicode character (including unicode escapes) in the [character classes](http://msdn.microsoft.com/en-us/library/20bw873z.aspx) [Lu](http://www.fileformat.info/info/unicode/category/Lu/list.htm), [Ll](http://www.fileformat.info/info/unicode/category/Ll/list.htm), [Lt](http://www.fileformat.info/info/unicode/category/Lt/list.htm), [Lm](http://www.fileformat.info/info/unicode/category/Lm/list.htm), [Lo](http://www.fileformat.info/info/unicode/category/Lo/list.htm), [Nl](http://www.fileformat.info/info/unicode/category/Nl/list.htm), [Mn](http://www.fileformat.info/info/unicode/category/Mn/list.htm), [Mc](http://www.fileformat.info/info/unicode/category/Mc/list.htm), [Nd](http://www.fileformat.info/info/unicode/category/Nd/list.htm), [Pc](http://www.fileformat.info/info/unicode/category/Pc/list.htm), and [Cf](http://www.fileformat.info/info/unicode/category/Cf/list.htm). The first character is an exception and it must be a letter (classes [Lu](http://www.fileformat.info/info/unicode/category/Lu/list.htm), [Ll](http://www.fileformat.info/info/unicode/category/Ll/list.htm), [Lt](http://www.fileformat.info/info/unicode/category/Lt/list.htm), [Lm](http://www.fileformat.info/info/unicode/category/Lm/list.htm), or [Lo](http://www.fileformat.info/info/unicode/category/Lo/list.htm)) or an underscore. Also, if the identifier is a keyword, you must stick an @ in front of it. The @ is optional otherwise. | Valid identifiers in C# are defined in the [C# Language Specification](https://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-334%201st%20edition%20December%202001.pdf), item 9.4.2. The rules are very simple:
* An identifier must start with a letter or an underscore
* After the first character, it may contain numbers, letters, connectors, etc
* If the identifier is a keyword, it must be prepended with “@”
*[source](http://blog.visualt4.com/2009/02/creating-valid-c-identifiers.html)* | What characters are allowed in C# class name? | [
"",
"c#",
"class",
"naming-conventions",
""
] |
Update: I posted a comment on [John Robbins](http://www.wintellect.com/CS/blogs/jrobbins/default.aspx) blog about the. He wrote a response here:
<http://www.wintellect.com/CS/blogs/jrobbins/archive/2009/06/19/do-pdb-files-affect-performance.aspx>
The project I am working on does not build symbols for its release binaries, and I would like to change this.
Some info:
* Mostly C++ code base, some C#.
* Compiled under VS2k5, will be moving to VS2k8 Team System.
* Time critical software.
* Must have optimizations enabled.
* Source code is provided to customer so full symbols are fine.
What are the best command line switches to generate what I need, and what, if any, performance hits am I going to take?
Also, are there any "Gotchas" to be aware of? | Update: I posted a comment on [John Robbins](http://www.wintellect.com/CS/blogs/jrobbins/default.aspx) blog about the. He wrote a response here:
<http://www.wintellect.com/CS/blogs/jrobbins/archive/2009/06/19/do-pdb-files-affect-performance.aspx>
I found the following link on microsofts website:
[Generating and Deploying Debug Symbols with Microsoft Visual C++ 6.0](http://msdn.microsoft.com/en-us/library/aa260783(VS.60).aspx)
This link pertains to Visual C++ 6, but I am assuming these instructions are the same for Visual C++ 8(2005) and 9(2008).
The information it gives is very similar to the link provided by TheBlack but more in-depth. | Generating debug symbols (ie PDB files) is just creating an external file that a debugger can reference when looking at your code in memory. It doesn't affect the code that the compiler or linker generate (sort of like generating a .MAP file).
Now if you're talking about defining \_DEBUG in a release build, that's a whole different question. | Generating Symbols in release binaries with Visual Studio | [
"",
"c++",
"visual-studio",
"debugging",
"symbols",
""
] |
I'm currently creating an application using ASP.NET MVC. I got some user input inside a textarea and I want to show this text with <br />s instead of newlines. In PHP there's a function called nl2br, that does exactly this. I searched the web for equivalents in ASP.NET/C#, but didn't find a solution that works for me.
The fist one is this (doesn't do anything for me, comments are just printed without new lines):
```
<%
string comment = Html.Encode(Model.Comment);
comment.Replace("\r\n", "<br />\r\n");
%>
<%= comment %>
```
The second one I found was this (Visual Studio tells me VbCrLf is not available in this context - I tried it in Views and Controllers):
```
<%
string comment = Html.Encode(Model.Comment);
comment.Replace(VbCrLf, "<br />");
%>
<%= comment %>
``` | Try (not tested myself):
```
comment = comment.Replace(System.Environment.NewLine, "<br />");
```
**UPDATED:**
Just tested the code - it works on my machine
**UPDATED:**
Another solution:
```
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringReader sr = new System.IO.StringReader(originalString);
string tmpS = null;
do {
tmpS = sr.ReadLine();
if (tmpS != null) {
sb.Append(tmpS);
sb.Append("<br />");
}
} while (tmpS != null);
var convertedString = sb.ToString();
``` | to view html tags like a `DisplayFor`
you need to use another method , in fact the mvc dosent allowed you to view tags in page
but you can used this to ignore this option
```
@Html.Raw(model => model.text)
```
good luck | Show new lines from text area in ASP.NET MVC | [
"",
"c#",
"asp.net-mvc",
"string",
"text",
""
] |
I have several tables where a field is for priority (1 to 5). Problem here is that different projects have been using 5 as highest and some 1 for highest and I going to harmonize this.
My easy option is to create a temp table and copy the data over and switch as this table:
1 -> 5
2 -> 4
3 -> 3
4 -> 2
5 -> 1
I'm not that good with SQL but it feels that there should be an easy way to switch those values right off with an statement but I do have concerns of when there are huge amount of data and if something goes wrong half way then the data will be in a mess.
Should I just go with my temp table solution or should do you have a nice way of doing this straight in SQL? (Oracle 10g is being used)
Many thanks! | simply update the second table like this, a temp table is not needed because you are just reversing the priority:
```
update table_2
set priority = 6-priority;
``` | You can use a CASE statement
```
case PRIORITY
when 5 then 1
when 4 then 2
when 3 then 3
when 2 then 4
when 1 then 5
else PRIORITY
end
```
Edit: texBlues' solution is much better, but I leave this here for cases where the maths isn't as neat. | SQL statement to switch values | [
"",
"sql",
"oracle10g",
""
] |
On the front page of a site I am building, several `<div>`s use the CSS `:hover` pseudo-class to add a border when the mouse is over them. One of the `<div>`s contains a `<form>` which, using jQuery, will keep the border if an input within it has focus. This works perfectly except that IE6 does not support `:hover` on any elements other than `<a>`s. So, for this browser only we are using jQuery to mimic CSS `:hover` using the `$(#element).hover()` method. The only problem is, now that jQuery handles both the form `focus()` *and* `hover()`, when an input has focus then the user moves the mouse in and out, the border goes away.
I was thinking we could use some kind of conditional to stop this behavior. For instance, if we tested on mouse out if any of the inputs had focus, we could stop the border from going away. AFAIK, there is no `:focus` selector in jQuery, so I'm not sure how to make this happen. Any ideas? | ## jQuery 1.6+
jQuery added a [`:focus`](http://api.jquery.com/focus-selector/) selector so we no longer need to add it ourselves. Just use `$("..").is(":focus")`
## jQuery 1.5 and below
**Edit:** As times change, we find better methods for testing focus, the new favorite is [this gist from Ben Alman](https://gist.github.com/450017):
```
jQuery.expr[':'].focus = function( elem ) {
return elem === document.activeElement && ( elem.type || elem.href );
};
```
Quoted from Mathias Bynens [here](https://stackoverflow.com/questions/967096/using-jquery-to-test-if-an-input-has-focus/5391608#5391608):
> Note that the `(elem.type || elem.href)` test was added to filter out false positives like body. This way, we make sure to filter out all elements except form controls and hyperlinks.
You're defining a new selector. See [Plugins/Authoring](http://docs.jquery.com/Plugins/Authoring). Then you can do:
```
if ($("...").is(":focus")) {
...
}
```
or:
```
$("input:focus").doStuff();
```
## Any jQuery
If you just want to figure out which element has focus, you can use
```
$(document.activeElement)
```
If you aren't sure if the version will be 1.6 or lower, you can add the `:focus` selector if it is missing:
```
(function ( $ ) {
var filters = $.expr[":"];
if ( !filters.focus ) {
filters.focus = function( elem ) {
return elem === document.activeElement && ( elem.type || elem.href );
};
}
})( jQuery );
``` | CSS:
```
.focus {
border-color:red;
}
```
JQuery:
```
$(document).ready(function() {
$('input').blur(function() {
$('input').removeClass("focus");
})
.focus(function() {
$(this).addClass("focus")
});
});
``` | Using jQuery to test if an input has focus | [
"",
"javascript",
"jquery",
"jquery-events",
"jquery-on",
""
] |
How would the following query look if I was using the extension method syntax?
```
var query = from c in checks
group c by string.Format("{0} - {1}", c.CustomerId, c.CustomerName)
into customerGroups
select new { Customer = customerGroups.Key, Payments = customerGroups }
``` | It would look like this:
```
var query = checks
.GroupBy(c => string.Format("{0} - {1}", c.CustomerId, c.CustomerName))
.Select (g => new { Customer = g.Key, Payments = g });
``` | First, the basic answer:
```
var query = checks.GroupBy<Customer, string>(delegate (Customer c) {
return string.Format("{0} - {1}", c.CustomerId, c.CustomerName);
}).Select(delegate (IGrouping<string, Customer> customerGroups) {
return new { Customer = customerGroups.Key, Payments = customerGroups };
});
```
Then, how do you figure out these things yourself?
First, download Reflector from [here](http://www.red-gate.com/products/reflector/), and install it.
Then build a sample program, like a smallish console program, containing the code you want to analyze. Here's the code I wrote:
```
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication11
{
public class Customer
{
public Int32 CustomerId;
public Int32 CustomerName;
}
class Program
{
static void Main(string[] args)
{
var checks = new List<Customer>();
var query = from c in checks
group c by String.Format("{0} - {1}", c.CustomerId, c.CustomerName)
into customerGroups
select new { Customer = customerGroups.Key, Payments = customerGroups };
}
}
}
```
Then you build that, and open reflector, and ask it to open the .exe file in question.
Then you navigate to the method in question, which in my case was `ConsoleApplication11.Program.Main`.
The trick here is to go to the options page of Reflector, and ask it to show C# 2.0 syntax, which will substitute Linq with the appropriate static method calls. Doing that gives me the following code:
```
private static void Main(string[] args)
{
List<Customer> checks = new List<Customer>();
var query = checks.GroupBy<Customer, string>(delegate (Customer c) {
return string.Format("{0} - {1}", c.CustomerId, c.CustomerName);
}).Select(delegate (IGrouping<string, Customer> customerGroups) {
return new { Customer = customerGroups.Key, Payments = customerGroups };
});
}
```
Now, of course this code can be written a bit prettier with lambdas and similar, like what [@mquander](https://stackoverflow.com/users/55943/mquander) [showed](https://stackoverflow.com/questions/967099/groupby-with-linq-method-syntax-not-query-syntax/967108#967108), but with Reflector, at least you should be able to understand the method calls being involved. | GroupBy with linq method syntax (not query syntax) | [
"",
"c#",
"linq",
"translation",
"linq-query-syntax",
""
] |
I have to maintain a J2ME application. There is a lot of `System.gc()` inside the application. Before calling System.gc() all the attributes are setted to null. Does setting attributes to null make sense? Does calling `System.gc()` make sense? Shouldn't the jvm call the garbage collector when is necessary? | The reason for all the nulling of attributes and System.gc() calls is definitely part of a fight against device fragmentation. It's easy enough to say that you should never null a value yourself, that you should let it just go out of scope, and actually this is the appropriate way for PC development. However, the mobile space is a completely different animal and it would be naive to say that you can handle memory management the same way on a limited mobile device as you do on a PC that has gigs and gigs of RAM at its disposal.
Even now, the high-end smart phones have around 32-64MB of heap available to a J2ME application. Many devices are still around 1-4MB and often to meet carrier specification you will need to target even smaller heap sizes. The Razr only has 800K of heap and is still required to be supported by most carriers, due to the fact that so many of their subscribers still use the device.
Memory fragmentation happens because even though a block of memory is no longer in use, that it has been nullified, it is not yet available until it is garbage collected. Most mobile VMs only GC when memory is needed. So when it finally does run the GC, the heap could possibly be fragmented into tiny blocks of memory. When a larger block of memory needs to be allocated it will be unable to allocate to the smaller block. If you have enough of these smaller blocks polluting the heap, not supplying a block big enough for a larger object, eventually you will get an OutOfMemory exception, even though it may appear that you have tons of memory available.
For instance, imagine you create a local Object variable that requires 50 bytes. Next you allocate a member variable that will persist throughout the life of the application that requires 200 bytes of heap to exist. If you do this process over and over again, you could possibly get in the situation where you have thousands of blocks of memory that are only 50 bytes in length. Because you need 200 bytes for the persistent object, you will eventually be screwed and get an OutOfMemory exception.
Now if you created the same String object, used it, then nulled it yourself and called System.gc() (also you might want to call Thread.yield() to give the GC a chance to run) you would then have those 50 bytes available to create the new persistent object, avoid fragmentation and avoid the eventual OutOfMemory exceptions.
This is a very basic example, but if you have a lot of large images like in a game application, you run into this situation very quickly in the mobile space.
One last note, with BlackBerry devices you should avoid calling the garbage collector yourself as it is much more sophisticated (it will defrag the heap for you). Being more sophisticated makes it much slower (we're talking several seconds per run) than the normal down and dirty GCs on most devices. | On a good modern VM it generally makes little sense call System.gc(). It generally never makes sense to set attributes to null unless that is the only way you're making them unreachable.
On less sophisticated VMs, that you *might* get on mobile devices, it could make sense to null a reference if it is no longer used part way through a method but is still in scope. (On modern desktop VMs like Hotspot, this is generally no longer necessary-- the VM has your code in front of it and can generally work out whether or not you're still going to use a local reference, irrespective of scope.)
Now, coming back to System.gc(), it is true that mobile VMs have historically been simpler than the fairly sophisticated "fully fledged" VMs that we're used to such as Hotspot. However:
* mobile VMs have come on a lot in recent years-- object throughput, like other aspects of performance, has definitely improved on many devices;
* in any case, **System.gc() has no consistent, well-defined behaviour**. On some devices, it may do precisely nothing; on others, as with desktop VMs, it may cause a type of garbage collection that actually hurts performance compared to the normal, "gradual" garbage collection that the VM automatically performs while the app is running.
So I would be very wary of using System.gc(). | Calling System.gc() in mobile | [
"",
"java",
"java-me",
"garbage-collection",
""
] |
It often happens that I need to iterate over a list of strings in my C++ code.
In languages like Perl, this is easy:
```
foreach my $x ("abc", "xyz", "123") {.... }
```
In the past, this is what I've done in C++
```
const char* strs[] = { "abc", "xyz", "123" };
for (int i=0; i<sizeof(strs)/sizeof(const char*); i++) {
const char *str = strs[i];
...
```
If I already have an STL container, I can use BOOST\_FOREACH
```
std::vector<std::string> strs;
BOOST_FOREACH(std::string str, strs) {
...
```
I've tried to create a macro to combine all these concepts but without success.
I'd like to be able to write code like this:
```
SPECIAL_STRING_FOREACH(const char* str, {"abc", "xyz", "123"}) {
...
}
```
Surely someone's cooked this up before. | Here is my attempt at it. Sadly it relies on variadic macros which is a C99/C++1x feature. But works in GCC.
```
#include <boost/foreach.hpp>
#include <boost/type_traits.hpp>
#include <iostream>
#define SEQ_FOR_EACH(D, ...) \
if(bool c = false) ; else \
for(boost::remove_reference<boost::function_traits<void(D)> \
::arg1_type>::type _t[] = __VA_ARGS__; \
!c; c = true) \
BOOST_FOREACH(D, _t)
int main() {
SEQ_FOR_EACH(std::string &v, { "hello", "doctor" }) {
std::cout << v << std::endl;
}
}
```
Note that you can also iterate with a reference variable, to avoid useless copying. Here is one using `boost.preprocessor` and the `(a)(b)...` syntax, compiling down to the same code after pre-processing stage.
```
#define SEQ_FOR_EACH(D, SEQ) \
if(bool c = false) ; else \
for(boost::remove_reference<boost::function_traits<void(D)> \
::arg1_type>::type _t[] = { BOOST_PP_SEQ_ENUM(SEQ) }; \
!c; c = true) \
BOOST_FOREACH(D, _t)
int main() {
SEQ_FOR_EACH(std::string &v, ("hello")("doctor")) {
std::cout << v << std::endl;
}
}
```
The trick is to assemble a function type that has as parameter the enumeration variable, and getting the type of that parameter. Then `boost::remove_reference` will remove any reference. First version used `boost::decay`. But it would also convert arrays into pointers, which i found is not what is wanted sometimes. The resulting type is then used as the array element type.
For use in templates where the enumerator variable has a dependent type, you will have to use another macro which puts `typename` before `boost::remove_reference` and `boost::function_traits`. Could name it `SEQ_FOR_EACH_D` (D == dependent). | Note that dealing with C array of string is easier if you mark the end of the array:
```
const char* strs[] = { "abc", "xyz", "123", NULL };
for (int i=0; strs[i] != NULL i++) {
...
}
``` | Is there an easy way to iterator over a static list of strings in C++ | [
"",
"c++",
"string",
"iterator",
""
] |
I wrote this code:
```
function get_feed(){
// Get RSS Feed(s)
include_once(ABSPATH . WPINC . '/rss.php');
$rss = fetch_rss('http://dorar.shamekh.ws/?feed=rss2');
$maxitems = 1;
$items = array_slice($rss->items, 0, $maxitems,false);
return $items;
}
```
As a part of a plugin for WordPress , it works fine on my local server , but when I upload it to my blog I get the message:
> Warning: array\_slice()
> [function.array-slice]: The first
> argument should be an array in
php version on my local host : `5.2.6`
php version on my site : `5.2.5` | It seems from the documentation that `$rss->items` should already be an array. I'd guess that the RSS fetch is failing. Try:
```
if (is_array($rss->items)) {
$items = array_slice($rss->items, 0, $maxitems,false);
} else { var_dump($rss->items); }
```
MagpieRSS combined with dorar.shamekh.ws' (use of/configuration of) Apache 1.3.41 is leading to a very bizarre behaviour:
A "normal" HTTP request:
```
GET /feed/ HTTP/1.0
Host: dorar.shamekh.ws
```
MagpieRSS's request:
```
GET /feed/ HTTP/1.0
User-Agent: MagpieRSS/0.72 (+http://magpierss.sf.net)
Host: dorar.shamekh.ws:80
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*
```
Note the different 'Host' headers. When the port number is appended, as in MagpieRSS, the site returns a 301:
```
HTTP/1.1 301 Moved Permanently
Date: Fri, 22 May 2009 02:45:03 GMT
Server: Apache/1.3.41 (Unix) PHP/5.2.5 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635 mod_ssl/2.8.31 OpenSSL/0.9.7a
X-Powered-By: PHP/5.2.5
X-Pingback: http://dorar.shamekh.ws/xmlrpc.php
Last-Modified: Wed, 20 May 2009 22:03:05 GMT
ETag: "e591693fdf2d27ee7dae19e256db2f46"
Location: http://dorar.shamekh.ws/feed/
Connection: close
Content-Type: text/html
``` | What about casting $rss->items as an array first:
```
function get_feed(){
// Get RSS Feed(s)
include_once(ABSPATH . WPINC . '/rss.php');
$rss = fetch_rss('http://dorar.shamekh.ws/?feed=rss2');
$maxitems = 1;
$rss->items = (array) $rss->items;
$items = array_slice($rss->items, 0, $maxitems,false);
return $items;
}
``` | array_slice() warning in php and WordPress | [
"",
"php",
"wordpress",
""
] |
I usually always find it sufficient to use the concrete classes for the interfaces listed in the title. Usually when I use other types (such as LinkedList or TreeSet), the reason is for functionality and not performance - for example, a LinkedList for a queue.
I do sometimes construct ArrayList with an initial capcacity more than the default of 10 and a HashMap with more than the default buckets of 16, but I usually (especially for business CRUD) never see myself thinking "hmmm...should I use a LinkedList instead ArrayList if I am just going to insert and iterate through the whole List?"
I am just wondering what everyone else here uses (and why) and what type of applications they develop. | Those are definitely my default, although often a LinkedList would in fact be the better choice for lists, as the vast majority of lists seem to just iterate in order, or get converted to an array via Arrays.asList anyway.
But in terms of keeping consistent maintainable code, it makes sense to standardize on those and use alternatives for a reason, that way when someone reads the code and sees an alternative, they immediately start thinking that the code is doing something special.
I always type the parameters and variables as Collection, Map and List unless I have a special reason to refer to the sub type, that way switching is one line of code when you need it.
I could see explicitly requiring an ArrayList sometimes if you need the random access, but in practice that really doesn't happen. | For some kind of lists (e.g. listeners) it makes sense to use a [CopyOnWriteArrayList](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/CopyOnWriteArrayList.html) instead of a normal [ArrayList](http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html). For almost everything else the basic implementations you mentioned are sufficient. | Java: ArrayList for List, HashMap for Map, and HashSet for Set? | [
"",
"java",
""
] |
When a javascript error occures in IE (or in other browsers) you get a popup saying that javascript error has occurred - usually this comes with a line number and some hint.
Sometimes it comes with line 0 and with no way of knowing what the problem is.
Javscript can come from HTML itself, from a js file or from JSP (and more).
Microsoft has a script debugger that helps a lot in finding where js errors are, however sometimes when a js error occurs the script debugger cannot find the code portion and thus its difficult of finding where is the root cause of the problem.
My question is whether anyone knows any way of making script debugger find the code any way (mostly happen with js code that is in JSP file), or at least include in the IE popup the method or js file where the error has occurred. (it only display the line number, and many times its line 0...).
Thanks,
Tal. | The error object which is created when an error is thrown by JavaScript is very unreliable when it comes to the source line, especially within IE. Browsers like Firefox and Safari are better at line numbers, but they are generally pointless due to minification of the files.
What is obviously of more use is getting the call stack, but due to the anonymous nature of JavaScript functions (well, that they can be anonymous) a call stack can often be hard to work out.
If you're doing a `try/ catch` you can do `arguments.callee` which will return you the method which called the current method which failed.
Here's a good example of doing a complete stack in JavaScript - <http://eriwen.com/javascript/js-stack-trace/> | There is a version of Firebug called [Firebug Lite](http://getfirebug.com/lite.html) that will work with Internet Explorer. It's performance is going to be based on how complex your pages are; however, for relatively lightweight pages, it should provide some insight.
I recommend this tool rather than simply using Firebug and Firefox **because not all errors that occur in Internet Explorer will occur in Firefox**, and so performing any debugging in that browser may not yield any results. | on a javascript error, how to identify method or js file with the problem? | [
"",
"javascript",
"debugging",
""
] |
I'm learning Python-this gives me an IO error-
```
f = open('money.txt')
while True:
currentmoney = float(f.readline())
print(currentmoney, end='')
if currentmoney >= 0:
howmuch = (float(input('How much did you put in or take out?:')))
now = currentmoney + howmuch
print(now)
str(now)
f.close()
f = open('money.txt', 'w')
f.write(str(now))
f.close()
```
Thanks! | The `while True` is going to loop forever unless you break it with `break`.
The I/O error is probably because when you have run through the loop once the last thing you do is `f.close()`, which closes the file. When execution continues with the loop in the line `currentmoney = float(f.readline())`: `f` will be a closed filehandle that you can't read from. | well theres a couple of things...
you `open(money.txt)` outside the while loop but you close it after the first iteration...
(technically you close, reopen & close again)
Put when the loop comes round the second time, `f` will be closed and f.readLine() will most likely fail | Python generates an IO error while interleaving open/close/readline/write on the same file | [
"",
"python",
"python-3.x",
""
] |
I'm doing an example from the book: The Complete Reference C# 3.0 by Herbert Schildt. It's about writing in Console.WriteLine with arguments. Here is the example:
I tried this but I was getting an error:
```
Project1.exe has encountered a problem and needs to be close. We are sorry for the inconvenience. Please tell Microsoft about this problem. Send Error Report or Don't Send. And if I click, I get another error in the command prompt. "Unhandled Exception: System.Format.Exception input string was not in a correct format.
at System.Text.StringBuilder.AppendFormatError()
at System.Text.StringBuilder.AppendFormat(IFormatProvider provider,String Format, Object[]args)
at System.IO.TextWriter.WriteLine(String format, Object arg0)
at System.IO.TextWriter.SyncTextWriter.WriteLine(String format, Object arg0)
At Example2.Main() in D:\myPath
```
I'm not sure if the book has some error or is it my code?
I would appreciate your help. Thanks
> One of the easiest ways to specify a
> format is to describe a template that
> WriteLine( ) will use. To do this,
> show an example of the format that you
> want, using #s to mark the digit
> positions. You can also specify the
> decimal point and commas. For example,
> here is a better way to display 10
> divided by 3:
> Console.WriteLine("Here is 10/3: {0:#.##}", 10.0/3.0);
> The output from this statement is shown here: Here is 10/3: 3.33
Btw this is my code looks like:
```
static void Main()
{
Console.WriteLine("Here is 10/3: {0:#.##)", 10);
}
``` | You are using the wrong ending brace for the format parameter.
Note the end parenthesis ) after #.##, it should be a } instead (curly braces).
Also note that you have left out the division, and if you simply change your code to this (corrected the brace as well):
```
static void Main()
{
Console.WriteLine("Here is 10/3: {0:#.##}", 10/3);
}
```
Then you're going to have another question as well, since the result of that will be:
```
Here is 10/3: 3.00
```
The reason for this is that 10/3 is integer division, see how many times 3 goes up completely in 10, which is 3 times.
If you want floating point division, divide 10 by 3 to get 3 and 1/3rd, then you need to make sure at least one of the numbers are floating point, hence 10.0/3 will do. | Your code is wrong. You used a parenthesis instead of a curly brace in your string literal. Try this:
```
static void Main()
{
Console.WriteLine("Here is 10/3: {0:#.##}", 10);
}
``` | argument error c# | [
"",
"c#",
""
] |
Ok I have a very simple mysql database but when i try to run this query via mysql-admin i get weird errors
> INSERT INTO customreports (study,
> type, mode, select, description)
> VALUES ('1', '2', '3', '4', '5');
Error:
> 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select, description) VALUES ('1', '2', '3', '4', '5')' at line 1 | You're having problems because you're using SQL reserved words as column names and not escaping them. Try like this:
```
INSERT INTO `customreports`
(`study`, `type`, `mode`, `select`, `description`)
VALUES
('1', '2', '3', '4', '5');
``` | Yeah, I would rewrite as:
INSERT INTO [customreports] ([study], [type], [mode], [select], [description]) VALUES ('1', '2', '3', '4', '5'); | Why does this SQL INSERT statement return a syntax error? | [
"",
"mysql",
"sql",
""
] |
I have this code:
```
set<int>::iterator new_end =
set_difference(set1.begin(), set1.end(),
set2.begin(), set2.end(),
set1.begin());
set1.erase(new_end, set1.end);
```
It compiles and runs fine in visual studio. However, in a [previous question](https://stackoverflow.com/questions/908949/what-happens-when-you-modify-an-element-of-an-stdset), people stated that a `set`'s iterators are supposed to be `const`. I don't see anything like that in the standard. Can someone tell me where it says that, or if this is well-defined behavior?
If it's not, please provide code that does what I need. Is there a way to do this without creating a temporary set? | Your code violates a couple of the invariants for `set_difference`. From page 420 of the [Josuttis Book](http://www.josuttis.com/libbook/):
* The caller must ensure that the destination range is big enough or that insert iterators are used.
* The destination range should not overlap the source ranges.
You're trying to write back over the first set, which is not allowed. You need to write someplace other than the source ranges - for that we can use a third set:
```
std::set<int> set3;
std::set_difference(set1.begin(), set1.end(),
set2.begin(), set2.end(),
std::inserter(set3, set3.begin()));
```
The second argument to `std::inserter` is a hint for where the elements should be inserted. It's only a hint, however, rest assured that the elements will end up in the right place. `set3` is initially empty, so `begin()` is about the only hint we can give.
After the call to `set_difference`, `set3` will contain what you tried to make `set1` contain in your original code. You can go on using `set3` or `swap` it with `set1` if you prefer.
**Update:**
I'm not sure about the performance of this, but if you just want to remove all elements from `set1` that appear in `set2`, you can try:
```
for (std::set<int>::iterator i = set2.begin(); i != set2.end(); ++i)
{
set1.erase(*i);
}
``` | One suggestion to solve it:
```
std::set<int> tmp;
std::set_difference(set1.begin(), set1.end(),
set2.begin(), set2.end(),
std::inserter(tmp, tmp.begin()));
std::swap(tmp, set1);
```
I can't think of a way to do it without using a temporary set (apart from iterating through the containers and doing erase on individual elements). | Is the following code using std::set "legal"? | [
"",
"c++",
"stl",
"iterator",
"set",
""
] |
What's the difference between ECMAScript and JavaScript? From what I've deduced, ECMAScript is the standard and JavaScript is the implementation. Is this correct? | I think a little history lesson is due.
JavaScript was originally named Mocha and changed to Livescript but ultimately became JavaScript.
It's important to note that JavaScript came before ECMAscript and the history will tell you why.
To start from the beginning, JavaScript derived its name from Java and initially Brendan Eich (the creator of JS) was asked to develop a language that resembled Java for the web for Netscape.
Eich, however decided that Java was too complicated with all its rules and so set out to create a simpler language that even a beginner could code in. This is evident in such things like the relaxing of the need to have a semicolon.
After the language was complete, the marketing team of Netscape requested Sun to allow them to name it JavaScript as a marketing stunt and hence why most people who have never used JavaScript think it's related to Java.
About a year or two after JavaScript's release in the browser, Microsoft's IE took the language and started making its own implementations such as JScript. At the same time, IE was dominating the market and not long after Netscape had to shut its project.
Before Netscape went down, they decided to start a *standard* that would guide the path of JavaScript, named ECMAScript ([ECMA-262](https://ecma-international.org/publications-and-standards/standards/ecma-262/)).
ECMAScript had a few releases and in 1999 they released their last version (ECMAScript 3) before they went into hibernation for the next 10 years. During this 10 years, Microsoft dominated the scenes but at the same time they weren't improving their product and hence Firefox was born (led by Eich) and a whole heap of other browsers such as Chrome, Opera.
ECMAScript released its 5th Edition in 2009 (the 4th edition was abandoned) with features such as strict mode. Since then, ECMAScript has gained a lot of momentum and is scheduled to release its 6th Edition in a few months from now with the biggest changes its had thus far.
You can use a list of features for ECMAScript 6 here <http://kangax.github.io/es5-compat-table/es6/> and also the browser support. You can even start writing ECMAScript 6 like you do with CoffeeScript and use a compiler to compile down to ECMAScript 5.
Whether ECMAScript is the language and JavaScript is a dialect is arguable, but not important. If you continue to think like this it might confuse you. There is no compiler out there that would run ECMAScript, and I believe JavaScript is considered the Language which implements a standard called ECMAScript.
There are also other noticeable languages that implement ECMAScript such as ActionScript (used for Flash). | ECMAScript is the language, whereas JavaScript, JScript, and even ActionScript 3 are called "dialects". [Wikipedia](http://en.wikipedia.org/wiki/ECMAScript) sheds some light on this. | What is the difference between JavaScript and ECMAScript? | [
"",
"javascript",
"ecma262",
""
] |
I have a query I want to run as a subquery that will return a set of FK's. With them I want to return only rows that has a matching key.
### Subquery:
```
SELECT ID
FROM tblTenantTransCode
WHERE
tblTenantTransCode.CheckbookCode =
(SELECT ID FROM tblCheckbookCode WHERE Description = 'Rent Income')
```
That will return all the transaction codes that have a checkbook code that matches Rent Income
Now I want to select All Transactions where their transactioncode matches an ID returned in the subquery. I've gotten this far, but SQL Server complains of a syntax error. How can I do this?
### Full Query:
```
SELECT *
FROM tblTransaction
WHERE
tblTransaction.TransactionCode IN
(SELECT ID FROM tblTenantTransCode
WHERE tblTenantTransCode.CheckbookCode =
(SELECT ID FROM tblCheckbookCode WHERE Description = 'Rent Income'))
```
### Tables:
```
tblCheckbookCode
ID
Description
Other Info
tblTenantTransCode
ID
CheckbookCode <-- fk we're looking for
in the tblCheckbookCode.
We're selecting only checkbook codes
that have the Description 'Rent Income'
Other Info
tblTransactions
ID
TransactionCode <-- fk to tenant transaction code.
We're looking for an ID that is returned
in the above query/join
``` | To answer your question about using the **EXISTS** keyword, here is an example query that uses an EXISTS predicate, based on the query as currently given in your question.
```
SELECT t.*
FROM tblTransaction t
WHERE EXISTS
(
SELECT 1
FROM tblTenantTransCode ttc
JOIN tblCheckbookCode cc
ON (cc.ID = ttc.CheckbookCode AND cc.Description='Rent Income')
WHERE ttc.ID = t.TransactionCode
)
```
---
**Additional Details:**
We all recognize that there are a variety of SQL statements that will return the result set that meets the specified requirements. And there are likely going to be differences in the observed performance of those queries. Performance is particularly dependent on the DBMS, the optimizer mode, the query plan, and the statistics (number of rows and data value distribution).
One advantage of the `EXISTS` is that it makes clear that we aren't interested returning any expressions from tables in the subquery. It serves to logically separate the subquery from the outer query, in a way that a `JOIN` does not.
Another advantage of using `EXISTS` is that avoids returning duplicate rows that would be (might be) returned if we were to instead use a `JOIN`.
An `EXISTS` predicate can be used to test for the existence of any related row in a child table, without requiring a join. As an example, the following query returns a set of all orders that have at least one associated line\_item:
```
SELECT o.*
FROM order o
WHERE EXISTS
( SELECT 1
FROM line_item li
WHERE li.order_id = o.id
)
```
Note that the subquery doesn't need to find ALL matching line items, it only needs to find one row in order to satisfy the condition. (If we were to write this query as a `JOIN`, then we would return duplicate rows whenever an order had more than one line item.)
A `NOT EXISTS` predicate is also useful, for example, to return a set of orders that do **not** have any associated line\_items.
```
SELECT o.*
FROM order o
WHERE NOT EXISTS
( SELECT 1
FROM line_item li
WHERE li.order_id = o.id
)
```
Of course, `NOT EXISTS` is just one alternative. An equivalent result set could be obtained using an OUTER join and an IS NULL test (assuming we have at least one expression available from the line\_item table that is NOT NULL)
```
SELECT o.*
FROM order o
LEFT
JOIN line_item li ON (li.order_id = o.id)
WHERE li.id IS NULL
```
There seems to be a lot of discussion (relating to answers to the original question) about needing to use an `IN` predicate, or needing to use a `JOIN`.
Those constructs are alternatives, but aren't necessary. The required result set can be returned by a query without using an `IN` and without using a `JOIN`. The result set can be returned with a query that uses an `EXISTS` predicate. (Note that the title of the OP question did ask about how to use the `EXISTS` keyword.)
Here is another alternative query (this is not my first choice), but the result set returned does satisfy the specified requirements:
```
SELECT t.*
FROM tblTransaction t
WHERE EXISTS
(
SELECT 1
FROM tblTenantTransCode ttc
WHERE ttc.ID = t.TransactionCode
AND EXISTS
(
SELECT 1
FROM tblCheckbookCode cc
WHERE cc.ID = ttc.CheckbookCode
AND cc.Description = 'Rent Income'
)
)
```
Of primary importance, the query should return a correct result set, one that satisfies the specified requirements, given all possible sets of conditions.
Some of the queries presented as answers here do *NOT* return the requested result set, or if they do, they happen to do so by accident. Some of the queries will work if we pre-assume something about the data, such that some columns are `UNIQUE` and `NOT NULL`.
**Performance differences**
Sometimes a query with an `EXISTS` predicate will not perform as well as a query with a `JOIN` or an `IN` predicate. In some cases, it may perform better. (With the `EXISTS` predicate, the subquery only has to find one row that satisfies the condition, rather than finding ALL matching rows, as would be required by a `JOIN`.)
Performance of various query options is best gauged by observation. | You are describing an inner join.
```
select tc.id
from tblTenantTransCode tc
inner join tblCheckbookCode cc on tc.CheckbookCode = cc.CheckbookCode
```
EDIT: It's still an inner join. I don't see any reason yet to use the IN clause.
```
select *
from tblTransaction t
inner join tblTenantTransCode tc on tc.id = t.TransactionCode
inner join tblCheckbookCode cc on cc.id = tc.CheckbookCode
where cc.description = 'Rent Income'
```
EDIT: If you must use the EXISTS predicate to solve this problem, see @spencer7953's answer. However, from what I'm seeing, the solution above is simpler and there are assumptions of uniqueness based on the fact that "Subquery" works for you (it wouldn't 100% of the time if there wasn't uniqueness in that table). I'm also addressing
> Now I want to select All Transactions
> where **their transactioncode
> matches** an ID returned in the subquery
in my answer. If the request were something on the lines of this:
> Now I want to select All Transcations
> **when any** transactioncode matches an ID returned in the subquery.
I would use EXISTS to see if any transactioncode existed in the child table and return every row or none as appropriate. | How do I use T-SQL's Exists keyword? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
When you have automatic properties, C# compiler asks you to call the `this` constructor on any constructor you have, to make sure everything is initialized before you access them.
If you don't use automatic properties, but simply declare the values, you can avoid using the `this` constructor.
What's the overhead of using `this` on constructors in structs? Is it the same as double initializing the values?
Would you recommend not using it, if performance was a top concern for this particular type? | I would recommend not using automatic properties at all for structs, as it means they'll be mutable - if only privately.
Use readonly fields, and public properties to provide access to them where appropriate. Mutable structures are almost always a bad idea, and have all kinds of nasty little niggles.
Do you definitely need to create your own value type in the first place though? In my experience it's *very* rare to find a good reason to create a struct rather than a class. It may be that you've got one, but it's worth checking.
Back to your original question: if you care about performance, *measure it*. Always. In this case it's really easy - you can write the struct using an automatic property and then reimplement it without. You could use a `#if` block to keep both options available. Then you can measure typical situations and see whether the difference is significant. Of course, I think the design implications are likely to be more important anyway :) | Yes, the values will be initialized twice and without profiling it is difficult to say whether or not this performance hit would be significant.
The default constructor of a `struct` initializes all members to their default values. After this happens your constructor will run in which you undoubtedly set the values of those properties again.
I would imagine this would be no different than the CLR's practice of initializing all fields of a reference type upon instantiation. | Overhead of using this on structs | [
"",
"c#",
".net",
"performance",
"struct",
""
] |
I do scientific programming, and often want to show users prompts and variable pairs, let them edit the variables, and then do the calulations with the new variables. I do this so often, that I wrote a wxPython class to move this code out of the main program. You set up a list for each variable with the type of the variable (string, float, int), the prompt, and the variable's current value. You then place all of these lists in one big list, and my utility creates a neatly formated wxPython panel with prompts and the current values which can be edited.
When I started, I only had a few variables, so I would write out each variable.
```
s='this is a string'; i=1; f=3.14
my_list=[ ['s','your string here',s], ['i','your int here',i], ['f','your float here'],]
input_panel = Input(my_list)
# the rest of the window is created, the input_panel is added to the window, the user is
# allowed to make choices, and control returns when the user hits the calculate button
s,i,f = input_panel.results() # the .results() function returns the values in a list
```
Now I want to use this routine for a lot of variables (10-30), and this approach is breaking down. I can create the input list to the function over multiple lines using the list.append() statements. When the code returns from the function, though, I get this huge list that needs to be unpacked into the right variables. This is difficult to manage, and it looks like it will be easy to get the input list and output list out of sync. And worse than that, it looks kludgy.
What is the best way to pass lots of variables to a function in Python with extra information so that they can be edited, and then get the variables back so that I can use them in the rest of the program?
If I could pass the variables by reference into the function, then users could change them or not, and I would use the values once the program returned from the function. I would only need to build the input list over multiple lines, and there wouldn't be any possiblity of the input list getting out of sync with the output list. But Python doesn't allow this.
Should I break the big lists into smaller lists that then get combined into big lists for passing into and out of the functions? Or does this just add more places to make errors? | The simplest thing to do would be to create a class. Instead of dealing with a list of variables, the class will have attributes. Then you just use a single instance of the class. | There are two decent options that come to mind.
The first is to use a dictionary to gather all the variables in one place:
```
d = {}
d['var1'] = [1,2,3]
d['var2'] = 'asdf'
foo(d)
```
The second is to use a class to bundle all the arguments. This could be something as simple as:
```
class Foo(object):
pass
f = Foo()
f.var1 = [1,2,3]
f.var2 = 'asdf'
foo(f)
```
In this case I would prefer the class over the dictionary, simply because you could eventually provide a definition for the class to make its use clearer or to provide methods that handle some of the packing and unpacking work. | How do I pass lots of variables to and from a function in Python? | [
"",
"python",
"pass-by-reference",
"pass-by-value",
""
] |
i have a string:
e.g. `WORD1_WORD2_WORD3`
how do i get just WORD1 from the string?
i.e the text before the first underscore | ```
YOUR_STRING.Split('_')[0]
```
In fact the Split method returns an array of strings resulting from splitting the original string at any occurrence of the specified character(s), not including the character at which the split was performed. | It may be tempting to say `Split` - but that involves the creating of an array and lots of individual strings. IMO, the optimal way here is to find the first underscore, and take a substring:
```
string b = s.Substring(0, s.IndexOf('_')); // assumes at least one _
```
(edit)
If you are doing this lots, you could add some extension methods:
```
public static string SubstringBefore(this string s, char value) {
if(string.IsNullOrEmpty(s)) return s;
int i = s.IndexOf(value);
return i > 0 ? s.Substring(0,i) : s;
}
public static string SubstringAfter(this string s, char value) {
if (string.IsNullOrEmpty(s)) return s;
int i = s.IndexOf(value);
return i >= 0 ? s.Substring(i + 1) : s;
}
```
then:
```
string s = "a_b_c";
string b = s.SubstringBefore('_'), c = s.SubstringAfter('_');
``` | Extracting first token from a delimeted string | [
"",
"c#",
"string",
""
] |
I have an ASP.NET DropDownList with a rather wide content, while the closed list's width has to be quite small due to room limitations on the site. That's why I need to be able to set a specific width to the list when it's closed, but want it to be as wide as the content when it's opened.
By default, Firefox automatically makes DropDownLists as wide as its content when opened. Internet Explorer on the other hand does not.
Is there any way to tell IE to make the opened DDL as wide as the content when it's opened, but have it in a smaller size when closed? Preferably without using javascript.
EDIT: Ok, I wasn't clear enough in my first post. The emphasis is on *when opened*. I want a specific width on the list when it's closed, but I want it to be as wide as the content *when opened*. As I said, Firefox does this, IE does not. | I'd recommend not using the drop down list, but a more javascript friendly one like this
<http://jquery.sanchezsalvador.com/samples/example.htm>
This will allow your content to expand past the selects width. | IE default to as wide as content.
Set a CSSClass and give it a specified width and you will be able to change it.
You can also go
```
select{
width:42px;
}
```
**edit**: from what you're saying now, I feel like you need to do some javascript, because IE will not handle that. Try looking into jquery | DropDownList width in Internet Explorer | [
"",
"c#",
"asp.net",
"internet-explorer",
""
] |
Is there a way to pass more data into a callback function in jQuery?
I have two functions and I want the callback to the `$.post`, for example, to pass in both the resulting data of the AJAX call, as well as a few custom arguments
```
function clicked() {
var myDiv = $("#my-div");
// ERROR: Says data not defined
$.post("someurl.php",someData,doSomething(data, myDiv),"json");
// ERROR: Would pass in myDiv as curData (wrong)
$.post("someurl.php",someData,doSomething(data, myDiv),"json");
}
function doSomething(curData, curDiv) {
}
```
I want to be able to pass in my own parameters to a callback, as well as the result returned from the AJAX call. | The solution is the binding of variables through closure.
---
As a more basic example, here is an example function that receives and calls a callback function, as well as an example callback function:
```
function callbackReceiver(callback) {
callback("Hello World");
}
function callback(value1, value2) {
console.log(value1, value2);
}
```
This calls the callback and supplies a single argument. Now you want to supply an additional argument, so you wrap the callback in closure.
```
callbackReceiver(callback); // "Hello World", undefined
callbackReceiver(function(value) {
callback(value, "Foo Bar"); // "Hello World", "Foo Bar"
});
```
Or, more simply using [ES6 Arrow Functions](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions):
```
callbackReceiver(value => callback(value, "Foo Bar")); // "Hello World", "Foo Bar"
```
---
As for your specific example, I haven't used the `.post` function in jQuery, but a quick scan of the documentation suggests the call back should be a *function pointer* with the following signature:
```
function callBack(data, textStatus, jqXHR) {};
```
Therefore I think the solution is as follows:
```
var doSomething = function(extraStuff) {
return function(data, textStatus, jqXHR) {
// do something with extraStuff
};
};
var clicked = function() {
var extraStuff = {
myParam1: 'foo',
myParam2: 'bar'
}; // an object / whatever extra params you wish to pass.
$.post("someurl.php", someData, doSomething(extraStuff), "json");
};
```
What is happening?
In the last line, `doSomething(extraStuff)` is *invoked* and the result of that invocation is a *function pointer*.
Because `extraStuff` is passed as an argument to `doSomething` it is within scope of the `doSomething` function.
When `extraStuff` is referenced in the returned anonymous inner function of `doSomething` it is bound by closure to the outer function's `extraStuff` argument. This is true even after `doSomething` has returned.
I haven't tested the above, but I've written very similar code in the last 24 hours and it works as I've described.
You can of course pass multiple variables instead of a single 'extraStuff' object depending on your personal preference/coding standards. | When using `doSomething(data, myDiv)`, you actually call the function and do not make a reference to it.
You can either pass the `doStomething` function directly but you must ensure it has the correct signature.
If you want to keep doSomething the way it is, you can wrap its call in an anonymous function.
```
function clicked() {
var myDiv = $("#my-div");
$.post("someurl.php",someData, function(data){
doSomething(data, myDiv)
},"json");
}
function doSomething(curData, curDiv) {
...
}
```
Inside the anonymous function code, you can use the variables defined in the enclosing scope. This is the way Javascript scoping works. | jQuery pass more parameters into callback | [
"",
"javascript",
"jquery",
"function",
"callback",
"arguments",
""
] |
So I have a map:
```
Map<String, Class> format = new HashMap<String, Class>();
```
And I would add elements to it like this:
```
format.put("Vendor Number", Integer.class);
format.put("Vendor Dispatch", Date.class);
....
```
I have a generic method as follows:
```
public static <T> T verifyType(String name, Class<T> type) {
if (type == Integer.class) {
return type.cast(new Integer(Integer.parseInt(name)));
}
......
return null;
}
```
Now this piece of code works great with no compiler issues:
```
Integer i = verifyType("100",Integer.class);
```
But, when I try this:
```
Integer i = verifyType("100",format.get("Vendor Number"));
OR
Class type = Integer.class
Integer i = verifyType("100",type);
```
Compiler shows me this warning:
Type safety: Unchecked invocation verifyType(String,Class) of the generic method verifyType(String, Class)
That leaves me puzzled... please help... | Change:
```
Class type = Integer.class
Integer i = verifyType("100",type);
```
to
```
Class<Integer> type = Integer.class
Integer i = verifyType("100",type);
```
By only declaring the type as 'Class', you're losing the generic parameter and the verifyType() method can't infer the class, thus the unchecked warning.
This problem:
```
Map<String, Class> format = new HashMap<String, Class>();
format.put("Vendor Number", Integer.class);
format.put("Vendor Dispatch", Date.class);
Integer i = verifyType("100",format.get("Vendor Number"));
```
can't really be solved due to type erasure. The compiler can't infer the type based on a generic parameter that is gone by runtime. This is because Java generics are little more than smoke and mirrors for casting. | You have to genericize your references to Class. For example:
```
Class<Integer> type = Integer.class
Integer i = verifyType("100",type);
```
would work fine.
As would:
```
Map<String, Class<?>> format = new HashMap<String, Class<?>>();
```
However, this will never work:
```
Integer i = verifyType("100",format.get("Vendor Number"));
```
Because format is not defined as:
```
Map<String, Class<Integer>>
```
If it was, the casting would work, but the design would be pointless.
The closest you can get is:
```
Integer i = verifyType("100",(Class<Integer>) format.get("Vendor Number"));
```
However, you will get a compiler warning doing it, as you must - it is an inherently unsafe cast. The compiler is taking your word for it that that format.get statement will return an integer. If you are sure of that, then that is what unsafe casts are for. If you want to get rid of the compiler warning, you could do this:
```
Class<?> type = format.get("Vendor Number");
Integer i = null;
if (type == Integer.class) {
i = verifyType("100", Integer.class);
} else {
//What do you want to do?
}
``` | Java Generics with Class <T> | [
"",
"java",
"generics",
""
] |
This is a question about Qt library, not about Web design.
For QLabel and other controls I can set HTML text, for example "<h3>Some Text</h3>". The question is: where is the default HTML style is defined? How can I find out what a font would be used for <h3> tag?
The next question: can I change the default HTML style?
Edit: I want to specify in one place in my code how my controls would be displayed. To specify css style in all the labels doesn't seem to be an elegant solution to me.
Edit2: It seems people don't get the question. I'll try again. Suppose I do the following:
```
QLabel* label = ...
label->setText("This <b>is</b> a <h3>Header</h3>");
```
The question: what fonts will be used for label text rendering? How can I control them? Is there a way to specify, say, default font size for <h3> headers?
Edit3: Thomi have suggested to use QTextDocument::setDefaultStyleSheet. But this is just a workaround. I have to manually apply css style to all the QTextEdits (and not QLabels) in the interface. And the question was: how to *find out* the default style sheet? QTextDocument::setDefaultStyleSheet just overrides it for a single QTextDocument object. Maybe QTextDocument::defaultStyleSheet returns it? I don't have a computer with Qt insatlled right now so I can't check it. | What you want cannot be done with a QLabel. The QLabel is designed to hold primative text labels - it's HTML support is rather... ropey.
However, You *can* achieve this using a QTextEdit & QTextDocument.
Try something like this (I'm writing this from memory, so it may not compile or be 100% correct):
```
QTextDocument *doc = new QTextDocument(this);
doc->setDefaultStyleSheet("h3 { font-color: red; }");
QTextEdit *edit = new QTextEdit(this);
edit->setDocument(doc);
edit->setHTML("this is a red <h3>heading</h3>");
```
The important thing is to use a QTextDocument, which allows you to change the HTML stylesheet. From the QT documentation:
```
The default style sheet is applied to all newly HTML formatted text that is inserted into the document, for example using setHtml() or QTextCursor::insertHtml().
The style sheet needs to be compliant to CSS 2.1 syntax.
Note: Changing the default style sheet does not have any effect to the existing content of the document.
```
[see here for more info](http://doc.trolltech.com/4.5/qtextdocument.html#defaultStyleSheet-prop)
# Edit:
To get the default stylesheet, you can call `QTextDocument::DefaultStyleSheet()` - however, this only applies to QTextDocuments, and may or may not apply to all Qt controls (including QLabel). | As mentioned in other answers you can do it for widget styles but not for HTML tags. The only way to do it is to set CSS styles inside your widgets `text` property individually.
Qt uses its rich text engine to render HTML tags which are defined according to rules in HTML 4 specification. See [Supported HTML Subset](http://doc.qt.io/archives/qt-4.8/richtext-html-subset.html)
If you need just one style for all your labels why not to set it using `setStyleSheet()` like this:
```
MainWindow w;
w.setStyleSheet("QLabel{font-size:20px; color:purple;};");
```
Unless you want to use more than one style inside your labels (for example: "**More** than ***one*** style") that's the right way to do it. | Default HTML style for controls in the Qt library | [
"",
"c++",
"qt",
""
] |
I have some library code (I cannot not change the source code) that returns a pointer to an object (B). I would like to store this pointer as shared\_ptr under a class with this type of constructor:
```
class A
{
public:
A(boost::shared_ptr<B> val);
...
private:
boost::shared_ptr<B> _val;
...
};
int main()
{
B *b = SomeLib();
A a(b); //??
delete b;
...
}
```
That is, I would like to make a deep-copy of b and control its life-time under a (even if original b is deleted (delete b), I still have an exact copy under a).
I'm new to this, sorry if it seems trivial... | As you say, you have to copy them not just copy a pointer. So either B already has implemented 'clone' method or you have to implement some external `B* copy(B* b)` which will create new B with same state.
In case B has implemented copy constructor you can implement copy as just
```
B* copyOf(B* b)
{
return new B(*b);
}
```
In case B has implemented [clone method or similar](http://en.wikipedia.org/wiki/Prototype_pattern) you can implement copy as
```
B* copyOf(B* b)
{
return b->clone();
}
```
and then your code will look like
```
int main()
{
B *b = SomeLib();
A a(copyOf(b));
delete b;
...
}
``` | If the library defines this B object, the library should provide (or outright prohibit) the mechanism for copying B.
As a sidenote,
If your class A is exclusively controlling the lifetime of this copied object, the smart pointer you really want to use is `boost::scoped_ptr`.
`boost::shared_ptr` is named after its ability to share lifetime responsibility, which it sounds like you don't want. `scoped_ptr` won't let that accidentally happen. | convert pointer to shared_ptr | [
"",
"c++",
"pointers",
""
] |
I have two related entities, say
```
@Entity
public class Book {
@ManyToOne
Shelf shelf;
}
@Entity
public class Shelf {
@OneToMany(mappedBy="shelf")
Set<Book> books;
}
```
If I fetch an empty shelf (no books), create and persist a new book to the shelf and then fetch that shelf again, its books collection is empty. When I run it with debug logging I see that Hibernate doesn't search for the shelf for the second time, it just returns it from the session cache, where it lies not knowing, that it's books collection has been updated.
How can I get rid of the effect and get the updated state of the shelf?
Thanks,
Artem. | Seems like you have to maintain it by hand in the scope of a single session (transaction). Neither @Cascade nor EAGER influence session cache | Try to set fetch type EAGER for books set in Shelf:
```
@Entity
public class Shelf {
@OneToMany(mappedBy="shelf",fetch=FetchType.EAGER)
Set<Book> books;
}
``` | How to update a collection-type relation with mappedBy in Hibernate? | [
"",
"java",
"hibernate",
"session-cache",
""
] |
Is there a kind of Java collection that the order of my fetching is random? For example, I put integer 1, 2, 3 into the collection and when I try to print them all the result can be "1 2 3","3 2 1" or "1 3 2"? | If you just want a random sequence you could use Collections.shuffle
```
List<Integer> list = new LinkedList();
//Add elements to list
Collections.shuffle(list);
``` | Take a normal collection and shuffle it, then iterate over it in a normal way.
You can use `java.util.Collections.shuffle(List<T>)` to do the shuffling. | Java random collection | [
"",
"java",
""
] |
We're having a problem where indexes on our tables are being ignored and SQL Server 2000 is performing table scans instead. We can force the use of indexes by using the `WITH (INDEX=<index_name>)` clause but would prefer not to have to do this.
As a developer I'm very familiar with SQL Server when writing T-SQL, but profiling and performance tuning isn't my strong point. I'm looking for any advice and guidance as to why this might be happening.
**Update:**
I should have said that we've rebuilt all indexes and updated index statistics.
The table definition for one of the culprits is as follows:
```
CREATE TABLE [tblinvoices]
(
[CustomerID] [int] NOT NULL,
[InvoiceNo] [int] NOT NULL,
[InvoiceDate] [smalldatetime] NOT NULL,
[InvoiceTotal] [numeric](18, 2) NOT NULL,
[AmountPaid] [numeric](18, 2) NULL
CONSTRAINT [DF_tblinvoices_AmountPaid] DEFAULT (0),
[DateEntered] [smalldatetime] NULL
CONSTRAINT [DF_tblinvoices_DateEntered] DEFAULT (getdate()),
[PaymentRef] [varchar](110),
[PaymentType] [varchar](10),
[SyncStatus] [int] NULL,
[PeriodStart] [smalldatetime] NULL,
[DateIssued] [smalldatetime] NULL
CONSTRAINT [DF_tblinvoices_dateissued] DEFAULT (getdate()),
CONSTRAINT [PK_tblinvoices] PRIMARY KEY NONCLUSTERED
(
[InvoiceNo] ASC
) ON [PRIMARY]
) ON [PRIMARY]
```
There is one other index on this table (the one we want SQL to use):
```
CustomerID (Non-Unique, Non-Clustered)
```
The following query performs a table scan instead of using the `CustomerID` index:
```
SELECT
CustomerID,
Sum(InvoiceTotal) AS SumOfInvoiceTotal,
Sum(AmountPaid) AS SumOfAmountPaid
FROM tblInvoices
WHERE CustomerID = 2112
GROUP BY customerID
```
**Updated:**
In answer to [Autocracy's question](https://stackoverflow.com/questions/969575/why-are-my-sql-indexes-being-ignored/969748#969748), both of those queries perform a table scan.
**Updated:**
In answer to [Quassnoi's question](https://stackoverflow.com/questions/969575/why-are-my-sql-indexes-being-ignored/969643#969643) about `DBCC SHOW_STATISTICS`, the data is:
```
RANGE_HI_KEY RANGE_ROWS EQ_ROWS DISTINCT_RANGE_ROWS AVG_RANGE_ROWS
1667 246 454 8 27.33333
2112 911 3427 16 56.9375
2133 914 775 16 57.125
``` | The best thing to do is make the index a **covering index** by including the **InvoiceTotal** and **AmountPaid** columns in the CustomerID index. (In SQL 2005, you would add them as "included" columns". In SQL 2000, you have to add them as additional key columns.) If you do that, I'll *guarantee* the query optimizer will choose your index\*.
**Explanation**:
Indexes seem like they would always be useful, but there is a hidden cost to using a (non-covering) index, and that is the "**bookmark lookup**" that has to be done to retrieve any *other* columns that might be needed from the main table. This bookmark lookup is an expensive operation, and is (one possible) reason why the query optimizer might not choose to use your index.
By including all needed columns in the index itself, this bookmark lookup is avoided entirely, and the optimizer doesn't have to play this little game of figuring out if using an index is "worth it".
(\*) Or I'll refund your StackOverflow points. Just send a self-addressed, stamped envelope to...
Edit: Yes, if your primary key is NOT a clustered index, then by all means, do that, too!! But even with that change, making your CustomerID index a covering index should increase performance by an order of magnitude (10x or better)!! | > We're having a problem where indexes on our tables are being ignored and `SQL Server 2000` is performing table scans instead.
Despite `4,302` days that have passed since `Aug 29, 1997`, `SQL Server`'s optimizer has not evolved into `SkyNet` yet, and it still can make some incorrect decisions.
Index hints are just the way you, a human being, help the artificial intelligence.
If you are sure that you collected statistics and the optimizer is still wrong, then go on, use the hints.
They are legitimate, correct, documented and supported by `Microsoft` way to enforce the query plan you want.
In your case:
```
SELECT CustomerID,
SUM(InvoiceTotal) AS SumOfInvoiceTotal,
SUM(AmountPaid) AS SumOfAmountPaid
FROM tblInvoices
WHERE CustomerID = 2112
GROUP BY
CustomerID
```
, the optimizer has two choises:
* Use the index which implies a nested loop over the index along with `KEY LOOKUP` to fetch the values of `InvoiceTotal` and `AmountPaid`
* Do not use the index and scan all tables rows, which is faster in `rows fetched per second`, but longer in terms of total row count.
The first method may or may not be faster than the second one.
The optimizer tries to estimate which method is faster by looking into the statistics, which keep the index selectivity along with other values.
For selective indexes, the former method is faster; for non-selective ones, the latter is.
Could you please run this query:
```
SELECT 1 - CAST(COUNT(NULLIF(CustomerID, 2112)) AS FLOAT) / COUNT(*)
FROM tlbInvoices
```
**Update:**
Since `CustomerID = 2112` covers only `1,4%` of your rows, you should benefit from using the index.
Now, could you please run the following query:
```
DBCC SHOW_STATISTICS ([tblinvoices], [CustomerID])
```
, locate two adjacents rows in the third resultset with `RANGE_HI_KEY` being less and more than `2112`, and post the rows here?
**Update 2:**
Since the statistics seem to be correct, we can only guess why the optimizer chooses full table scan in this case.
Probably (probably) this is because this very value (`2112`) occurs in the `RANGE_HI_KEY` and the optimizer sees that it's unusually dense (`3427` values for `2112` alone against only `911` for the whole range from `1668` to `2111`)
Could you please do two more things:
1. Run this query:
```
DBCC SHOW_STATISTICS ([tblinvoices], [CustomerID])
```
and post the first two resultsets.
* Run this query:
SELECT TOP 1 CustomerID, COUNT(\*)
FROM tblinvoices
WHERE CustomerID BETWEEN 1668 AND 2111
, use the top `CustomerID` from the query above in your original query:
```
SELECT CustomerID,
SUM(InvoiceTotal) AS SumOfInvoiceTotal,
SUM(AmountPaid) AS SumOfAmountPaid
FROM tblInvoices
WHERE CustomerID = @Top_Customer
GROUP BY
CustomerID
```
and see what plan will it generate. | Why are my SQL indexes being ignored? | [
"",
"sql",
"sql-server",
"indexing",
""
] |
I got a string like:
```
settings.functionName + '(' + t.parentNode.id + ')';
```
that I want to translate into a function call like so:
```
clickedOnItem(IdofParent);
```
This of course will have to be done in JavaScript. When I do an alert on `settings.functionName + '(' + t.parentNode.id + ')';` it seems to get everything correct. I just need to call the function that it would translate into.
Legend:
```
settings.functionName = clickedOnItem
t.parentNode.id = IdofParent
``` | Seeing as I hate eval, and I am [not alone](https://ericlippert.com/2003/11/01/eval-is-evil-part-one/):
```
var fn = window[settings.functionName];
if(typeof fn === 'function') {
fn(t.parentNode.id);
}
```
**Edit:** In reply to @Mahan's comment:
In this particular case, `settings.functionName` would be `"clickedOnItem"`. This would, at runtime translate `var fn = window[settings.functionName];` into `var fn = window["clickedOnItem"]`, which would obtain a reference to `function clickedOnItem (nodeId) {}`. Once we have a reference to a function inside a variable, we can call this function by "calling the variable", i.e. `fn(t.parentNode.id)`, which equals `clickedOnItem(t.parentNode.id)`, which was what the OP wanted.
More full example:
```
/* Somewhere: */
window.settings = {
/* [..] Other settings */
functionName: 'clickedOnItem'
/* , [..] More settings */
};
/* Later */
function clickedOnItem (nodeId) {
/* Some cool event handling code here */
}
/* Even later */
var fn = window[settings.functionName];
/* note that settings.functionName could also be written
as window.settings.functionName. In this case, we use the fact that window
is the implied scope of global variables. */
if(typeof fn === 'function') {
fn(t.parentNode.id);
}
``` | ```
window[settings.functionName](t.parentNode.id);
```
No need for an eval() | How to turn a String into a JavaScript function call? | [
"",
"javascript",
"function",
""
] |
I've always wondered, if it's good or bad practice to define trivial method twice, depending
if the project's on debug / release -state. This is for inlining them. For instance, Foo.h:
```
class Foo
{
public:
...
const bool& IsBoolean() const;
private:
bool _boolean;
};
#ifndef _DEBUG
/** We're in release, so let's advice compiler to inline this...
*
*
*/
inline const bool& Foo::IsBoolean() const
{
return _boolean;
}
#endif
```
And now, in Foo.cpp:
```
#include "Foo.h"
...
#ifdef _DEBUG
/** We're debugging this, no need for inlining...
*
*
*/
const bool& Foo::IsBoolean() const
{
return _boolean;
}
#endif
```
Is this completely useless? For example due to compiler's (MSVC) ability to inline / optimize methods all by itself?
Nevertheless, this is something I've been using for years now. Please correct me, if I'm completely wrong here... | It's a waste of time, for several reasons.
The inline keyword is a *hint* that the compiler may ignore at will. Just like it is free to inline even if the keyword is not specified. So whether or not you add it probably won't change anything for the compiler
Further, any functions defined inside the class definition are implicitly inlined. That is why short functions like getters and setters are almost always defined inside the class definition.
Next, if you want to mark a function as inline, there's no reason not to do it in debug builds as well.
The `inline` keyword has almost nothing to do with the compiler actually inlining functions. They are separate concepts. A function marked `inline` by the programmer means that the linker shouldn't worry if it sees multiple identical definitions. That typically happens if the function is defined in a header, which gets included into multiple compilation units. If the function is marked inline, the linker will merge the definitions together. If it isn't, you get an error. In other words, adding and removing this keyword will cause compiler errors. That's probably not what you want.
The only reason there is a bit of overlap between the C++ `inline` keyword and the compiler optimization is that if a function is marked `inline`, it is safe to #include it in every compilation unit, which means the definition will always be visible when the function is called. And that makes it *easire* for the compiler to inline calls to the function.
Finally, inlining is not always a performance improvement. It is easy to create a situation where inlining does nothing more than make the code size explode, cause more cache misses, and overall, slow down your code. That is one of the reasons why `inline` is (at best) treated as a hint by the optimizer. At worst, it is ignored entirely.
So what you're doing will 1) cause compiler errors in debug mode that didn't exist in release builds, and 2) have no effect on performance. | Looks like a waste of space and an unnecessary code duplication. Usually the compiler is very capable of determining on its own which functions to inline and which not. Even more so if you're using MSVC which has the `/LTCG` (Link Time Code Generation) switch that means your trivial methods are going to get inlined even if they are in the cpp. | Is it any good to define trivial inlined methods twice based to debug / release -state of the project? | [
"",
"c++",
"optimization",
"class-design",
""
] |
Well, the title says it all. When passing a file name to a method, should I use a FileInfo object or a plain file name (string)? Why would I prefer one to the other?
Some of my colleagues like to write method like this:
* void Export(FileInfo fileInfo)
Is it better than:
* void Export(string fileName)
Thanks! | I'd usually just use a `string` - it's simpler in most cases. Otherwise you're likely to just create a new `FileInfo` from the string in the first place.
If you're creating the method, you could always provide overloads to allow both.
Of course, if you know that where you're intending to call it, you usually *have* a `FileInfo` rather than a `string`, that's a different matter.
I can see your colleagues' point of view - in some ways a `FileInfo` is a "cleaner" way of expressing the parameter. I think `string` is the more pragmatic approach though :) | Typically I would pass the string. **However, you could overload the method to make everyone happy.** | When passing a file name to a method, should I use FileInfo or a plain file name? | [
"",
"c#",
"fileinfo",
""
] |
I'm going to be doing some PHP editing for my job this summer, and am looking for an effective Emacs setup for editing it. I'm already heavily invested in Emacs, so switching to another editor is not worthwhile.
Right now, I have [nXhtml-mode](http://ourcomments.org/Emacs/nXhtml/doc/nxhtml.html), which provides a PHP mode with syntax highlighting (there are at least three different ones in the wild) as well as MuMaMo for editing PHP embedded in HTML. I just started using [Auto-Complete](http://www.emacswiki.org/emacs/AutoComplete) and [Anything](http://www.emacswiki.org/emacs/Anything) for programming and general Emacs stuff, respectively.
What I'm really looking for is an effective way to get Emacs to really understand the project, beyond just highlighting. [Etags](http://www.emacswiki.org/emacs/EmacsTags) looks like a good option, but it looks like the process for generating new tags is kind of arduous and manual (or at least not invisible). The nice thing about Etags is that they integrate well with Anything and Auto-Complete. Other potential options are [gtags](http://www.emacswiki.org/emacs/GnuGlobal) (though I'm hesitant to install non-elisp files, just for the complexity), [vtags](http://www.emacswiki.org/cgi-bin/wiki/VTags), or [Semantic](http://www.emacswiki.org/emacs/SemanticBovinator), which I've messed with before and seems complicated to set up, plus it doesn't look like it has support for PHP.
Another option is [Imenu](http://www.emacswiki.org/emacs/ImenuMode), but it only works for the current buffer, and I would like to be able to jump to function definitions in other files (preferably using Anything for completion of the name).
The projects I will be working on are not that big (about 30,000 lines total), so the overhead of Etags probably won't be that big of an issue, but I'd rather not use it if there is a better solution.
So what is your preferred PHP editing system? | In addition to features you are already familiar with, I suggest you the followings.
### ETags
I do not use ETags, but there is a question already on SO *[How to programmatically create/update a TAGS file with emacs](https://stackoverflow.com/questions/548414/how-to-programmatically-create-update-a-tags-file-with-emacs)*. No good answer was posted, though, but it may be a good entry point to get an idea.
### Debugging
[Flymake](http://www.emacswiki.org/emacs/FlyMake) is a mode to get on the fly syntax checking. It has support for PHP as well. It hints at syntax errors immediately as you type. The Flymake version shipped with Emacs 23 contains PHP support. If you have previous version, check Sacha Chua's post on *[Emacs and PHP: On-the-fly syntax checking with Flymake](http://sachachua.com/wp/2008/07/31/emacs-and-php-on-the-fly-syntax-checking-with-flymake/)*.
Another useful package is [Geben](http://code.google.com/p/geben-on-emacs/) that allows you to debug your scripts interactively. For PHP, you can use XDebug. There is a detailed tutorial on how to do that, see *[Debug php in emacs with geben](http://blog.local.ch/archive/2008/08/08/debug-php-in-emacs-with-geben.html)*.
### Documentation lookup
PHP Mode has a nice feature to lookup the function's definition in PHP's manual in your web browser (`M-x php-search-documentation` or `C-c C-f`). You can combine it with [Emacs-W3M](http://emacs-w3m.namazu.org/) to get the relevant manual page without leaving Emacs. | web-model.el (available on [web-mode.org](http://web-mode.org)) handles pretty well php blocks embedded in an html document. This major mode will also highlight js and css parts. | What is a good setup for editing PHP in Emacs? | [
"",
"php",
"emacs",
"editor",
"autocomplete",
""
] |
Suppose I have a program running that periodically adds information to a .CSV file. Is there a way to write to the file while it is already open in Excel? Obviously the changes wouldn't be noticed until the file was re-opened in Excel, but as it stands right now, I'm catching IOException and just starting a new .csv file if the current one is already open. | Excel seems to open the file in exclusive mode, so the only way I can think of would be to write your changes to a temporary file, and then use `FileSystemWatcher` to see when the file is closed, and overwrite the file.
Not a very good idea, as you could lose data. The whole reason excel locks the file is so that you don't accidentally overwrite changes made in excel. | It sounds like the file is locked. I doubt you will be able to write to that file if it is open in another process. | Write to file that is open in Excel | [
"",
"c#",
"file-io",
""
] |
I am working with the Webbrowser control on a windows.form application written in C#. I would like to write a method for deleting the cookies from the Webbrowers control after it visits a certain site. Unfortunately, I don't know how to do that exactly and haven't found a lot of help on the internet.
If anyone has experience actually doing this, not just hypothetical because it might be trickier than it seems, I don't know.
```
int count = webBrowser2.Document.Cookie.Length;
webBrowser2.Document.Cookie.Remove(0,count);
```
I would just assume something like the above code would work but I guess it won't. Can anyone shed some light on this whole cookie thing? | If you have JavaScript enabled you can just use this code snippet to clear to clear the cookies for the site the webbrowser is currently on.
```
webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())")
```
It's derived from [this bookmarklet](http://ostermiller.org/bookmarklets/cookies.html) for clearing cookies. | I modified the solution from here:
<http://mdb-blog.blogspot.ru/2013/02/c-winforms-webbrowser-clear-all-cookies.html>
Actually, you don't need an unsafe code. Here is the helper class that works for me:
```
public static class WinInetHelper
{
public static bool SupressCookiePersist()
{
// 3 = INTERNET_SUPPRESS_COOKIE_PERSIST
// 81 = INTERNET_OPTION_SUPPRESS_BEHAVIOR
return SetOption(81, 3);
}
public static bool EndBrowserSession()
{
// 42 = INTERNET_OPTION_END_BROWSER_SESSION
return SetOption(42, null);
}
static bool SetOption(int settingCode, int? option)
{
IntPtr optionPtr = IntPtr.Zero;
int size = 0;
if (option.HasValue)
{
size = sizeof (int);
optionPtr = Marshal.AllocCoTaskMem(size);
Marshal.WriteInt32(optionPtr, option.Value);
}
bool success = InternetSetOption(0, settingCode, optionPtr, size);
if (optionPtr != IntPtr.Zero) Marshal.Release(optionPtr);
return success;
}
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool InternetSetOption(
int hInternet,
int dwOption,
IntPtr lpBuffer,
int dwBufferLength
);
}
```
You call SupressCookiePersist somewhere at the start of the process and
EndBrowserSession to clear cookies when browser is closed as described here:
[Facebook multi account](https://stackoverflow.com/questions/23206199/facebook-multi-account) | How to delete Cookies from windows.form? | [
"",
"c#",
"cookies",
"webbrowser-control",
""
] |
So I have an example question as follows:
```
Explain how a JSP page is executed and what kind of problems may occur.
```
I'm fine with the first part, compile the static html and the scriptlets to java to be served by the servlet etc.
But I'm stumped by what problems may occur? The JSP page is held in memory... so maybe that may exhaust memory? I'm kinda grabbing at straws here... | One potentially problematic thing that a lot of people overlook when writing JSP pages is the fact that JSP declarations, i.e.:
```
<%! String foo = "bar" %>
```
create instance variables when they get compiled into servlets, which destroys the thread safety of the JSP.
More generally though, common problems include using a semicolon at the end of an expression, or not using a semicolon in a scriptlet; attempting to retrieve parameter or attribute or session values that are null or are the wrong type; using the wrong scope when trying to access variables. All sorts of fun stuff. | I must say that the question is a bit awkward to me. In general when you have a JSP page (executed) it should handle any exceptions that might arise from the use of scriptlets, expressions or other JSP things. When you do not handle those by specifying that the web container should forward control to the error page when an exception occurs, things may go wrong :). Ofcourse an unpredicted error can always arise but thisone can be handled as well by using "Handling Unhandled Exceptions".
So the answer is that there are infinitely many errors which can occur based on what your code is in the JSP page. The thing is you can predict them and handle them in advance? | What kind of problems may occur when executing a JSP page? | [
"",
"java",
"jsp",
""
] |
I am wondering what the best practice is for including javascript files inside partial views. Once rendered this will end up as a js include tag in the middle of my page's html. From my point of view this isn't a nice way of doing this. They belong in the head tag and as such should not prevent the browser from rendering the html in one go.
**An example:**
I am using a jquery picturegallery plugin inside a 'PictureGallery' partial view as this partial view will be used on several pages. This plugin only needs to be loaded when this view is used and **I don't want to have to need to know which plugins each partial view is using...**
Thanks for your answers. | Seems very similar to this question: [Linking JavaScript Libraries in User Controls](https://stackoverflow.com/questions/885990/linking-javascript-libraries-in-user-controls/886184#886184)
I'll repost my answer that that question here.
I would definitely advise against putting them inside partials for exactly the reason you mention. There is a high chance that one view could pull in two partials that both have references to the same js file. You've also got the performance hit of loading js before loading the rest of the html.
I don't know about best practice but I choose to include any common js files inside the masterpage and then define a separate ContentPlaceHolder for some additional js files that are specific to a particular or small number of views.
Here's an example master page - it's pretty self explanatory.
```
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<head runat="server">
... BLAH ...
<asp:ContentPlaceHolder ID="AdditionalHead" runat="server" />
... BLAH ...
<%= Html.CSSBlock("/styles/site.css") %>
<%= Html.CSSBlock("/styles/ie6.css", 6) %>
<%= Html.CSSBlock("/styles/ie7.css", 7) %>
<asp:ContentPlaceHolder ID="AdditionalCSS" runat="server" />
</head>
<body>
... BLAH ...
<%= Html.JSBlock("/scripts/jquery-1.3.2.js", "/scripts/jquery-1.3.2.min.js") %>
<%= Html.JSBlock("/scripts/global.js", "/scripts/global.min.js") %>
<asp:ContentPlaceHolder ID="AdditionalJS" runat="server" />
</body>
```
Html.CSSBlock & Html.JSBlock are obviously my own extensions but again, they are self explanatory in what they do.
Then in say a SignUp.aspx view I would have
```
<asp:Content ID="signUpContent" ContentPlaceHolderID="AdditionalJS" runat="server">
<%= Html.JSBlock("/scripts/pages/account.signup.js", "/scripts/pages/account.signup.min.js") %>
</asp:Content>
```
HTHs, Charles
Ps. Here is a follow up question I asked about minifying and concatenating js files:
[Concatenate & Minify JS on the fly OR at build time - ASP.NET MVC](https://stackoverflow.com/questions/890561/concatenate-minify-js-on-the-fly-or-at-build-time-asp-net-mvc)
**EDIT:** As requested on my other answer, my implementation of .JSBlock(a, b) as requested
```
public static MvcHtmlString JSBlock(this HtmlHelper html, string fileName)
{
return html.JSBlock(fileName, string.Empty);
}
public static MvcHtmlString JSBlock(this HtmlHelper html, string fileName, string releaseFileName)
{
if (string.IsNullOrEmpty(fileName))
throw new ArgumentNullException("fileName");
string jsTag = string.Format("<script type=\"text/javascript\" src=\"{0}\"></script>",
html.MEDebugReleaseString(fileName, releaseFileName));
return MvcHtmlString.Create(jsTag);
}
```
And then where the magic happens...
```
public static MvcHtmlString MEDebugReleaseString(this HtmlHelper html, string debugString, string releaseString)
{
string toReturn = debugString;
#if DEBUG
#else
if (!string.IsNullOrEmpty(releaseString))
toReturn = releaseString;
#endif
return MvcHtmlString.Create(toReturn);
}
``` | The reason you would put a script at the bottom of the page is to ensure the dom has been loaded before attempting any manipulation. This can also be achieved in something like the $(document).ready(callback); jQuery method.
I share the view of not putting embedded JavaScript in the html. Instead I use an Html helper to create an empty div to use as a server instruction. The helper sig is Html.ServerData(String name, Object data);
I use this ServerData method for instructions from the server to the client. The div tag keeps it clean and the "data-" attribute is valid html5.
For the loadScript instruction I may do something like this in my ascx or aspx:
```
<%= Html.ServerData("loadScript", new { url: "pathTo.js" }) %>
```
Or add another helper to do this which looks a little cleaner:
```
<%= Html.LoadScript("~/path/to.js") %>
```
The html output would be:
```
<div name="loadScript" data-server="encoded json string">
```
Then I have a jQuery method that can find any server data tag:
$(containingElement).serverData("loadScript"); // returns a jQuery like array of the decoded json objects.
The client may look something like this:
```
var script = $(containingelement").serverData("loadScript");
$.getScript(script.url, function () {
// script has been loaded - can do stuff with it now
});
```
This technique is great for user controls or scripts that need to be loaded within ajax loaded content. The version I wrote is a little more involved handling caching scripts so they load only once per full page load and contain callbacks and jQuery triggers so you can hook into it when it is ready.
If anyone is interested in the full version of this (from MVC to jQuery extension) I would be happy to show off this technique in more detail. Otherwise - hopes it gives someone a new way of approaching this tricky problem. | Include JavaScript file in partial views | [
"",
"javascript",
"jquery",
"asp.net-mvc",
"partial-views",
""
] |
What kind of information should an Application Log ideally contain? How is it different from Error Log? | You are going to get a lot of different opinions for this question.....
Ultimately it should contain any information that you think is going to be relevant to your application. It should also contain information that will help you determine what is happening with the application. That is not to say it should contain errors, but could if you wanted to use it that way.
At a minimum I would suggest that you include:
* application start/stop time
* application name
* pass/fail information (if applicable)
Optional items would be:
* call processing (if not too intensive)
* errors if you decide to combine application and error logs
* messaging (if not too intensive)
One thing you want to keep in mind is that you do not want to be writing so much information to your logs that you impact your application performance. Also, want to make sure you don't grow your log files so large that you run out of disk space. | A true error log should really contain:
* The stack trace of where the error took place
* The local variables present at the point of error.
* A timestamp of when the error took place.
* Detail of the exception thrown (if it is an exception).
A general application log file, for tracking events, etc, should contain less internal information, and perhaps be more user friendly.
To be honest, the answer really depends on what software the log is for. | What should an Application Log ideally contain? | [
"",
"c#",
""
] |
Specifically, in relational database management systems, why do we need to know the data type of a column (more likely, the attribute of an object) at creation time?
To me, data types feel like an optimization, because one data point can be implemented in any number of ways. Wouldn't it be better to assign semantic roles and constraints to a data point and then have the engine internally examine and optimize which data type best serves the user?
I suspect this is where the heavy lifting is and why it's easier to just ask the user rather than to do the work.
What do you think? Where are we headed? Is this a realistic expectation? Or do I have a misguided assumption? | You're right: assigning a data type to a column is an implementation detail and has nothing to do with the set theory or calculus behind a database engine. As a theoretical model, a database ought to be "typeless" and able to store whatever we throw at it.
But we have to implement the database on a real computer with real constraints. It's not practical, from a performance standpoint, to have the computer dynamically try to figure out how to best store the data.
For example, let's say you have a table in which you store a few million integers. The computer could -- correctly -- figure out that it should store each datum as an integral value. But if you were to one day suddenly try to store a string in that table, should the database engine stop everything until it converts all the data to a more general string format?
Unfortunately, specifying a data type is a necessary evil. | The type expresses a desired constraint on the values of the column. | Why do we care about data types? | [
"",
"sql",
"database",
"theory",
""
] |
> **Possible Duplicate:**
> [How to determine the date one day prior to a given date in Java?](https://stackoverflow.com/questions/745443/how-to-determine-the-date-one-day-prior-to-a-given-date-in-java)
If I have a Java.Util.Date object, what is the best way to get an object representing the 24 hours in the past of it? | Using Java 1.6 [java.util.Calendar.add](http://java.sun.com/javase/6/docs/api/java/util/Calendar.html#add(int,%20int)):
```
public static Date subtractDay(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.getTime();
}
```
Others suggest using [Joda Time](http://joda-time.sourceforge.net/), which is currently [JSR 310](http://jcp.org/en/jsr/detail?id=310), and should later be included in Java itself. | The important thing to remember is that the Date class should represent any points in time whilst the Calendar class is used to manipulate those points in time. Last of all, SimpleDateFormat will represent them as Strings.
So, the best way is to use the Calendar class to calculate the new Date for you. This will ensure that any vagaries (Daylight Saving, Leap Years and the like) are accounted for.
I'm assuming that you don't really want to find '24 Hours previous' but actually do want a new Date instance representing 'this time yesterday' - either way, you can ask the Calendar instance for a Date 24Hours prior to another or 1 Day prior.
The Daylight savings is a great example. The UK 'sprang forward' on the 26th March 2009. So, 1 day prior to 3.00a.m. on the 26.Mar.2009 should yield 3.00a.m. 25.Mar.2009 but 24 Hrs prior will yield 2.00a.m.
```
public class DateTests extends TestCase {
private static String EXPECTED_SUMMER_TIME = "2009.Mar.29 03:00:00";
private static String EXPECTED_SUMMER_TIME_LESS_DAY = "2009.Mar.28 03:00:00";
private static String EXPECTED_SUMMER_TIME_LESS_24_HRS = "2009.Mar.28 02:00:00";
private static String EXPECTED_SUMMER_TIME_LESS_FURTHER_24_HRS = "2009.Mar.27 02:00:00";
public void testSubtractDayOr24Hours() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MMM.dd HH:mm:SS");
Calendar calendar = Calendar.getInstance();
// Create our reference date, 3.00 a.m. on the day the clocks go forward (they 'went' forward at 02.00)
calendar.clear();
calendar.set(2009, 2, 29, 3, 0);
Date summerTime = calendar.getTime(); // Sun Mar 29 03:00:00 BST 2009
String formattedSummerTime = formatter.format(summerTime);
calendar.add(Calendar.DAY_OF_MONTH, -1);
// Our reference date less 'a day'
Date summerTimeLessADay = calendar.getTime(); // Sat Mar 28 03:00:00 GMT 2009
String formattedSummerTimeLessADay = formatter.format(summerTimeLessADay);
// reset the calendar instance to the reference day
calendar.setTime(summerTime);
// Our reference date less '24 hours' (is not quite 24 hours)
calendar.add(Calendar.HOUR, -24);
Date summerTimeLess24Hrs = calendar.getTime(); // Sat Mar 28 02:00:00 GMT 2009
String formattedSummerTimeLess24Hrs = formatter.format(summerTimeLess24Hrs);
// Third date shows that taking a further 24 hours from yields expected result
calendar.add(Calendar.HOUR, -24);
Date summerTimeLessFurther24Hrs = calendar.getTime(); // Fri Mar 27 02:00:00 GMT 2009
String formattedSummerTimeLessFurther24Hrs = formatter.format(summerTimeLessFurther24Hrs);
// reset the calendar once more to the day before
calendar.setTime(summerTimeLess24Hrs);
// Take a 'day' from the Sat will yield the same result as date 03 because Daylight Saving is not a factor
calendar.add(Calendar.DAY_OF_MONTH, -1);
Date summerTimeLessFurtherDay = calendar.getTime(); // Fri Mar 27 02:00:00 GMT 2009
String formattedSummerTimeLessFurtherDay = formatter.format(summerTimeLessFurtherDay);
assert(formattedSummerTime.equals(EXPECTED_SUMMER_TIME));
assert(formattedSummerTimeLessADay.equals(EXPECTED_SUMMER_TIME_LESS_DAY));
assert(formattedSummerTimeLess24Hrs.equals(EXPECTED_SUMMER_TIME_LESS_24_HRS));
assert(formattedSummerTimeLessFurther24Hrs.equals(EXPECTED_SUMMER_TIME_LESS_FURTHER_24_HRS));
// This last test proves that taking 24 hors vs. A Day usually yields the same result
assert(formattedSummerTimeLessFurther24Hrs.equals(formattedSummerTimeLessFurtherDay));
}
}
```
For testing date functions, wwwdot-timeanddate-dot-com is a great resource. | Get Previous Day | [
"",
"java",
"datetime",
"date",
""
] |
If gathering requirements for a medium-to-large web-based project, at what point should one consider using Java-based back-end, JSP, etc, over a scripting language like PHP, Python, or Ruby?
Hearing "use the right tool...", when is Java the right tool for web-based projects? | What is the "Best" language is often degrades to an emotional debate rather than practical. Champions of each language are extremely good at making arguments for why each language is the best. I ususally look ata couple of factors:
A) What languages are you and your team confortable with?
B) Is there an existing application/system to be extended or integrated? If so, what languages are most effective for such an integration
C) Are there built in or redily available libararies, components, etc that will allow you to more effectively produce results in one language over another
My decisions almost always boil down to what language/platform is my team going to be most effective on both developming and maintaining. | In my opinion, the language decision cannot be made independently of the larger development and runtime platform. This is implied by [what James Conigliaro wrote](https://stackoverflow.com/questions/967137/web-when-should-i-consider-using-java-rather-than-php-python-django-ruby-rails/967166#967166), and also by [what jonnii wrote](https://stackoverflow.com/questions/967137/web-when-should-i-consider-using-java-rather-than-php-python-django-ruby-rails/967151#967151), but neither called it out specifically.
Making such a decision, people often use unwarranted relative weightings for different evaluation criteria. For example, one of the criteria might be "runs on iPhone." But if you are not actually developing on an iPhone, you really don't care.
"Performance" is another criterion that can get an unwarranted weighting. Most Intel-based servers today, costing let's say $2000 without storage, are plenty fast to support a fairly high-volume web site regardless of your choice of language. If your load exceeds that which can be run on a single server (don't assume!), or if you need to share the server among different workloads, then perf may become more important. But generally your app load will fit in a 1-server box.
The development environment, including the IDE but also the source code control, the configuration management, and defect tracking - I guess what you might call application lifecycle stuff - is more important, in my opinion, than the language per se.
Another aspect you may wish to consider is, the "pull" the language itself will have on devs for your team. In the early days of Java, you could attract devs just by saying "we're doing it in Java." Now, that phenomenon has largely faded for Java, but in pockets it may still be true for other langs and platforms. This factor may or may not be important to you. | Web: When should I consider using Java rather than PHP, Python/Django, Ruby/Rails, etc? | [
"",
"java",
""
] |
Is there a way to get a value of a local variable specified by its name dynamically in SQL Server SP?
```
declare @foo int
declare @bar int
declare @variable_name varchar(10)
set @variable_name = '@foo'
print -- magic happens here - how to print the value of the variable
-- which name is stored in @variable_name, in this case @foo
```
*eval* won't help since it does not have access to local variables of the enclosing scope.
I'm doing this for debugging/diagnostics purposes mostly. | AFAIK, no: there is no **direct** way of doing this on SQL Server. | Technically this is possible by passing all local variables to sp\_executesql:
```
declare @foo int
declare @bar int
declare @variable_name varchar(10)
set @variable_name = '@foo'
set @foo = 1;
set @bar = 2;
declare @sql nvarchar(max);
set @sql = N'SELECT ' + @variable_name;
exec sp_executesql @sql, N'@foo int, @bar int', @foo, @bar
```
Of course this would be quite hard to maintain in real life, the call to sp\_executesql would have to be constantly kept up to date with the local variables on the current frame (batch or procedure call). While this is somewhat 'generic', is hardly any better than using a big CASE with all local variable names. | Get a value of a variable dynamically in SQL Server SP | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
Say, I need to run a bunch of code that is prone to crash so I need to run it on a different process. Typically I'd do it like this:
```
pid = fork();
if (pid == -1) {
std::cout << "Cant Spawn New Thread";
exit(0);
} else if (pid == 0) {
std::cout << "Im a child that will crash\n";
char *foo = (char *) 0xffff;
std::cout << foo;
exit(0);
} else {
std::cout << "PID: " << pid << "\n";
}
do {
std::cout << "Waiting for " << pid << " to finish .. \n";
pid_w = waitpid(pid,&status,0);
} while (pid_w == -1);
```
Obviously I can just use fork in my Qt4 application but I'm wondering if can I archive same functionality with any anything that Qt4 provides or any portable manner without resorting to having bunch of architecture `#ifdefs` ?
In any case, I'm targeting this app to have only `pthread` implementation but I'd still like to keep things as much close to "native" Qt API as possible.
I've tested `QThread`, and segfaulting in thread crashes the whole application obviously and it seems that `QProcess` is only targetted to be used when spawning completely different executables. Any other alternatives ? | Windows flat-out doesn't have fork() in any publicly consumable way, so there's no Qt call to emulate it; you'll need to do something like start yourself with special command-line params or something. | I think you should go with [QtConcurrent](http://doc.qtsoftware.com/4.5/threads.html#qtconcurrent) as it's the most high-level API for multithreaded programming available in Qt. This way your code will be more simple and cleaner.
As this is a high-level API it's probably implemented on top of lower-level APIs you already tried so this probably may not solve your problem, however. | Portable way to "fork()" in Qt4 application? | [
"",
"c++",
"qt",
"qt4",
"fork",
""
] |
I'd like to serialize Python objects to and from the plist format (this can be done with plistlib). My idea was to write a class PlistObject which wraps other objects:
```
def __init__(self, anObject):
self.theObject = anObject
```
and provides a "write" method:
```
def write(self, pathOrFile):
plistlib.writeToPlist(self.theObject.__dict__, pathOrFile)
```
Now it would be nice if the PlistObject behaved just like wrapped object itself, meaning that all attributes and methods are somehow "forwarded" to the wrapped object. I realize that the methods `__getattr__` and `__setattr__` can be used for complex attribute operations:
```
def __getattr__(self, name):
return self.theObject.__getattr__(name)
```
But then of course I run into the problem that the constructor now produces an infinite recursion, since also `self.theObject = anObject` tries to access the wrapped object.
How can I avoid this? If the whole idea seems like a bad one, tell me too. | > But then of course I run into the problem that the constructor now produces an infinite recursion, since also self.theObject = anObject tries to access the wrapped object.
That's why the manual suggests that you do this for all "real" attribute accesses.
```
theobj = object.__getattribute__(self, "theObject")
``` | Unless I'm missing something, this will work just fine:
```
def __getattr__(self, name):
return getattr(self.theObject, name)
```
---
**Edit:** for those thinking that the lookup of `self.theObject` will result in an infinite recursive call to `__getattr__`, let me show you:
```
>>> class Test:
... a = "a"
... def __init__(self):
... self.b = "b"
... def __getattr__(self, name):
... return 'Custom: %s' % name
...
>>> Test.a
'a'
>>> Test().a
'a'
>>> Test().b
'b'
>>> Test().c
'Custom: c'
```
`__getattr__` is only called as a [last](http://docs.python.org/reference/datamodel.html#object.__getattr__) [resort](http://docs.python.org/3.0/reference/datamodel.html?highlight=__getattr__#object.__getattr__). Since `theObject` can be found in `__dict__`, no issues arise. | Wrapping a Python Object | [
"",
"python",
""
] |
How do you group your class members inside the class? When you add a new method to a class, do you add them to where it should be alphabetically for instance?
Do you use regions? I use them along with the groups created by Visual Studio's interface implementation stub generator, like:
```
#region IEnumerable
...
#endregion
```
I use region names like "Properties", etc, but some members prove to be a little more tricky to group/organize.
How do you deal with this? | I personally follow the ordering rules put forth by [StyleCop](http://code.msdn.microsoft.com/sourceanalysis) in this. It's very strict on the order of your methods/properties/events/etc.
I don't necessarily believe that it has the "best" rules, but I still follow it, mostly because it's a good tool to guarantee consistency. I'd prefer my code to always be consistent rather than to always fit some ideal that I would dream up - especially since I have multiple programmers, and an external tool helps enforce the rules solution-wide. | Maybe this is overly strict, but I'd think that if you have so many class members that you're worried about how to group them to maintain readability, you should probably break your classes up into smaller ones with fewer members.
Besides that, I just use common sense; similar methods or methods that call each other are grouped together, constructors are grouped together, properties are grouped together, public things are on top, things that people are almost never going to need to look at are on bottom. | Guidelines for internal class member grouping | [
"",
"c#",
".net",
""
] |
I have written a jQuery plugin, but I want it to check if jQuery has been loaded, if not then load it, as well as a couple of other javascript files and also check if CSS file has been loaded, if not then load it.
Am wondering how to go about it?
thank you very much for your time. | ## To detect if CSS is loaded
Add this to your CSS:
```
._css_loaded_test {
display: none;
}
```
Define this JavaScript function:
```
function cssIsLoaded() {
var test = document.createElement("div");
test.className = "_css_loaded_test";
return getComputedStyle(test, null).display === "none";
}
```
## To detect if jQuery is loaded
Use this JavaScript to detect if jQuery is loaded:
```
if (typeof jQuery !== "undefined") {
// put your code here
}
``` | Your plugin, unless it is comparable to jQuery in size and complexity, should probably not be loading jQuery. I think simply checking if jQuery is present, and throwing a warning if it is absent is sufficient for any developers to understand what is happening.
I suppose you could be working on a plugin that people will often include without 'knowing' if they have jQuery or not. | Javascript/CSS load and append to document | [
"",
"javascript",
"jquery",
""
] |
Is there a simple way to run a Python script on Windows/Linux/OS X?
On the latter two, `subprocess.Popen("/the/script.py")` works, but on Windows I get the following error:
```
Traceback (most recent call last):
File "test_functional.py", line 91, in test_functional
log = tvnamerifiy(tmp)
File "test_functional.py", line 49, in tvnamerifiy
stdout = PIPE
File "C:\Python26\lib\subprocess.py", line 595, in __init__
errread, errwrite)
File "C:\Python26\lib\subprocess.py", line 804, in _execute_child
startupinfo)
WindowsError: [Error 193] %1 is not a valid Win32 application
```
---
> *[monkut's](https://stackoverflow.com/users/24718/monkut) comment*: The use case isn't clear. Why use subprocess to run a python script? Is there something preventing you from importing the script and calling the necessary function?
I was writing a quick script to test the overall functionality of a Python-command-line tool (to test it on various platforms). Basically it had to create a bunch of files in a temp folder, run the script on this and check the files were renamed correctly.
I could have imported the script and called the function, but since it relies on `sys.argv` and uses `sys.exit()`, I would have needed to do something like..
```
import sys
import tvnamer
sys.argv.append("-b", "/the/folder")
try:
tvnamer.main()
except BaseException, errormsg:
print type(errormsg)
```
Also, I wanted to capture the stdout and stderr for debugging incase something went wrong.
Of course a better way would be to write the script in more unit-testable way, but the script is basically "done" and I'm doing a final batch of testing before doing a "1.0" release (after which I'm going to do a rewrite/restructure, which will be far tidier and more testable)
Basically, it was much easier to simply run the script as a process, after finding the `sys.executable` variable. I would have written it as a shell-script, but that wouldn't have been cross-platform. The final script can be found [here](http://github.com/dbr/tvdb_api/blob/c8d7b356cd1a7bb2ab22b510ea74e03a7d27fad6/tests/test_functional.py) | Just found [`sys.executable`](https://docs.python.org/library/sys.html#sys.executable) - the full path to the current Python executable, which can be used to run the script (instead of relying on the shbang, which obviously doesn't work on Windows)
```
import sys
import subprocess
theproc = subprocess.Popen([sys.executable, "myscript.py"])
theproc.communicate()
``` | How about this:
```
import sys
import subprocess
theproc = subprocess.Popen("myscript.py", shell = True)
theproc.communicate() # ^^^^^^^^^^^^
```
This tells `subprocess` to use the OS shell to open your script, and works on anything that you can just run in cmd.exe.
Additionally, this will search the PATH for "myscript.py" - which could be desirable. | Using subprocess to run Python script on Windows | [
"",
"python",
"windows",
"subprocess",
""
] |
I've seen a lot of discussion on here about copy protection. I am more interested in anti-reversing and IP protection.
There are solutions such as Safenet and HASP that claim to encrypt the binary, but are these protected from reversing when used with a valid key?
What kinds of strategies can be used to obfuscate code and throw off reversers? Are there any decent commercial implementations out there?
I know most protection schemes can be cracked, but the goal here is to delay the ability to reverse the software in question, and make it much more blatant if another company tries to implement these methods. | > There are solutions such as Safenet and HASP that claim to encrypt the binary, but are these protected from reversing when used with a valid key?
No. A dedicated reverse engineer can decrypt it, because the operating system has to be able to decrypt it in order to run it.
Personally, I wouldn't worry. Admittedly I don't know anything about your business, but it seems to me that reverse engineering C++ is relatively difficult compared to languages like Java or .NET. That will be enough protection to see off all but the most determined attackers.
However, a determined attacker will always be able to get past whatever you implement, because at some point it has to be turned into a bunch of CPU instructions and executed. You can't prevent them from reading that.
But that's a *lot* of effort for a non-trivial program. It seems a lot more likely to me that somebody might just create a competitor after seeing your program in action (or even just from your marketing material). It's probably easier than trying to reverse engineer yours, and avoids any potential legal issues. That isn't something you can (or should) prevent. | hire some of the people I've worked with over the years, they will completely obfuscate the source code! | C++ Intellectual Property Protection/Anti-Reversing | [
"",
"c++",
"obfuscation",
"copy-protection",
""
] |
I am wondering how immutability is defined? If the values aren't exposed as public, so can't be modified, then it's enough?
Can the values be modified inside the type, not by the customer of the type?
Or can one only set them inside a constructor? If so, in the cases of double initialization (using the `this` keyword on structs, etc) is still ok for immutable types?
How can I guarantee that the type is 100% immutable? | > If the values aren't exposed as public, so can't be modified, then it's enough?
No, because you need read access.
> Can the values be modified inside the type, not by the customer of the type?
No, because that's still mutation.
> Or can one only set them inside a constructor?
Ding ding ding! With the additional point that immutable types often have methods that construct and return new instances, and also often have extra constructors marked `internal` specifically for use by those methods.
> How can I guarantee that the type is 100% immutable?
In .Net it's tricky to get a guarantee like this, because you can use reflection to modify (mutate) private members. | The previous posters have already stated that you should assign values to your fields in the constructor and then keep your hands off them. But that is sometimes easier said than done. Let's say that your immutable object exposes a property of the type `List<string>`. Is that list allowed to change? And if not, how will you control it?
Eric Lippert has written a series of posts in his blog about immutability in C# that you might find interesting: [you find the first part here](http://blogs.msdn.com/ericlippert/archive/2007/11/13/immutability-in-c-part-one-kinds-of-immutability.aspx). | The true definition of immutability? | [
"",
"c#",
".net",
"immutability",
""
] |
I have a class "Address" that has the following check:
```
if(thisAddress == null)
thisAddress = new Address();
```
When the code is run I get "Index was outside the bounds of the array" on the first line. If I remove the IF statement I get the error on the second line.
The class comes from Linq to SQL, but I have extended it. This worked before, I'm not sure why it started happening all of a sudden. thisAddress is a private variable in a UserControl.
Any ideas? | Figured it out. Apparently I left out a crucial piece of information. The code is inside the get {} section for a control property. The error was a different line in the code (where I was using a split()), but the debugger pointed to the first line of the get{} statement. | The code is not in sync with the binary.
Try recompiling the assembly that contains the usercontrol.
Has anything changed in the DB that you think can break the LINQ to SQL mapping? | "Index was outside the bounds of the array" when checking non-array variable | [
"",
"c#",
""
] |
Can someone tell me how to get the name of the child page being called in a Master page scenario. For example, if I have the following masterpage:
```
<%@ Master Language="VB" CodeFile="MasterPage.master.vb" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<asp:ContentPlaceHolder ID="cphMainContent" runat="server">
</asp:ContentPlaceHolder>
</body>
</html>
```
And I create a page called Test.aspx which inherits this masterpage, how can I, from the masterpage, know that Test.aspx has been requested (since this masterpage can be inherited by more then 1 aspx page)? | Going with your comments, I see a couple of options:
1) In your login page, on a non-postback, check the Referrer - this will be the page that sent you to the login page ([Request.UrlReferrer](http://msdn.microsoft.com/en-us/library/system.web.httprequest.urlreferrer.aspx)), store that in session for the postback of their login details, and then send the user back.
2) Use the [standard features of ASP.NET](http://msdn.microsoft.com/en-us/library/879kf95c.aspx) to handle login/redirections (which basically use the same system as 1). | This is a [similar question](https://stackoverflow.com/questions/269050/c-asp-net-how-to-determine-which-child-page-is-being-displayed-from-master-page) to what you're asking, but I would pay attention to the accepted answer, trying to figure out the child page from the master page is probably not a good design idea. | Master pages -- Getting calling page name | [
"",
"c#",
"asp.net",
"vb.net",
"master-pages",
""
] |
In C# the concept of Multidimension arrays are pretty cool. But I don't understand when to use them. Like in what type of applications does this concept is used. | Not to sound trite but you use multidimensional arrays when you have multidimensional data.
Matrices are a common example but it could just as easily be a game board (eg Chess) or as the data model for an N-dimensional maze or a tally or anything really. | One common use is matrices. | When to use Multidimension arrays | [
"",
"c#",
".net",
""
] |
My URLs look like "/pages.php?page=pageName" because I am using a database to supply the page's content. Does rewriting URLs to something like "/pageName" help search engines find the pages? If so how do I rewrite them? | It probably doesn't help a crawler to find the pages, but it may have a positive impact in how it's going to rank them, as better URIs get usually better ranking (other things being equal, of course). It's also good to have them permanent.
See [Cool URIs don't change](http://www.w3.org/Provider/Style/URI)
About how you have [mod\_rewrite](http://httpd.apache.org/docs/2.0/misc/rewriteguide.html) in Apache world and some [other](http://www.micronovae.com/ModRewrite/ModRewrite.html) [options](http://www.isapirewrite.com/) in IIS world.
Example (Apache's syntax):
```
RewriteEngine On
RewriteRule ^(.*)$ pages.php?page=$1
```
That will pass everything in the URI after the domain name (there's a caveat regarding the trailing slash) to pages.php as a page parameter.
This is
```
http://yourdomain.com/bears
```
will return the content as served by
```
http://yourdomain.com/pages.php?page=bears
``` | Maybe a better question is "Does rewriting a URL help **a user** find the page in a search engine?". And the answer to this is "yes". For example, let's say that the content of your page discusses dolphins. Google puts more weight for the search term "Dolphins" into:
```
/Dolphins.php
```
than
```
/pages.php?page=1323
```
You'll find this is what most modern websites are doing (including stackoverflow). | Does rewriting a URL help a search engine find the page? | [
"",
"php",
"url",
"seo",
"search-engine",
"url-rewriting",
""
] |
We're developing a .NET 3.5 Windows Forms app, using LINQ to SQL and MVP. We have a DataRepository class for retrieving data:
```
public class DbUserRepository : IUserRepository
{
private IList<UserName> _users;
public IList<UserName> GetUserNames()
{
if (_users == null)
{
// retrieve _users from DB
}
return _users;
}
```
In order to cache the list of users across all instances of the DBUserRepository, we were going to use the Enterprise Library's Caching Application Block.
But it occured to me, couldn't I just make \_users a static member? For some reason that seems like an "old school" way, but it works. Are there any downsides to doing this? Is this considered bad design?
```
private static IList<UserName> _users;
```
Thanks | The biggest down-side to doing this is exactly due to what `static` means; although you can have many `DbUserRepository` objects, they will always only share one `_users` variable. Cases where this causes problems:
* If your app ever becomes multi-threaded, and you want each thread to have its own distinct user repository (whether or not this is a concern depends on what the repository means in the context of your system)
* Unit testing the `DbUserRepository` class becomes trickier, because if you run multiple unit tests on this class, they will carry state along with them from test to test, meaning that the test-run becomes order dependent... which is pretty undesirable | for simple caching I think static variable is fine, just need to be a bit careful about using locks to protect multiple threads accessing the \_users variable. However, a better approach might be using ASP.NET Cache class. I know it is in the System.Web namespace but you can [use it outside of ASP.NET application too](http://www.hanselman.com/blog/UsingTheASPNETCacheOutsideOfASPNET.aspx). | Using a static variable to cache data | [
"",
"c#",
""
] |
I have an abstract class with an abstract property that is set to have both Get and Set. I know I'll always want to be able to **get** this property from derived classes but there are some cases where it doesn't make sense to **set** this property in certain types of derived classes.
I can't just omit the Set accessor in a derived class (see code example below). I could override the set accessor in a derived classes to do nothing with the values passed by the user. But is there another way that actually make the property in a specific derived class read only? Ultimately I'm displaying these properties in a property grid and I don't want the user to be entering values into a field that is going to do nothing. Maybe I just attribute the property as read only in specific derived classes?
Also I'd really really rather not mess with any of the type descriptor stuff to get properties to display correctly in a property grid, such as overriding ICustomTypeDescriptor.
```
public abstract class MyClass
{
public abstract string MyProperty
{
get;
set;
}
}
public abstract class MyDerivedClass
{
public override string MyProperty
{
//VS complains that the Set accessor is missing
get;
}
}
``` | You should not do this. What you are saying by defining your getter and setter in the abstract class is "you must implement this if you want to inherit from me." Then you are asking, "how can I made a derived class ignore this rule."
The answer is that if you have a situation that every derived class needs a getter, put that in the abstract class and let the derived class decide if they will implement a setter or not by leaving it out of the abstract class.
Or alternatively, you can create two more classes that derive from the initial abstract class, one that implement the setter and one that does not and then have your derived class generalize the one of those that makes sense, but that is overkill I think. | You should use `abstract` not `override`:
```
public abstract class MyClass
{
public abstract string MyProperty
{
get;
set;
}
}
public abstract class MyDerivedClass
{
public abstract string MyProperty
{
get;
}
}
```
but like @JP wrote, you shouldn't do this. | Accessibility of abstract properties | [
"",
"c#",
"properties",
"abstract",
""
] |
I haven't done C++ in a while and can't figure out why following doesn't work:
```
class A {
protected:
int num;
};
class B : public A {
};
main () {
B * bclass = new B ();
bclass->num = 1;
}
```
Compiling this produces:
> error C2248: 'A::num' : cannot access protected member declared in class 'A'
Shouldn't protected members be accessible by derived classes?
What am I missing? | yes protected members are accessible by derived classes but you are accessing it in the main() function, which is outside the hierarchy. If you declare a method in the class B and access num it will be fine. | Yes, protected members are accessible by the derived class, but only from within the class.
example:
```
#include <iostream>
class A {
protected:
int num;
};
class B : public A { public:
void printNum(){
std::cout << num << std::endl;
}
};
main () {
B * bclass = new B ();
bclass->printNum();
}
```
will print out the value of `num`, but `num` is accessed from within class `B`. `num` would have to be declared public to be able to access it as `bclass->num`. | Why can't I access a protected member from an instance of a derived class? | [
"",
"c++",
"inheritance",
""
] |
Let us say I have a textbox or any other form of input that asks for a social security number. I do want to note that the SSN is a pure example I simply thought of as of right now.
This input will naturally be stored as a string initially.
```
string s = Console.ReadLine();
```
Let us say I want to have a method that validates an SSN and it might be used throughout my code in all sorts of places. Heck, I might even call the method on a variable which has not been determined by user-input.
Is this acceptable?
```
public bool IsValidSSN(Object SSN)
{
int mySSN;
if(Int.Parse(SSN == false)
{
mySSN = Convert.toInt32(SSN);
}
...
}
```
Or would you guy **insist** that I ask for a specific datatype, e.g
```
public bool IsValidSSN(int SSN)
{
...
}
```
and therefor I am required to convert the input to the correct datatype BEFORE I call the method on it.
BTW: I am not asking how to do a proper IsValidSSN code :) I just wanted to give an example of what I meant when I said: Can I accept the Object datatype as a parameter or should I try to avoid it? | If you must accept an object I would at least have overloads of the method which take strongly typed parameters. Then have the object variants feed into these methods.
```
public bool IsValidSSN(object ssn) {
...
IsValidSSN(Convert.ToInt32(ssn));
...
}
public bool IsValidSSN(int ssn) {
...
}
``` | It COMPLETELY depends on your design and where you want your validation to occur. It really fundamentally depends upon your overall architecture and your class hierarchy. It's not wrong to do it either way; just be sure that it's the way that fits with your architectural design. | Is accepting Object as a parameter acceptable? | [
"",
"c#",
"type-conversion",
"conventions",
""
] |
Here is a seemingly simple problem: given a list of iterators that yield sequences of integers in ascending order, write a concise generator that yields only the integers that appear in every sequence.
After reading a few papers last night, I decided to hack up a completely minimal full text indexer in Python, [as seen here](http://code.google.com/p/ghetto-fts/) (though that version is quite old now).
My problem is with the `search()` function, which must iterate over each posting list and yield only the document IDs that appear on every list. As you can see from the link above, my current non-recursive 'working' attempt is terrible.
**Example**:
```
postings = [[1, 100, 142, 322, 12312],
[2, 100, 101, 322, 1221],
[100, 142, 322, 956, 1222]]
```
Should yield:
```
[100, 322]
```
There is at least one elegant recursive function solution to this, but I'd like to avoid that if possible. However, a solution involving nested generator expressions, `itertools` abuse, or any other kind of code golf is more than welcome. :-)
It should be possible to arrange for the function to only require as many steps as there are items in the smallest list, and without sucking the entire set of integers into memory. In future, these lists may be read from disk, and larger than available RAM.
For the past 30 minutes I've had an idea on the tip of my tongue, but I can't quite get it into code. Remember, this is just for fun! | ```
import heapq, itertools
def intersect(*its):
for key, values in itertools.groupby(heapq.merge(*its)):
if len(list(values)) == len(its):
yield key
>>> list(intersect(*postings))
[100, 322]
``` | ```
def postings(posts):
sets = (set(l) for l in posts)
return sorted(reduce(set.intersection, sets))
```
... you could try and take advantage of the fact that the lists are ordered, but since reduce, generator expressions and set are all implemented in C, you'll probably have a hard time doing better than the above with logic implemented in python. | Joining a set of ordered-integer yielding Python iterators | [
"",
"python",
"join",
"code-golf",
"iterator",
"generator",
""
] |
When I use `current_timestamp` with MySQL, I get the correct time, but when I use
`$mysqldate = date( 'Y-m-d H:i:s' );`
I get the date with with an hour delay (eg, 4:42 PM is 5:42 PM).
I understood that both function use the server's local time - can someone explain the difference?
Thanks. | The global system time will be set via the /etc/localtime file, which will be either a symlink or a copy of a zone file from /usr/share/zoneinfo/ on most systems. Applications will use this as their default.
PHP can override this in a couple different ways:
1. [date.timezone](https://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone) in php.ini
2. setting the TZ environment variable, e.g. `putenv("TZ=US/Central");`
3. [date\_default\_timezone\_set](https://www.php.net/manual/en/function.date-default-timezone-set.php) function (in PHP >= 5.1.0)
MySQL can override this by running the following query immediately after connecting:
```
SET time_zone = 'US/Central'
``` | There are php locale settings, it takes it from php.ini, not from system time | mysql time and php time not the same | [
"",
"php",
"mysql",
"datetime",
""
] |
Take the code below, adapted from [this question](https://stackoverflow.com/questions/652742/linq-caveats/652749#652749):
```
//Borrowed from another question because its a simpler example of what happened to me.
IEnumerable<char> query = "Not what you might expect";
foreach(char vowel in "aeiou")
{
query = query.Where(c => c != vowel);
}
foreach (char Output in query)
{
System.Out.WriteLine(Output);
}
```
This only removes the 'u' from the query char collection. The core issue has something to do with the fact that the `c` variable in the `Where` clause isn't evaluated until the second foreach. My question is:
1) Why would the delegate generated by the first foreach not capture each value of `c` as it is built up? Is there some situation I'm unaware of where that is not the desired behavior?
2) If its not capturing the value of `c`, how is that value even still in scope in the second foreach when the query is actually run? It would seem to me that if its not storing the values of the variables being passed in, then trying to resolve the statement for the second foreach would fail because the the variable `c` is clearly out of scope.
I don't understand how it is that 'use the last value we saw on this variable back when it was in scope' was a good design decision for this circumstance, and was hoping someone could shed some light on the subject. | It is capturing `vowel`; try:
```
foreach(char vowel in "aeiou") {
char tmp = vowel;
query = query.Where(c => c != tmp);
}
```
Jon has a list of related posts [here](https://stackoverflow.com/questions/295593#295597).
As for why... `foreach` is defined (in ECMA 334v4 §15.8.4) as:
```
A foreach statement of the form `foreach (V v in x) embedded-statement` is then expanded to:
{
E e = ((C)(x)).GetEnumerator();
try {
V v;
while (e.MoveNext()) {
v = (V)(T)e.Current;
embedded-statement
}
}
finally {
… // Dispose e
}
}
```
Note the `V` is **outside** the `while` - this means it is captured **once only** for the `foreach`. I gather that the C# team have, at times, doubted the wisdom of this change (it was **inside** the `while` in the C# 1.2 spec, which would have avoided the problem completely). Maybe it'll change back eventually, but for now it is being true to the specification. | As Marc says, it's capturing `vowel` as a variable, rather than the value of `vowel` in each case. This is almost always undesirable, but it *is* the specified behaviour (i.e. the compiler is following the language spec). There's a single vowel variable, rather than a "new variable instance" per iteration.
Note that there's no expression tree involved here - you're using `IEnumerable<T>` so it's just converting the lambda expression into a delegate.
See section 7.14.4 of the C# 3 spec for more information. | Why doesn't deferred execution cache iterative values? | [
"",
"c#",
".net",
"linq",
"language-design",
""
] |
is there a way to find out from within a python program if it was started in a terminal or e.g. in a batch engine like sun grid engine?
the idea is to decide on printing some progress bars and other ascii-interactive stuff, or not.
thanks!
p. | The standard way is `isatty()`.
```
import sys
if sys.stdout.isatty():
print("Interactive")
else:
print("Non-interactive")
``` | You can use `os.getppid()` to find out the process id for the parent-process of this one, and then use that process id to determine which program that process is running. More usefully, you could use `sys.stdout.isatty()` -- that doesn't answer your title question but appears to better solve the actual problem you explain (if you're running under a shell but your output is piped to some other process or redirected to a file you probably don't want to emit "interactive stuff" on it either). | python: find out if running in shell or not (e.g. sun grid engine queue) | [
"",
"python",
"shell",
"terminal",
"stdout",
""
] |
Is it possible to use the JQuery Slider (range slider / dual slider) to have non-linear (non consistent "step" size) values?
I want to horizontal Slider to look like:
```
|----|----|----|----|----|--------|--------|-------------------------|--------------------------|...
0 500 750 1000 1250 1500 2000 2500 75000 100000...
```
For example, I want to have the following JQuery code:
```
var values = [0, 500, 750, 1000, 1250, 1500, 2000, 2500, 75000, 100000, 150000, 200000, 250000, 300000, 350000, 400000, 500000, 1000000];
var slider = $("#price-range").slider({
orientation: 'horizontal',
range: true,
min: 0,
max: 1000000,
values: [0, 1000000],
slide: function(event, ui) {
var includeLeft = event.keyCode != $.ui.keyCode.RIGHT;
var includeRight = event.keyCode != $.ui.keyCode.LEFT;
slider.slider('option', 'value', findNearest(includeLeft, includeRight, ui.value));
$("#price-amount").html('$' + ui.values[0] + ' - $' + ui.values[1]);
return false;
},
change: function(event, ui) {
getHomeListings();
}
});
function findNearest(includeLeft, includeRight, value) {
var nearest = null;
var diff = null;
for (var i = 0; i < values.length; i++) {
if ((includeLeft && values[i] <= value) || (includeRight && values[i] >= value)) {
var newDiff = Math.abs(value - values[i]);
if (diff == null || newDiff < diff) {
nearest = values[i];
diff = newDiff;
}
}
}
return nearest;
}
```
The code above is not exactly working but the snap to grid functionality doesn't work. | Not sure if you want the slider scale to be in proportion to your values\* but if so, I provided a solution to this for someone else who asked the same question. [You can find my solution here](https://stackoverflow.com/questions/681303/is-there-a-plugin-or-example-of-a-jquery-slider-working-with-non-equably-divisibl). Basically I make use of the `slide` event that gets triggered when you move the slider to mimic the stepping, but based off a custom array defining the steps. This way it only allows you to "step" to your predefined values, even if they're not evenly spread.
\*In other words if you want your slider to look like this:
```
|----|----|----|----|----|----|----|
0 10 20 100 1000 2000 10000 20000
```
then go with one of the other solutions here, but if you want your slider to look like this (diagram not to scale):
```
|--|--|-------|-----------|-----------|--------------------|--------------------|
0 10 20 100 1000 2000 10000 20000
```
Then the solution I linked to may be more what you're after.
---
**Edit:** Ok, this version of the script should work with dual sliders:
```
$(function() {
var values = [0, 500, 750, 1000, 1250, 1500, 2000, 2500, 75000, 100000, 150000, 200000, 250000, 300000, 350000, 400000, 500000, 1000000];
var slider = $("#price-range").slider({
orientation: 'horizontal',
range: true,
min: 0,
max: 1000000,
values: [0, 1000000],
slide: function(event, ui) {
var includeLeft = event.keyCode != $.ui.keyCode.RIGHT;
var includeRight = event.keyCode != $.ui.keyCode.LEFT;
var value = findNearest(includeLeft, includeRight, ui.value);
if (ui.value == ui.values[0]) {
slider.slider('values', 0, value);
}
else {
slider.slider('values', 1, value);
}
$("#price-amount").html('$' + slider.slider('values', 0) + ' - $' + slider.slider('values', 1));
return false;
},
change: function(event, ui) {
getHomeListings();
}
});
function findNearest(includeLeft, includeRight, value) {
var nearest = null;
var diff = null;
for (var i = 0; i < values.length; i++) {
if ((includeLeft && values[i] <= value) || (includeRight && values[i] >= value)) {
var newDiff = Math.abs(value - values[i]);
if (diff == null || newDiff < diff) {
nearest = values[i];
diff = newDiff;
}
}
}
return nearest;
}
});
```
Note that it looks a little funny down the far left end, since the jumps are so close together compared to the right hand end, but you can see its stepping as desired if you use your keyboard arrows to move the slider. Only way to get around that is to change your scale to not be quite so drastically exponential.
---
**Edit 2:**
Ok, if the spacing is too exaggerated when you use the true values, you could use a set of fake values for the slider & then look up the real value this corresponds to when you need to use the real value (in a similar way to what the other solutions here suggested). Here's the code:
```
$(function() {
var trueValues = [0, 500, 750, 1000, 1250, 1500, 2000, 2500, 75000, 100000, 150000, 200000, 250000, 300000, 350000, 400000, 500000, 1000000];
var values = [0, 1, 2, 3, 4, 5, 6, 7, 10, 15, 20, 25, 30, 40, 50, 60, 75, 100];
var slider = $("#price-range").slider({
orientation: 'horizontal',
range: true,
min: 0,
max: 100,
values: [0, 100],
slide: function(event, ui) {
var includeLeft = event.keyCode != $.ui.keyCode.RIGHT;
var includeRight = event.keyCode != $.ui.keyCode.LEFT;
var value = findNearest(includeLeft, includeRight, ui.value);
if (ui.value == ui.values[0]) {
slider.slider('values', 0, value);
}
else {
slider.slider('values', 1, value);
}
$("#price-amount").html('$' + getRealValue(slider.slider('values', 0)) + ' - $' + getRealValue(slider.slider('values', 1)));
return false;
},
change: function(event, ui) {
getHomeListings();
}
});
function findNearest(includeLeft, includeRight, value) {
var nearest = null;
var diff = null;
for (var i = 0; i < values.length; i++) {
if ((includeLeft && values[i] <= value) || (includeRight && values[i] >= value)) {
var newDiff = Math.abs(value - values[i]);
if (diff == null || newDiff < diff) {
nearest = values[i];
diff = newDiff;
}
}
}
return nearest;
}
function getRealValue(sliderValue) {
for (var i = 0; i < values.length; i++) {
if (values[i] >= sliderValue) {
return trueValues[i];
}
}
return 0;
}
});
```
You can fiddle with the numbers in the `values` array (which represent the slider stop points) until you get them spaced out how you want. This way you can make it feel, from the user's perspective, like it's sliding proportionally to the values, but without being as exaggerated. Obviously if your true values are dynamically created, you may need to come up with an algorithm to generate the slider values instead of statically defining them... | HTML:
```
<body>
<p>
Slider Value: <span id="val"></span><br/>
Nonlinear Value: <span id="nlVal"></span><br/>
</p>
<div id="slider"></div>
</body>
```
JS:
```
$(function() {
var valMap = [0, 25,30,50,55,55,60,100];
$("#slider").slider({
// min: 0,
max: valMap.length - 1,
slide: function(event, ui) {
$("#val").text(ui.value);
$("#nlVal").text(valMap[ui.value]);
}
});
});
``` | JQuery Slider, how to make "step" size change | [
"",
"javascript",
"jquery",
"html",
"user-interface",
"slider",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.