Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Is there any way to register for an event that fires when an executable of a particular filename starts? I know it's easy enough to get an event when a process exits, by getting the process handle and registering for the exited event. But how can you be notified when a process, that isn't already running, starts...without polling all the running processes?
You could use the following: ``` private ManagementEventWatcher WatchForProcessStart(string processName) { string queryString = "SELECT TargetInstance" + " FROM __InstanceCreationEvent " + "WITHIN 10 " + " WHERE TargetInstance ISA 'Win32_Process' " + " AND TargetInstance.Name = '" + processName + "'"; // The dot in the scope means use the current machine string scope = @"\\.\root\CIMV2"; // Create a watcher and listen for events ManagementEventWatcher watcher = new ManagementEventWatcher(scope, queryString); watcher.EventArrived += ProcessStarted; watcher.Start(); return watcher; } private ManagementEventWatcher WatchForProcessEnd(string processName) { string queryString = "SELECT TargetInstance" + " FROM __InstanceDeletionEvent " + "WITHIN 10 " + " WHERE TargetInstance ISA 'Win32_Process' " + " AND TargetInstance.Name = '" + processName + "'"; // The dot in the scope means use the current machine string scope = @"\\.\root\CIMV2"; // Create a watcher and listen for events ManagementEventWatcher watcher = new ManagementEventWatcher(scope, queryString); watcher.EventArrived += ProcessEnded; watcher.Start(); return watcher; } private void ProcessEnded(object sender, EventArrivedEventArgs e) { ManagementBaseObject targetInstance = (ManagementBaseObject) e.NewEvent.Properties["TargetInstance"].Value; string processName = targetInstance.Properties["Name"].Value.ToString(); Console.WriteLine(String.Format("{0} process ended", processName)); } private void ProcessStarted(object sender, EventArrivedEventArgs e) { ManagementBaseObject targetInstance = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value; string processName = targetInstance.Properties["Name"].Value.ToString(); Console.WriteLine(String.Format("{0} process started", processName)); } ``` You would then call either WatchForProcessStart and/or WatchForProcessEnd passing in your process name (eg "notepad.exe"). The ManagementEventWatcher object is returned from the two Watch\* methods as it implements IDisposable and so you should call Dispose on these objects when you have finished with them to prevent issues. You could also change the polling value in the queries if you need the event to be raised more quickly after the process has started. To do this change the line "WITHIN 10" to be WITHIN something less than 10.
WMI can create events when processes are created. You could then filter these events.
.NET Events for Process executable start
[ "", "c#", ".net", "events", "process", "" ]
Since its possibly one of the most widely used methods of the Java language, why does it have to accept an array of Strings and doesn't work without it? For example, I could always live with: ``` public static void main() {} ``` over ``` public static void main(String[] args) {} ``` Is there a higher purpose to this than just being able to accept command-line arguments, especially since a vast majority of Java programs are GUI driven and don't need to receive args through command line?
even a gui driven java app will start with some main method. The "higher purpose" has never been to accept command line arguments. The purpose is just to accept arguments. Period. Whenever you start any program not just Java you will always need some syntax to pass arguments
I agree that it could be more flexible. In C# for instance, all of these are acceptable entry points: ``` static void Main() static void Main(string[] args) static int Main() static int Main(string[] args) ``` The versions returning `int` use the return value as the exit code for the process. If you don't care about receiving any arguments, you can use one of the versions which doesn't take any. Any arguments given when the program is launched are ignored. So yes, it *could* be more flexible - but it's never struck me as a significant problem in Java.
Why does Java main() method accept an array of String args?
[ "", "java", "programming-languages", "" ]
I want to find the successor of each element in my encoded string. For example K->M A->C etc. ``` string.each_char do |ch| dummy_string<< ch.succ.succ end ``` However this method translates y->aa. Is there a method in Ruby that is like maketrans() in Python?
You seem to be looking for [String#tr](http://ruby-doc.org/core/classes/String.html#M000845). Use like this: `some_string.tr('a-zA-Z', 'c-zabC-ZAB')`
``` def successor(s) s.tr('a-zA-Z','c-zabC-ZAB') end successor("Chris Doggett") #"Ejtku Fqiigvv" ```
Ruby String Translation
[ "", "python", "ruby", "string", "" ]
So, I have a class with an array inside. Currently, my strategy for enumerating over the class's items is to use the code, `foreach (item x in classInstance.InsideArray)` . I would much rather use `foreach (item x in classInstance)` and make the array private. My main concern is that I really need to avoid anything slow; the array gets hit a lot (and has a couple hundred items). It is vital that enumerating over this array is cheap. One thought was to just have the class implement `IEnumerable<item>`, but `InsideArray.getEnumerator()` only gives me a non-generic enumerator. I also tried implementing the `IEnumerable` interface. This worked but was very slow, possibly due to boxing. Is there a way to make the class itself enumerable without a performance hit? Normal Code: ``` //Class public class Foo { //Stuff public Item[,] InsideArray {get; private set;} } //Iteration. Shows up all over the place foreach (Item x in classInstance.InsideArray) { //doStuff } ``` Adjusted, much slower code: ``` //Class public class Foo : IEnumerable { //Stuff private Item[,] InsideArray; System.Collections.IEnumerator System.Collections.IEnumerable GetEnumerator() { return InsideArray.GetEnumerator(); } } //Iteration. Shows up all over the place foreach (Item x in classInstance) { //doStuff } ``` Note: Adding an implementation for the nongeneric iterator is possible and faster than my slow solution, but it is still a bit worse than just using the array directly. I was hoping there was a way to somehow tell C#, "hey, when I ask you to iterate over this object iterate over it's array, just as fast," but apparently that is not quite possible...at least from the answers suggested thus far.
How about adding an indexer to the class: ``` public MyInsideArrayType this[int index] { get{return this.insideArray[index]; } ``` And if you REALLY need foreach capabilities: ``` public IEnumerable<MyInsideArrayType> GetEnumerator() { for(int i = 0; i<this.insideArray.Count;i++) { yield return this[i]; } } ```
A bespoke iterator might make it quicker (**edited** to return as known type): ``` Basic: 2468ms - -2049509440 Bespoke: 1087ms - -2049509440 ``` (you would use the ArrayIterator directly as Foo's GetEnumerator - essentially copying the code from ArrayEnumerator.GetEnumerator; my point is to show that a typed iterator is faster than the interface) With code: ``` using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; class Foo { public struct ArrayIterator<T> : IEnumerator<T> { private int x, y; private readonly int width, height; private T[,] data; public ArrayIterator(T[,] data) { this.data = data; this.width = data.GetLength(0); this.height = data.GetLength(1); x = y = 0; } public void Dispose() { data = null; } public bool MoveNext() { if (++x >= width) { x = 0; y++; } return y < height; } public void Reset() { x = y = 0; } public T Current { get { return data[x, y]; } } object IEnumerator.Current { get { return data[x, y]; } } } public sealed class ArrayEnumerator<T> : IEnumerable<T> { private readonly T[,] arr; public ArrayEnumerator(T[,] arr) { this.arr = arr; } public ArrayIterator<T> GetEnumerator() { return new ArrayIterator<T>(arr); } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } public int[,] data; public IEnumerable<int> Basic() { foreach (int i in data) yield return i; } public ArrayEnumerator<int> Bespoke() { return new ArrayEnumerator<int>(data); } public Foo() { data = new int[500, 500]; for (int x = 0; x < 500; x++) for (int y = 0; y < 500; y++) { data[x, y] = x + y; } } static void Main() { Test(1); // for JIT Test(500); // for real Console.ReadKey(); // pause } static void Test(int count) { Foo foo = new Foo(); int chk; Stopwatch watch = Stopwatch.StartNew(); chk = 0; for (int i = 0; i < count; i++) { foreach (int j in foo.Basic()) { chk += j; } } watch.Stop(); Console.WriteLine("Basic: " + watch.ElapsedMilliseconds + "ms - " + chk); watch = Stopwatch.StartNew(); chk = 0; for (int i = 0; i < count; i++) { foreach (int j in foo.Bespoke()) { chk += j; } } watch.Stop(); Console.WriteLine("Bespoke: " + watch.ElapsedMilliseconds + "ms - " + chk); } } ```
Faster enumeration: Leveraging Array Enumeration
[ "", "c#", "arrays", "performance", "ienumerable", "" ]
Is there a way to only show the first N lines of output from an `SQL` query? Bonus points, if the query stops running once the `N` lines are outputted. I am most interested in finding something which works in `Oracle`.
It would be helpful if you specify what database you are targetting. Different databases have different syntax and techniques to achieve this: For example in Oracle you can ahieve this by putting condition on `RowNum` (`select ... from ... where ... rownum < 11` -> would result in outputting first 10 records) In `MySQL` you can use you can use `limit` clause. **Microsoft SQL Server =>** `SELECT TOP 10 column FROM table` **PostgreSQL and MySQL =>** `SELECT column FROM table LIMIT 10` **Oracle =>** `select * from (SELECT column FROM table ) WHERE ROWNUM <= 10` (thanks to stili) **Sybase =>** `SET rowcount 10 SELECT column FROM table` **Firebird =>** `SELECT FIRST 10 column FROM table` NOTE: Modern `ORM` tools such as Hibernate give high level API (Query, Restriction, Condition interfaces) that abstract the logic of top n rows based on the dialect you choose.
For Oracle the suggested and accepted solution is wrong. Try using an order clause, and the results will be unpredictable. The SQL will need to be nested to accomplish this in Oracle. ``` select name, price from ( select name, price, row_number() over (order by price) r from items ) where r between 1 and 5; ``` The example above was borrowed from <http://www.adp-gmbh.ch/ora/sql/examples/first_rows.html> which has a good discussion on this topic.
Show only the first N lines of output of a SQL query
[ "", "sql", "" ]
I was planning to use jquery autocomplete for a site and have implemented a test version. Im now using an ajax call to retrieve a new list of strings for every character input. The problem is that it gets rather slow, 1.5s before the new list is populated. What is the best way to make autocomplete fast? Im using cakephp and just doing a find and with a limit of 10 items.
[This article](http://code.flickr.com/blog/2009/03/18/building-fast-client-side-searches/) - about how [flickr](http://www.flickr.com/) does autocomplete is a very good read. I had a few "wow" experiences reading it. > "This widget downloads a list of all > of your contacts, in JavaScript, in > under 200ms (this is true even for > members with 10,000+ contacts). In > order to get this level of > performance, we had to completely > rethink how we send data from the > server to the client."
Try preloading your list object instead of doing the query on the fly. Also the autocomplete has a 300 ms delay by default. Perhaps remove the delay ``` $( ".selector" ).autocomplete({ delay: 0 }); ```
How to improve performance of Jquery autocomplete
[ "", "javascript", "jquery", "autocomplete", "" ]
(Edit: randrange is just random.randrange, I didn't write my own RNG) I'm trying to create a list of instances of a class I defined. Here's the entire class (by request): ``` from random import randrange class Poly: points = [0] * 8 fill = 'red' alpha = 1.0 def __init__(self, width=100, height=100): for i in range(0, 8, 2): self.points[i] = randrange(width) self.points[i+1] = randrange(height) self.alpha = random() return ``` Seems to work fine: ``` >>> for i in range(5): Poly().points [28, 64, 93, 26, 15, 31, 44, 50] [24, 14, 47, 14, 35, 17, 63, 62] [99, 28, 90, 29, 56, 59, 57, 33] [62, 56, 48, 28, 40, 73, 70, 99] [99, 32, 27, 99, 42, 57, 86, 12] ``` But if I try to create a list of these objects, I get separate instances (different memory addresses) but they all have the same random values: ``` >>> p = [] >>> for i in range(5): p.append(Poly()) >>> p [<gen_image.Poly instance at 0x02D773C8>, <gen_image.Poly instance at 0x02D77FD0>, <gen_image.Poly instance at 0x0321D030>, <gen_image.Poly instance at 0x02D51E40>, <gen_image.Poly instance at 0x02D51DA0>] >>> for poly in p: print poly.points [75, 18, 5, 76, 6, 64, 95, 54] [75, 18, 5, 76, 6, 64, 95, 54] [75, 18, 5, 76, 6, 64, 95, 54] [75, 18, 5, 76, 6, 64, 95, 54] [75, 18, 5, 76, 6, 64, 95, 54] ``` What's going on here? And what's the right way to do what I'm trying to do?
Move the creation of the array into the `__init__` method. You're working with a shared array among all objects. The reason the first shows different is that you print the contents of that array before you construct a new Poly object and thus trample over the array contents. If you had kept them around and inspected them later they would all appear to have the same contents as the last one you generated. Oh, and try not to simplify code when posting questions. Always post complete, but short, programs that reproduce the problem. Here's a short, but complete, program that demonstrates the problem you're having: ``` from random import randrange class Poly: points = [0]*8 def __init__(self, width=100, height=100): for i in range(0, 8, 2): self.points[i] = randrange(width) self.points[i+1] = randrange(height) return p1 = Poly() print "p1:", p1.points p2 = Poly() print "p2:", p2.points print "p1:", p1.points ``` Sample output: ``` [C:\Temp] test.py p1: [19, 5, 1, 46, 93, 18, 18, 57] p2: [92, 71, 42, 84, 54, 29, 27, 71] p1: [92, 71, 42, 84, 54, 29, 27, 71] ``` Notice how p1 changed. The fixed code could be as simple as: ``` from random import randrange class Poly: def __init__(self, width=100, height=100): self.points = [0]*8 for i in range(0, 8, 2): self.points[i] = randrange(width) self.points[i+1] = randrange(height) return ``` although I prefer the append variant that [@Doug](https://stackoverflow.com/users/51305/doug) posted [here](https://stackoverflow.com/questions/874121/python-list-of-objects-with-random-attributes/874140#874140)
You have a class attribute `Poly.points`. In your `__init__` method you do `self.points[i] = ...`. Now this makes Python use `Poly.points` which is shared by all instances. But you want `points` to be an instance attribute. I'd suggest this: ``` class Poly: # you don't need this here #points = [0] * 8 #fill = 'red' #alpha = 1.0 def __init__(self, width=100, height=100): self.points = [0]*8 self.fill = 'red' self.alpha = random() for i in range(0, 8, 2): self.points[i] = randrange(width) self.points[i+1] = randrange(height) ```
Python list of objects with random attributes
[ "", "python", "random", "" ]
How would you suggest the best way of avoiding duplicate event subscriptions? if this line of code executes in two places, the event will get ran twice. I'm trying to avoid 3rd party events from subscribing twice. ``` theOBject.TheEvent += RunMyCode; ``` In my delegate setter, I can effectively run this ... ``` theOBject.TheEvent -= RunMyCode; theOBject.TheEvent += RunMyCode; ``` but is that the best way?
I think, the most efficient way, is to make your event a property and add concurrency locks to it as in this **[Example](http://codinglight.blogspot.com/2009/02/preventing-duplicate-subscriptions-to.html)**: ``` private EventHandler _theEvent; private object _eventLock = new object(); public event EventHandler TheEvent { add { lock (_eventLock) { _theEvent -= value; _theEvent += value; } } remove { lock (_eventLock) { _theEvent -= value; } } } ```
I have done this before....it assumes it is acceptable that the last subscriber is what gets called. ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { MyObject my = new MyObject(); my.Changed += new EventHandler(my_Changed); my.Changed += new EventHandler(my_Changed1); my.Update(); Console.ReadLine(); } static void my_Changed(object sender, EventArgs e) { Console.WriteLine("Hello"); } static void my_Changed1(object sender, EventArgs e) { Console.WriteLine("Hello1"); } } public class MyObject { public MyObject() { } private EventHandler ChangedEventHandler; public event EventHandler Changed { add { ChangedEventHandler = value; } remove { ChangedEventHandler -= value; } } public void Update() { OnChanged(); } private void OnChanged() { if (ChangedEventHandler != null) { ChangedEventHandler(this, null); } } } } ```
Avoid duplicate event subscriptions in C#
[ "", "c#", "events", "event-handling", "delegates", "" ]
I need to draw peak meters for audio in realtime. Minimum 44100 samples per second times a minimum 40 streams. Each buffer is between 64 and 1024 samples. I need to grab the abs max from each buffer. (These are then fed through a kind of lowpass filter and drawn at about 20ms intervals.) ``` for(int i = 0; i < numSamples; i++) { absMaxOfBuffer = MAX( fabs( buffer[i] ), absMaxOfBuffer); } ``` That's how I do it now. I'd like to do it much faster. The buffers have floats in the -1 to 1 range, hence the fabs. Question, is there some tricky comp-sci quicksort-esque way of doing this faster? Failing that, branchless ABS and MAX functions for floats, do they exist? edit: Primary platform is Linux/gcc but a windows port is planned (probably with mingw). edit, the second: I gave the accept to onebyone because of the bit regarding the actual algo structure which was central to the question. I'll try unrolling the loop to four at the time, zeroing the signbits and then getting the max with SSE (maxps instruction) and see if that doesn't peel the banana. Thanks for the suggestions, I've up-voted a few of you, as runners up. :)
fabs and comparison are both really fast for IEEE floats (like, single-integer-op fast in principle). If the compiler isn't inlining both operations, then either poke it until it does, or find the implementation for your architecture and inline it yourself. You can maybe get something out of the fact that *positive* IEEE floats go in the same order as the integers with the same bit patterns. That is, ``` f > g iff *(int*)&f > *(int*)&g ``` So once you've fabs'ed, I think that a branch-free max for int will also work for float (assuming they're the same size of course). There's an explanation of why this works here: <http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm>. But your compiler already knows all this, as does your CPU, so it may not make any difference. There is no complexity-faster way of doing it. Your algorithm is already O(n), and you can't beat that and still look at every sample. I guess there's probably something in your processor's SIMD (that is, SSE2 on Intel) that would help, by processing more data per clock cycle than your code. But I don't know what. If there is, then it quite possibly will be several times faster. You could probably parallelize on a multi-core CPU, especially since you're dealing with 40 independent streams anyway. That will be at best a few factors faster. "Just" launch the appropriate number of extra threads, split the work between them, and use the lightest-weight primitive you can to indicate when they're all complete (maybe a thread barrier). I'm not quite clear whether you're plotting the max of all 40 streams, or the max of each separately, so maybe you don't actually need to synchronise the worker threads, other than to ensure results are delivered to the next stage without data corruption. It's probably worth taking a look at the disassembly to see how much the compiler has unrolled the loop. Try unrolling it a bit more, see if that makes any difference. Another thing to think about is how many cache misses you are getting, and whether it's possible to reduce the number by giving the cache a few clues so it can load the right pages ahead of time. But I have no experience with this, and I wouldn't hold out much hope. \_\_builtin\_prefetch is the magic incantation on gcc, and I guess the first experiment would be something like "prefetch the beginning of the next block before entering the loop for this block". What percentage of the required speed are you currently at? Or is it a case of "as fast as possible"?
Things to try: * fabs() might not be an inline function. * Special assembly instructions might help. On Intel, SSE has an instruction to compute the maximum of four floats at once. * Failing that, the IEEE 754 specification is such that if a and b are *non-negative* floats, then a < b is equivalent to \*(int \*)&a < \*(int \*)&b. Moreover, for any a, you can compute -a from a by flipping the MSB. Together, these properties might enable some bit-twiddling hacks. * Do you really need the maximum of every sample? Perhaps the maximum might occur more than once, opening up the possibility of not examining every input. * Can you compute the maximum in a streaming fashion?
Faster abs-max of float array
[ "", "c++", "performance", "optimization", "signal-processing", "" ]
I would like to know what I should use to compile in C. I am brand new to programing in general and would greatly appreciate a comprehensive explanation of this process. I am on Windows Vista. I heard about something called "djgpp" that is free and effective for windows.
For the answer to this question and many others you may have as you start out, try [this website][1] which has beginner tutorials. [Here's the page][2] on compilers and getting set up. An excerpt on what compilers you can use: **Windows/DOS** * Code::Blocks and MINGW * Borland * DJGPP * Dev-C++ and Digital Mars **Windows Only** * Microsoft Visual C++ * nix * g++ is a C++ compiler that comes with most \*nix distributions. * gcc is a C compiler that comes with most \*nix distributions. **Macintosh** - XCode ``` Personally, I'd also recommend you strongly to read [The C Programming Language by Kernighan and Ritchie.][3] It will really help you understand both core principles of programming as well as C-specific details. [1]: http://www.cprogramming.com/tutorial/c/lesson1.html [2]: http://www.cprogramming.com/compilers.html [3]: http://www.amazon.com/C-Programming-Language-2nd-Ed/dp/0131103709/ref=ed_oe_h ```
Depends on which platform, but on Linux, Mac OS X and similar (including Cygwin), [gcc](http://gcc.gnu.org/) is most common. Say I have a script named `myapp.c`: ``` #import <stdio.h> int main(){ printf("Hi!\n"); return 0; } ``` To compile it from the command line using gcc is very simple, just run: ``` gcc myapp.c ``` ..that outputs the binary as "a.out" (the default filename). To run the compiled app, just do.. ``` ./a.out #which outputs: Hi! ``` Or put it somewhere within your $PATH (for example, `/usr/bin` or `~/bin/`) and run `a.out` You can specify the output filename with the `-o` flag: ``` gcc myapp.c -o myapp ./myapp # output: Hi! ``` As for more complete guides, ["Learn C for Cocoa"](http://cocoadevcentral.com/articles/000081.php) is a good, quick guide on the C language, and covers compiling. If you're interested in learning ObjC, the [next part of the guide](http://cocoadevcentral.com/d/learn_objectivec/) is also great. On Windows, I would recommend looking into Visual Studio, specifically the [Express editions](http://www.microsoft.com/Express/) (which are free). There's no "Visual C", but the Visual C++ edition will compile C code (since C++ is an extension of C). There's also an option to "Compile as C code" somewhere in the build options. Finally, [The C Programming Language](https://rads.stackoverflow.com/amzn/click/com/0131103628) book covers, well, everything.
Brand new to C (how to compile?)
[ "", "c++", "c", "" ]
I'm trying to call a row update from php to an mysql database. It fails out but when i try to call an insert new row formated just the same it works. ``` $result = mysql_query("INSERT INTO auth (username, password, studycode, description, server) VALUES ('$username', '$password', '$studycode', '$description', '$server')"); ``` but this code fails ``` $result = mysql_query("UPDATE auth SET username='$username', password='$password', studycode='$studycode', description='$description', server='$server' WHERE index='$id' LIMIT 1;"); ``` index is the first column and its the key/id for the table. Edit: Ok so i just went into mysql admin and tried the exact command my code would have sent to track the error. ``` UPDATE auth SET username='username', password='password', studycode='ab9102y', description='test change', server='server2' WHERE index='5' LIMIT 1; ``` gives me the 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 'index='5' LIMIT 1' at line 1 ```
Possibly a reserved keyword issue with index. Try: ``` $result = mysql_query("UPDATE auth SET username='$username', password='$password', studycode='$studycode', description='$description', server='$server' WHERE `index` ='$id'"); ```
I believe it's because the word `index` is a reserved word in MySQL. There for you need change your where clause to: ``` WHERE `index` = '$id' ``` Notice the ticks around index.
PHP/MySQL Update code
[ "", "php", "mysql", "database", "" ]
At my work we are currently having some serious pains pushing our database changes across environments. The issue starts to show up when we create a new non-nullable column on an existing table. The script that SQL Compare generates creates the column as non-nullable, so it will always fail. I was hoping that there was some alternative to having to manually edit the script. Is there any way to get around this? If not, how do you guys handle it?
Create a table: ``` create table #bingo ( id int ) ``` Add a value: ``` insert into #bingo values (1) ``` Add a new column: ``` alter table #bingo add userid int ``` Populate the new column: ``` update #bingo set userid = 1 where id = 1 ``` Change the new column to not nullable: ``` alter table #bingo alter column userid int not null ``` You would have to manually edit the RedGate Sql Compare to make it work like this.
How do you plan on filling the NOT NULL column? I don't see how SQL Compare could really come up with a solution since it has no way of knowing how you would fill it. You could create the column with a DEFAULT, then simply add an update statement at the end of the generated scripts to properly update the column if you have some source for the values.
Is there an easy way to add a custom migration script to SQL Compare scripts?
[ "", "sql", "migration", "redgate", "" ]
In C++ projects there is the possibility to set a custom build step for files. Is there a similar functionality in C# projects? I couldn't really find anything. One idea would be to create a second project (makefile or c++) and move the files there.
I think you are on the right track with your comment about multiple projects. Combine this with the fact that you can include multiple projects within a single Solution and you may have your answer. I use this functionality to build several components at a time and it works quite well.
MsBuild should work for you although it might take some time to figure out how it works. It appears that you can setup a step that runs prior to building each .cs file by separating each .cs file into its own build group. In [MSBuild script for compiling each .cs file into an EXE](http://blogs.msdn.com/dotnetinterop/archive/2008/04/16/msbuild-script-for-compiling-each-cs-file-into-an-exe.aspx), Dino Chiesa comments: > By using the %(CSFile.identity) > scalar, we run this task once for each > file. The converse would be > @(CSFile.identity). That would run > the compile once, for all files, > compiling them all together into a > single assembly. Also, these links might help: [Custom build step for C# files](http://social.msdn.microsoft.com/Forums/en-US/msbuild/thread/ab3bcb1b-4ced-4e28-abd3-05c1be1156be/) [Master Complex Builds with MSBuild](http://www.devx.com/dotnet/Article/39347/1763)
Custom build step for C# project
[ "", "c#", "" ]
What is the easiest way to hide the Contents of an Update Panel when the UpdateProgress is invoked?
Here is a nice example doing this using [Ajax Control Toolki](http://www.asp.net/AJAX/AjaxControlToolkit/Samples/UpdatePanelAnimation/UpdatePanelAnimation.aspx) ``` <ajaxToolkit:UpdatePanelAnimationExtender ID="ae" runat="server" TargetControlID="up"> <Animations> <OnUpdating> ... </OnUpdating> <OnUpdated> ... </OnUpdated> </Animations> </ajaxToolkit:UpdatePanelAnimationExtender> * TargetControlID - ID of the UpdatePanel whose updates are used to play the animations (this is also the default target of the animations) * OnUpdating - Generic animation played as when any UpdatePanel begins updating * OnUpdated - Generic animation played after the UpdatePanel has finished updating (but only if the UpdatePanel was changed) ``` Also you may [watch this video](http://www.asp.net/learn/ajax-videos/video-164.aspx)
I'm not sure if this will work but you can put script tags inside the progresstemplate and hide a div inside the updatepanel. It most likely won't un-hide when it comes back though. You could catch the postback when it returns with javascript like so: ``` Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(){ alert('postback returned'); }); ```
How can the UpdatePanel's ContentTemplate be hidden while an UpdateProgress is being used?
[ "", "c#", "asp.net", "ajax", "asp.net-ajax", "" ]
I have a GridView which I am populating by calling a method to return a datatable with two columns. After I return the datatable, I bind it to the gridview and display it. I am not using a SqlDataSource or an ObjectDataSource, so what is the proper way to Delete a row from the gridview and the underlying data in the database. I just need to delete from one table which is called portfolio. It has 3 columns, ID, which is the unique key, PortfolioID, and PortfolioName. The datatable returns the PortfolioName and the number of items in the Portfolio. I was thinking I could do this in the Row\_Deleting event where I would do something like: ``` DELETE * FROM Portfolio WHERE PortfolioID = @PortfolioID ``` Am I on the right track and how would I do this? Could I bind the PortfolioID to the GridView DataKey property (What is the correct syntax to do this?)
I assume that you're deleting a row on a button press. If so, I usually do something like this: ``` <asp:GridView ID="myGrid" runat="server" DataKeyNames='PortfolioID' OnRowCommand="dgStudent_RowCommand"> <Columns> <asp:ButtonField ButtonType="Button" CommandName="Delete" Text="Delete"></asp:ButtonField> </Columns> </asp:GridView> ``` Then in your code-behind: ``` protected void myGrid_RowCommand(object sender, GridViewCommandEventArgs e) { // create and open DB connection int PortfolioID = (int)myGrid.DataKeys[Convert.ToInt32(e.CommandArgument)].Value; DeleteRow(PortfolioID); // your implementation myGrid.DataBind(); } ``` `DeleteRow` is your implementation of the row delete (maybe the SQL you have above). myGrid is your grid. `PortfolioID` is the primary key. This also assumes that the only button in your grid is the delete button. If you have more than one button, you'll need to check `e.CommandName=="Delete"` to make sure you get the delete button.
As i understood you want to delete an row from datagrid view that is filed from database table. This means you want to delete and Table record from some database. The best way to do this is to put an textbox somewhere and creat an event for your datagridview ( on Row select event). This way when you will selct the row you want to delete the id of that roow will be sent to the textbox ( this will be coded). After you have the id of the row you want to delete just add one more button to delete the record in database and bind the datagridview once again. ``` private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { this.txt_portfolioId.Text=dataGridView1.CurrentRow.Cells["portfolioID"].Value.ToString(); } private void btn_Delete(object sender, EventArgs e) { //You need to connect to database(regular database connection this connection string and sqlcommand and add this sqlquerry: ``` Delete \* from yourtable where portfolioid = '"+Convert.ToInt32(this.portfolioId.Text)+"'; }
How to delete a row in a gridview and the underlying datasource without using a SqlDataSource, ObjectDataSource, etc
[ "", "c#", "asp.net", "gridview", "" ]
I'm using ASP.net and an SQL database. I have a blog like system where a number of comments are made against a post and I want to display the number of those comments next to the post. To get that number I could either hold it in the post record and add/subtrack when a comment is added or deleted or I could use the SQL to calculate the number of comments using a query each time a user hits the page. The latter seems to be a bad idea as its going to hit my SQL database harder however holding the number against the record feels like it could be error prone. What do you think is best coding practice in this case?
Always start with a normalized database (your second option). Only denormalize if you have an absolute necessity for performance reasons. Designing it in the denormalized way (which is error-prone as you guessed) is premature optimization. With proper indexes it should be fine calculating the number on the fly.
I think the SQL statement should be fine. The other is duplication of data you already have. A count query should be quick.
Calculating Number Of Comments/Posts
[ "", "asp.net", "sql", "" ]
I am returning a List<> from a webservice as a List of JSON objects. I am trying to use a for loop to iterate through the list and grab the values out of the properties. This is a sample of the returning JSON: ``` {"d":[{"__type":"FluentWeb.DTO.EmployeeOrder", "EmployeeName":"Janet Leverling", "EmployeeTitle":"Sales Representative", "RequiredDate":"\/Date(839224800000)\/", "OrderedProducts":null}]} ``` So I am trying to extract the contents using something like this: ``` function PrintResults(result) { for (var i = 0; i < result.length; i++) { alert(result.employeename); } ``` How should this be done?
had same problem today, Your topic helped me so here goes solution ;) ``` alert(result.d[0].EmployeeTitle); ```
Be careful, `d` is the list. ``` for (var i = 0; i < result.d.length; i++) { alert(result.d[i].employeename); } ```
Loop through JSON object List
[ "", "javascript", "jquery", "web-services", "json", "" ]
a)In this case does the random number generator uses the system's clock (making the seed change) on each run? b)Is the seed used to generate the pseudo-random values of expovariate(lambda)?
"Use the Source, Luke!"...;-). Studying <https://svn.python.org/projects/python/trunk/Lib/random.py> will rapidly reassure you;-). What happens when seed isn't set (that's the "i is None" case): ``` if a is None: try: a = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time a = long(time.time() * 256) # use fractional seconds ``` and the expovariate: ``` random = self.random u = random() while u <= 1e-7: u = random() return -_log(u)/lambd ``` obviously uses the same underlying random generator as every other method, and so is identically affected by the seeding or lack thereof (really, how else would it have been done?-)
a) It typically uses the system clock, the clock on some systems may only have ms precision and so seed twice very quickly may result in the same value. > seed(self, a=None) > Initialize internal state from hashable object. > > ``` > None or no argument seeds from current time or from an operating > system specific randomness source if available. > ``` > > <http://pydoc.org/2.5.1/random.html#Random-seed> b) I would imagine expovariate does, but I can't find any proof. It would be silly if it didn't.
Python's random: What happens if I don't use seed(someValue)?
[ "", "python", "random", "seed", "" ]
I'm currently running some SQL which uses an IN expression to match against multiple IDs. However, I would ideally like to be able to match up certain IDs with others so they must appear together to return a result. Here's an example: Edit: The IDs I'm matching are a part of a many-to-many relationship. The structure is like this: Articles ArticleKeywords Keywords An article can have multiple Keywords linked to it by the ArticleKeywords table. I am currently using the IN expression to match any of the Keyword IDs against the records. However, I'd like to match certain records against small groups of keywords i.e. a keyword must appear with another keyword for a record to be matched. Current: ... AND id IN ('25', '566', '156', '166', '7345') More specific: ... AND ((id = '25' AND id = '566') OR (id = '156' AND id = '166') OR (id = '7345')) Although the second option might work, I'm thinking it probably won't be very performance savvy. Is there another way this can be done, or should I be going about it another way? Thanks for your help.
Edited based on comments. Say you're searching for articles that: * Have a keyword named 'a1' * Or, have both keywoards named 'b1' and 'b2' * Or, have either keyword 'c1', 'c2' or 'c3' You can query like: ``` select a.id from Articles a inner join ArticleKeywords ak on ak.articleid = a.id inner join Keywords k on k.id = ak.keywordid group by a.id having sum(case when k.name in ('a1') then 1 else 0 end) = 1 or sum(case when k.name in ('b1','b2') then 1 else 0 end) = 2 or sum(case when k.name in ('c1','c2,'c3') then 1 else 0 end) > 0 ``` Per SquareCog's comment, you can greatly increase performance with an early WHERE clause. The clause would limit the grouping to the relevant keywords only. In the above query, add the WHERE just before the HAVING: ``` ... inner join Keywords k on k.id = ak.keywordid where k.name in ('a1','b1','b2','c1','c2','c3') group by a.id ... ``` You can retrieve the other details of the article(s) like: ``` select * from Articles where id in ( ...query from above here... ) ``` Say you have a table that contains groups to search for, defined like: ``` groupid - keywordid 1 - 1 1 - 2 2 - 3 ``` Meaning the article has to match ((keyword 1 and keyword2) or keyword3). Then you can query like this: ``` select ak.articleid from ArticleKeywords ak inner join Search s on ak.keywordid = s.keywordid group by s.searchgroup, ak.articleid having count(*) = ( select count(*) from #Search s2 where s2.Searchgroup = s.SearchGroup ) ```
Well your second option will never work... ``` ((id = '25' AND id = '566') --For this to return the column `id` would have to = both 25 & 566 which it obviously can't OR (id = '156' AND id = '166') --For this to return the column `id` would have to = both 156 & 166 which it obviously can't OR (id = '7345')) ``` What exactly are you trying to achieve... What do you mean by "match up certain IDs with others so they must appear together" Do you mean on consecutive rows ?
'Better' Method for matching ID sets in MySQL statement
[ "", "sql", "mysql", "" ]
Are there any command line scripts and/or online tools that can reverse the effects of minification similar to how Tidy can clean up horrific HTML? (I'm specifically looking to unminify a minified JavaScript file, so variable renaming might still be an issue.)
You can use this : <http://jsbeautifier.org/> But it depends on the minify method you are using, this one only formats the code, it doesn't change variable names, nor uncompress base62 encoding. edit: in fact it can unpack "packed" scripts (packed with Dean Edward's packer : <http://dean.edwards.name/packer/>)
Chrome developer tools has this feature built-in. Bring up the developer tools (pressing F12 is one way), in the Sources tab, the bottom left bar has a set of icons. The "{}" icon is "Pretty print" and does this conversion on demand. UPDATE: IE9 "F12 developer tools" also has a "Format JavaScript" feature in the Script tab under the Tools icon there. (*see* Tip #4 in [F12 The best kept web debugging secret](http://blogs.msdn.com/b/cdndevs/archive/2011/10/18/f12-the-best-kept-web-debugging-secret.aspx)) [![enter image description here](https://i.stack.imgur.com/wIMSh.jpg)](https://i.stack.imgur.com/wIMSh.jpg)
Tool to Unminify / Decompress JavaScript
[ "", "javascript", "code-formatting", "minify", "compression", "unminify", "" ]
With the .NET Framework 2.0/3.5 TabControl, I can programmatically select a tab using the SelectedTab property as shown in the code below: ``` //toggles between tabPage1 and tabPage2 private void button1_Click(object sender, EventArgs e) { if (tabControl1.SelectedTab == tabPage1) tabControl1.SelectedTab = tabPage2; else tabControl1.SelectedTab = tabPage1; } ``` The .NET **Compact** Framework TabControl doesn't have a SelectedTab property like its .NET Framework counterpart. So, how do I select a tab programmatically?
TabControl.SelectedIndex
I programmed this code. When click on tabPage1, then the program will close: ``` private void tabControl1_MouseClick(object sender, MouseEventArgs e) { if (tabControl1.SelectedTab == tabPage1) { MessageBox.Show("Logout!"); Application.Exit(); } } ```
How do I programmatically select a tab on a .NET CF TabControl?
[ "", "c#", ".net", "compact-framework", "tabcontrol", "" ]
Let's say we have a method: ``` public String wishes(Date birthday) { String birthayDateString = convertToString(birthay); ... } ``` I wonder what's the best name to give to the string called now "birthayDateString". This string represents date converted to text. I can't name it "birthay" beause this name is alredy used. Does nameing it "birthdayString" or "birthdayDateString" violate some naming convention good practice rules?
That actually looks fine. I personally would prefer `birthdayStr` - shorter and to the point - making it both meaningful and yet concise. Yielding: ``` public String wishes(Date birthday) { String birthdayStr = convertToString(birthday); // whatever } ```
No, I don't think you're violating any "best practice" standards. In cases like those, I often use variable names like `birthdayText` or `birthdayStr`. In general, though, I try to make variable names as meaningful as possible—I don't just automatically tack on "Str" or "Text" if there's a naming collision. But in this case, it's just the string representation of the date, so I'd say it's meaningful enough.
Simple yet reoccurring naming problem
[ "", "java", "naming-conventions", "readability", "" ]
In the interface required to implement a WCF service, I declare the main class with the `[ServiceContract()]` attribute and any exposed method with `[OperationContract()]`. How can i expose public properties? Thanks
You can't. That's not how it works. Methods only.
Since the *get* portion of a property is a method, this will technically work but, as mentioned in previous answers/comments, this may not be advisable; just posting it here for general knowledge. **Service Contract:** ``` [ServiceContract] public interface IService1 { string Name { [OperationContract] get; } } ``` **Service:** ``` public class Service1 : IService1 { public string Name { get { return "Steve"; } } } ``` **To access from your client code:** ``` var client = new Service1Client(); var name = client.get_Name(); ```
Do WCF Services Expose Properties?
[ "", "c#", "wcf", "" ]
Can anyone help? I have been designing a site using Javascript but the rest of the html content is static ie. images etc When i load my page in Firefox i have to clear the cache.. I remember a long time ago there was something you could add to the html to force a reload. My question is, is this a good thing? I presume it caches for a reason i.e to cahce images etc.. But this causes my pages not to refresh And how to do it? Really appreciate any feedback
For web pages you can how the page is cached in the HTTP Header. You should look at `Expires` if you have a particular date for the cache to expire or `Cache-Control` for dynamic expiration based on when the page was requested. Here's a pretty good [tutorial](http://www.mnot.net/cache_docs/#META) that covers how cache works and covers set up on the major web servers.
If you want only the js to be loaded afresh everytime, and leave everything else to load from cache, you can add a version number to the js include line like so: ``` <script src="scripts.js?v=5643" type="text/javascript"></script> ``` Change the version number (?v=num) part each time you change the js file. This forces the browser to get the js file from the server. Note: Your actual file name will be the same - `scripts.js` For disabling cache for all files, if you're using apache, put this in your httpd.conf ``` <Directory "/home/website/cgi-bin/"> Header Set Cache-Control "max-age=0, no-store" </Directory> ``` You can also put a meta tag on your html like so: ``` <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" content="no-cache" /> ``` More info on this [here](http://websiteoptimization.com/speed/tweak/cache/)
Problems with Cache in Firefox when i upload my app to web server
[ "", "javascript", "html", "firefox", "caching", "" ]
Earlier today I asked a [question](https://stackoverflow.com/questions/853483/can-i-pass-dictionary-values-entry-and-keys-to-function) about passing dictionary values to a function. While I understand now how to accomplish what I was trying to accomplish the why question (which was not asked) was never answered. So my follow up is why can't I ``` def myFunction(newDict['bubba']): some code to process the parameter ``` Is it simply because the parser rules do not allow this? I Googled for +Python +function +"allowable parameters" and did not find anything useful so I would appreciate any information. I am oversimplifying what is going on. I have a dictionary that is structured like ``` myDict={outerkey1:(innerkey1:value,innerkey2:value,. . .innerkeyn:value),outerkey2:(innerkey1:value,innerkey2:value,. . .innerkeyn:value),. . .} ``` As I said, I know how to do what I wanted-I got a very helpful answer. But I started wondering why ``` def myFunction(outerkey,myDict[outerkey]): ``` gives a syntax error which finely it occurred to me that it has to be a parsing problem.
Yes, the parser will reject this code. Parameter lists are used in function definitions to bind identifiers within the function to arguments that are passed in from the outside **on invocation**. Since `newDict['bubba']` is not a valid identifier, this doesn't make any sense -- you need to provide it as an invocation argument instead of a function parameter, since function parameters can only be identifiers. Because you seem interested in the [formal grammar](https://docs.python.org/2/reference/grammar.html), here are the relevant parts: ``` funcdef ::= [decorators] "def" funcname "(" [parameter_list] ")" ":" suite parameter_list ::= (defparameter ",")* (~~"*" identifier [, "**" identifier] | "**" identifier | defparameter [","] ) defparameter ::= parameter ["=" expression] identifier ::= (letter|"_") (letter | digit | "_")* ``` In fact, the construct you are trying to use as an identifier is a subscription: ``` subscription ::= primary "[" expression_list "]" ```
It looks like you might be confused between the *definition* of a function and *calling* that function. As a simple example: ``` def f(x): y = x * x print "x squared is", y ``` By itself, this function doesn't do anything (ie. it doesn't print anything). If you put this in a source file and run it, nothing will be output. But then if you add: ``` f(5) ``` you will get the output "x squared is 25". When Python encounters the name of the function followed by *actual* parameters, it substitutes the value(s) of those actual parameters for the *formal* parameter(s) in the function definition. In this case, the formal parameter is called `x`. Then Python runs the function `f` with the value of `x` as 5. Now, the big benefit is you can use the same function again with a different value: ``` f(10) ``` prints "x squared is 100". I hope I've understood the source of your difficulty correctly.
Why can't I pass a direct reference to a dictionary value to a function?
[ "", "python", "function", "dictionary", "parameters", "" ]
There's a good discussion of this in the [general case](https://stackoverflow.com/questions/628950/constructors-vs-factory-methods). However, I was wondering specifically why the [`Pattern`](https://docs.oracle.com/javase/9/docs/api/java/util/regex/Pattern.html) class uses the [`compile`](https://docs.oracle.com/javase/9/docs/api/java/util/regex/Pattern.html#compile-java.lang.String-) static method to create an object, rather than the constructor? Seems to me to be more intuitive to use a constructor.
The Pattern class is newer than a lot of the stuff in the JDK. As such I believe they adopted the more modern approach of using factory methods rather than the older approach of public constructors. You can't really retrofit factory methods to existing classes. Generally speaking, there's not a lot of reason to use a constructor over a factory method so I think that's all there was to it. Factory methods allow you to abstract object creation, which can be pretty useful.
Why would you two `Pattern` instance of the same regex? A static creation method allows implementations to potentially cache `Pattern`s sometimes returning the same object if the same regex is asked for multiple times. Compiling `Pattern`s can be expensive. Also if additional `compile` methods became necessary (say different syntaxes), they could be given different names instead of a confusingly overloaded set of constructors.
Why does Java Pattern class use a factory method rather than constructor?
[ "", "java", "constructor", "factory", "" ]
Is it necessary to learn about Code Access Security (CAS) for desktop application development in C#.
That’s a pretty broad question to ask, and the answer depends on a number of things. The two most important factors, however, are your target environment your method of deployment. Most consumer software is installed with an installer (MSI) and gets full-trust on the target machine. If this is your environment and method of delivery, you’ll likely never need to learn or master Code Access Security. On the other hand, enterprise customers generally want more control over what software can and can’t do. Code Access Security provides IT with the ability to lock down applications and the control they can assert of the machine they’re installed on. So if you’re building for Enterprise, understanding CAS may be a requirement. Regardless of your target market, how you deploy your application may require you to learn about CAS. XBAP applications are by default NOT full-trust and require significant steps to elevate to full-trust. Click-Once deployed applications are also not full-trust but can be elevated to full-trust more easily. So if you plan to deploy software using either of these methods, you’ll likely want to understand CAS. And finally, Silverlight as a platform by definition is not full-trust. In fact it can never be full-trust. This is not a CAS issue because no depth of understanding CAS will help you overcome the fact that Silverlight does not include code required to perform full-trust activities. The reason I include Silverlight here, however, is that a good understanding of CAS might come in handy when understanding some of the security limitations that exist in the platform by design. Hope that helps.
Yes if you want to get an MCPD. In the real world I have never needed it. I write applications for the Government and they are pretty tight on security and they have never requested it.
Is it necessary to learn about Code Access Security (CAS)?
[ "", "c#", "" ]
I'm using Resharper 4.5 and I need custom formatting of braces when writing an array or object initializer. Resharper supports some styles: *Gnu Style:* ``` int[] array = new int[] { 1, 2, 3 } ``` but I need: ``` int[] array = new int[] { 1, 2, 3 } ``` Is there any way to customize this templates?
You can customize ReSharper to do just that, you'll need to do the following (All in **ReSharper -> Options -> C# -> Formatting Style**): 1. In **Braces Layout**, set *Array and object initializer* to **At Next line (BSD Style)**. 2. In **Other**, make sure that *Continuous line indent multiplier* is set to **1**. 3. In **Other**, make sure that *Indent array, object and collection initializer block* is **unchecked**. You should get the style you want.
As of R#7.1 some Option attributes were changed: 1. In **Braces Layout**, set *Array and object initializer* to **At Next line (BSD Style)**. 2. In **Other**, make sure that *Continuous line indent multiplier* is set to **1**. like in older versions and 1. In **Other**, at *Align Multiline Constructs* make sure that **Array, object and collection initializer** is unchecked.
Custom Brace formatting with Resharper
[ "", "c#", "resharper", "indentation", "auto-indent", "" ]
I have the following code in a class of mine. The purpose of this class is to get the balance from a web server. Just in case something goes wrong with getting the balance. I will handle a exception. However, all this is easy to do. But I am left wondering what do I return in my catch statement. Most of the examples I looked at just write to the console using: ``` Console.WriteLine(ex.Message); ``` That is all very well. But in a real application what do most developers do? ``` //Download only when the webclient is not busy. if (!wc.IsBusy) { // Sleep for 1/2 second to give the server time to update the balance. System.Threading.Thread.Sleep(500); try { // Download the current balance. wc.DownloadStringAsync(new Uri(strURL)); } catch (WebException ex) { Console.Write("GetBalance(): " + ex.Message); } } else { Console.Write("Busy please try again"); } ``` My function at the moment returns void. And I am just wondering what else I would return if the webclient is busy? Many thanks for any advice,
**Do not catch an exception if you cannot handle it.** If you return just some value, the calling method has to check if the value is a real result or just an indicator of an exception. And now this method must decide what to do and return. And the method calling this method. And the method... So just let the exception bubble up the stack and catch it somewhere where you can handle it. Maybe directly below the user interface and then display a message box asking if the user wants to retry or display information how to solve the problem. If you have no user interface, catch it somewhere where you can solve the problem and retry. If it is a temporary problem, retry the whole task at a reasonable level until the call succeeds. If you want to log something, use the following pattern to log the exception an rethrow it. ``` try { DoStuff(); } catch (Exception exception) { Log(exception.ToString()); throw; } ``` Note that it is `throw;` and not `throw exception;`. If you do the later, you lose the original stack trace. If you can infer more details about the cause of the exception, you should wrap the caught exception into a more meaningful exception with additional information. ``` try { DoStuff(); } catch (SpecificMeaninglessException exception) { Log(exception.ToString()); throw new MeaningfulException("Details about the error.", exception); } catch (Exception exception) { Log(exception.ToString()); throw; } ```
You should use ex.ToString() method > Exception.Message > contains a simple description of the exception (e.g. "Object reference not set..."). > > Exception.ToString() > contains a description of the exception along with a complete stack trace. [Exception Handling Best Practices in .NET](http://www.codeproject.com/KB/architecture/exceptionbestpractices.aspx)
C# Returning something from exception handle
[ "", "c#", "exception", "" ]
I currently have a community site that I run that is made up of 15 or so php pages. It is not currently very dynamic, only using php for includes/templates. Currently no content is generated via a query string. The pages do not follow a standard naming convention and there are many inbound links. I am looking to expand the site (and start using query strings to build pages) but before I do this I want to change over to use pretty url’s. With this in mind I have a few questions though. 1) Is it best to point all requests to a url rewriting page catch any request to .php pages first and pass them through to keep existing links then a giant case statement for each of the 15 pages finally the rewrite the url's of new pages as these will follow a set format? 2) How can I prevent duplicates in google after I have updated my sitemap.xml or will it remove the old pages? Thanks
1) I'd redirect using apache's URL rewrite, and leave that static. It'll avoid the mess of having those 15 files you already have in your site. I hope I have not misunderstood your question and this helps. 2) Edit robots.txt in the root of your website to tell google (and most others) what it should index, and what it shouldn't: * Google's info on the subject: <http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=40360> * Wikipedia: <http://en.wikipedia.org/wiki/Robots_exclusion_standard> * More info: <http://www.robotstxt.org/>
You should use a 301 permanent redirect from the old pages to the new URLs. This will redirect users that follow links from the old to the new and Google will pass the PageRank you have accumulated on the old pages to the new one. You might also look at using Googles new canonical tag on the old pages to ensure they transfer authority to the new page. <http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html> In .htaccess, you want a bunch of redirect 301 /old/old.htm <http://www.you.com/new.htm>
Migrating an existing PHP site to use URL re-writing (Pretty URL's)
[ "", "php", "url", "mod-rewrite", "url-rewriting", "url-routing", "" ]
In C# I use the Length property embedded to the array I'd like to get the size of. How to do that in C++?
Arrays in C/C++ do not store their lengths in memory, so it is impossible to find their size purely given a pointer to an array. Any code using arrays in those languages relies on a constant known size, or a separate variable being passed around that specifies their size. A common solution to this, if it does present a problem, is to use the [`std::vector`](http://www.cplusplus.com/reference/stl/vector/) class from the standard library, which is much closer to a managed (C#) array, i.e. stores its length and additionally has a few useful member functions (for searching and manipulation). Using `std::vector`, you can simply call `vector.size()` to get its size/length.
It really depends what you mean by "array". Arrays in C++ will have a size (meaning the "raw" byte-size now) that equals to N times the size of one item. By that one can easily get the number of items using the `sizeof` operator. But this requires that you still have access to the type of that array. Once you pass it to functions, it will be converted to pointers, and then you are lost. No size can be determined anymore. You will have to construct some other way that relies on the value of the elements to calculate the size. Here are some examples: ``` int a[5]; size_t size = (sizeof a / sizeof a[0]); // size == 5 int *pa = a; ``` If we now lose the name "a" (and therefor its type), for example by passing "pa" to a function where that function only then has the value of that pointer, then we are out of luck. We then cannot receive the size anymore. We would need to pass the size along with the pointer to that function. The same restrictions apply when we get an array by using `new`. It returns a pointer pointing to that array's elements, and thus the size will be lost. ``` int *p = new int[5]; // can't get the size of the array p points to. delete[] p; ``` It can't return a pointer that has the type of the array incorporated, because the size of the array created with `new` can be calculated at runtime. But types in C++ must be set at compile-time. Thus, `new` erases that array part, and returns a pointer to the elements instead. Note that you don't need to mess with `new` in C++. You can use the `std::vector` template, as recommended by another answer.
How to get the size of an Array?
[ "", "c++", "arrays", "" ]
I am trying to upload file using php. I am using the function move\_uploaded\_file. However it work okay in my local machine but when I test it in the server , it is not working. How can I know what is missing in my server. Thanks IN advance.
1. `file_uploads` must be **On**. 2. You must not exceed the `upload_max_filesize` size of the file uploaded. 3. You must not exceed the `post_max_size` of the data you're submitting. 4. You must not exceed the `max_input_time` as well. 5. Make sure the user used by apache has permission to write files in the target directory. Check if those variables in `php.ini` are in sync with your local server or, if you don't have access to the target server's settings, make your local ones the same and work on that.
whenever you face problems in PHP, I suggest checking out log files of the web server. in this situation, I think it could be PHP configurations. check your PHP configurations and make sure that file uploads are allowed on the web server. PHP configurations are stored in a php.ini file. to find out more information, create a simple php file, say info.php and enter these lines in it: ``` <?php phpinfo(); ?> ``` upload info.php to your server and open the page in your web browser. try to find "file\_uploads". it should be "on". if it is off, find your php.ini file and change the value of "file\_uploads" to "on".
file upload problem in my server
[ "", "php", "" ]
I always thought an SQL compiler would break but apparently nesing can nearly be infinite. Is this code to be trashed immediately or is there some glimmer of hope that something like this can function? This query doesn't really belong to me so I cannot post it... However let's just pretend it is [this one](http://forums.oracle.com/forums/message.jspa?messageID=1326516#1326516): ``` [SELECT /*+ NOPARALLEL bypass_recursive_check */ SP_ALIAS_190, ((CASE SP_ALIAS_191 WHEN 1 THEN 'PROVIDER::ALL_PROV::' WHEN 0] ```
If the query is generated by a tool (or by code), then it may be relatively simple to maintain (in the sense that the query generation code may in fact be well written and maintainable)
Clearly, you've never seen the SQL that comes out of the Sharepoint DAL.
Is it possible to maintain a 43 page query?
[ "", "sql", "maintainability", "" ]
I'm working on a little C++-Game in Visual Studio 2008. I want to see the content of a vector after a couple of seconds or after I pressed some buttons. Breakpoints are useless in this case, because they stop me at every call of the gameloop (~60 times per second). How do I debug in this case? Thanks!
Use function OutputDebugString from Windows API. You can call it anytime you want e.g. every 100th loop in your code. Function info is [here](http://msdn.microsoft.com/en-us/library/aa363362(VS.85).aspx) Please read all comments on this page - some people claim that in your IDE (VS2008) output of this function is shown in "Immediate Window" not the "Output".
You can set **conditional** breakpoints, i.e. breakpoints which hit at a certain position only when a given expression is true. You can, for example, set a breakpoint which hits only every nth time in a loop.
How to log stuff in console in Visual Studio C++
[ "", "c++", "visual-studio-2008", "debugging", "" ]
I've got an array with data from a MySQL table in nested set model I'd like to get sorted, not only alphabetical but also with the child nodes directly after the parent node. Example - array to be sorted (before the sorting): ``` Array ( [0] => Array ( [id] => 1 [name] => Kompetenser [parent] => 0 [depth] => 0 ) [1] => Array ( [id] => 2 [name] => Administration [parent] => 1 [depth] => 1 ) [2] => Array ( [id] => 11 [name] => Organisation [parent] => 2 [depth] => 2 ) [3] => Array ( [id] => 4 [name] => Arbetsledning [parent] => 2 [depth] => 2 ) [4] => Array ( [id] => 17 [name] => Planering [parent] => 2 [depth] => 2 ) [5] => Array ( [id] => 9 [name] => Hantverke [parent] => 1 [depth] => 1 ) [6] => Array ( [id] => 10 [name] => Snickeri [parent] => 9 [depth] => 2 ) [7] => Array ( [id] => 12 [name] => Språk [parent] => 1 [depth] => 1 ) [8] => Array ( [id] => 13 [name] => Tolk [parent] => 12 [depth] => 2 ) [9] => Array ( [id] => 15 [name] => Arabiska [parent] => 13 [depth] => 3 ) [10] => Array ( [id] => 14 [name] => Persiska [parent] => 13 [depth] => 3 ) [11] => Array ( [id] => 16 [name] => Polska [parent] => 13 [depth] => 3 ) [12] => Array ( [id] => 18 [name] => Apotekare [parent] => 1 [depth] => 1 ) [13] => Array ( [id] => 19 [name] => Dotkorand [parent] => 1 [depth] => 1 ) [14] => Array ( [id] => 21 [name] => Atomfysik [parent] => 19 [depth] => 2 ) [15] => Array ( [id] => 20 [name] => Fysik [parent] => 19 [depth] => 2 ) [16] => Array ( [id] => 22 [name] => Ekonom [parent] => 1 [depth] => 1 ) [17] => Array ( [id] => 23 [name] => Industriell ekonomi [parent] => 22 [depth] => 2 ) [18] => Array ( [id] => 24 [name] => Filosofi [parent] => 1 [depth] => 1 ) ) ``` I want the array this way (after the sorting): ``` Array ( [0] => Array ( [id] => 1 [name] => Kompetenser [parent] => 0 [depth] => 0 ) [1] => Array ( [id] => 2 [name] => Administration [parent] => 1 [depth] => 1 ) [3] => Array ( [id] => 4 [name] => Arbetsledning [parent] => 2 [depth] => 2 ) [2] => Array ( [id] => 11 [name] => Organisation [parent] => 2 [depth] => 2 ) [4] => Array ( [id] => 17 [name] => Planering [parent] => 2 [depth] => 2 ) [12] => Array ( [id] => 18 [name] => Apotekare [parent] => 1 [depth] => 1 ) [13] => Array ( [id] => 19 [name] => Dotkorand [parent] => 1 [depth] => 1 ) [14] => Array ( [id] => 21 [name] => Atomfysik [parent] => 19 [depth] => 2 ) [15] => Array ( [id] => 20 [name] => Fysik [parent] => 19 [depth] => 2 ) [16] => Array ( [id] => 22 [name] => Ekonom [parent] => 1 [depth] => 1 ) [17] => Array ( [id] => 23 [name] => Industriell ekonomi [parent] => 22 [depth] => 2 ) [18] => Array ( [id] => 24 [name] => Filosofi [parent] => 1 [depth] => 1 ) [5] => Array ( [id] => 9 [name] => Hantverke [parent] => 1 [depth] => 1 ) [6] => Array ( [id] => 10 [name] => Snickeri [parent] => 9 [depth] => 2 ) [7] => Array ( [id] => 12 [name] => Språk [parent] => 1 [depth] => 1 ) [8] => Array ( [id] => 13 [name] => Tolk [parent] => 12 [depth] => 2 ) [9] => Array ( [id] => 15 [name] => Arabiska [parent] => 13 [depth] => 3 ) [10] => Array ( [id] => 14 [name] => Persiska [parent] => 13 [depth] => 3 ) [11] => Array ( [id] => 16 [name] => Polska [parent] => 13 [depth] => 3 ) ) ``` As you might see, I want all posts with parent 2 directly after the post with id 2, and so on. Any help would be highly appreciated. Thank you in advance.
Problem solved - I made two simple functions. I hope other people could have use of this as well: ``` class data_comp { var $fetched_tree = array(); function tree_fetch($parent = 0) { $query = 'SELECT node.id, node.name, node.parent, (COUNT(parent.name) - 1) AS depth FROM test_competence AS node, test_competence AS parent WHERE node.lft BETWEEN parent.lft AND parent.rgt GROUP BY node.name ORDER BY node.name'; $result = mysql_query($query) or die(mysql_error()); $tree = array(); while($data = mysql_fetch_assoc($result)) { $tree[$data['parent']][$data['id']] = array('name' => $data['name'], 'depth' => $data['depth']); } $this->tree_print($tree, $parent); } function tree_print($tree, $parent) { foreach($tree[$parent] as $id => $value) { $this->fetched_tree[] = array('id' => $id, 'name' => $value['name'], 'depth' => $value['depth']); if(isset($tree[$id]) && is_array($tree[$id])) { $this->tree_print($tree, $id); } } } } ``` Thank you for your time. Any improvements are more than welcome.
***Don't do this in PHP!*** The MySQL server is specificly designed to query AND sort data, read up on the MySQL "[ORDER BY](http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html)" syntax. Doing this on the MySQL server will save run-time, CPU Load and Memory Consumption.
Sort a 2d array based on parent-child relationships between rows (not simply ASC on column values)
[ "", "php", "arrays", "sorting", "hierarchical-data", "nested-sets", "" ]
I have a php function I wrote that will take a text file and list each line as its own row in a table. The problem is the classic "works fine on my machine", but of course when I ask somebody else to generate the .txt file I am looking for, it keeps on reading in the whole file as 1 line. When I open it in my text editor, it looks just as how I would expect it with a new name on each line, but its the newline character or something throwing it off. So far I have come to the conclusion it might have something to do with whatever text editor they are using on their Mac system. Does this make sense? and is there any easy way to just detect this character that the text editor is recognizing as a new line and replace it with a standard one that php will recognize? UPDATE: Adding the following line solved the issue. ``` ini_set('auto_detect_line_endings',true); ``` Function: ``` function displayTXTList($fileName) { if(file_exists($fileName)) { $file = fopen($fileName,'r'); while(!feof($file)) { $name = fgets($file); echo('<tr><td align="center">'.$name.'</td></tr>'); } fclose($file); } else { echo('<tr><td align="center">placeholder</td></tr>'); } } ```
This doesn't work for you? <https://www.php.net/manual/en/filesystem.configuration.php#ini.auto-detect-line-endings>
What's wrong with [`file()`](http://php.net/manual/en/function.file.php)? ``` foreach (file($fileName) as $name) { echo('<tr><td align="center">'.$name.'</td></tr>'); } ```
Read in text file line by line php - newline not being detected
[ "", "php", "newline", "text-editor", "" ]
There's a dropdown displaying 1-10 from where the user selects the number of textboxes he wants - if he chooses unlimited, it shows him a textbox wherein he enters the exact number of textboxes he'd like. if he enters 40, it shows him 40 textboxes which are created at runtime. My question is, how do I enter the data from 40 - or 'whatever number he enters' textboxes into the MS SQL database. There's no way I can create a column name dynamically, and that'd be too tedious and messy. Is there any way I can do this?
What you have is a 1-to-many relationship between whatever it is that is on that page and the comments or descriptions or whatever. You shouldn't have this modeled in your database as text\_box\_1, text\_box\_2, etc. Instead, it should be: ``` CREATE TABLE Some_Entity ( some_entity_id INT NOT NULL, CONSTRAINT PK_Some_Entity PRIMARY KEY CLUSTERED (some_entity_id) ) GO CREATE TABLE Some_Entity_Comments ( some_entity_id INT NOT NULL, comment_number INT NOT NULL, comments VARCHAR(1000) NOT NULL, CONSTRAINT PK_Some_Entity_Comments PRIMARY KEY CLUSTERED (some_entity_id, comment_number), CONSTRAINT FK_Some_Entity_Comments_Some_Entity FOREIGN KEY (some_entity_id) REFERENCES Some_Entity (some_entity_id) ) GO ``` Once that's done, you can use code similar to what Mun wrote to handle things on the front end. You'll just pass the text box index as the comment\_number.
When you create the textboxes, you can give them sequential ID's, and then iterate through these on the postback, writing the values to your database. For example: ``` /// <Summary> /// This would be fired when the user enters the number of textboxes /// the want and click the 'Create Textboxes' button. /// </Summary> protected void CreateTextBoxes_Click(object sender, EventArgs e) { // Check how many textboxes the user wants int count = Convert.ToInt32(CountTextBox.Text); // Generate the number of textboxes requested // and add them to the page for (int i=0; i < count; i++) { // Create the textbox TextBox textbox = new Textbox(); // Set the ID so we can access it later textbox.ID = "TextBox_" + i; // Add the textbox to the panel TextBoxPanel.Controls.Add(textbox); } } /// <Summary> /// This would be fired when the user has entered values in the textboxes /// and clicked the Save button to save the values to the database. /// </Summary> protected void SaveButton_Click(object sender, EventArgs e) { // Check how many textboxes the user created int count = Convert.ToInt32(CountTextBox.Text); // Loop through them for (int i=0; i < count; i++) { // Get the TextBox TextBox textbox = (TextBox) FindControl("TextBox_" + i); // Get the value string val = textbox.Text; // Insert into DB SaveValueToDatabase(val); } ] ```
Entering values into database from 'unlimited' dynamic controls
[ "", "sql", "asp.net", "database", "controls", "" ]
Where do JVM Implementations differ (except licensing)? Does every JVM implement Type Erasure for the Generic handling? Where are the differences between: * JRockit * IBM JVM * SUN JVM * Open JDK * Blackdown * Kaffe ..... Deals one of them with Tail-Call-Optimization?
JVM implementations can differ in the way they implement JIT compiling, optimizations, garbage collection, platforms supported, version of Java supported, etc. They all must meet set of features and behaviors so that it will execute your Java bytecodes correctly. As you've pointed out, the major difference tends to be in licensing. Other non-technical differences tend to be in free/paid support options, integration with other technologies (usually J2EE servers), and access to source code. Note: While a J2EE server runs on the JVM, some servers have integrated tools for monitoring, analyzing, and tweaking JVM performance. As far as technical differences, those have grown less significant over the years. Once upon a time, the IBM and JRockit JVM's had far superior performance to the reference Sun implementation. This was due to significant differences in the types of runtime optimizations, differences in garbage collection, and differences in native-code (and how much native code various classes uses). These performance differences aren't as significant anymore. Some JVM's also include or integrate with diagnostics and monitoring tools. JRockit includes a set of tools for monitoring your JVM performance. Sun provides various JMX-based tools with overlapping features to do the same. IBM Websphere once upon a time included a similar set of tools for their whole J2EE application server (not sure if they still do, but I would assume that's still true)... Some of the open source JVM's tend to have a little slower performance because they have been redeveloped from the ground up. As such, they've got a bit more catching up to do. Last I checked about 2 years ago, Blackdown was significantly slower (1.5x-2x?) than the Sun JVM. It was also a bit behind of supported versions of Java.
Type erasure is a [compiler function](http://java.sun.com/docs/books/tutorial/java/generics/erasure.html) and as such JVM independent.
Differences between JVM implementations
[ "", "java", "generics", "jvm", "jvm-languages", "tail-call-optimization", "" ]
Is there a way to find out the time since the JVM started? Of course, other than starting a timer somewhere near the beginning of `main`, because in my scenario I am writing library code and the requirement that something be called immediately after startup is a too burdensome.
Use this snippet: ``` long jvmUpTime = ManagementFactory.getRuntimeMXBean().getUptime(); ``` or: ``` long jvmStartTime = ManagementFactory.getRuntimeMXBean().getStartTime(); ``` This is the **correct** way of retrieving JVM up-time. For more info see [RuntimeMXBean](https://docs.oracle.com/en/java/javase/15/docs/api/java.management/java/lang/management/RuntimeMXBean.html)
You can get the start time of the JVM in the following code: ``` import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; ... RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); long uptimeInMillis = runtimeMXBean.getUptime(); ``` See more are <https://docs.oracle.com/javase/6/docs/api/java/lang/management/RuntimeMXBean.html>.
time since JVM started
[ "", "java", "time", "jvm", "" ]
I am trying to track what users are searching for on my site (from a simple search form on the front page) with PHP and MySQL. At the end of all my queries I am using this query: ``` INSERT INTO `DiggerActivity_Searches` ( `SearchTerms`, `SearchType`, `NumResults`, `Location`, `Date`, `Time` ) VALUES ( 'SearchKeywords', 'SearchTypes', 'NumberOfResults', 'User'sLocation', 'CurDate', 'CurTime' ) ``` Now, whenever there is a new search keyword, it inserts 3 identical rows. However, if I refresh the page it only inserts 1 row, as it should. The values are passed as a GET like this (I have mod rewritten the URL stuff): > <http://www.mysite.com/Search-Category-Search_these_words>
You might want to check first whether your script executes the query three times or the script is invoked three times (e.g. by some browser addons). If you do not have a debugger installed you can use something like ``` function trace_log() { static $magic = null; if (is_null($magic)) { $magic = uniqid(); } $s = $magic . ' '. microtime(true) . ":\r\n"; foreach( debug_backtrace() as $d) { $s .= ' '. $d['file'].'@'.$d['line']."\r\n"; } file_put_contents('trace_log.txt', $s, FILE_APPEND); } ... trace_log(); mysql_query(....) // or stmt->execute() or whatever you use to execute the query. ``` If the first value of each log entry (the "magic" id) in trace\_log.txt changes, your script is invoked multiple times. If it's the same for all three calls to trace\_log(), your script executes the query three times.
Your table is missing a primary key. Id suggest a PK like search ID or something similar Read more about this at [Unique key - Wikipedia](http://en.wikipedia.org/wiki/Primary_key)
Why is my MySQL INSERT query inserting 3 identical rows?
[ "", "php", "mysql", "insert", "" ]
I have a BO method that must do two operations to fulfill its contract. 1. insert a record into the db 2. send an email notification containing the metadata for the record Both are handled with calls to individual DAO methods responsible for completing the action. I do not trap exceptions in my DAO, I handle and publish them in the BO. The first call is to the DAO to insert, and can throw a NullReferenceException or one of the sql exceptions. The email method uses SmtpClient.Send which can throw a slew of exceptions. Is it possible to force the child method that calls the email functionality to return only one type of exception, a custom one, through an attribute? To illustrate this: ``` public void AddSupportTicket(SupportTicketDTO ticket) { try { supportTicketDAO.Insert(ticket); email.SendNotification(ticket); } catch (ExceptionA exc) { ... } // both of the methods can throw exceptions that catch (ExceptionB exc) { ... } // can overlap. I just care about returning catch (ExceptionC exc) { ... } // a custom EmailException or DataException } ``` I can wrap each child method call in its own try catch and throw the custom exception I want, but thats just another level of try catch that gets trapped by another try catch in AddSupportTicket, and then one in the UI to redirect to an intelligent error, so that doesn't sound great to me. How should I efficiently throw the correct custom exception?
Yes, it's very possible. Check out Enterprise Library [exception handling block](http://msdn.microsoft.com/en-us/library/dd203116.aspx). Lots of great stuff on raising, wrapping, logging exceptions from and between layers as well as setting up policies so you can handle it in configuration if you want to. Combined with the logging application block, it's a powerful combination.
If your using WCF you can specify what kind of exception can be thrown from a given function, so in your service interface you would have something like ``` [OperationContract] [FaultContract(typeof(MemberAlreadyExistsException))] void MemberInsert(Member mu); ```
C# Contract Implementations and Exceptions
[ "", "c#", "exception", "business-logic", "" ]
I've been using xdebug to debug and understand code in php projects for a while now, and have sometimes come into situations where it's been unclear what's going on inside of PHP. Is it possible to set xdebug or gdb up so that i can trace into actual php builtin functions?
If you are using a macosx, solaris or recent freebsd system you can throw a little dtrace at it. It can come in handy for those all too numerous "WTF is PHP doing?" moments.
One way to test the output of the Zend engine, to peek inside at the opcodes, you can use **[Derick Rethan's VLD](http://derickrethans.nl/vld.php) (Vulcan Logic Dissasembler)**, which also appears to be on [PECL](http://pecl.php.net/package/vld). *Note:* only works on \*nix systems (see site for requirements). Some examples of debugging these opcodes can be found on [Sara Golemon's blog](http://blog.libssh2.org/index.php?/categories/1-PHP), in articles such as [Understanding Opcodes](http://blog.libssh2.org/index.php?/archives/92-Understanding-Opcodes.html) and [How long is a piece of string?](http://blog.libssh2.org/index.php?/archives/28-How-long-is-a-piece-of-string.html).
Debugging PHP
[ "", "php", "debugging", "xdebug", "" ]
I want to remove all null properties in a generic object. It doesn't have to be recursive, one level deep is also fine. The reason I need is for a custom JavascriptConvertor implementation for JSON serialization which gives me: {"Name":"Aleem", "Age":null, "Type":"Employee"} And I would like to skip over the null object. The function for this task takes in the objct and returns a Dictionary: ``` IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) ``` So I would like to remove all null properties from obj. All properties have getter but if the property is not set, the getter returns `null`.
You can implement your own [JavaScriptConverter](http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptconverter.aspx) to handle serialization of your type. Then you get full control on how properties are serialized. @Richards answer provides a nice implementation of the Serialize method. The Deserialize method would be quite similar but I'll leave the implementation up to you. Now the only drawback with JavaScriptConverter is that it has to get the supported types from somewhere. Either hardcode it like this: ``` public override IEnumerable<Type> SupportedTypes { get { var list = new List<Type>{ typeof(Foo), typeof(Bar)...}; return list.AsReadOnly(); } } ``` ...or make it configurable, e.g. via the class constructor.
Something along the lines of the following will probably do the trick: ``` public IDictionary<string, object> GetNonNullProertyValues(object obj) { var dictionary = new Dictionary<string, object>(); foreach (var property in obj.GetType().GetProperties()) { var propertyValue = property.GetValue(obj, null); if (propertyValue != null) { dictionary.Add(property.Name, propertyValue); } } return dictionary; } ``` NB: this method does not handle indexed properties.
C#: How to remove all null properties from a generic object using reflection?
[ "", "c#", "reflection", "" ]
I'm running into some compiler errors I don't understand. I'm pretty sure I'm doing something very wrong here but I don't know what. I would like all the world constants to be defined as belonging to the class. Notes: I'm only using classes as structs with attached members. I'm not following strict Object-Orriented Design on purpose. Please do not comment the public variables. I'm not concerned very much about the compiler inlining stuff. I'm using this structure because it's easy for me to use. (If it worked) ``` class Board{ public: enum PhysicsResult{ BOUNCE, OUT_OF_BOUNDS_TOP, OUT_OF_BOUNDS_BOTTOM, CONTINUE }; //World constants const static float Height = 500; const static float Width = 300; //ERROR: 'Board::Width' cannot appear in a constant-expression. const static float PaddleWidth = Width/15; const static float BallRadius = 5; const static float BounceDistance = 1.5; //World Objects Ball ball; Paddle paddle1; Paddle paddle2; /* 1---2 | | 0---3 */ //ERROR: a brace-enclosed initalizer is not allowed here before '{' token //ERROR: invalid in-class initalization of static data member of nonintegral type 'const Pair[4]' const static Pair corners[4] = {Pair(0, 0), Pair(0, Height), Pair(Width, Height), Pair(Width, 0)}; //ERROR: a brace-enclosed initalizer is not allowed here before '{' token //ERROR: invalid in-class initalization of static data member of nonintegral type 'const Pair[2]' const static Pair left_wall[2] = {corners[0], corners[1]}; //ERROR: a brace-enclosed initalizer is not allowed here before '{' token //ERROR: invalid in-class initalization of static data member of nonintegral type 'const Pair[2]' const static Pair right_wall[2] = {corners[3], corners[2]}; //ERROR: a brace-enclosed initalizer is not allowed here before '{' token //ERROR: invalid in-class initalization of static data member of nonintegral type 'const Pair[2]' const static Pair top_wall[2] = {corners[1], corners[2]}; //ERROR: a brace-enclosed initalizer is not allowed here before '{' token //ERROR: invalid in-class initalization of static data member of nonintegral type 'const Pair[2]' const static Pair bottom_wall[2] = {corners[0], corners[3]}; ``` If it is possible to do this, what is the proper syntax for doing this? If this is not possible, what alternative should I use?
Defining the static consts outside of the body of the class compiles and executes with gcc. ``` #include <iostream> using namespace std; struct Pair { int a; int b; Pair(int x, int y) : a(x),b(y) {}}; struct F { static const float blah = 200.0; static const Pair corners[4]; }; // square boards are so ordinary const Pair F::corners[4] = { Pair(0,0), Pair(0,1), Pair(2,0), Pair(2,2) }; const float F::blah ; int main(int, char **) { cout << F::corners[0].a << endl ; cout << F::blah << endl; return 0; } ``` I cannot overemphasize the importance of [ebo](https://stackoverflow.com/users/104480/ebo)'s comment about order of initialization.
You must initialize const members in the constructor initialization list. ``` class blah { public: blah() : _constant( 1 ) { } private: const int _constant; }; ```
How do I create const arrays and calculated const values in C++ class?
[ "", "c++", "gcc", "syntax", "" ]
The following two different code snippets seem equivalent to me: ``` var myArray = Array(); myArray['A'] = "Athens"; myArray['B'] = "Berlin"; ``` and ``` var myObject = {'A': 'Athens', 'B':'Berlin'}; ``` because they both behave the same, and also `typeof(myArray) == typeof(myObjects)` (both yield 'object'). **Is there any difference between these variants?**
Virtually everything in javascript is an object, so you can "abuse" an [Array](https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array) object by setting arbitrary properties on it. This [should be considered harmful](http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/) though. Arrays are for numerically indexed data - for non-numeric keys, use an Object. Here's a more concrete example why non-numeric keys don't "fit" an Array: ``` var myArray = Array(); myArray['A'] = "Athens"; myArray['B'] = "Berlin"; alert(myArray.length); ``` This won't display '2', but '0' - effectively, no elements have been added to the array, just some new properties added to the array object.
In JS arrays are objects, just slightly modified (with a few more functions). Functions like: ``` concat every filer forEach join indexOf lastIndexOf map pop push reverse shift slice some sort splice toSource toString unshift valueOf ```
Why can I add named properties to an array as if it were an object?
[ "", "javascript", "arrays", "object", "javascript-objects", "" ]
When creating a simple object hierarchy in Python, I'd like to be able to invoke methods of the parent class from a derived class. In Perl and Java, there is a keyword for this ([`super`](https://docs.oracle.com/javase/tutorial/java/IandI/super.html)). In Perl, I might do this: ``` package Foo; sub frotz { return "Bamf"; } package Bar; @ISA = qw(Foo); sub frotz { my $str = SUPER::frotz(); return uc($str); } ``` In Python, it appears that I have to name the parent class explicitly from the child. In the example above, I'd have to do something like `Foo::frotz()`. This doesn't seem right since this behavior makes it hard to make deep hierarchies. If children need to know what class defined an inherited method, then all sorts of information pain is created. Is this an actual limitation in python, a gap in my understanding or both?
Use the [`super()`](http://docs.python.org/library/functions.html#super) function: ``` class Foo(Bar): def baz(self, **kwargs): return super().baz(**kwargs) ``` For Python < 3, you must explicitly opt in to using [new-style classes](http://docs.python.org/glossary.html#term-new-style-class) and use: ``` class Foo(Bar): def baz(self, arg): return super(Foo, self).baz(arg) ```
Python also has [super](http://docs.python.org/library/functions.html) as well: `super(type[, object-or-type])` > Return a proxy object that delegates method calls to a parent or sibling class of type. > This is useful for accessing inherited methods that have been overridden in a class. > The search order is same as that used by getattr() except that the type itself is skipped. Example: ``` class A(object): # deriving from 'object' declares A as a 'new-style-class' def foo(self): print "foo" class B(A): def foo(self): super(B, self).foo() # calls 'A.foo()' myB = B() myB.foo() ```
How do I call a parent class's method from a child class in Python?
[ "", "python", "class", "oop", "object", "inheritance", "" ]
I'm .net newbie starting one project for fun. I'm using list box filled with some city names so user can pick one. Every city class has name and UID. How do I know which city user clicked on? Obviously, I can get text of selected item, run through city list and find one by name but that seems stupid. Is there equivalent to MFC SetItemDataPtr type of thing or what is the most common way of doing it?
Assuming that you are referring to a WinForms [`ListBox`](http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.aspx), this can be done in the following way. Instead of setting the `Items` of the `ListBox` to an array/collection of strings (as I presume you are currently doing), you could rather set it to an collection of a user-defined type (`City` in your case), and then use the [`DisplayMember`](http://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.displaymember.aspx) property (set to `Name` or whatever the property of your `City` class that you want to display), so that each item in the `ListBox` can actually be accessed as the user-defined `City` object, while it is still displayed by its `Name` property.
I would use a ListView (in details mode) instead of a ListBox. Then you could use the Tag property of ListViewItem which is the equivalent of MFC's SetItemDataPtr.
Keeping track of an item in List Box
[ "", "c#", ".net", "winforms", "" ]
I'm doing a Get and Post method for an android project and I need to "translate" HttpClient 3.x to HttpClient 4.x (using by android). My problem is that I'm not sure of what I have done and I don't find the "translation" of some methods... This is the HttpClient 3.x I have done and (-->) the HttpClient 4.x "translation" if I have found it (Only parties who ask me problems) : ``` HttpState state = new HttpState (); --> ? HttpMethod method = null; --> HttpUriRequest httpUri = null; method.abort(); --> httpUri.abort(); //httpUri is a HttpUriRequest method.releaseConnection(); --> conn.disconnect(); //conn is a HttpURLConnection state.clearCookies(); --> cookieStore.clear(); //cookieStore is a BasicCookieStore HttpClient client = new HttpClient(); --> DefaultHttpClient client = new DefaultHttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(SOCKET_TIMEOUT) --> HttpConnectionParams.setConnectionTimeout(param, SOCKET_TIMEOUT); client.setState(state); --> ? client.getParams().setCookiePolicy(CookiePolicy.RFC_2109); --> HttpClientParams.setCookiePolicy(param, CookiePolicy.RFC_2109); PostMethod post = (PostMethod) method; --> ? post.setRequestHeader(...,...); --> conn.setRequestProperty(...,...); post.setFollowRedirects(false); --> conn.setFollowRedirects(false); RequestEntity tmp = null; --> ? tmp = new StringRequestEntity(...,...,...); --> ? int statusCode = client.executeMethod(post); --> ? String ret = method.getResponsBodyAsString(); --> ? Header locationHeader = method.getResponseHeader(...); --> ? ret = getPage(...,...); --> ? ``` I don't know if that is correct. This has caused problems because the packages are not named similarly, and some methods too. I just need documentation (I haven't found) and little help.
The easiest way to answer my question is to show you the class that I made : ``` public class HTTPHelp{ DefaultHttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); private boolean abort; private String ret; HttpResponse response = null; HttpPost httpPost = null; public HTTPHelp(){ } public void clearCookies() { httpClient.getCookieStore().clear(); } public void abort() { try { if(httpClient!=null){ System.out.println("Abort."); httpPost.abort(); abort = true; } } catch (Exception e) { System.out.println("HTTPHelp : Abort Exception : "+e); } } public String postPage(String url, String data, boolean returnAddr) { ret = null; httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109); httpPost = new HttpPost(url); response = null; StringEntity tmp = null; httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux " + "i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)"); httpPost.setHeader("Accept", "text/html,application/xml," + "application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); try { tmp = new StringEntity(data,"UTF-8"); } catch (UnsupportedEncodingException e) { System.out.println("HTTPHelp : UnsupportedEncodingException : "+e); } httpPost.setEntity(tmp); try { response = httpClient.execute(httpPost,localContext); } catch (ClientProtocolException e) { System.out.println("HTTPHelp : ClientProtocolException : "+e); } catch (IOException e) { System.out.println("HTTPHelp : IOException : "+e); } ret = response.getStatusLine().toString(); return ret; } } ``` I used [this tutorial](https://hc.apache.org/httpcomponents-client-ga/tutorial/html/) to do my post method and [thoses examples](https://hc.apache.org/httpcomponents-client-ga/examples.html)
Here are the [HttpClient 4 docs](http://hc.apache.org/httpcomponents-client-ga/index.html), that is what Android is using (4, not 3, as of 1.0->2.x). The docs are hard to find (thanks Apache ;)) because HttpClient is now part of HttpComponents (and if you just look for HttpClient you will normally end up at the 3.x stuff). Also, if you do any number of requests you do not want to create the client over and over again. Rather, as the [tutorials for HttpClient note](http://hc.apache.org/httpcomponents-client/tutorial/html/connmgmt.html#d4e604), create the client once and keep it around. From there use the [ThreadSafeConnectionManager](http://hc.apache.org/httpcomponents-client/httpclient/apidocs/org/apache/http/impl/conn/tsccm/ThreadSafeClientConnManager.html). I use a helper class, for example something like [HttpHelper](http://code.google.com/p/and-bookworm/source/browse/trunk/src/com/totsp/bookworm/data/HttpHelper.java) (which is still a moving target - I plan to move this to its own Android util project at some point, and support binary data, haven't gotten there yet), to help with this. The helper class creates the client, and has convenience wrapper methods for get/post/etc. Anywhere you USE this class from an [Activity](http://developer.android.com/reference/android/app/Activity.html), you should create an internal inner [AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html) (so that you do not block the UI Thread while making the request), for example: ``` private class GetBookDataTask extends AsyncTask<String, Void, Void> { private ProgressDialog dialog = new ProgressDialog(BookScanResult.this); private String response; private HttpHelper httpHelper = new HttpHelper(); // can use UI thread here protected void onPreExecute() { dialog.setMessage("Retrieving HTTP data.."); dialog.show(); } // automatically done on worker thread (separate from UI thread) protected Void doInBackground(String... urls) { response = httpHelper.performGet(urls[0]); // use the response here if need be, parse XML or JSON, etc return null; } // can use UI thread here protected void onPostExecute(Void unused) { dialog.dismiss(); if (response != null) { // use the response back on the UI thread here outputTextView.setText(response); } } } ```
Android project using httpclient --> http.client (apache), post/get method
[ "", "java", "android", "http", "apache-httpclient-4.x", "" ]
I have a function that receives three different "people" objects and generates a new "compatibility" object based on the combined values in the "people" objects. However, about 1/3 of the time the three "people" objects that it receives as input are the same as one before, though possibly in a different order. In these cases I do NOT want to make a new "score" object, but simply return a value contained within the existing object. Originally, the program just loops through the list<> of "compatibility" objects searching for the one that belongs to these three "people" (since each "compatibility" object contains an array of people objects). This method is really slow considering that there's over thousands of "compatibility" objects and over a million "people" objects. I had the idea of using a dictionary where the key is a number I generated by combining the three people objects' id values into a single UInt64 using XOR, and storing the score objects in as dictionary values rather than in a list. This cuts down the time by about half, and is acceptable in terms of time performance, but there's way too many collisions, and it returns a wrong score too often. Any suggestions or pointers would be much appreciated. Edit: To add to the original question, each "people" object has a bunch of other fields that I could use, but the problem is making a key that is UNIQUE and COMMUTATIVE.
I think you're looking at things in a much too complex manner. Take the 3 PersonID values and sort them,so that they're always in the same order, no matter which order they were passed in. Then set a value in a hashtable using the three PersonIDs as the key, separated with a hyphen or some other character that won't occur in a PersonID value. Then later, check if there's a value in the hashtable with that key. So if the three PersonIDs are 10, 5 and 22, the hash key could be something like "5-10-22".
Create the key by concatinating objectids after sorting the trio in a pre-determined order.
C# - Need Suggestions on Improving a Section of Code
[ "", "c#", "performance", "list", "dictionary", "" ]
I have a form with some controls. (Actually, this is a sort of ongoing problem.) Some of the forms I have had are resizable, some are not. Regardless, when the form is displayed, it would be nice to have it appear in the "minimum" size needed. Other Windowing toolkits, such as wxWidgets (wxWindow::GetMinSize) and Qt (QWidget::minimumSize) have this functionality. This functionality, if you are not familiar with it, allows a window to resize itself to a minimum size, which is often all the window needs, and looks quite nice. If I have two static texts, and two edit boxes laid out thusly: ``` Username: [ Edit/text box for user's password] Password: [ Edit/text box for user's password] [ Cancel ][ OK ] ``` I can then tell this form to size itself to it's "minimum size", and it would appear much like above. (Minimum width in a text box is partly subjective - I would have to set that myself in one/both of the text boxes, but the form would query the child controls and learn of that minimum width) This is usually combined with layouts of some sort. (Which .Net has.) This has the added benefit that the form is the correct size regardless of font settings, locale, dpi, gui skin, etc. (If done right, at least.) Does this exist in .Net, and if so, where? If you need any more description, ask, and I'll be glad to provide. Edit: What I'm looking for is the above example, resizable only in the X direction (I'm willing to accept both) but can't be resized smaller than a certain W/H. The controls should anchor - ie, the text boxes get bigger, the buttons stay right aligned. Edit: I can do images! Supposedly they're worth a thousand words: [alt text http://www.freeimagehosting.net/uploads/79e9ee10e5.png](http://www.freeimagehosting.net/uploads/79e9ee10e5.png) **Edit:** I guess I'm going to start marking answers. Henk's answer has gotten me pretty far with a non-resizable dialog that fits to it's contents. Most of the posts below are valuable, but miss the point (unless I'm really off base here?): I understand how to use Anchor/TableLayout, and to get controls to flow there - it was mostly getting one or both dimensions of the dialog to fit to the contents of the dialog. You essentially have three cases: 1. The dialog is not resizable - See Henk's answer. Combined with TableLayout and Anchors, you'll get a decent dialog. 2. The dialog is only resizable in one dimension - Go with 1 or 3 - You can constrain a dimension by using the Resize event, but the dialog flickers horribly. (This seems to be a defect in Win32 as far as I can tell - there is some stuff out there about overriding the background erase, which works for controls, but not windows, as you'll get artifacts in the form's background (because you're not erasing them). The real answer is that this should probably be handled by Win32 itself - I should not have to reinvent the double-buffer wheel just to get a decent look dialog...)) 3. The dialog is fully resizable. Anchors and TableLayout are your friend. Unfortunately, the MinimumSize attribute seems to be bogus (at least, I don't know what it is for...) - for example, if you query the MinimumSize of a textbox, by default the height is 4 pixels. Further, the MinimumSize property doesn't seem to propogate - a control does not query it's children. (I can resize the form smaller than the textbox within the form, and the textbox is then off the form.) If you wonder what I'm babbling about, see wxWidgets and how layouts and minimum size work for it. I've also since discovered that .Net does not seem to respect the system font, and always uses the same font for Forms, so font changes won't affect my dialog (sadly) which alieviates most of my worries (happily?). Again, refer to how wxWidgets does it - if the system font is 22pt, all wxFrames (forms) respect and resize appropriately. .Net should get onboard this train... (And I know someone who uses 22+pt font day-to-day for their standard GUI font.)
There is something that comes close, try the following: design your Form a bit large and avoid Right and Bottom docked controls. Then some code like this: ``` private void button1_Click(object sender, EventArgs e) { this.AutoSize = true; this.Size = new Size(10, 10); } ``` The AutoSize will find the extend of the Controls.
I handle these sort of things using [TableLayoutPanel](http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel(VS.80).aspx). TableLayoutPanel lets you layout your controls in columns and rows. Columns and rows have three SizeTypes: AutoSize, Percent, and Absolute. AutoSize sizes the column or row according to the minimum necessary value, Percent sizes the column or row according a percent of unused area, and Absolute sizes the column or row according to an absolute number of pixels. The VisualStudio designer is helpful. If you would rather write all code by hand, it is still a good idea to play with TableLayoutPanel in the designer and examine the resulting designer code to learn how to operate TableLayoutPanel. In order to get the minimum necessary size, you should: * Dock.Fill the TableLayoutPanel in your form. * Dock.Fill controls in cells. * Handle spacing between controls using Control.Margin. * Make the SizeType of all the columns and rows AutoSize. Also, you can use ColumnSpan and RowSpan to make a control take up multiple cells. Once you set things up the way you want them to look, you can use TableLayoutPanel.GetPreferredSize() to determine the minimum required area of the TableLayoutPanel and assign that value to Form.ClientSize. If the user will be able to resize your form, after you determine the minimum required size you should set the SizeType of the column and row you want to grow with the form to SizeType.Percent and use a value of 100, like this: ``` // "columnIndex" is the zero based index of the column this.tableLayoutPanel.ColumnStyles[columnIndex] = new ColumnStyle(SizeType.Percent, 100); // "rowIndex" is the zero based index of the row this.tableLayoutPanel.RowStyles[rowIndex] = new RowStyle(SizeType.Percent, 100); ```
C#, Windows Forms, Best/min fit window to contents
[ "", "c#", ".net", "winforms", "" ]
I have an application that requires the user to reenter their password between 15 and 30 minutes of inactivity to allow them to carry on with what they were doing. My current idea is to have a piece of javascript that calls a popup after 15 minutes, asking the user to log in again. The site as a whole has a 15 minute forms authentication timeout, and a 30 minute session timeout. I would then like it to allow the original page to have a postback if the user successfully authenticates themselves in the popup. Currently I have the popup working (with a 15 minute countdown using JS) and the user is able to log in again, however when the popup window is closed and the user attempts to perform an action on their original page, they are asked to log in again. I assume this is because their original cookie that was attached to the original page will have now expired, and it won't detect the new one. **How can I pass the successful authentication from the popup window to the original page?**
If you add a meta tag, or a hidden div, that populates the authentication token in the content attribute for a meta tag, and just in the div body for a hidden div, you could grab it from the popup window like this... ``` var debugWin = window.open('','aWindow','width=600,height=600,scrollbars=yes'); var somevar = debugWin.document.body.getElementById("my_hidden_div_id").innerText; ``` Then you could update the session cookie with the contents of somevar from JavaScript. As long as you maintain the handle to the window, you should be able to get at the window's DOM. There may be some cross browser variance in how you get at the dom, I think IE has a slightly different method, but it is easily tested for and the result is the same.
I'd create a panel that requires the password, and has a proper code behind method through a button. Then you can use AJAX or jQuery to trigger a modal "popup" box to require them to submit the details. By doing this, you can keep everything on a single page without having to worry about passing credentials between pages/forms/tabs/whatever. In addition, you can have 1 script method that fires after x minutes to prompt for the refresh, and have a second javascript that fires after x + 2 minutes to log the user out of the application, should they fail to respond. Your code behind method can properly reset all the cookie and reset the timeouts and can be reused on any page you wish.
How do you keep a user logged in with a popup window?
[ "", "asp.net", "javascript", "cookies", "forms-authentication", "" ]
i want to do test and build simple debugger GUI in c++ that debugging Java as i read from view docs i will have to work with the JVM debugger protocol do any one here have experience with it? where can i learn about it ? Thanks
The [Java Virtual Machine Debug Interface (JVMDI) Reference](http://java.sun.com/j2se/1.5.0/docs/guide/jpda/jvmdi-spec.html) at Sun would be a good place to start.
The home of the official documentation is here: <http://java.sun.com/javase/technologies/core/toolsapis/jpda/> There are links there to the APIs and the low-level wire protocols that Java debuggers can use.
where i can learn about JVM debugger protocol?
[ "", "java", "debugging", "jvm", "" ]
I can't seem to find a more efficient way to "copy" an embedded resource to disk, than the following: ``` using (BinaryReader reader = new BinaryReader( assembly.GetManifestResourceStream(@"Namespace.Resources.File.ext"))) { using (BinaryWriter writer = new BinaryWriter(new FileStream(path, FileMode.Create))) { long bytesLeft = reader.BaseStream.Length; while (bytesLeft > 0) { // 65535L is < Int32.MaxValue, so no need to test for overflow byte[] chunk = reader.ReadBytes((int)Math.Min(bytesLeft, 65536L)); writer.Write(chunk); bytesLeft -= chunk.Length; } } } ``` There appears to be no more direct way to do the copy, unless I'm missing something...
I'm not sure why you're using `BinaryReader`/`BinaryWriter` at all. Personally I'd start off with a useful utility method: ``` public static void CopyStream(Stream input, Stream output) { // Insert null checking here for production byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, bytesRead); } } ``` then call it: ``` using (Stream input = assembly.GetManifestResourceStream(resourceName)) using (Stream output = File.Create(path)) { CopyStream(input, output); } ``` You can change the buffer size of course, or have it as a parameter to the method - but the main point is that this is *simpler* code. Is it more efficient? Nope. Are you sure you really *need* this code to be more efficient? Do you actually have hundreds of megabytes you need to write out to disk? I find I rarely need code to be ultra-efficient, but I almost always need it to be simple. The sort of difference in performance that you might see between this and a "clever" approach (if one is even available) isn't likely to be a complexity-changing effect (e.g. O(n) to O(log n)) - and *that's* the type of performance gain which really can be worth chasing. EDIT: As noted in comments, .NET 4.0 has [`Stream.CopyTo`](http://msdn.microsoft.com/en-us/library/system.io.stream.copyto.aspx) so you don't need to code this up yourself.
If the resource (file) is binary. ``` File.WriteAllBytes("C:\ResourceName", Resources.ResourceName); ``` And if the resource (file) is text. ``` File.WriteAllText("C:\ResourceName", Resources.ResourceName); ```
Write file from assembly resource stream to disk
[ "", "c#", ".net", "" ]
This is my first bash at using extJS, and after a few hours of struggling, some things are working OK, except I have combo lists that I can't filter down to less than 2000 items in edge cases, so I'm trying to page the lists through remotely, but I must be doing something wrong. My data store and combo look as follows: ``` var remoteStore = new Ext.data.JsonStore({ //autoLoad : true, url : 'addition-lists.aspx', fields : [{name: 'extension_id'}, {name: 'extension'}], root : 'extensionList', id : 'remoteStore' }); . . xtype : 'combo', fieldLabel : 'Remote', name : 'remote', displayField : 'extension', valueField : 'extension_id', mode : 'remote', //pageSize : 20, triggerAction : 'query', typeAhead : true, store : remoteStore, anchor : '95%' ``` The combo works loading locally, but as soon as I switch to remote it remains blank. My ASP.NET page returning the JSON is like this: ``` protected void Page_Load(object sender, EventArgs e) { Response.Clear(); Response.Write(GetRemote()); } ```
On remote stores the combo defaults its `minChars` property to 4, so the query only gets sent after typing 4 chars. Setting `minChars` almost gives the desired behaviour. I say almost because even if the item sought by autocomplete is in the current page, a new server query still gets sent, defaulting the selection to the first item in the new page.
The way you configured your store above, the result from your ASP script should read something like this: ``` {"extensionList": [ {"extension_id": 1, "extension": "js"}, {"extension_id": 2, "extension": "aspx"} ]} ``` If it doesn't look like that, your remote store will not find anything.
Loading extJS Combo Remotely not Working
[ "", "asp.net", "javascript", "extjs", "" ]
I have a java desktop application with information about several entities. There is a "print" button than WHEN pressed various information should be collected and printed. The question is: How can i select WHAT will be printed ON a specific location on the paper? A more general question would be: How can i format information to be printed on paper?
I would suggest using something like [iText](http://www.lowagie.com/iText/) for generating a PDF and print the PDF instead. As a bonus, the output can be saved easily and attached to an e-mail.
You need the Java Print Service - <http://java.sun.com/javase/6/docs/technotes/guides/jps/index.html>
java printing on paper - formatting output for print
[ "", "java", "printing", "" ]
``` ... case 1: string x = "SomeString"; ... break; case 2: x = "SomeOtherString"; ... break; ... ``` Is there something that I am not understanding about the switch statement in C#? Why would this not be an error when case 2 is used? Edit: This code works and doesn't throw an error.
You have to be careful how you think about the `switch` statement here. There's *no creation of variable scopes* going on at all, in fact. Don't let the fact that just because the code within cases gets indented that it resides within a child scope. When a switch block gets compiled, the `case` labels are simply converted into labels, and the appropiate `goto` instruction is executed at the start of the switch statement depending on the switching expression. Indeed, you can manually use `goto` statements to create "fall-through" situations (which C# does directly support), as [the MSDN page](http://msdn.microsoft.com/en-us/library/06tc147t(VS.71).aspx) suggests. ``` goto case 1; ``` If you specifically wanted to create scopes for each case within the `switch` block, you could do the following. ``` ... case 1: { string x = "SomeString"; ... break; } case 2: { string x = "SomeOtherString"; ... break; } ... ``` This *requires* you to redeclare the variable `x` (else you will receive a compiler error). The method of scoping each (or at least some) can be quite useful in certain situations, and you will certainly see it in code from time to time.
The documentation on [MSDN](http://msdn.microsoft.com/en-us/library/aa691132.aspx) says : > The scope of a local variable declared in a switch-block of a switch statement (Section 8.7.2) is the switch-block. Also, a similar question has been asked before: [Variable declaration in c# switch statement](https://stackoverflow.com/questions/222601/variable-declaration-in-c-switch-statement)
C# switch variable initialization: Why does this code NOT cause a compiler error or a runtime error?
[ "", "c#", "switch-statement", "" ]
Could any one suggest good Python-related podcasts out there, it could be anything about Python or its eco-system (like django, pylons, etc).
[Google Code University](http://code.google.com/edu/languages/index.html) (several languages there) [Python Podcasts](http://advocacy.python.org/podcasts/) [Python Learning Foundation](http://www.awaretek.com/python/index.html) [Python411 on PodcastAlley.com](http://www.podcastalley.com/podcast_details.php?pod_id=5786)
I didn't think much of Python411 - the episode I downloaded primarily consisted of the host talking about how he was planning on writing a GAE site. [This Week in Django](http://thisweekindjango.com/) as pointed out by Geo is (or possibly was) a good Python podcast. Obviously, as it's focused on Django development there is a lot of Djangoisms discussed however there's also a lot of general Python knowledge shared as well. TWID is currently going through a revamp, keep an eye on [@djangodose](http://twitter.com/djangodose) for updates.
Best Python podcasts?
[ "", "python", "podcast", "" ]
In .NET can I use any string as a dictionary key? This is part of a templating engine and I'm planning allow users to add their custom headers and values. Headers will be something like "Value of X" or "Summary of Analyse & XYZ Reports", I'm worried if they would get an exception in a rare character or something like that. I assume there size limit but expecting it to be larger than 256 characters. MSDN hasn't got any details on the subject.
Yes, it can use any valid string (which is limited to a couple billion bytes). BTW, you might pass a custom `IEqualityComparer<T>` that you might pass to the `Dictionary` constructor which might require a maximum limit.
The dictionary doesn't have any special knowledge of the types used as its keys and values. Irrespective of the object type it will simply call the `GetHashCode` and `Equals` methods to allow it to put the value in the right bucket and retrieve it again. Which means that any class which correctly implements these methods can be used as the key. The `string` class does correctly implement these methods based on its value, so as long as you can construct an instance of the string, then you can use it as the key.
Is there any character limitation in Dictionary Keys?
[ "", "c#", ".net", "dictionary", "key", "key-value", "" ]
I have a JEE application that runs on WAS 6. It needs to have the class loader order setting to "Classes loaded with application class loader first", and the WAR class loader policy option set to "Single class loader for application". Is it possible to specify these options inside the EAR file, whether in the ibm-web-bnd.xmi file or some other file, so the admin doesn't need to change these setting manually? Since the app is deployed via an automated script, and the guy who is in charge of deployment is off site, and also for some other political reasons, this would greatly help!
Thanks to @Matthew Murdoch's answer, I was able to come up with a solution. Here it is, in case it helps someone else. I created a deployment.xml like this: ``` <?xml version="1.0" encoding="UTF-8"?> <appdeployment:Deployment xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:appdeployment="http://www.ibm.com/websphere/appserver/schemas/5.0/appdeployment.xmi" xmi:id="Deployment_1241112964096"> <deployedObject xmi:type="appdeployment:ApplicationDeployment" xmi:id="ApplicationDeployment_1241112964096" startingWeight="1" warClassLoaderPolicy="SINGLE"> <classloader xmi:id="Classloader_1241112964096" mode="PARENT_LAST"/> <modules xmi:type="appdeployment:WebModuleDeployment" xmi:id="WebModuleDeployment_1241112964096" startingWeight="10000" uri="AGS.war"> <classloader xmi:id="Classloader_1241112964097"/> </modules> </deployedObject> </appdeployment:Deployment> ``` Make sure to change the name of your WAR file(s) to match (mine is called AGS.war). I also changed the numbers in the `xmi:id` attributes, to be sure they are unique, though I'm not sure it it really matters that they be unique across applications. Then, I put the deployment.xml file in the root of my EAR file, via ANT: ``` <ear destfile="${artifactsDir}/${earName}.ear" appxml="${projectName}_EAR/application.xml"> <fileset dir="${artifactsDir}" includes="${warName}.war"/> <fileset dir="${projectName}_EAR/" includes="deployment.xml"/> </ear> ```
**Edit (2):** The [WebSphere Application Server Toolkit (AST)](http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/tins_ast_roadmap.html) is a tool you can use to enhance an EAR file with this information (see for example the 'Configure an Enhanced EAR' section in [this document](http://media.techtarget.com/digitalguide/images/Misc/wapp.pdf)). **Edit (1):** [This post](http://www.ibm.com/developerworks/forums/thread.jspa?threadID=201067) suggests that the 'Classes loaded with application class loader first' (the PARENT\_LAST setting) can be set in the deployment.xml file within the EAR. If you have control over the automated deployment scripts this can be done. Below is some wsadmin jython code for setting the web module class loader order to 'Classes loaded with application class loader first' (interestingly the setting is called PARENT\_LAST which is what it was labelled in previous versions of the admin console...). wsadmin example (jython): ``` def getWebModule(config, applicationName): webModules = config.list('WebModuleDeployment'). split(system.getProperty('line.separator')) for webModule in webModules: if (webModule.find(applicationName) != -1): return webModule return None applicationName = "<Your application name here>" webModule = getWebModule(AdminConfig, applicationName) if (webModule != None): AdminConfig.modify(webModule, "[[classloaderMode PARENT_LAST]]") AdminConfig.save() else: print "Error: Cannot find web module for application: " + applicationName ```
Can I set the classloader policy for WebSphere in the ibm-web-bnd.xmi file?
[ "", "java", "websphere", "classloader", "" ]
In Java you can define generic class that accepts only types that extend a class of your choice: ``` public class ObservableList<T extends List> { /* ... */ } ``` This is done using `extends` keyword. Is there some simple equivalent to this keyword in C++?
I suggest using Boost's [static assert](http://www.boost.org/doc/libs/1_39_0/doc/html/boost_staticassert.html) feature in concert with [`is_base_of`](http://www.boost.org/doc/libs/1_39_0/libs/type_traits/doc/html/boost_typetraits/reference/is_base_of.html) from the Boost Type Traits library: ``` template<typename T> class ObservableList { BOOST_STATIC_ASSERT((is_base_of<List, T>::value)); //Yes, the double parentheses are needed, otherwise the comma will be seen as macro argument separator ... }; ``` In some other, simpler cases, you can simply forward-declare a global template, but only define (explicitly or partially specialise) it for the valid types: ``` template<typename T> class my_template; // Declare, but don't define // int is a valid type template<> class my_template<int> { ... }; // All pointer types are valid template<typename T> class my_template<T*> { ... }; // All other types are invalid, and will cause linker error messages. ``` **[Minor EDIT 6/12/2013: Using a declared-but-not-defined template will result in *linker*, not compiler, error messages.]**
This typically is unwarranted in C++, as other answers here have noted. In C++ we tend to define generic types based on other constraints other than "inherits from this class". If you really wanted to do that, it's quite easy to do in C++11 and `<type_traits>`: ``` #include <type_traits> template<typename T> class observable_list { static_assert(std::is_base_of<list, T>::value, "T must inherit from list"); // code here.. }; ``` This breaks a lot of the concepts that people expect in C++ though. It's better to use tricks like defining your own traits. For example, maybe `observable_list` wants to accept any type of container that has the typedefs `const_iterator` and a `begin` and `end` member function that returns `const_iterator`. If you restrict this to classes that inherit from `list` then a user who has their own type that doesn't inherit from `list` but provides these member functions and typedefs would be unable to use your `observable_list`. There are two solutions to this issue, one of them is to not constrain anything and rely on duck typing. A big con to this solution is that it involves a massive amount of errors that can be hard for users to grok. Another solution is to define traits to constrain the type provided to meet the interface requirements. The big con for this solution is that involves extra writing which can be seen as annoying. However, the positive side is that you will be able to write your own error messages a la `static_assert`. For completeness, the solution to the example above is given: ``` #include <type_traits> template<typename...> struct void_ { using type = void; }; template<typename... Args> using Void = typename void_<Args...>::type; template<typename T, typename = void> struct has_const_iterator : std::false_type {}; template<typename T> struct has_const_iterator<T, Void<typename T::const_iterator>> : std::true_type {}; struct has_begin_end_impl { template<typename T, typename Begin = decltype(std::declval<const T&>().begin()), typename End = decltype(std::declval<const T&>().end())> static std::true_type test(int); template<typename...> static std::false_type test(...); }; template<typename T> struct has_begin_end : decltype(has_begin_end_impl::test<T>(0)) {}; template<typename T> class observable_list { static_assert(has_const_iterator<T>::value, "Must have a const_iterator typedef"); static_assert(has_begin_end<T>::value, "Must have begin and end member functions"); // code here... }; ``` There are a lot of concepts shown in the example above that showcase C++11's features. Some search terms for the curious are variadic templates, SFINAE, expression SFINAE, and type traits.
How do you constrain a template to only accept certain types
[ "", "c++", "templates", "constraints", "" ]
OK I keep getting this error after about 3-4 minutes of churning: ``` Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. Source Error: Line 93: Line 94: DataSet getData; Line 95: getData = SqlHelper.ExecuteDataset(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString, CommandType.StoredProcedure, "Course_NewReportGet_Get_Sav", objPara); Line 96: Line 97: foreach (DataRow dr in getData.Tables[0].Rows) ``` Here is the code, I think I am not doing something properly, I set the timeout to 5000 seconds though so it must be something else. You'll notice it's quite the nested loop of procedure calls. I am getting every Company, then getting every Course assigned to each Company, then for each course I am getting a report of all the users activity. There is about 250 companies, anywhere from 2-70 courses per comapany, and from 8 to 1000 users per course report, per company... so we're dealing with a lot of data here. That final call to the get report is a pretty massive stored procedure also... I am trying to transform the data into a new form that will make it faster and easier to work with later but for now I have to parse through what we have and post it in the new way. It is all in the same database but I am not exactly sure how I would do this all in just SQL. Basically am using a stored procedure that is used by our reporting tools to get the data to post to the new table. But I need to run the procedure for each course for each company and then post the data for each user returned in the report from each course from each company... It's huge... ``` using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; using Mexico.Data; public partial class admin_tools_Optimus : System.Web.UI.Page { protected int step = 0; protected string[] companies = new string[260]; protected string[] coursestrings = new string[260]; protected int total = 0; protected int[] totalcourses = new int[260]; protected void Page_Load(object sender, EventArgs e) { } protected void Proceed(object sender, EventArgs e) { DataSet getCompanies = SqlHelper.ExecuteDataset(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString, CommandType.StoredProcedure, "Companies_All_Get"); int counter = 0; foreach (DataRow dr in getCompanies.Tables[0].Rows) { lstData.Items.Add(dr["companyid"].ToString() + ": " + dr["companyname"].ToString()); companies[counter] = dr["companyid"].ToString(); counter++; } lblCurrentData.Text = counter.ToString() + " companies ready, click next to get all company courses."; total = counter; GetCompanies(); } protected void GetCompanies() { string[,] courses = new string[260, 200]; for (int i = 0; i < total-1; i++) { DataSet getBundles = SqlHelper.ExecuteDataset(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString, CommandType.StoredProcedure, "CompanyCourses_ByCompanyID_Get_Sav", new SqlParameter("@companyid", companies[i])); int counter = 0; foreach (DataRow dr in getBundles.Tables[0].Rows) { courses[i, counter] = dr["bundleid"].ToString(); counter++; } string allID = ""; allID += courses[i, 0]; for (int ii = 0; ii < counter; ii++) { allID += "," + courses[i, ii]; } Response.Write(allID + " <br/>"); coursestrings[i] = allID; totalcourses[i] = counter; } GetUsers(); } protected void GetUsers() { for (int i = 0; i < total - 1; i++) { SqlParameter[] objPara = new SqlParameter[10]; objPara[0] = new SqlParameter("@CompanyID", companies[i]); objPara[1] = new SqlParameter("@CourseID", coursestrings[i]); objPara[2] = new SqlParameter("@DateRangeType", 1); //objPara[3] = new SqlParameter("@StartDate", startDate); //objPara[4] = new SqlParameter("@EndDate", System.DateTime.Now.ToString("MM/dd/yyyy")); objPara[5] = new SqlParameter("@UserName", ""); objPara[6] = new SqlParameter("@StartIndex", 1); objPara[7] = new SqlParameter("@MaximumRows", 100000); DataSet getData; getData = SqlHelper.ExecuteDataset(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString, CommandType.StoredProcedure, "Course_NewReportGet_Get_Sav", objPara); foreach (DataRow dr in getData.Tables[0].Rows) { Response.Write("user: " + dr["userid"].ToString() + " / course: " + dr["bundleid"].ToString() + " - progress: " + dr["viewed"].ToString() + " - scored: " + dr["scored"].ToString() + "<br/><br/>"); } } } } ``` PAGE CODE: ``` <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Optimus.aspx.cs" Inherits="admin_tools_Optimus" Debug="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lblCurrentData" runat="server" Text="Click next to get all Companies"/><br /> <asp:Button ID="btnNext" runat="server" Text="Next" OnClick="Proceed" /> <br/> <asp:ListBox ID="lstData" runat="server" height="300" Width="300" /> </div> </form> </body> </html> ```
It looks like the timeout is happening when you're running the sql stored procedure (Your exception is of type SqlException). You would need to increase the Timeout of your Sql Stored Procedure execution, but I don't think you can do that with the SqlHelper class. You'll need to go with the SqlCommand class, and set the timeout there.
There are five different timeouts you have to know about when talking to a database from an asp.net page: 1. **The database connection timeout** Set on your `SQLConnection` object, possibly via the connection string. 2. **The database command timeout** Set on your `SQLCommand` object. 3. **The ASP.Net Script Timeout** Set on your page via `Server.ScriptTimeout`. 4. **Other IIS timeouts** Imposed on your page by IIS. See this link: <http://msdn.microsoft.com/en-us/library/ms525386.aspx?ppud=4> 5. **The internet browser timeout** The browser/client will only wait so long. You don't control this so there's no point worrying about it, but you should still know it exists. Make sure you check the first 4 I listed. Normally I'd also say something to the effect that 3+ minutes is *way* to long to wait for a page to load. You might have enough data to justify the query time, but if so that's too much data for a user to really evaluate in one page. Consider breaking it up. But in this case it sounds like you're building a 'report' that needs to be run infrequently. While I still question the merits of such reports (it's just too much data to go through by hand — dump it into a fact table or somewhere similar for additional data mining instead), I understand that businesses often want them anyway. Also, looking at your code I can see where you might be able to write that all as one big query instead of a bunch of little ones. That would be a lot more efficient for the database at the expense of some additionally complexity in assembling your results, but the result will run much faster. But for something that doesn't run often, when you already have the stored procedures built to do it this way, you may not be able to justify re-writing things. So I'll give you a pass on the long-running page... this time.
Time out period not elapsed, but still timing out (see code)?
[ "", "asp.net", "sql", "timeout", "" ]
I have the below methods: ``` public static byte[] ConvertFileToBytes(string filePath) { var fInfo = new FileInfo(filePath); var numBytes = fInfo.Length; var dLen = Convert.ToDouble(fInfo.Length / 1000000); var fStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); var br = new BinaryReader(fStream); var data = br.ReadBytes((int)numBytes); br.Close(); fStream.Close(); fStream.Dispose(); return data; } public static void ConvertBytesToFile(byte[] file, string filePath) { var ms = new MemoryStream(file); var fs = new FileStream(filePath, FileMode.Create); ms.WriteTo(fs); ms.Close(); fs.Close(); fs.Dispose(); } ``` **What is the correct to name these methods?** (because Convert*XXX*to*YYY* just doesn't cut it in a Utilities library)
How about [File.ReadAllBytes](http://msdn.microsoft.com/en-us/library/system.io.file.readallbytes.aspx) and [File.WriteAllBytes](http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx) ;)
The terms usually used are "serialize" and "deserialize" (or sometimes "marshal" and "demarshal").
Correct terminology for streaming a file into bytes and back
[ "", "c#", "file", "streaming", "naming", "" ]
I've got a large set of inherited classes (criteria) which inherit from a base class (criterion). Here's `criterion`'s code ``` class criterion { public: virtual unsigned __int32 getPriorityClass() const = 0; virtual BOOL include(fileData &file) const = 0; virtual void reorderTree() = 0; virtual unsigned int directoryCheck(const std::wstring& directory) const = 0; virtual std::wstring debugTree() const = 0; }; ``` Some examples of derived classes from this one: ``` class fastFilter : public criterion { public: void reorderTree() {}; unsigned int directoryCheck(const std::wstring& /*directory*/) const { return DIRECTORY_DONTCARE; }; unsigned __int32 getPriorityClass() const { return PRIORITY_FAST_FILTER; }; }; class isArchive : public fastFilter { public: BOOL include(fileData &file) const { return file.getArchive(); } std::wstring debugTree() const { return std::wstring(L"+ ISARCHIVE\n"); }; }; ``` Since I don't have a destructor here at all, but yet this is supposed to be a base class, do I need to insert an empty virtual destructor, I.e. like this?: ``` virtual void ~criterion() = 0; ``` If that virtual destructor declaration is needed, do all intermediate classes need one as well? I.e. would fastFilter above need a virtual destructor as well?
Yes - the base class needs a virtual destructor, even if it's empty. If that is not done, then when something `delete`'s a derived object through a base pointer/reference, the derived object's member objects will not get a chance to destroy themselves properly. Derived classes do not need to declare or define their own destructor unless they need something other than default destructor behavior.
The recommendation is to insert: ``` virtual ~criterion() {} ``` Starting from C++11, you can use `= default;` instead of an empty body `{}`. This is to avoid problems with deleting from a base class' pointer. Otherwise you will leak memory as derived classes' destructors will not be called. ``` criterion *c = new fastFilter(); delete c; // leaks ```
Virtual Default Destructors in C++
[ "", "c++", "virtual-destructor", "" ]
I'm working on a Firefox extension where I'll want to keep multiple windows in sync with the same information. The toolbar queries a remote server for info periodically, based on when the window was opened. Because Firefox windows are all separately self-contained environments, each with their own toolbar running separate code I thought I'd use a singleton here. There's really no need for multiple requests, there can be one request for each of the windows, the problem though is that there is no global master scope over-lording it over the multiple windows context, there are only windows contexts. I thought I'd create a factory class that checks to see if one of the windows already has an instance of my notification class running and if so uses that same instance to get updates. It seems like a legitimate use of a singleton, but I keep reading about how they're evil beasts. Is this an ok use?
The problem is that each Firefox window is an entirely separate process as far as JavaScript is concerned. So yeah, it'll work, but only if you conditionally create the singleton. If it's just unconditionally created at global scope (in my case, as a member of my top-level extension object), it's going to be in all windows. The other problem you're going to have is that windows take a while to start and run JavaScript, and you don't have anything like synchronization. It's entirely possible that window 1 checks to see if window 2 has created the singleton, sees it hasn't, window 2 check window 1, sees it hasn't, and then both create their own singleton. I speak from experience: I wrote a Firefox extension that does something very much like what you want to do: only one window is supposed to check the remote server (and all other windows need to be informed when anyone window closes). (In mine, each window on start-up queries all other windows to find the "master" window.) The cleaner way around this is to create a service, just like the ones the browser exposes to javascript; but that requires coding in C, not javascript, and makes installing the extension cross-platform more of a pain.
There's nothing inherently wrong with a singleton, per se. The problem lies in how it can be (ab)used: it's essentially a fancy way to have globals. A singleton just lets you have a level of indirection that self-contains most of that data. Sometimes, though, this pattern is the only way you can solve certain problems. In that case, it's perfectly fine. However, if you can think of another way that uses maybe only a little bit more code/memory/performance-hit to accomplish, I'd go with that if I could. Otherwise, there's really nothing wrong with using a singleton, as long as you're aware of what you're getting into.
Do I actually have a need for a Singleton?
[ "", "javascript", "design-patterns", "singleton", "firefox-addon", "" ]
I am working on an application/GUI created with Win32/ATL . So there is UI field( text field) which works fine as designed in debug build. With release build it gets malformed and it looks like the width of text field is infinite. It works fine in debug build but creating issues in release build. So my question how same code can work in debug build and not working in release build. Is there any chance that it could be releated to optimization settings in release builds ? In release build we have optimization settings set to Minimum Size, Favour small code. Also when I try to debug release build ,it again works fine. Does debugging in release build removes optimization? I want to reproduce the issue while debugging in release build or may be if possible in debug build. Any suggestions?
VC++ fills its runtime-memory in debug mode with special values. It does not ensure any fixed or zero-initialization though. Read this SO thread for details. [Uninitialized Memory Blocks](https://stackoverflow.com/questions/65724/uninitialized-memory-blocks-in-vc). These values may not crash the application every time. I have run into similar situations some times. One common example is that accessing past the array boundaries is an error. Many a time this was not evident in debug mode but crashed in release builds. In general, the runtime is leniant in debug modes and provides more cover to programmer errors. As others have pointed out, there is definitely some problem with the code; most probably uninitialized variables.
Try enabling the [/RTC (Run-Time Error Checks](http://msdn.microsoft.com/en-us/library/8wtf2dfz(VS.80).aspx) compiler flag with the **s** option. This initializes local variables to a non zero value which helps diagnose uninitialized variables.
Optimization settings in VS
[ "", "c++", "visual-studio", "" ]
### Exact Duplicate > [Table Naming Dilemma: Singular vs. Plural Names](https://stackoverflow.com/questions/338156/table-naming-dilemma-singular-vs-plural-names) Is it better to use singular or plural database table names ? Is there an accepted standard ? I've heard arguments for and against it, what do you guys think ?
IMHO, Table names should be plural like Customers. Class names should be singular like Customer if it maps to a row in Customers table.
Singular, so you can have: * Customer * CustomerAddress * CustomerAddressAuditTrail etc.
Singular or plural database table names?
[ "", "sql", "mysql", "sql-server", "" ]
I've written a simple Application that utilizes WCF to communicate between client and server. When I run it locally it works fine, however when I run the server and client on two different boxes I get the following exception: ``` Unexpected error occured, while getting the group names from the VDN server System.ServiceModel.Security.SecurityNegotiationException: The server has rejected the client credentials. System.Security.Authentication.InvalidCredentialException: The server has rejected the client credentials. System.ComponentModel.Win32Exception: The logon attempt failed ``` What are the credentials that are not being accepted? And how can I set them? Is there a way to configure the server to not require authentication? The application is a simple monitoring app to security is not really an issue. **Sorry about not being very specific:** The app uses a pipe proxy and there is no wcf config file as the wcf code is hand coded. My WCF code is based on the code in this tutorial: <http://www.switchonthecode.com/tutorials/wcf-tutorial-basic-interprocess-communication> I didn't konw it was standard proctice to generate the wcf classes from a config till after I'd finished writing all the code. Now whenever I look at a tutorial/ help doc they use generated code and everything requires changing the config. I don't have the bandwidth (I'm juggling 3 projects already) to replace my wcf component with one tht uses generated code but I will make sure to use the code generation next time I use wcf.
Create a method like this... ``` void SetImpersonation(ref IServiceClient proxy) { proxy.ClientCredentials.Windows.ClientCredential.Domain = "MYDOMAIN"; proxy.ClientCredentials.Windows.ClientCredential.UserName = "A_USER"; proxy.ClientCredentials.Windows.ClientCredential.Password = "P4SSW0RD"; } ``` and call it when you create the new client class. ``` IServiceClient proxy = new IServiceClient (); SetImpersonation(ref proxy); ``` Obvously, this is setting the information to be a specific user, and has security implications if your code is decompiled, but it should work in your (config file-less scenario)
Here's a solution I found in a search for disabling wcf security/authentication. From [MSDN](http://social.msdn.microsoft.com/forums/en-US/wcf/thread/0aa606b7-171e-4c00-9dd6-6c635f96d906): ``` WSHttpBinding b = new WSHttpBinding(); b.Security.Mode = SecurityMode.None; ``` or add the following in config: ``` <wsHttpBinding> <binding name="myBinding"> <security mode="None" /> </binding> </wsHttpBinding> ```
Setting credentials for a WCF application?
[ "", "c#", ".net", "wcf", "" ]
I have been given a specification that requires the `ISO 8601` date format, does any one know the conversion codes or a way of getting these 2 examples: ``` ISO 8601 Extended Date 2000-01-14T13:42Z ISO 8601 Basic Date 20090123T105321Z ```
When dealing with dates in SQL Server, the ISO-8601 format is probably the best way to go, since it just works regardless of your language and culture settings. In order to INSERT data into a SQL Server table, you don't need any conversion codes or anything at all - just specify your dates as literal strings ``` INSERT INTO MyTable(DateColumn) VALUES('20090430 12:34:56.790') ``` and you're done. If you need to convert a date column to ISO-8601 format on SELECT, you can use conversion code 126 or 127 (with timezone information) to achieve the ISO format. ``` SELECT CONVERT(VARCHAR(33), DateColumn, 126) FROM MyTable ``` should give you: ``` 2009-04-30T12:34:56.790 ```
This ``` SELECT CONVERT(NVARCHAR(30), GETDATE(), 126) ``` will produce this ``` 2009-05-01T14:18:12.430 ``` And some more detail on this can be found at [MSDN](http://msdn.microsoft.com/en-us/library/ms187928(SQL.90).aspx).
TSQL DATETIME ISO 8601
[ "", "sql", "sql-server", "t-sql", "datetime", "" ]
I'm doing javascript on a daily basis at the moment. I'm coming from an OO background and most of the code I have contact with is somewhat procedural/OO style. I'm looking for good examples that solves more or less typical web programming tasks but in a functional manner. I'm not interested to have any arbitrary example that just looks like functional. I'm looking for an example that can show how to use the functional powers to solve problems better than with another approach. I know this is kind of subjective/style dependent but don't make it too hard for yourself (myself).
Firstly, you want to comprehend what functional programming means; that is, what are the core concepts and how well the language allows you to adhere to those concepts. For OOP, the core concepts are encapsulation, inheritance, and polymorphism (or just message passing for smalltalkers). For FP the central tenet is [referential transparency](http://en.wikipedia.org/wiki/Referential_transparency) (which implies statelessness). Trying to program in a functional style in a language that doesn't support functional features (e.g. functions as first class objects) will be awkward if not impossible. Same with programming in OOP in languages that don't have OOP features. Fortunately Javascript is multi-paradigm and supports both. Instead of looking for examples of code that is 'functional' just think about all the ways in which you can ensure referential transparency and this will *naturally* lead to using the FP features of the language such as lambdas, closures, higher-order functions (e.g. map, reduce, filter), currying, etc. Seriously, this is not meant to be a non-answer. I really think this is the most motivating and efficient way of approaching it. That said, here are some hopefully helpful links. 1. [FP programming in JavaScript](http://www.ibm.com/developerworks/library/wa-javascript.html) 2. [Mostly adequate guide to FP](https://github.com/MostlyAdequate/mostly-adequate-guide)
Douglas Crockford links to [Functional JavaScript](http://osteele.com/sources/javascript/functional/) from his [JavaScript](http://javascript.crockford.com/) resource page. Here is a snippet from the site: > Functional is a library for functional > programming in JavaScript. It defines > the standard higher-order functions > such as map, reduce (aka foldl), and > select (aka filter). It also defines > functions such as curry, rcurry, and > partial for partial function > application; and compose, guard, and > until for function-level programming. > And all these functions accept > strings, such as 'x -> x+1', 'x+1', or > '+1' as synonyms for the more verbose > function(x) {return x+1}.
What is a good example for functional style web programming using javascript?
[ "", "javascript", "functional-programming", "" ]
How do I loop through the all controls in a window in WPF?
Class to get a list of all the children's components of a control: ``` class Utility { private static StringBuilder sbListControls; public static StringBuilder GetVisualTreeInfo(Visual element) { if (element == null) { throw new ArgumentNullException(String.Format("Element {0} is null !", element.ToString())); } sbListControls = new StringBuilder(); GetControlsList(element, 0); return sbListControls; } private static void GetControlsList(Visual control, int level) { const int indent = 4; int ChildNumber = VisualTreeHelper.GetChildrenCount(control); for (int i = 0; i <= ChildNumber - 1; i++) { Visual v = (Visual)VisualTreeHelper.GetChild(control, i); sbListControls.Append(new string(' ', level * indent)); sbListControls.Append(v.GetType()); sbListControls.Append(Environment.NewLine); if (VisualTreeHelper.GetChildrenCount(v) > 0) { GetControlsList(v, level + 1); } } } } ```
I found this in the [MSDN documenation](http://msdn.microsoft.com/en-us/library/system.windows.media.visualtreehelper.aspx) so it helps. ``` // Enumerate all the descendants of the visual object. static public void EnumVisual(Visual myVisual) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myVisual); i++) { // Retrieve child visual at specified index value. Visual childVisual = (Visual)VisualTreeHelper.GetChild(myVisual, i); // Do processing of the child visual object. // Enumerate children of the child visual object. EnumVisual(childVisual); } } ``` Looks simpler to me. I used it to find textboxes in a form and clear their data.
WPF: How do I loop through the all controls in a window?
[ "", "c#", ".net", "wpf", "" ]
I have a couple of functions that loop around the surrounding cells of a cell. The grid is contained inside an array. In my code, I have checks to make sure it's not one of the edge cells, as checking an undefined cell causes an error. As such, I have code like this: ``` if(x > 0) { var firstX = x - 1; } else { var firstX = x; } if(x < 199) { var lastX = x + 1; } else { var lastX = x; } if(y > 0) { var firstY = y - 1; } else { var firstY = y; } if(y < 199) { var lastY = y + 1; } else { var lastY = y; } ``` A lot of lines of code to do very little. Is there a more elegant way to do this?
You can use the conditional operator: ``` var firstX = x > 0 ? x - 1 : x; var lastX = x < 199 ? x + 1 : x; var firstY = y > 0 ? y - 1 : y; var lastY = y < 199 ? y + 1 : y; ``` You *could* remove the redundancy by writing a function to calculate "first" given a value, and a similar one for "last" - but I think that would be overkill in this case.
Or more clearly: ``` var firstX = Math.max(x - 1, 0); var lastX = Math.min(x + 1, 199); var firstY = Math.max(y - 1, 0); var lastY = Math.min(y + 1, 199); ```
More compact way to do this?
[ "", "javascript", "arrays", "loops", "" ]
This is my procedure: ``` bool Open(std::string filename) { ... HANDLE hFile = CreateFile(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); ... } ``` Error:'CreateFileW' : cannot convert parameter 1 from 'const char \*' to 'LPCWSTR' Types pointed to are unrelated; conversion requires reinterpret\_cast, C-style cast or function-style cast Where is the problem?
A std::string consists of an array of char's, and so the `c_str` function returns a `const char*`. A `LPCWSTR` is a Long Pointer to a Constant Wide String, or in other words, `const wchar_t*`. So you have a couple of options. Either get the filename as a wide string (std::wstring), or specify that you want the non-wide version of CreateFile instead. That can be done either by calling CreateFileA or disabling UNICODE in your project settings. CreateFile is a macro which either resolves to CreateFileA (the char version) or CreateFileW (the wide char version) depending on whether or not unicode is enabled.
You have specified std::string, whose character type is `char`. And the code you're using `CreateFile()` in must be being compiled under the definition of the pre-processor symbol `UNICODE`, since that selects the actual underlying function `CreateFileW()`. Either get rid of the `UNICODE` definition, or explicitly use `CreateFileA()`.
C++ std::string conversion problem on Windows
[ "", "c++", "windows", "string", "" ]
I am having some issues trying to convert a double to C++ string. Here is my code ``` std::string doubleToString(double val) { std::ostringstream out; out << val; return out.str(); } ``` The problem I have is if a double is being passed in as '10000000'. Then the string value being returned is 1e+007 How can i get the string value as "10000000"
``` #include <iomanip> using namespace std; // ... out << fixed << val; // ... ``` You might also consider using `setprecision` to set the number of decimal digits: ``` out << fixed << setprecision(2) << val; ```
``` #include <iomanip> std::string doubleToString(double val) { std::ostringstream out; out << std::fixed << val; return out.str(); } ```
Converting Double to String in C++
[ "", "c++", "string", "double", "" ]
I would like to print scrollable div as WYSWYG. Is there a way?
Not with pure css, I don't think. My...interpretation of what happens when you hit the print button is that the document's reloaded with either the `media="print"` or other relevant stylesheet, and then sent to print-preview/the printer as a new document, with all content in the default/start position as defined in that stylesheet. Since I can't think of a way to position the scrolling content, using css, I'd have to say that it's not possible. Javascript's almost certainly the way to go on this one. ...may I ask why you'd want to do this? It's not a criticism, I just...don't understand.
I don't think you can do it even with javascript. It is against the spirit of the web. Printed document is *supposed* to look different. I suspect that when you see a scroll bars on printed page, it is a bug to be fixed in future version of a browser.
Persisting the scroll position of DIV while printing
[ "", "javascript", "html", "css", "printing", "" ]
Is it possible to read binary MATLAB .mat files in Python? I've seen that SciPy has alleged support for reading .mat files, but I'm unsuccessful with it. I installed SciPy version 0.7.0, and I can't find the `loadmat()` method.
An import is required, `import scipy.io`... ``` import scipy.io mat = scipy.io.loadmat('file.mat') ```
Neither `scipy.io.savemat`, nor `scipy.io.loadmat` work for MATLAB arrays version 7.3. But the good part is that MATLAB version 7.3 files are hdf5 datasets. So they can be read using a number of tools, including [NumPy](http://en.wikipedia.org/wiki/NumPy). For Python, you will need the `h5py` extension, which requires HDF5 on your system. ``` import numpy as np import h5py f = h5py.File('somefile.mat','r') data = f.get('data/variable1') data = np.array(data) # For converting to a NumPy array ```
Read .mat files in Python
[ "", "python", "matlab", "file-io", "scipy", "mat-file", "" ]
The JDK documentation for [`java.lang.String.hashCode()`](http://java.sun.com/javase/6/docs/api/java/lang/String.html#hashCode()) [famously](https://stackoverflow.com/questions/299304) says: > The hash code for a String object is computed as > > ``` > s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] > ``` > > using `int` arithmetic, where `s[i]` is the \*`i`\*th character of the string, `n` is the length of the string, and `^` indicates exponentiation. The standard implementation of this expression is: ``` int hash = 0; for (int i = 0; i < length; i++) { hash = 31*hash + value[i]; } return hash; ``` Looking at this makes me feel like I was sleeping through my algorithms course. How does that mathematical expression translate into the code above?
I'm not sure if you missed where it says "^ indicates exponentiation" (not xor) in that documentation. Each time through the loop, the previous value of hash is multipled by 31 *again* before being added to the next element of `value`. One could prove these things are equal by induction, but I think an example might be more clear: Say we're dealing with a 4-char string. Let's unroll the loop: ``` hash = 0; hash = 31 * hash + value[0]; hash = 31 * hash + value[1]; hash = 31 * hash + value[2]; hash = 31 * hash + value[3]; ``` Now combine these into one statement by substituting each value of hash into the following statement: ``` hash = 31 * (31 * (31 * (31 * 0 + value[0]) + value[1]) + value[2]) + value[3]; ``` 31 \* 0 is 0, so simplify: ``` hash = 31 * (31 * (31 * value[0] + value[1]) + value[2]) + value[3]; ``` Now multiply the two inner terms by that second 31: ``` hash = 31 * (31 * 31 * value[0] + 31 * value[1] + value[2]) + value[3]; ``` Now multiply the three inner terms by that first 31: ``` hash = 31 * 31 * 31 * value[0] + 31 * 31 * value[1] + 31 * value[2] + value[3]; ``` and convert to exponents (not really Java anymore): ``` hash = 31^3 * value[0] + 31^2 * value[1] + 31^1 * value[2] + value[3]; ```
unroll the loop. Then you get: ``` int hash = 0; hash = 31*hash + value[0]; hash = 31*hash + value[1]; hash = 31*hash + value[2]; hash = 31*hash + value[3]; ... return hash; ``` Now you can do some mathematical manipulation, plug in 0 for the initial hash value: ``` hash = 31*(31*(31*(31*0 + value[0]) + value[1]) + value[2]) + value[3])... ``` Simplify it some more: ``` hash = 31^3*value[0] + 31^2*value[1] + 31^1*value[2] + 31^0*value[3]... ``` And that is essentially the original algorithm given.
Proof: why does java.lang.String.hashCode()'s implementation match its documentation?
[ "", "java", "algorithm", "math", "hashcode", "" ]
How do you optimize the heap size usage of an application that has a lot (millions) of long-lived objects? (big cache, loading lots of records from a db) * Use the right data type + Avoid java.lang.String to represent other data types * Avoid duplicated objects + Use enums if the values are known in advance + Use object pools + String.intern() (good idea?) * Load/keep only the objects you need I am looking for general programming or Java specific answers. No funky compiler switch. Edit: Optimize the memory representation of a POJO that can appear millions of times in the heap. Use cases * Load a huge csv file in memory (converted into POJOs) * Use hibernate to retrieve million of records from a database Resume of answers: * Use flyweight pattern * Copy on write * Instead of loading 10M objects with 3 properties, is it more efficient to have 3 arrays (or other data structure) of size 10M? (Could be a pain to manipulate data but if you are really short on memory...)
You don't say what sort of objects you're looking to store, so it's a little difficult to offer detailed advice. However some (not exclusive) approaches, in no particular order, are: * Use a [flyweight pattern](http://en.wikipedia.org/wiki/Flyweight_pattern) wherever possible. * Caching to disc. There are [numerous](http://java-source.net/open-source/cache-solutions) cache solutions for Java. * There is some debate as to whether String.intern is a good idea. See [here](https://stackoverflow.com/questions/725640/optimize-memory-usage-of-a-collection-of-strings-in-java) for a question re. String.intern(), and the amount of debate around its suitability. * Make use of [soft](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ref/SoftReference.html) or [weak](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ref/WeakReference.html) references to store data that you can recreate/reload on demand. See [here](http://java.sys-con.com/node/36434) for how to use soft references with caching techniques. Knowing more about the internals and lifetime of the objects you're storing would result in a more detailed answer.
I suggest you use a memory profiler, see where the memory is being consumed and optimise that. Without quantitative information you could end up changing thing which either have no effect or actually make things worse. You could look at changing the representation of your data, esp if your objects are small. For example, you could represent a table of data as a series of columns with object arrays for each column, rather than one object per row. This can save a significant amount of overhead for each object if you don't need to represent an individual row. e.g. a table with 12 columns and 10,000,000 rows could use 12 objects (one per column) rather than 10 million (one per row)
How do you make your Java application memory efficient?
[ "", "java", "caching", "memory", "heap-memory", "objectpool", "" ]
how can i check admin-privileges for my script during running?
On Unix you can check whether you are root using the [os.getuid](http://docs.python.org/3.0/library/os.html#os.getuid) function: ``` os.getuid() == 0 and "root" or "not root" ```
The concept of "admin-privileges" in our day of fine grained privilege control is becoming hard to define. If you are running on unix with "traditional" access control model, getting the effective user id (available in os module) and checking that against root (0) could be what you are looking for. If you know accessing a file on the system requires the privileges you want your script to have, you can use the os.access() to check if you are privileged enough. Unfortunately there is no easy nor portable method to give. You need to find out or define the security model used, what system provided APIs are available to query and set privileges and try to locate (or possibly implement yourself) the appropriate python modules that can be used to access the API. The classic question, why do you need to find out? What if your script tries to do what it needs to do and "just" catches and properly handles failures?
Admin privileges for script
[ "", "python", "unix", "root", "sudo", "" ]
How can I only load the HTML of a page into an IFRAME, without automatically triggering the download of all the css,scripts,images,videos on the page? Or can you get an event the moment the DOM is "ready".. when the initial HTML has loaded and nothing much more.
There is no cross-browser way to do this. Some browsers provide events that fire when the DOM loads, like [DOMContentLoaded](https://developer.mozilla.org/en/Gecko-Specific_DOM_Events) for Gecko. [jQuery implements this functionality](http://docs.jquery.com/Events/ready). I suggest you either use jQuery for this: ``` $(document).ready(function () { // Function is called when the DOM is loaded. }); ``` Or check how jQuery implements it. See the `bindReady` function in the [jQuery source code](http://code.jquery.com/jquery-latest.js).
To get only the HTML contents, try using an AJAX call. That would, of course, return the content in a variable, but you might process it as you see fit afterward.
Only load HTML into an IFRAME
[ "", "javascript", "html", "dom", "iframe", "" ]
I created a Converter to convert from double to integer. But the line "return (int)value;" always gets a "specified cast is not valid." What do I have to do so that my Converter successfully converts a double and sends back an integer? **Converter:** ``` namespace TestChangeAngle { [ValueConversion(typeof(double), typeof(int))] class DoubleToIntegerConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return (int)value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } } ``` **XAML:** ``` <Page x:Class="TestChangeAngle.Page1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestChangeAngle" Title="Page1"> <Page.Resources> <local:DoubleToIntegerConverter x:Key="DoubleToIntegerConverter"/> </Page.Resources> <StackPanel HorizontalAlignment="Left" Margin="20"> <Image Source="images\logo2.png" RenderTransformOrigin="0.5, 0.5" Width="100" Margin="10"> <Image.RenderTransform> <RotateTransform Angle="{Binding ElementName=TheSlider, Path=Value}"/> </Image.RenderTransform> </Image> <Slider x:Name="TheSlider" Width="200" Minimum="0" Maximum="360" HorizontalAlignment="Center" Margin="10" Cursor="Hand"/> <TextBox x:Name="TheAngle" Margin="10" Width="100"> <TextBox.Text> <Binding ElementName="TheSlider" Path="Value" UpdateSourceTrigger="PropertyChanged" Converter="{StaticResource DoubleToIntegerConverter}" Mode="TwoWay"> <Binding.ValidationRules> <local:MinMaxValidationRule Minimum="0" Maximum="360"/> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> </StackPanel> </Page> ```
You are attempting to cast (not convert) from double to int, which won't work. You need to do an implicit conversion or use Convert.ToInt32() -- since the argument is actually of type object I think you'll need the latter to keep the compiler happy. It's up to you whether you want to include the culture's format provider or not. ``` public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return Convert.ToInt32(value); } ``` You can use the cast operator when the object's have the same *shape*, that is, when one object is an instance of the type to which you are casting. For example, if class Foo extends class Bar, then you can cast an object of type Foo to type Bar - because a Foo object has all the methods and properties that a Bar object would. You couldn't, however, cast an object of type Bar to type Foo because Foo changes (or can change, as far as the compiler is concerned) the *shape* of Bar, by adding methods or properties that a Bar object doesn't have. In your case you are dealing with primitive types which only share the object interface - there isn't an inheritance relationship between them except that they both derive from object. There is, however, an implicit **conversion** between the two. You can assign an object one type to a variable of the other, though you may lose some precision in the value. ``` double x = 1.1; int y = 0; y = x; // implicit conversion, this works, y will be 1 x = y; // implicit conversion, this works, x will be 1.0 ``` You can't, however, cast an object of one type to the other. Casting implies that you will be using the object as if it were of the other type. In this case the *shapes* differ and it can't be done.
The problem is that you are attempting to do both an unbox and a cast at the same time. This will fail. You must first unbox and then cast to the appropriate type. ``` return (int)(double)value; ``` Eric Lippert Recently wrote a nice article on exactly why this is necessary. It's worth the read * <http://blogs.msdn.com/ericlippert/archive/2009/03/19/representation-and-identity.aspx>
Why does my converter giving an invalid cast error?
[ "", "c#", "wpf", "xaml", "casting", "converters", "" ]
Is there a good C# library for drawing/visualizing graphs? I'm talking about node-path visualization instead of line graphs or the like. (preferably native, not wrappers for pstricks or anything like that) Thank you
Some pointers: * [QuickGraph](http://www.codeplex.com/quickgraph/) is an open-source general graphing library, it supports MSAGL and graphviz * [MSAGL](http://en.wikipedia.org/wiki/Graph_Layout_Execution_Engine) is Microsoft's graph layout engine * [Netron Reloaded](http://netron-reloaded.sourceforge.net/) is a .NET graphing library (but it looks like there was no new development on the project in the last 3 years)
Native: * Graph# (open source) (also based on QuickGraph) * [Netron](http://www.orbifold.net/default/?p=1936) (abandonware); G2 There are plenty of diagram editing packages but I don't know how good they are at layout.
graph viewer/drawer for c#?
[ "", "c#", "drawing", "graph", "" ]
I have an xml document where an xml node with a particular name, say 'Data' can appear anywhere in the xml document i.e anywhere in the hierarchy. I need to read these nodes with their node name alone and edit the node attributes. What is the easiest way to do it?
``` XmlDocument doc = new XmlDocument(); doc.Load(@"Test.xml"); XmlNodeList elem = doc.GetElementsByTagName("Data"); foreach (XmlNode tag in elem) { //do whatever you want to the attribute using SetAttribute method } ``` [XmlElement.GetElementsByTagName Method](http://msdn.microsoft.com/en-us/library/system.xml.xmlelement.getelementsbytagname(VS.71).aspx) would do the trick
Using XPath you can find all Data nodes with:- ``` foreach(XmlElement elem in dom.SelectNodes("//Data")) { //do stuff to each elem. } ``` where dom is an XmlDocument loaded with your Xml. Alternatively if you prefer XDocument:- ``` foreach(XElement elem in doc.Descendents("Data")) { //do stuff to each elem. } ```
Edit Xml Node
[ "", "c#", "xml", "" ]
What is the rationale of not providing no-arg constructors in Wrapper Classes? I know that they were inherently built for Wrapping primitive types, so the right way is to provide a primitive type for constructors. However, considering primitive types have no-arg constructor, why don't they have one? Besides, if they had no-arg constructors, they could be instantiated as `T.class.newInstance()`. However, since `newInstance()` requires no-arg constructor, this won't work with Wrapper Classes.
Wrapper objects are immutable. This means that once a wrapper object has a value assigned to it, that value cannot be changed. It doesn't make much sense to have a default value for an object whose value can't be changed. You wouldn't *want* to get a `newInstance()` of a wrapper class, because then you'd be stuck with the default value.
I think it's because the values wrapped by these classes are meant to be ~~final~~ immutable (*that* was the word I was looking for, thanks Bill:)). If there was a default constructor, it would be quite useless, as you couldn't change the the primitive wrapped by the class later on.
Why don't Java wrapper classes have no-arg constructors?
[ "", "java", "wrapper", "" ]
I'm doing my first javascript project that makes heavy use of objects. Because of how it works, nearly all the custom objects are done like this: ``` namespaceobj = {}; namespaceobj.subobject = {}; namespaceobj.subobject.somefunction = function(arg, uments) { // Do Stuff } namespaceobj.subobject.somedata = 10; namespaceobj.othersubject = {}; namespaceobj.othersubject.somefunction = function(some, args) { // Do more stuff } // More subobjects etc. ``` Which is fine, as all the custom objects only have a single instance anyway (examples of subobjects are the UI, the tools, the shared data, etc.). However I have seen code done something like this (syntax is probably wrong, this is just from memory of seeing similar code) ``` function SomeClass() { this.somedata = 42; this.somefunction = function(a, few, args) { // Do Stuff } } // More classes and stuff // Elsewhere: someInstance = new SomeClass(); // AFA I recall, new was optional someInstance.somefunction(); ``` Could someone explain how the "classes" in the second example work, and any pitfalls I might encounter while using them.
I think the syntax you were thinking of looks like this:- ``` function SomeClass() { var somedata = 42; this.somefunction = function(a, few, args) { // Do Stuff like:- return somedata + a; } } // More classes and stuff // Elsewhere: someInstance = new SomeClass(); // AFA I recall, new was optional someInstance.somefunction(15); //returns 57 ``` The function that is assigned to the somefunction is created in an **Execution Context** which results when a function is executed (in this case when SomeClass() is executed as part of the new operation that is assigned to someInstance). Functions can access variables that are part of the execution context in which they are created, so in this case somedata is a variable that somefunction has access to. This approach effectively makes somedata the private state of the object, since only functions created inside the SomeClass function body can access it. This is an oversimplification, you should consider researching Javascript without reference to OO programming first, learn about **scope chains** and **prototype chains**. When you understand these you can better understand the number of different approaches to implementing an OO design in Javascript and which approach best fits your needs.
This is a pretty big topic but what you are seeing is the difference between *object literal notation* (your first example) and JavaScript's particular brand of OOP. The main difference you will encounter between the two is that you first example has only one, static instance while a revised version of your second example (you were close) would allow you to create multiple instances of the class. I would suggest that you read [JavaScript and Object Oriented Programming (OOP)](http://wsabstract.com/javatutors/oopjs.shtml): > JavaScript is an excellent language to > write object oriented web > applications. It can support OOP > because it supports inheritance > through prototyping as well as > properties and methods. Many > developers cast off JS as a suitable > OOP language because they are so used > to the class style of C# and Java. > Many people don't realize that > JavaScript supports inheritance. When > you write object-oriented code it > instantly gives you power; you can > write code that can be re-used and > that is encapsulated.
Javascript "classes" (no frameworks)
[ "", "javascript", "class", "" ]
I have two classes A and B, where B is subclass of A and A is not abstract. Therefore I can have objects that are instance of A and objects that are instance of B (and therefore of A). How can I distinguish objects that are only instance of A? Sure, I can write something like "object instaceof A && !(object instance of B)" but this is a very poor design since I'll need to change the code every time I add new subclasses to A. Better alternatives?
``` object.getClass() == A.class ```
Why you want them to distinguish? Usually this is the opposite of OO. You have different instances that you don't need to distinguish because the different implementation does everything right. If you need to do so than there should be a protocol for it. Have a method for that purpose that returns something to recognize. That is more flexible,too. I would instanceOf and getClass already consider bad style if this is used without good reason
Most specific subclass for a Java object?
[ "", "java", "inheritance", "instanceof", "" ]
I am trying to download some data from the reporting services instance on our TFS server. Given that the code should run on a computer that is not domain-joined, I figured that I would set the credentials myself. No luck, got a HTTP 401 Unauthorized back. Ok, so I hooked up Fiddler to see what was happening. But that's when I got [Heisenberged](http://en.wikipedia.org/wiki/Uncertainty_principle) - the call now went through without a hitch. So the authentication goes through with Fiddler connected, but fails without it. Is the Webclient broken or am I missing something profound here? ``` private void ThisWorksWhenDomainJoined() { WebClient wc = new WebClient(); wc.Credentials = CredentialCache.DefaultNetworkCredentials; wc.DownloadString("http://teamfoundationserver/reports/........"); //Works } private void ThisDoesntWork() { WebClient wc = new WebClient(); wc.Credentials = new NetworkCredential("username", "password", "domain"); wc.DownloadString("http://teamfoundationserver/reports/........"); //blows up wih HTTP 401 } ```
Take a look at this link: [HTTP Authorization and .NET WebRequest, WebClient Classes](http://www.hashemian.com/blog/2007/06/http-authorization-and-net-webrequest.htm) I had the same problem as you. I have only added one line and it started to work. Try this ``` private void ThisDoesntWork() { WebClient wc = new WebClient(); wc.Credentials = new NetworkCredential("username", "password", "domain"); //After adding the headers it started to work ! wc.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); wc.DownloadString("http://teamfoundationserver/reports/........"); //blows up wih HTTP 401 } ```
Try this ... ``` var credCache = new CredentialCache(); credCache.Add(new Uri("http://teamfoundationserver/reports/........""), "Basic", new NetworkCredential("username", "password", "DOMAIN")); wc.Credentials = credCache; ``` If that does not work, try replacing "Basic" with "Negotiate".
System.Net.WebClient fails weirdly
[ "", "c#", "webclient", "system.net", "" ]
All, my situation is that I have the basic route, plus some other simple routes: ``` routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = 1} ); ``` So the following url works: **<http://somesite.com/tags/index/1>** However, some of my index pages take url parameters in the following fashion: **<http://somesite.com/tags/index/1?when=lastmonth>** **How do I use Html.RouteLink to link to this?** You **can't** add '?' to routes in the global asax file like this: ``` routes.MapRoute("TagsWhen", "Tags/index/{id}?when={when}", new {controller = "Tags", action = "Index", id = "", when = ""}); ``` If this route worked I could link to it using: ``` Html.RouteLink(string.Format("{0} ", link.Rating), "LinksWhen", new {id=link.ReferenceId, when=Model.When}) ``` but it doesn't! So I'm not sure how I would use a Html.RouteLink to generate <http://somesite.com/tags/index/1?when=lastmonth>
Just found the solution myself. You can just do a regular Html.RouteLink and any object properties you don't have mapped to the url in global.asax it adds as a url parameter. So using this route: ``` routes.MapRoute( "Links", "Links/details/{id}", new { controller = "Links", action = "Details", id = ""} defaults ); ``` and this routelink: ``` Html.RouteLink("Link Text", "Links", new {id=link.ReferenceId, when=Model.When }) ``` generates the correct url: <http://localhost:2535/Links/details/1?when=onemonth>
Matthew's approach probably didn't work because he needed another `null` parameter on the end, otherwise it passes the route values as html attributes. :) ``` <%= Html.ActionLink("Link text", "Index", "Home", new { id = 1, when = "lastmonth" }, null) %> ``` That last `MapRoute()` you came up with should work fine against it.
how do I add a url parameter to a routelink in asp.net mvc?
[ "", "c#", ".net", "asp.net", "asp.net-mvc", "" ]
I'm currently in the process of stripping down, refactoring and cleaning up a medium sized (15 ish projects) Visual Studio solution. The solution contains projects in both C++ and C#. I'm keen to keep things as neat as possible in terms of output - seperating anything compiler created from source code, as it helps subversion (okay, I can tell it to ignore files, but I still feel it's messy) from freaking out. The output I would like to achieve is as follows: ``` SolutionDir/ SolutionDir/src/project1/{ Code here } SolutionDir/int/project1/configuration/{.obj files and other misc compiler junk here} SolutionDir/bin/project1/configuration/{The fun stuff goes here} ``` This seems trivial with C++ projects as you can specify both the output and the intermediates directory. However with C#, at least through the Visual Studio 2008 User Interface it seems impossible to move the obj directory? After doing some digging, I added ``` <IntermediateOutputPath>..\..\int\ProjectName\Debug\</IntermediateOutputPath> ``` to the C# .csproj This appears to work, sort of. It's true the intermediates appear to end up there, but a directory 'obj' and under it a configuration directory (e.g. 'debug') and then a 'TempPE' directory are created in the old location - all of which are empty. This isn't really a big deal, but it would be nice to know the cause of this behavior and if possible a way to fix it. Thanks in advance!
I've been searching for a solution for this problem myself, and came up with something less intrusive. Create a bat file named "CleanSrcDir.bat" somewhere (i placed mine in my project path) with the following contents: ``` rmdir /S /Q %1obj SET %ERRORLEVEL%=0 ``` After this, add something similar to the C# project's post-build events: ``` $(ProjectDir)CleanSrcDir.bat $(ProjectDir) ``` (This assumes you placed your bat file in the project directory, of course.) Then change the post-build settings to "Always", and you're done. It's a little hackish, but sure makes the version control problem go away.
If you add both of the following lines to each build configuration then the "obj" folder is not created by default and there is no need for a post-build action: ``` <IntermediateOutputPath>Assembly\obj\Debug\</IntermediateOutputPath> <BaseIntermediateOutputPath>Assembly\obj\Debug\</BaseIntermediateOutputPath> ``` SVN / SCC ignore properties are also useful if desired
Move intermediates directory on C# projects in Visual Studio
[ "", "c#", "visual-studio", "" ]
I need a simple php library which can be used to easily pass rules and field names to, and then validation could be easily performed. There should also be an easy way to retrieve the errors. Any suggestions?
I wrote a simple class of my own, combining some regexes i collected over the years with PHP's sanatize and filter functions. ``` <? /** * Pork Formvalidator. validates fields by regexes and can sanatize them. Uses PHP filter_var built-in functions and extra regexes * @package pork */ /** * Pork.FormValidator * Validates arrays or properties by setting up simple arrays * * @package pork * @author SchizoDuckie * @copyright SchizoDuckie 2009 * @version 1.0 * @access public */ class FormValidator { public static $regexes = Array( 'date' => "^[0-9]{4}[-/][0-9]{1,2}[-/][0-9]{1,2}\$", 'amount' => "^[-]?[0-9]+\$", 'number' => "^[-]?[0-9,]+\$", 'alfanum' => "^[0-9a-zA-Z ,.-_\\s\?\!]+\$", 'not_empty' => "[a-z0-9A-Z]+", 'words' => "^[A-Za-z]+[A-Za-z \\s]*\$", 'phone' => "^[0-9]{10,11}\$", 'zipcode' => "^[1-9][0-9]{3}[a-zA-Z]{2}\$", 'plate' => "^([0-9a-zA-Z]{2}[-]){2}[0-9a-zA-Z]{2}\$", 'price' => "^[0-9.,]*(([.,][-])|([.,][0-9]{2}))?\$", '2digitopt' => "^\d+(\,\d{2})?\$", '2digitforce' => "^\d+\,\d\d\$", 'anything' => "^[\d\D]{1,}\$" ); private $validations, $sanatations, $mandatories, $errors, $corrects, $fields; public function __construct($validations=array(), $mandatories = array(), $sanatations = array()) { $this->validations = $validations; $this->sanatations = $sanatations; $this->mandatories = $mandatories; $this->errors = array(); $this->corrects = array(); } /** * Validates an array of items (if needed) and returns true or false * */ public function validate($items) { $this->fields = $items; $havefailures = false; foreach($items as $key=>$val) { if((strlen($val) == 0 || array_search($key, $this->validations) === false) && array_search($key, $this->mandatories) === false) { $this->corrects[] = $key; continue; } $result = self::validateItem($val, $this->validations[$key]); if($result === false) { $havefailures = true; $this->addError($key, $this->validations[$key]); } else { $this->corrects[] = $key; } } return(!$havefailures); } /** * * Adds unvalidated class to thos elements that are not validated. Removes them from classes that are. */ public function getScript() { if(!empty($this->errors)) { $errors = array(); foreach($this->errors as $key=>$val) { $errors[] = "'INPUT[name={$key}]'"; } $output = '$$('.implode(',', $errors).').addClass("unvalidated");'; $output .= "alert('there are errors in the form');"; // or your nice validation here } if(!empty($this->corrects)) { $corrects = array(); foreach($this->corrects as $key) { $corrects[] = "'INPUT[name={$key}]'"; } $output .= '$$('.implode(',', $corrects).').removeClass("unvalidated");'; } $output = "<script type='text/javascript'>{$output} </script>"; return($output); } /** * * Sanatizes an array of items according to the $this->sanatations * sanatations will be standard of type string, but can also be specified. * For ease of use, this syntax is accepted: * $sanatations = array('fieldname', 'otherfieldname'=>'float'); */ public function sanatize($items) { foreach($items as $key=>$val) { if(array_search($key, $this->sanatations) === false && !array_key_exists($key, $this->sanatations)) continue; $items[$key] = self::sanatizeItem($val, $this->validations[$key]); } return($items); } /** * * Adds an error to the errors array. */ private function addError($field, $type='string') { $this->errors[$field] = $type; } /** * * Sanatize a single var according to $type. * Allows for static calling to allow simple sanatization */ public static function sanatizeItem($var, $type) { $flags = NULL; switch($type) { case 'url': $filter = FILTER_SANITIZE_URL; break; case 'int': $filter = FILTER_SANITIZE_NUMBER_INT; break; case 'float': $filter = FILTER_SANITIZE_NUMBER_FLOAT; $flags = FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND; break; case 'email': $var = substr($var, 0, 254); $filter = FILTER_SANITIZE_EMAIL; break; case 'string': default: $filter = FILTER_SANITIZE_STRING; $flags = FILTER_FLAG_NO_ENCODE_QUOTES; break; } $output = filter_var($var, $filter, $flags); return($output); } /** * * Validates a single var according to $type. * Allows for static calling to allow simple validation. * */ public static function validateItem($var, $type) { if(array_key_exists($type, self::$regexes)) { $returnval = filter_var($var, FILTER_VALIDATE_REGEXP, array("options"=> array("regexp"=>'!'.self::$regexes[$type].'!i'))) !== false; return($returnval); } $filter = false; switch($type) { case 'email': $var = substr($var, 0, 254); $filter = FILTER_VALIDATE_EMAIL; break; case 'int': $filter = FILTER_VALIDATE_INT; break; case 'boolean': $filter = FILTER_VALIDATE_BOOLEAN; break; case 'ip': $filter = FILTER_VALIDATE_IP; break; case 'url': $filter = FILTER_VALIDATE_URL; break; } return ($filter === false) ? false : filter_var($var, $filter) !== false ? true : false; } } ``` Now this requires mootools for some of the javascript you see here, but you can easily change that to your favorite javascript framework. All it does is look up the element, and add the 'unvalidated' CSS class to it. Usage is as simple as i always ever wanted: Example: ``` $validations = array( 'name' => 'anything', 'email' => 'email', 'alias' => 'anything', 'pwd'=>'anything', 'gsm' => 'phone', 'birthdate' => 'date'); $required = array('name', 'email', 'alias', 'pwd'); $sanatize = array('alias'); $validator = new FormValidator($validations, $required, $sanatize); if($validator->validate($_POST)) { $_POST = $validator->sanatize($_POST); // now do your saving, $_POST has been sanatized. die($validator->getScript()."<script type='text/javascript'>alert('saved changes');</script>"); } else { die($validator->getScript()); } ``` To validate just one element: ``` $validated = new FormValidator()->validate('blah@bla.', 'email'); ``` To sanatize just one element: ``` $sanatized = new FormValidator()->sanatize('<b>blah</b>', 'string'); ``` The coolest thing about this class is that you can send your form with an ajax or iframe target and execute the resulting script. No need to refresh the page or re-send the same form data back to the browser :) Also, if the script needs changing, there's no difficult overdesigned framework to analyze, just change it any way you want :) Oh yeah, feel free to use this anywhere you want. No licenses
The answer from SchizoDuckie above was awesome. I've used his code in project I'm working on with the permission of the author. One issue I had using this code was that if a required field was not submitted then it would not register an error. I've modified the code to cover this scenario. I've also removed the code to generate HTML and javascript as my project demands separation of UI from logic per MVC pattern. The modified code simply returns JSON encoded result. I repost the modified code here in case it is of some use to others. ``` <? /** * Pork Formvalidator. validates fields by regexes and can sanatize them. Uses PHP filter_var built-in functions and extra regexes * @package pork */ /** * Pork.FormValidator * Validates arrays or properties by setting up simple arrays * * @package pork * @author SchizoDuckie * @copyright SchizoDuckie 2009 * @version 1.0 * @access public */ class FormValidator { public static $regexes = Array( 'date' => "^[0-9]{4}[-/][0-9]{1,2}[-/][0-9]{1,2}\$", 'amount' => "^[-]?[0-9]+\$", 'number' => "^[-]?[0-9,]+\$", 'alfanum' => "^[0-9a-zA-Z ,.-_\\s\?\!]+\$", 'not_empty' => "[a-z0-9A-Z]+", 'words' => "^[A-Za-z]+[A-Za-z \\s]*\$", 'phone' => "^[0-9]{10,11}\$", 'zipcode' => "^[1-9][0-9]{3}[a-zA-Z]{2}\$", 'plate' => "^([0-9a-zA-Z]{2}[-]){2}[0-9a-zA-Z]{2}\$", 'price' => "^[0-9.,]*(([.,][-])|([.,][0-9]{2}))?\$", '2digitopt' => "^\d+(\,\d{2})?\$", '2digitforce' => "^\d+\,\d\d\$", 'anything' => "^[\d\D]{1,}\$", 'username' => "^[\w]{3,32}\$" ); private $validations, $sanatations, $mandatories, $equal, $errors, $corrects, $fields; public function __construct($validations=array(), $mandatories = array(), $sanatations = array(), $equal=array()) { $this->validations = $validations; $this->sanatations = $sanatations; $this->mandatories = $mandatories; $this->equal = $equal; $this->errors = array(); $this->corrects = array(); } /** * Validates an array of items (if needed) and returns true or false * * JP modofied this function so that it checks fields even if they are not submitted. * for example the original code did not check for a mandatory field if it was not submitted. * Also the types of non mandatory fields were not checked. */ public function validate($items) { $this->fields = $items; $havefailures = false; //Check for mandatories foreach($this->mandatories as $key=>$val) { if(!array_key_exists($val,$items)) { $havefailures = true; $this->addError($val); } } //Check for equal fields foreach($this->equal as $key=>$val) { //check that the equals field exists if(!array_key_exists($key,$items)) { $havefailures = true; $this->addError($val); } //check that the field it's supposed to equal exists if(!array_key_exists($val,$items)) { $havefailures = true; $this->addError($val); } //Check that the two fields are equal if($items[$key] != $items[$val]) { $havefailures = true; $this->addError($key); } } foreach($this->validations as $key=>$val) { //An empty value or one that is not in the list of validations or one that is not in our list of mandatories if(!array_key_exists($key,$items)) { $this->addError($key, $val); continue; } $result = self::validateItem($items[$key], $val); if($result === false) { $havefailures = true; $this->addError($key, $val); } else { $this->corrects[] = $key; } } return(!$havefailures); } /* JP * Returns a JSON encoded array containing the names of fields with errors and those without. */ public function getJSON() { $errors = array(); $correct = array(); if(!empty($this->errors)) { foreach($this->errors as $key=>$val) { $errors[$key] = $val; } } if(!empty($this->corrects)) { foreach($this->corrects as $key=>$val) { $correct[$key] = $val; } } $output = array('errors' => $errors, 'correct' => $correct); return json_encode($output); } /** * * Sanatizes an array of items according to the $this->sanatations * sanatations will be standard of type string, but can also be specified. * For ease of use, this syntax is accepted: * $sanatations = array('fieldname', 'otherfieldname'=>'float'); */ public function sanatize($items) { foreach($items as $key=>$val) { if(array_search($key, $this->sanatations) === false && !array_key_exists($key, $this->sanatations)) continue; $items[$key] = self::sanatizeItem($val, $this->validations[$key]); } return($items); } /** * * Adds an error to the errors array. */ private function addError($field, $type='string') { $this->errors[$field] = $type; } /** * * Sanatize a single var according to $type. * Allows for static calling to allow simple sanatization */ public static function sanatizeItem($var, $type) { $flags = NULL; switch($type) { case 'url': $filter = FILTER_SANITIZE_URL; break; case 'int': $filter = FILTER_SANITIZE_NUMBER_INT; break; case 'float': $filter = FILTER_SANITIZE_NUMBER_FLOAT; $flags = FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND; break; case 'email': $var = substr($var, 0, 254); $filter = FILTER_SANITIZE_EMAIL; break; case 'string': default: $filter = FILTER_SANITIZE_STRING; $flags = FILTER_FLAG_NO_ENCODE_QUOTES; break; } $output = filter_var($var, $filter, $flags); return($output); } /** * * Validates a single var according to $type. * Allows for static calling to allow simple validation. * */ public static function validateItem($var, $type) { if(array_key_exists($type, self::$regexes)) { $returnval = filter_var($var, FILTER_VALIDATE_REGEXP, array("options"=> array("regexp"=>'!'.self::$regexes[$type].'!i'))) !== false; return($returnval); } $filter = false; switch($type) { case 'email': $var = substr($var, 0, 254); $filter = FILTER_VALIDATE_EMAIL; break; case 'int': $filter = FILTER_VALIDATE_INT; break; case 'boolean': $filter = FILTER_VALIDATE_BOOLEAN; break; case 'ip': $filter = FILTER_VALIDATE_IP; break; case 'url': $filter = FILTER_VALIDATE_URL; break; } return ($filter === false) ? false : filter_var($var, $filter) !== false ? true : false; } } ?> ```
Easiest Form validation library for PHP?
[ "", "php", "validation", "crud", "" ]
I have a table of housing listings. I would like to keep a maximum of 10 listings per city. (Most cities have less than 10 listings). When I do this query: ``` select city, count(city) as cityCount from tREaltyTrac group by city ``` SQL returns: ``` Acampo 1 Acton 1 Adelanto 20 Agua Dulce 1 Aguanga 1 Akron 19 Albany 12 Albion 3 Alexandria 14 Algonac 1 Alhambra 5 ``` So Adelanto, Akron, Albany, and Alexandria must be cut back to only 10 listings ordered by most recent datetime field called 'creation' (order by creation desc). Can anyone think of a procedure that will cut the listings back as described?
**DON'T LOOP!** I prefer marking th rows with a status, but this will do as you want and delete them... try this (sql server) set up table ``` create table tREaltyTrac (city varchar(20),creation datetime) insert into tREaltyTrac values ('Acampo' ,getdate()) --1 waitfor delay '00:00:01' insert into tREaltyTrac values ('Acton' ,getdate()) --1 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Adelanto' ,getdate()) --20 waitfor delay '00:00:01' insert into tREaltyTrac values ('Agua Dulce' ,getdate()) --1 waitfor delay '00:00:01' insert into tREaltyTrac values ('Aguanga' ,getdate()) --1 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Akron' ,getdate()) --19 waitfor delay '00:00:01' insert into tREaltyTrac values ('Albany' ,getdate()) --12 waitfor delay '00:00:01' insert into tREaltyTrac values ('Albany' ,getdate()) --12 waitfor delay '00:00:01' insert into tREaltyTrac values ('Albany' ,getdate()) --12 waitfor delay '00:00:01' insert into tREaltyTrac values ('Albany' ,getdate()) --12 waitfor delay '00:00:01' insert into tREaltyTrac values ('Albany' ,getdate()) --12 waitfor delay '00:00:01' insert into tREaltyTrac values ('Albany' ,getdate()) --12 waitfor delay '00:00:01' insert into tREaltyTrac values ('Albany' ,getdate()) --12 waitfor delay '00:00:01' insert into tREaltyTrac values ('Albany' ,getdate()) --12 waitfor delay '00:00:01' insert into tREaltyTrac values ('Albany' ,getdate()) --12 waitfor delay '00:00:01' insert into tREaltyTrac values ('Albany' ,getdate()) --12 waitfor delay '00:00:01' insert into tREaltyTrac values ('Albany' ,getdate()) --12 waitfor delay '00:00:01' insert into tREaltyTrac values ('Albany' ,getdate()) --12 waitfor delay '00:00:01' insert into tREaltyTrac values ('Albion' ,getdate()) --3 waitfor delay '00:00:01' insert into tREaltyTrac values ('Albion' ,getdate()) --3 waitfor delay '00:00:01' insert into tREaltyTrac values ('Albion' ,getdate()) --3 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alexandria' ,getdate()) --14 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alexandria' ,getdate()) --14 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alexandria' ,getdate()) --14 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alexandria' ,getdate()) --14 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alexandria' ,getdate()) --14 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alexandria' ,getdate()) --14 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alexandria' ,getdate()) --14 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alexandria' ,getdate()) --14 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alexandria' ,getdate()) --14 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alexandria' ,getdate()) --14 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alexandria' ,getdate()) --14 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alexandria' ,getdate()) --14 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alexandria' ,getdate()) --14 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alexandria' ,getdate()) --14 waitfor delay '00:00:01' insert into tREaltyTrac values ('Algonac' ,getdate()) --1 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alhambra' ,getdate()) --5 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alhambra' ,getdate()) --5 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alhambra' ,getdate()) --5 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alhambra' ,getdate()) --5 waitfor delay '00:00:01' insert into tREaltyTrac values ('Alhambra' ,getdate()) --5 ``` display table values ``` select city,count(*) from tREaltyTrac group by city select * from tREaltyTrac ``` delete the rows you don't want ``` delete from tREaltyTrac from tREaltyTrac inner join (select city,creation, row_number() over(partition by city order by city) AS RankValue from tREaltyTrac ) dt on tREaltyTrac.city=dt.city AND tREaltyTrac.creation=dt.creation where dt. RankValue>10 ``` show the rows you have left ``` select * from tREaltyTrac select city,count(*) from tREaltyTrac group by city ```
Something like this should take care of it for you, but deleting records automatically isn't a great idea. You'd be better off using an active flag. ``` DECLARE @CityName VARCHAR(30) DECLARE CitiesOver10 CURSOR FOR select city from tREaltyTrac group by city having count(city)>10 OPEN CitiesOver10 FETCH NEXT FROM CitiesOver10 INTO @CityName WHILE @@FETCH_STATUS = 0 BEGIN DELETE FROM dbo.tREaltyTrac WHERE ID NOT IN (SELECT TOP 10 ID FROM dbo.tREaltyTrac WHERE city = @CityName ORDER BY Creation DESC) AND City = @CityName FETCH NEXT FROM CitiesOver10 INTO @CityName END CLOSE CitiesOver10 DEALLOCATE CitiesOver10 ```
SQL delete loop
[ "", "sql", "loops", "count", "" ]
I have a list of items in a `JList` for the user to select. Since it's a lot of items (say, cities in states), I want to divide the list into sections. The section headings should not be selectable, though. So for my cities/states example, this might look like this: * State 1 + City 1 + City 2 + City 3 * State 2 + City 4 + City 5 + City 6 It wouldn't be so difficult to write this myself by embedding `JList`s in a custom `ListCellRenderer`, but I'm wondering if there already is a class like that out there.
I see this question is already answered, but I noticed that Robert commented that he was hoping for an open source solution. I'd recommend using Glazed Lists' Separator list, the API for which you can be found here: <http://publicobject.com/glazedlists/glazedlists-1.8.0/api/ca/odell/glazedlists/SeparatorList.html> Here's some sample code that will produce a list of items grouped by their first letter: [alt text http://img300.imageshack.us/img300/8977/separatorlist.png](http://img300.imageshack.us/img300/8977/separatorlist.png) ``` public class SeparatorListTest { private static Comparator<String> createComparator() { return new Comparator<String>() { public int compare(String stringOne, String stringTwo) { return stringOne.substring(0,1).compareTo(stringTwo.substring(0,1)); } }; } private static ListCellRenderer createListCellRenderer() { return new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof SeparatorList.Separator) { SeparatorList.Separator separator = (SeparatorList.Separator) value; label.setText(separator.getGroup().get(0).toString().substring(0,1)); label.setFont(label.getFont().deriveFont(Font.BOLD)); label.setBorder(BorderFactory.createEmptyBorder(0,5,0,0)); } else { label.setFont(label.getFont().deriveFont(Font.PLAIN)); label.setBorder(BorderFactory.createEmptyBorder(0,15,0,0)); } return label; } }; } public static void main(String[] args) { EventList<String> rawList = GlazedLists.eventListOf( "apple", "appricot", "acorn", "blueberry", "coconut", "chesnut", "grape"); SeparatorList<String> separatorList = new SeparatorList<String>(rawList, createComparator(), 1, 1000); JList list = new JList(new EventListModel<String>(separatorList)); list.setCellRenderer(createListCellRenderer()); JScrollPane scrollPane = new JScrollPane(list); scrollPane.setBorder(null); JFrame frame = new JFrame(); frame.add(scrollPane, BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(200,200); frame.setLocationRelativeTo(null); frame.setVisible(true); } ``` }
There's a component available with [JIDE](https://www.jidesoft.com/) that let's you do exactly this. It's called GroupList: [![alt text](https://i.stack.imgur.com/Ni5qg.png)](https://i.stack.imgur.com/Ni5qg.png) (source: [jidesoft.com](https://www.jidesoft.com/blog/wp-content/uploads/2007/11/grouplist.png))
Sectioned List in Java/Swing?
[ "", "java", "swing", "jlist", "segments", "" ]
When should I use a [`ThreadLocal`](https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html) variable? How is it used?
One possible (and common) use is when you have some object that is not thread-safe, but you want to avoid [synchronizing](https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html) access to that object (I'm looking at you, [SimpleDateFormat](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html)). Instead, give each thread its own instance of the object. For example: ``` public class Foo { // SimpleDateFormat is not thread-safe, so give one to each thread private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){ @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyyMMdd HHmm"); } }; public String formatIt(Date date) { return formatter.get().format(date); } } ``` [Documentation](https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html).
Since a `ThreadLocal` is a reference to data within a given `Thread`, you can end up with classloading leaks when using `ThreadLocal`s in application servers using thread pools. You need to be very careful about cleaning up any `ThreadLocal`s you `get()` or `set()` by using the `ThreadLocal`'s `remove()` method. If you do not clean up when you're done, any references it holds to classes loaded as part of a deployed webapp will remain in the [permanent heap](https://web.archive.org/web/20070104122432/http://www.brokenbuild.com/blog/2006/08/04/java-jvm-gc-permgen-and-memory-options/) and will never get garbage collected. Redeploying/undeploying the webapp will not clean up each `Thread`'s reference to your webapp's class(es) since the `Thread` is not something owned by your webapp. Each successive deployment will create a new instance of the class which will never be garbage collected. You will end up with out of memory exceptions due to `java.lang.OutOfMemoryError: PermGen space` and after some googling will probably just increase `-XX:MaxPermSize` instead of fixing the bug. If you do end up experiencing these problems, you can determine which thread and class is retaining these references by using [Eclipse's Memory Analyzer](http://www.eclipse.org/mat/) and/or by following [Frank Kieviet's guide](http://frankkieviet.blogspot.com/2006/10/classloader-leaks-dreaded-permgen-space.html) and [followup](http://frankkieviet.blogspot.com/2006/10/how-to-fix-dreaded-permgen-space.html). Update: Re-discovered [Alex Vasseur's blog entry](http://avasseur.blogspot.com/2003/11/threadlocal-and-memory-leaks.html) that helped me track down some `ThreadLocal` issues I was having.
When and how should I use a ThreadLocal variable?
[ "", "java", "multithreading", "concurrency", "thread-local", "thread-confinement", "" ]
I am designing a regular expression tester in HTML and JavaScript. The user will enter a regex, a string, and choose the function they want to test with (e.g. search, match, replace, etc.) via radio button and the program will display the results when that function is run with the specified arguments. Naturally there will be extra text boxes for the extra arguments to replace and such. My problem is getting the string from the user and turning it into a regular expression. If I say that they don't need to have `//`'s around the regex they enter, then they can't set flags, like `g` and `i`. So they have to have the `//`'s around the expression, but how can I convert that string to a regex? It can't be a literal since its a string, and I can't pass it to the RegExp constructor since its not a string without the `//`'s. Is there any other way to make a user input string into a regex? Will I have to parse the string and flags of the regex with the `//`'s then construct it another way? Should I have them enter a string, and then enter the flags separately?
Use the [RegExp object constructor](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp) to create a regular expression from a string: ``` var re = new RegExp("a|b", "i"); // same as var re = /a|b/i; ```
``` var flags = inputstring.replace(/.*\/([gimy]*)$/, '$1'); var pattern = inputstring.replace(new RegExp('^/(.*?)/'+flags+'$'), '$1'); var regex = new RegExp(pattern, flags); ``` or ``` var match = inputstring.match(new RegExp('^/(.*?)/([gimy]*)$')); // sanity check here var regex = new RegExp(match[1], match[2]); ```
Converting user input string to regular expression
[ "", "javascript", "html", "regex", "" ]
I want to mock a ResultSet. Seriously. I'm refactoring one big complicated piece of code which is parsing data from ResultSet, and I want my code to behave identically. So, I need to write a unit test for the piece being refactored to be able to test this. After googling I came up with 2 ideas: 1. Use EasyMock, write looooong mocking sequence. VERY BAD solution: hard to add initial data, hard to change data, big test debugging promices. 2. Use Apache Derby or HSQLDB to create in-memory DB, fill it from file or String array, query with some magical InMemoryDBUtils.query(sql). Then use that ResultSet. Unfortunately, I did not find any magical InMemoryDBUtils to write the test fast :-). IBM article "Isolated unit testing of persistence with Derby" seems just fine about what I need, though... Second approach looks somewhat easier and much more supportable. What would you advice for creating such a mock? (despite doctors, of course :-)? Am I missing an eyebrow some silver bullet? Possibly, DBUnit is the tool for this?
DBUnit doesn't present a result set, to my knowledge, although it will well help you populate your in memory database. I would say that a mocking framework is the wrong approach at this point. Mocking is about testing behavior and interaction, not just returning data, so it will likely get in your way. I would instead either implement a result set interface, or create a dynamic proxy of a result set interface to a class that implements the methods you care about without having to implement the whole result set. You will likely find maintaining a class as easy as maintaining an in memory database (provided that the dataset under test is consistent), and probably easier to debug. You could back up that class with DBUnit, where you take a snapshot of your result set with dbunit, and have dbunit read it back during the test from xml, and have your dummy result set read the data from dbunit's classes. This would be a reasonable approach if the data was mildly complex. I would go for the in memory database if the classes were so coupled that they need to read data that was modified as part of the same test. Even then, I would consider using a copy of the real database until you managed to pull that dependency apart. A simple proxy generation method: ``` private static class SimpleInvocationHandler implements InvocationHandler { private Object invokee; public SimpleInvocationHandler(Object invokee) { this.invokee = invokee; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { method = invokee.getClass().getMethod(method.getName(), method.getParameterTypes()); if (!method.isAccessible()) { method.setAccessible(true); } try { return method.invoke(invokee, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } } } public static <T> T generateProxy(Object realObject, Class... interfaces) { return (T) Proxy.newProxyInstance(realObject.getClass().getClassLoader(), interfaces, new SimpleInvocationHandler(realObject)); } ```
I've had success with the MockResultSet class from here: <http://mockrunner.sourceforge.net/>. It allows you to create a class that implements the ResultSet interface, and lets you set the values for each column and row. If your methods are working with ResultSets of reasonable size, you should be able to create tests that return the values you need fairly easily. Here's a simple example: ``` MockResultSet rs = new MockResultSet("myMock"); rs.addColumn("columnA", new Integer[]{1}); rs.addColumn("columnB", new String[]{"Column B Value"}); rs.addColumn("columnC", new Double[]{2}); // make sure to move the cursor to the first row try { rs.next(); } catch (SQLException sqle) { fail("unable to move resultSet"); } // process the result set MyObject obj = processor.processResultSet(rs); // run your tests using the ResultSet like you normally would assertEquals(1, obj.getColumnAValue()); assertEquals("Column B Value", obj.getColumnBValue()); assertEquals(2.0d, obj.getColumnCValue()); ```
Easy way to fill up ResultSet with data
[ "", "java", "unit-testing", "jdbc", "mocking", "resultset", "" ]
I've got a TextBox on a form that I am using to just display data. I have set it to ReadOnly which stops the user from changing the data displayed in the TextBox. Although the user can still highlight the data in the TextBox, how do I disable this? NOTE: I know using a label would be much easier, although for some reason the label wont let me display the data how I would like. I want to display a number starting from the right of the display area, IE: " 25", although the label displays it like "25 ". I have tried making the label right-justified this does not solve the issue. Therefore I am using a TextBox.
You can display right aligned text in label by setting TextAlign property to e.g. MiddleRight. Remember also to set AutoSize property to false, otherwise it will resize the label and the position will change to left.
``` TextBox1.Enabled = false; ``` Or you can use the label with the property RightToLeft set to True
How to make a TextBox non-interactive in C#
[ "", "c#", "textbox", "" ]
I have the following code in Ruby. I want to convert this code into JavaScript. What is the equivalent code in JS? ``` text = <<"HERE" This Is A Multiline String HERE ```
### Update: ECMAScript 6 (ES6) introduces a new type of literal, namely [**template literals**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings). They have many features, variable interpolation among others, but most importantly for this question, they can be multiline. A template literal is delimited by *backticks*: ``` var html = ` <div> <span>Some HTML here</span> </div> `; ``` (Note: I'm not advocating to use HTML in strings) [Browser support is OK](https://kangax.github.io/compat-table/es6/#test-template_literals), but you can use [transpilers](https://babeljs.io/) to be more compatible. --- ### Original ES5 answer: Javascript doesn't have a here-document syntax. You can escape the literal newline, however, which comes close: ``` "foo \ bar" ```
## ES6 Update: As the first answer mentions, with ES6/Babel, you can now create multi-line strings simply by using backticks: ``` const htmlString = `Say hello to multi-line strings!`; ``` Interpolating variables is a popular new feature that comes with back-tick delimited strings: ``` const htmlString = `${user.name} liked your post about strings`; ``` This just transpiles down to concatenation: ``` user.name + ' liked your post about strings' ``` ## Original ES5 answer: > [Google's JavaScript style guide](https://google.github.io/styleguide/javascriptguide.xml?showone=Multiline_string_literals#Multiline_string_literals) recommends to use string concatenation instead of escaping newlines: > > **Do not do this:** > > ``` > var myString = 'A rather long string of English text, an error message \ > actually that just keeps going and going -- an error \ > message to make the Energizer bunny blush (right through \ > those Schwarzenegger shades)! Where was I? Oh yes, \ > you\'ve got an error and all the extraneous whitespace is \ > just gravy. Have a nice day.'; > ``` > > The whitespace at the beginning of each line can't be safely stripped at compile time; whitespace after the slash will result in tricky errors; and while most script engines support this, it is not part of ECMAScript. > > **Use string concatenation instead:** > > ``` > var myString = 'A rather long string of English text, an error message ' + > 'actually that just keeps going and going -- an error ' + > 'message to make the Energizer bunny blush (right through ' + > 'those Schwarzenegger shades)! Where was I? Oh yes, ' + > 'you\'ve got an error and all the extraneous whitespace is ' + > 'just gravy. Have a nice day.'; > ```
Creating multiline strings in JavaScript
[ "", "javascript", "string", "multiline", "heredoc", "" ]
I've got a WebBrowser control on a WinForms app that is loading XML which is converted to HTML/CSS. Looks beautiful if I just want to view it there or in a regular browser. When the form loads, it's supposed to navigate to the file, then when the OnDocumentCompleted event fires, it should set the header, footer, and default printer name in the registry, then call Print() for however many copies the user has specified. I've run it through the debugger, and it's calling webBrowser.Print() the correct number of times in the OnDocumentCompleted event. Nothing is null that shouldn't be, Visible is true on the WebBrowser control, as is AllowNavigation. And yes, the printer is turned on and reachable over the network. The exact same code works elsewhere in the project, but not here. What else could be causing this hellish control to ignore my Print commands? Ideally, I'd like the whole thing to be hidden off-screen, as this is meant to run using Windows Scheduler, and the users should never see it. I've read that the control needs to be visible, though, so until I work out this first kink, that can wait. **EDIT**: The last two lines of my OnDocumentCompleted event handler set the DialogResult to OK and closed the form. Removing the call to Close() let it print, so I'm guessing it didn't get to the print spooler before the form was closed and the WebBrowser control was disposed. Short of just setting an arbitrary time limit to wait before closing, is there any way to tell when it is done printing?
Turned out to be a timing issue, with the form being closed before it could send the document to the print spooler. I wound up adding a Timer to the form, setting it for 30 seconds, and having it's Tick() event close the form. Where it was closing the form previously, it now just calls closeTimer.Start().
Try this: ``` mshtml.IHTMLDocument2 doc; doc = oWeb.Document; doc.execCommand("Print", True, Nothing); ``` **FROM EDIT:** It is possible to use SHELL commands to check the status of the jobs in the print queue
WebBrowser control won't print from C#
[ "", "c#", "winforms", "webbrowser-control", "" ]
If I have a C++ struct, defining a 64bit data word such as.. ``` struct SMyDataWord { int Name : 40; int Colour : 24; }; ``` What does the `: 40` syntax mean... does it mean that the first 40 bits are reserved for the Name and the remaining 24 bits for the Colour? This is how it appears to be being used, but I've not come across it before.
Bitfields, carried over from C. `Name` is 40 bits wide, `Colour` is 24 bits wide. Your struct therefore has at least 64 bits. On my system 64 bits would be 8 bytes.
Here `sizeof` nicely demonstrates what's going on under the hood: ``` #include <iostream> #include <climits> struct bc_1 { int a : 1; int b : 1; }; struct bc_2 { int a : 31; int b : 1; }; struct bc_3 { int a : 32; int b : 1; }; struct bc_4 { int a : 31; int b : 2; }; struct bc_5 { int a : 32; int b : 32; }; struct bc_6 { int a : 40; int b : 32; }; struct bc_7 { int a : 63; int b : 1; }; int main(int argc, char * argv[]) { std::cout << "CHAR_BIT = " << CHAR_BIT; std::cout << " => sizeof(int) = " << sizeof(int) << std::endl; std::cout << "1, 1: " << sizeof(struct bc_1) << std::endl; std::cout << "31, 1: " << sizeof(struct bc_2) << std::endl; std::cout << "32, 1: " << sizeof(struct bc_3) << std::endl; std::cout << "31, 2: " << sizeof(struct bc_4) << std::endl; std::cout << "32, 32: " << sizeof(struct bc_5) << std::endl; std::cout << "40, 32: " << sizeof(struct bc_6) << std::endl; std::cout << "63, 1: " << sizeof(struct bc_7) << std::endl; } ``` What follows depends on your compiler and OS, and possibly on your hardware. On macOS with gcc-7 (with a `CHAR_BIT` = 8, a 32 bit `int` (i.e. half of 64 bit `long`) has `sizeof(int)` = 4) this is the output I see: ``` CHAR_BIT = 8 => sizeof(int) = 4 1, 1: 4 31, 1: 4 32, 1: 8 31, 2: 8 32, 32: 8 40, 32: 12 63, 1: 8 ``` This tells us several things: if both fields of `int` type fit into a single `int` (i.e. 32 bits in the example above), the compiler allocates only a single `int`'s worth of memory (`bc_1` and `bc_2`). Once, a single `int` can't hold the bitfields anymore, we add a second one (`bc_3` and `bc_4`). Note that `bc_5` is at capacity. Interestingly, we can "select" more bits than allowed. See `bc_6`. Here g++-7 gives a warning: ``` bitfields.cpp::30:13: warning: width of 'bc_6::a' exceeds its type int a : 40; ^~ ``` Note that: clang++ explains this in better detail ``` bitfields.cpp:30:9: warning: width of bit-field 'a' (40 bits) exceeds the width of its type; value will be truncated to 32 bits [-Wbitfield-width] int a : 40; ^ ``` However it seems that under the hood, the compiler allocates another `int`'s worth of memory. Or at the very least, it determines the correct size. I guess the compiler is warning us not to access this memory as `int a = bc_6::a` (I would wager that `int a` would then only have the first 32 bits of field `bc_6::a`...). This is confirmed by `bc_7` whose total size is that of two `int`s, but the first field covers most of them. Finally replacing `int` with `long` in the example above behaves as expected: ``` CHAR_BIT = 8 => sizeof(long) = 8 1, 1: 8 31, 1: 8 32, 1: 8 31, 2: 8 32, 32: 8 40, 32: 16 63, 1: 8 ```
What does C++ struct syntax "a : b" mean
[ "", "c++", "data-structures", "syntax", "struct", "" ]
I have a datagrid populated by a Linq query. When the focused row in the datagrid changes I need to set a variable equal to one of the properties in that object. I tried... ``` var selectedObject = view.GetRow(rowHandle); _selectedId = selectedObject.Id; ``` ... but the compiler doesn't care for this at all ("Embedded statement cannot be a declaration or labled statement"). It seems like the property should be easy to access. Inspecting the object during runtime shows all the properties I expect, I just don't know how to access them. How can I get access to the anonymous object's property? **Edit for Clarifications:** I happen to be using DevExpress XtraGrid control. I loaded this control with a Linq query which was composed of several different objects, therefore making the data not really conforming with any one class I already have (ie, I cannot cast this to anything). I'm using .NET 3.5. When I view the results of the view.GetRow(rowHandle) method I get an anonymous type that looks like this: ``` { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 } ``` My objective is to get the ClientId from this anonymous type so I can do other things (such as a load a form with that client record in it). I tried a couple of the suggestions in the early answers but was unable to get to a point where I could get this ClientId.
Have you ever tried to use reflection? Here's a sample code snippet: ``` // use reflection to retrieve the values of the following anonymous type var obj = new { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 }; System.Type type = obj.GetType(); int clientid = (int)type.GetProperty("ClientId").GetValue(obj, null); string clientname = (string)type.GetProperty("ClientName").GetValue(obj, null); // use the retrieved values for whatever you want... ```
A generic solution for getting the value of a data item for a given key ``` public static T GetValueFromAnonymousType<T>( object dataitem, string itemkey ) { System.Type type = dataitem.GetType(); T itemvalue = (T)type.GetProperty(itemkey).GetValue(dataitem, null); return itemvalue; } ``` Example: ``` var dataitem = /* Some value here */; bool ismember = TypeUtils.GetValueFromAnonymousType<bool>(dataitem, "IsMember"); ```
How can I get a value of a property from an anonymous type?
[ "", "c#", ".net", "anonymous-types", "" ]
Is it possible to create WMP11+ (well, sure, the more versions the better, but I'm only targeting Vista onwards for now) plugin in C#? All the resources I've found show it for C++, but not for C#. I'm trying to create a plugin that interacts with WMP along the lines of Last.FM/the 'Now Playing' plugin (that is a "Background" class plugin), in that it sits in the background and does stuff, not a general app that wants to access WMP's data. The WMP Managed sample in the Windows SDK only shows the example of interacting with the WMP library/"control" from a separate application.
May not be exactly what you're looking for but you can have a look at the code from this project: <http://wmppluginsnet.codeplex.com/>
The same author that you have linked to, [Ianier Munoz](http://www.chronotron.com), did also publish a [C# article](http://www.microsoft.com/belux/msdn/fr/community/columns/munoz/extendwmp_part1.mspx) ([broken old link](http://www.microsoft.com/belux/msdn/nl/community/columns/munoz/wmpphaser.mspx)) on writing Windows Media Player plugins. You can probably use something from that.
Windows Media Player (11+) C# Plugins
[ "", "c#", "wmp", "" ]