Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I need to run a specific mysql query upon wget, which is running in the background, finishes downloading a file. For example... > wget <http://domain/file.zip> then run: > UPDATE `table` SET `status` = 'live' WHERE `id` = '1234' How would I go about doing this?
I would recommend launching the wget command in a subshell so you can ensure it completes before you run your mysql command. In bash, this is done with parentheses. Also use `&&` so that the mysql command runs only if the wget command has a success exit status. ``` #!/bin/sh ( wget "http://domain/file.zip" && mysql -u user -ppassword database -e "UPDATE..." ) & ``` Putting the password in plaintext in the script is [not necessarily a good idea](http://dev.mysql.com/doc/refman/5.1/en/password-security-user.html) because it can be viewed in a `ps` listing. Instead, you can rely on the `[client]` section in your `~/.my.cnf` file. You can also use the `MYSQL_PWD` environment variable. Either of these solutions means there's no password visible in the command listing.
`wget http://domain/file.zip && mysql -u user -ppassword database -e "UPDATE table SET status = 'live' WHERE id = '1234'"`
Run MySQL Query after wget finishes downloading file
[ "", "php", "mysql", "bash", "download", "wget", "" ]
Is there a cross-platform way to get the current date and time in C++?
Since C++ 11 you can use [`std::chrono::system_clock::now()`](http://en.cppreference.com/w/cpp/chrono/system_clock/now) Example (copied from [en.cppreference.com](https://en.cppreference.com/w/cpp/chrono)): ``` #include <iostream> #include <chrono> #include <ctime> int main() { auto start = std::chrono::system_clock::now(); // Some computation here auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end-start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "finished computation at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << "s" << std::endl; } ``` This should print something like this: ``` finished computation at Mon Oct 2 00:59:08 2017 elapsed time: 1.88232s ```
C++ shares its date/time functions with C. The [tm structure](http://en.cppreference.com/w/cpp/chrono/c/tm) is probably the easiest for a C++ programmer to work with - the following prints today's date: ``` #include <ctime> #include <iostream> int main() { std::time_t t = std::time(0); // get time now std::tm* now = std::localtime(&t); std::cout << (now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-' << now->tm_mday << "\n"; } ```
How to get current time and date in C++?
[ "", "c++", "date", "time", "cross-platform", "" ]
Why does this code sometimes return 1E+1 whilst for other inputs (e.g. 17) the output is not printed in scientific notation? ``` BigDecimal bigDecimal = BigDecimal.valueOf(doubleValue).multiply(BigDecimal.valueOf(100d)).stripTrailingZeros(); System.out.println("value: " + bigDecimal); ```
use [bigDecimal.toPlainString()](http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#toPlainString()): ``` BigDecimal bigDecimal = BigDecimal.valueOf(100000.0) .multiply(BigDecimal.valueOf(100d)) .stripTrailingZeros(); System.out.println("plain : " + bigDecimal.toPlainString()); System.out.println("scientific : " + bigDecimal.toEngineeringString()); ``` outputs: ``` plain : 10000000 scientific : 10E+6 ```
It's the implicit `.toString()` conversion that is happening when you pass the result into `System.out.println()`.
Why does Java BigDecimal return 1E+1?
[ "", "java", "floating-point", "bigdecimal", "" ]
I have a dictionary which store a string as the key, and an integer as the value. In my output I would like to have the key displayed as a string without parenthesis or commas. How would I do this? ``` for f_name,f_loc in dict_func.items(): print ('Function names:\n\n\t{0} -- {1} lines of code\n'.format(f_name, f_loc)) ``` output: ``` Enter the file name: test.txt line = 'def count_loc(infile):' There were 19 lines of code in "test.txt" Function names: ('count_loc(infile)',) -- 15 lines of code ``` Just incase it wasn't clear, I would like the last line of the output to be displayed as: ``` count_loc(infile) -- 15 lines of code ``` EDIT ``` name = re.search(func_pattern, line).groups() name = str(name) ``` Using type() before my output, I verified it remains a string, but the output is as it was when name was a tuple
To elaborate on [Peter's answer](https://stackoverflow.com/questions/928330/formatting-the-output-of-a-key-from-a-dictionary/928340#928340), It looks to me like you're assigning a one-item [tuple](http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange) as the key of your dictionary. If you're evaluating an expression in parentheses somewhere and using that as the key, be sure you don't have a stray comma in there. Looking at your further edited answer, it's indeed because you're using the groups() method of your regex match. That returns a tuple of `(the entire matched section + all the matched groups)`, and since you have no groups, you want the entire thing. `group()` with no parameters will give you that.
I don't have Python 3 so I can't test this, but the output of f\_name makes it look like it is a tuple with one element in it. So you would change `.format(f_name, f_loc)` to `.format(f_name[0], f_loc)` **EDIT**: In response to your edit, try using [`.group()`](http://docs.python.org/library/re.html#re.MatchObject.group) instead of `.groups()`
Formatting the output of a key from a dictionary
[ "", "python", "string", "dictionary", "python-3.x", "" ]
How do I write out my array with a repeater? ``` string[,] month = { {"Januari", "Februari", "Mars", "Apri", "Maj", "Juni", "Juli", "Agusti", "September", "November", "Oktober", "December"}, {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"} }; ``` Now I can use Container.DataItem, but how do I get the first string of items in one place and the second in another place? ``` <a href="Default.aspx?m=01">Januari</a> ```
It would be possible to use an array of arrays as data source (but not a two dimensional array), but you would have to arrange it the other way arround, so that each inner array would contain a name and a number. I would prefer a more OOP approach though, it gives a bit more structure and the repeater code gets a lot cleaner: Create a class for the month information: ``` public class MonthInfo { public string Name { get; private set; } public string Number { get; private set; } public MonthInfo(string name, string number) { Name = name; Number = number; } } ``` Now you can create an array of objects to use as data source for the repeater: ``` MonthInfo[] months = { new MonthInfo("Januari", "01"), new MonthInfo("Februari", "02"), new MonthInfo("Mars", "03"), new MonthInfo("April", "04"), // inte "Apri" ;) new MonthInfo("Maj", "05"), new MonthInfo("Juni", "06"), new MonthInfo("Juli", "07"), new MonthInfo("Augusti", "08"), // inte "Agusti" ;) new MonthInfo("September", "09"), new MonthInfo("Oktober", "10"), // kommer före november ;) new MonthInfo("November", "11"), new MonthInfo("December", "12") }; MonthRepeater.DataSource = months; ``` In the repeater you use the properties of the month info class: ``` <asp:Repeater runat="server" id="MonthRepeater"> <ItemTemplate> <a href="Default.aspx?m=<%#Eval("Number")>"%><%#Eval("Name")%></a> </ItemTemplate> </asp:Repeater"> ```
Looks like you should be using enums in this case... ie... ``` enum Month = {January=1, February, March}; Month month = Month.January; Month alsomonth = (Month)(1); // Should work ```
string [,] and repeater
[ "", "c#", "asp.net", "arrays", "string", "repeater", "" ]
I'm doing a java application. This are my files so far: ## Person Interface. has a setName(String aName) method ## PersonImpl Implementation of Person Interface. ## PersonFactory Interface has a createPerson() ## PersonFactoryImpl Implementation of PersonFactory Interface. The thing is I was willing to add a method getAll() that returns a Collection of Persons and I am not sure where to place it. I was thinking of adding it as an static method to PersonImpl or to PersonFactoryImpl, but I am not sure. Which is the best way? Thanks for reading!
If another implementation of PersonFactory is provided, should it also need to provide a #getAll? If so, it belongs on the interface... and then it can't be a static method in Java. Given that, is it a function of your PersonFactory or should there be an abstraction for your storage mechanism as well? If so, a PersonRepository interface whose implementations accept a PersonFactory, and provides a natural home for getAll-type functionality seems more appropriate. If not, then as a member of the concrete PersonFactory could be appropriate enough...
The logical way would be to add it as a static method to the `PersonFactory`. That is the class which generates your `Person` objects, and if it keeps references to all generated objects, it should be able to answer your `getAll()` API. Obviously, it is not reasonable for each `Person` object to be aware of other similar objects, thus this method does not belong there. **EDIT:** Given the fact that they reside on a database, it might be wise to decouple the `PersonFactory` (which job is to create `Person` objects), from a `PersonRepository` which will be actually accessing the database (or whatever persistency you have) and returning `Person` objects. It would seem awkward to me that the same class is responsible both for creating objects as well as fetching them from a database. That being said, if your application demands this tight-coupling, it might be acceptable.
Where to place a getAll() method when having a Factory
[ "", "java", "factory", "" ]
I have a table called Person that contain a field called PersonAge. I need to group the ages by age bands ie '12 and under', '13-17', '18-25', '25 and over' and return this resultset using a stored procedure. Ideally I need to get returned 2 fields , 'Age Band', 'Total' like so ``` Age band Total 12 and under 5 13 - 17 8 18 - 25 7 25 and over 10 ```
Create a table containing your bands: ``` CREATE TABLE agebands ( id INT NOT NULL PRIMARY KEY, lower_bound INT NOT NULL, upper_bound INT NOT NULL ) CREATE INDEX IDX_agebands_bounds ON (lower_bound, upper_bound) ``` Then populate it with your data: ``` INSERT INTO agebands VALUES (1, 0, 12) INSERT INTO agebands VALUES (2, 13, 17) INSERT INTO agebands VALUES (3, 18, 24) INSERT INTO agebands VALUES (4, 25, 199) ``` Then join with it: ``` SELECT lower_bound, upper_bound, COUNT(*) AS number_of_people FROM persons INNER JOIN agebands ON person_age BETWEEN lower_bound AND upper_bound GROUP BY lower_bound, upper_bound ORDER BY lower_bound ``` This allows for flexibility in adjusting the bands. Of course, the other answer here using UNION is usable too, which is more appropriate if you can/won't add another table to your database.
A simple UNION should suffice. ``` SELECT [Ageband] = '12 and under', COUNT(*) FROM dbo.Person WHERE PersonAge <= 12 UNION ALL SELECT '13-17', COUNT(*) FROM dbo.Person WHERE PersonAge BETWEEN 13 AND 17 UNION ALL SELECT '18-25', COUNT(*) FROM dbo.Person WHERE PersonAge BETWEEN 18 AND 25 UNION ALL SELECT '26 and over', COUNT(*) FROM dbo.Person WHERE PersonAge >= 26 ```
SQL Creating a stored proc for returning age bands
[ "", "sql", "stored-procedures", "" ]
In our current use of memcached, we are running into problems in a high volume server because so much time is used setting up and tearing down connections to our memcache server. Would using persistent connections to memcached help alleviate this problem? Also, what is the preferred way to connect and use persistent memcahced connections? I was thinking of setting a "pool\_size" variable then randomly choosing from `1-$POOL_SIZE` and using that connection ``` $mem = new Memcached(rand(1, $pool_size)); ``` Either I am looking in the wrong place or there is not a lot of information on this out there.
The php client doesn't handle persistent connections. you either need to use your pooling idea, or use a 3rd party memcached client for php that supports persistent connections. like this one: <http://github.com/andreiz/php-memcached/tree/master>
Both pecl/memcache and pecl/memcached support persistent connections per process. However, the bug does exist in pecl/memcached at this time.
Persistent connections to memcached in PHP
[ "", "php", "memcached", "persistent", "" ]
I want to change element name with following statement: ``` SET @myDoc.modify('replace value of (/CustomerInfo)[1] with "Customer"') ``` from <**CustomerInfo**>     <ID>1</ID> </**CustomerInfo**> to <**Customer**>     <ID>1</ID> </**Customer**> But failed. So how can i change it just in sql ?
I tried following sql: select @myDoc=( select @myDoc.query('/CustomerInfo/node()') for xml raw('Customer'),type) I guess it solve your question.
I think you need to select the values with .query or .nodes into a resultset that will render into the XML you want using [FOR XML](http://msdn.microsoft.com/en-us/library/ms178107(SQL.90).aspx)
Modify xml element name in SQL Server
[ "", "sql", "sql-server", "xml", "" ]
How would I get something like this to work? ``` $class_name = 'ClassPeer'; $class_name::doSomething(); ```
Depending on version of PHP: ``` call_user_func(array($class_name, 'doSomething')); call_user_func($class_name .'::doSomething'); // >5.2.3 ```
Use [`call_user_func`](https://www.php.net/manual/en/function.call-user-func.php). Also read up on PHP [`callbacks`](https://www.php.net/manual/en/language.pseudo-types.php#language.types.callback). ``` call_user_func(array($class_name, 'doSomething'), $arguments); ```
How can I call a static method from a class if all I have is a string of the class name?
[ "", "php", "" ]
I am trying to look for a SQL table by name and if it exists drop it. This all needs to be done in C# using SMO. To complicate it a bit more the table also has a schema other then "dbo". Ultimatly the table will be recreated via SMO (I have this working) but I have to make sure it is not there before I can recreate it. All of the examples that I have seen seem to be creating and then dropping the table all in the same context. In my case the table will have been created and populated in a previous session.
First question is, why can you not drop and recreate with DDL? And in answer to your question: ``` Table table = new Table(myDatabase, "MyTable", "MySchema"); ```
``` var connection = new SqlConnection(connectionString); var server = new Server(new ServerConnection(connection)); db = server.Databases["YourFavDB"]; db.Tables["YourHatedTable"].Drop(); ```
Checking for and dropping an existing table via C# and SMO
[ "", "c#", "smo", "" ]
I've been trying to do this for about 6 hours now and i'm stumped.. I want the equivalent of this in C#: ``` $settings = array(); foreach(file('settings.txt') as $l) $settings[]=explode(',',$l); print $settings[0][2]; ``` This is what i've got so far that doesn't work: ``` string fileName = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\" + "settings.txt"; string[,] settings; FileStream file = null; StreamReader sr = null; try { file = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read); sr = new StreamReader(file, Encoding.ASCII); string[] line; int i = 0; do { line = sr.ReadLine().Split(','); settings[i++, 0] = line[0]; } while (line != null); file.Close(); MessageBox.Show(settings[1, 0]); } catch (Exception err) { MessageBox.Show(err.Message); } ``` I get "Object reference not set to an instance of an object", any ideas would be greatly appreciated..
Use a *jagged array* instead of a multidimensional one – or better yet, a `List<string[]>`: ``` var settings = new List<string[]>(); foreach (string line in File.ReadLines("settings.txt", System.Text.Encoding.ASCII)) settings.Add(line.Split(',')); ``` Marc's use of LINQ instead of the loop is a good alternative.
You should initiate your array first, like that : ``` string[,] settings = new string[3,3]; ``` **EDIT :** Also by this line, you skip to set first item of the array : ``` settings[i++, 0] = line[0]; ``` You should assign your value like that : ``` settings[i, 0] = line[0]; i++; ```
C# Multidimensional Arrays Like PHP
[ "", "c#", "arrays", "" ]
I have a UDF that queries data out of a table. The table, however, needs to be definable as a parameter. For example I can't have: **Select \* From [dbo].[TableA]** I need something like: **Select \* From [dbo].[@TableName]** The above line doesn't work, and also the UDF prohibits me from setting the query as a string and calling exec(). I can do this in a procedure, but I can't call the procedure from the UDF either. Does anyone know how I can accomplish this within the UDF without having some kind of massive switch statement?
This can't be done, dynamic SQL is not supported in functions. See this SO question: [Executing dynamic SQL in a SQLServer 2005 function](https://stackoverflow.com/questions/150552/executing-dynamic-sql-in-a-sqlserver-2005-function)
``` SET @SQL = 'SELECT * FROM ' + @table EXEC (@SQL) -- parentheses are required ```
Using a variable for table name in 'From' clause in SQL Server 2008
[ "", ".net", "sql", "sql-server", "t-sql", "" ]
Web pages have moved to use URLs like: //weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx i.e. they include the title of the page in the url rather than having some coded id. I understand that this is useful for SEO, and also for users in finding the correct page where they wish to type in the url. I would like to follow this approach, but wonder how best to acheive it, and particularly how to deal with duplicates. Is a database trigger which creates the url based on the title and adds a numeric incremental suffix to any duplicates the best way to go, and if so what would such a trigger look like?
In Wordpress at least, the "slug" (as they call it) is generated once from the item's title and stored separately in the database. If two "slugs" collide, it appends `-1`, `-2`, etc. to the end. I personally prefer if you add an (optional) field to the submission form to allow people to insert their own—it allows people to specify a shorter URL than `my-long-article-is-hard-to-type`.
Instead of having an id based on a title they could use id based on both a date and a title (*2007/12/03/asp-net-mvc-framework-part-2-url-routing*). So if you don't have articles with the same titles in one day (which isn't too severe restriction) duplicates are eliminated.
ASP.Net MVC - route object id == title - how to deal with duplicates?
[ "", "c#", "sql-server", "asp.net-mvc", "" ]
I have links on a homepage that may or may not have attachments associated with them. If the links have attachments, then an icon will be placed next to the link. The icon will only be there if the link has an attachment. ``` protected void Page_Load(object sender, EventArgs e) { foreach (Image pic in imgAttachment) { int type = ds.Current_Events[index].AttachmentID; //ds is the dataset ``` The foreach loop is going through each of the "Current Event" pictures on the homepage then getting the type of attachment associated with each link aka the AtachmentID. The AttachmentID can be a 0, 1, 2, or 3 which means no attachment, photo attached, video attached, or document attached repectively. A switch statement is then used to change the ImageUrl attribute to the corresponding picture. ``` switch (type) { case 0: break; case 1: pic.ImageUrl = "images/eventicons/Photo.jpg"; //changed from just "Photo.jpg" break; case 2: pic.ImageUrl = "images/eventicons/Video.jpg"; //changed from just "Video.jpg" break; case 3: pic.ImageUrl = "images/eventicons/Doc.jpg"; //changed from just "Doc.jpg" break; default: pic.Visible = false; break; } index++; } } ``` The image does not load in IE, however it does work for firefox. The following is the aspx front ``` <div> <ul> <li> <asp:HyperLink ID="lblEvent1" runat="server"> <img src="images/bar_blank.gif" /> </asp:HyperLink> <asp:Image ID="Image1" runat="server" /> </li> <li> <asp:HyperLink ID="lblEvent2" runat="server"> <img src="images/bar_blank.gif" /> </asp:HyperLink> <asp:Image ID="Image2" runat="server" /> </li> </ul> </div> ```
I figured out the problem. The pictures that I was using were almost 500kb. I assumed the disk space size of the pictures were small because the images themselves were small but this was not true. I resized the images and got them down to around 40kb. The images now load in ie. So, there seems to be a problem in ie if you change the ImageUrl of an image control in asp.net during page load and the image file you are pointing to is large (500kb). The solution is to make the picture itself take up less disk space by resizing it, making it a gif, ect..
You should add the full path to your images. Instead of ``` pic.ImageUrl = "Photo.jpg"; ``` you could do this to have ASP.Net write out the path of the photo as well... ``` pic.ImageUrl = "~/MyImagePath/Photo.jpg"; ```
How to change an image's ImageUrl attribute on page load with asp.net and C# in IE
[ "", "c#", "asp.net", "internet-explorer", "image", "" ]
I'm creating a cell editor, but I've done (and seen) this in other code. I'm creating an object and then dropping it on the floor like this: `ButtonCellEditor buttonColumn = new ButtonCellEditor(table, 2);` This class takes the table and sets a TableColumnModel and custom cell renderers to it. Then, the method ends and I don't reference the buttonColumn object anymore. So, is there a difference between doing the above and doing this (which also works)? `new ButtonCellEditor(table, 2);` Anything really wrong with doing this?
You shouldn't have unused variables in your code, that makes it less clear. Also, a constructor is (as its name states) a method for initialize the object, this in your case is not done. I suggest you to have a **static method** instead: ``` ButtonCellEditor.niceNameHere(table, 2); ``` The only case I can think in which a constructor would be adequate is when it takes params to initialize itself and then perform some actions later, but not for doing the action inside and this is not like yours.
There's nothing wrong with either of those way of creating a ButtonCellEditor. However, if you later want to reference that object, with method two you have no way of doing so. With method 1 you can at least say buttonColumn.method().
Dropping objects on the floor
[ "", "java", "oop", "" ]
I am looking for a complete, precise and accurate documentation about Birt Chart Engine but I cant find anything, all documentations I have encountered are more Birt Designer related or inaccurate or even inexistante. I hope someone can help me... (I precise that I particularly look for a documentation about chart interactivity and scripting while being rendered as SWT content and made fully with Java code).
I believe the API docs can be found [here](http://www.birt-exchange.org/documentation/BIRT_220/ChartJavadoc/chart/api/index.html), which are precise and accurate regarding the various classes and how they can be used.
First, BIRT cannot render interactively like you've seen in demos on Actuate's website -- that is a web-based program that they sell -- it may have misled you. It can run from a .WAR on a server and feed some AJAX code or whatever. Second, there is no good, up-to-date, free documentation for BIRT, as far as I can find in three weeks of searching. The API docs are quite lacking with respect to integrating BIRT with your own application or extending its capabilities. I have found the "Integrating and Extending BIRT" book by Jason Weathersby et al to be marginally helpful -- it is available for "rent" online through Safari Books Online. Mostly you'll need to do lots of Google searches to find what you're looking for. The code examples are quite necessary to follow, since there are a lot of nit-picky details that will hurt you.
Birt Chart Engine Documentation
[ "", "java", "charts", "swt", "birt", "" ]
I am working on a web application that will deal with many image uploads. Its quite likely that the users will be in areas with slow internet connections and I'm hoping to save them upload time by compressing the images before uploading. I have seen that Aurigma Image Uploader achieves this using a java applet or active x but it's expensive and I'd rather something open source or at least a little cheaper. Ideally I'd like to roll my own if its at all possible. I'm developing on Ruby on Rails if that makes any difference.. Thanks! Edit just to clarify: I don't mind if the solution uses activeX or an applet (although js is ideal) - I'm just looking for something a little cheaper than Aurigma at this stage of development. Also, it may not be feasible for users to shrink the image themselves as in many instances they will uploading directly from an internet cafe or other public internet spot.
Generally, it isn't possible to write an image compressor in JavaScript. Sorry. You'll need to use a plugin of some sort, and as you mention, other sites use Java. It appears to be possible to write something to encode a JPEG in ActionScript (i.e. Flash), which will reach a much larger audience than the Java plugin you mention. [Here's a link to a blog post talking about PNG & JPEG encoders in ActionScript](http://www.kaourantin.net/2005/10/more-fun-with-image-formats-in-as3.html). [Here's another blog post with a demo of an inlined JPEG encoder in ActionScript.](http://henryjones.us/articles/using-the-as3-jpeg-encoder)
Only if you use Flash or Silverlight (only way to be cross-platform) <http://www.jeff.wilcox.name/2008/07/fjcore-source/> may be worth a read.
Is it possible to optimize/shrink images before uploading?
[ "", "javascript", "image", "upload", "compression", "" ]
I am attempting to create a custom widget. My Widget renders itself unless it is inside a scroll area. The code below works. If I change the if(0) to an if(1) inside the MainWindow constructor, it will not render the "Hello World" string. I assume that I must (re)implement some additional methods, but so far I have not been able to find the correct ones with trial and error. ``` // hellowidget.h #ifndef HELLOWIDGET_H #define HELLOWIDGET_H #include <QtGui> class HelloWidget : public QWidget { Q_OBJECT public: HelloWidget(QWidget *parent = 0); void paintEvent(QPaintEvent *event); }; #endif // HELLOWIDGET_H // hellowidget.cpp #include "hellowidget.h" HelloWidget::HelloWidget(QWidget *parent) : QWidget(parent) { } void HelloWidget::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.drawText(rect(), Qt::AlignCenter, "Hello World"); } // mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QtGui> class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); ~MainWindow(); private: }; #endif // MAINWINDOW_H // mainwindow.cpp #include "mainwindow.h" #include "hellowidget.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { HelloWidget *hello = new HelloWidget; QWidget *central = hello; if( 0 ) { QScrollArea *scroll = new QScrollArea ; scroll->setWidget(hello); central = scroll; } setCentralWidget( central ); } MainWindow::~MainWindow() { } // main.cpp #include <QtGui/QApplication> #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } ```
You just have to give your HelloWidget a size and place. Add this line to your code. ``` hello->setGeometry(QRect(110, 80, 120, 80)); ``` --- Or if you want to fill the scroll area with your widget: ``` MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { QScrollArea *const scroll(new QScrollArea); QHBoxLayout *const layout(new QHBoxLayout(scroll)); HelloWidget *const hello(new HelloWidget); hello->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); layout->addWidget(hello); setCentralWidget( scroll ); } ```
Per [Qt docs](http://doc.trolltech.com/4.5/qscrollarea.html#details), "When using a scroll area to display the contents of a custom widget, it is important to ensure that the size hint of the child widget is set to a suitable value. If a standard QWidget is used for the child widget, it may be necessary to call QWidget::setMinimumSize() to ensure that the contents of the widget are shown correctly within the scroll area." Does it work right if you follow these instructions?
Qt: Custom widget in QScrollArea
[ "", "c++", "qt", "qwidget", "" ]
How can I change the background and foreground colors of a WPF Textbox programmatically in C#?
``` textBox1.Background = Brushes.Blue; textBox1.Foreground = Brushes.Yellow; ``` WPF Foreground and Background is of type `System.Windows.Media.Brush`. You can set another color like this: ``` using System.Windows.Media; textBox1.Background = Brushes.White; textBox1.Background = new SolidColorBrush(Colors.White); textBox1.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0, 0)); textBox1.Background = System.Windows.SystemColors.MenuHighlightBrush; ```
If you want to set the background using a hex color you could do this: ``` var bc = new BrushConverter(); myTextBox.Background = (Brush)bc.ConvertFrom("#FFXXXXXX"); ``` Or you could set up a SolidColorBrush resource in XAML, and then use findResource in the code-behind: ``` <SolidColorBrush x:Key="BrushFFXXXXXX">#FF8D8A8A</SolidColorBrush> myTextBox.Background = (Brush)Application.Current.MainWindow.FindResource("BrushFFXXXXXX"); ```
Set background color of WPF Textbox in C# code
[ "", "c#", ".net", "wpf", "background-color", "" ]
i have code like this ``` string xml_path(conf("CONFIG")); xml_path+=FILE_NAME; ``` Where, conf function returns `char *` and FILE name is `const char *` I want to combine it to one line like ``` xml_path(conf("CONFIG")).append(FILE_NAME) ``` how do i do it? any suggestions ??
Question asked for one line: ``` string xml_path = string(conf("CONFIG")) + string(FILE_NAME); ``` (I assume `xml_path` is the name of the variable, and not some sort of call in a library I don't know about).
Alternatively, if you want to format variable of different type, use a ostringstream. eg. ``` std::ostringstream oss; int a = 2; char *s = "sometext"; oss<<s<<a<<endl; cout<<oss.str(); // will output "sometext2" ```
Concat string in C++(STL)
[ "", "c++", "string", "stl", "" ]
Is there a way to configure eclipse to open console apps in a new window rather than it's own console when you run/debug them? I'm debugging a client/server application and I'd like to see the output of both apps at once and not have to switch between the tabs...
In eclipse, you can have two console views... On the console view, you have a button called 'open console' (the most right button in the console view). If you click this and select option 3 (new console view), you will see two consoles. If you right click on the console tab and click on 'detached' the console will be detached from the eclipse frame. (for Eclipse Juno, see the HRJ's comment below) You can select which output you want to see on each console by clicking the 'display selected console' button (second button from the right on the console view)
I have a different solution to this that works for my situation, and can probably be adapted by others. I actually want a real second console window -- gnome-terminal in my case. I want this because I want ANSI color support and I want JLine to operate correctly. I can separately start my program and connect remotely for debugging, but that's annoying. Locate where Java runs from, for the JRE eclipse will run as part of your debug config. Create a script there named gjava, give it the following content, and set it executable: ``` #!/bin/sh gnome-terminal -x java $* ``` Then, in your launch configuration, on the common page, uncheck "Allocate console". On the JRE page, under Java executable, choose "Alternate" and enter gjava. When Eclipse launches in debug mode, it will launch a gnome terminal and pass the remaining args to the Java processor, which will be running inside its window. At that point you have a real console that supports JLine, ANSI colors, and full debug support.
Eclipse open console apps in separate window
[ "", "java", "eclipse", "debugging", "" ]
I am wondering about it in terms of whether one can implement some new functionality for convenience. Will this be possible, when it's out? C# 5.0: compiler as a service: <http://www.matthewlefevre.com/blog/entry.php/c-40-and-c-50/368>
Anders Hejlsberg said: > It is one of the directions we are looking at for future versions of > C#. Indeed, I see meta-programming as a piece of our bigger “Compiler > as a Service” theme that we are working on for a future release. We > want to open up our compiler so it becomes an API you can call to > compile a piece of code and get back expression trees and/or IL. This > enables a whole host of scenarios, such as application > programmability, an interactive prompt, user-written refactorings, and > domain specific languages that have little islands of C# imbedded in > them. > [Source](http://www.simple-talk.com/opinion/geek-of-the-week/anders-hejlsberg-geek-of-the-week/) He also said elsewhere (in a [Channel9](http://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Anders-Hejlsberg-The-Future-of-C/Default.aspx?wa=wsignin1.0) interview) that they were porting the core of the C# compiler to managed code, to enable this. There is a [demo](http://channel9.msdn.com/pdc2008/TL16/) of this available from the last PDC. The C# compiler is indeed managed code.
That really depends on a lot of different things. Including but not limited too ... 1. Will Microsoft write a C# compiler in C# ? 2. Is the compiler delivered in source and binary form or just binary? 3. Do you want to write a binary extension or just modify the source? 4. What license will the source and binary be listed under? 5. Do you want to use the binary in a commercial or hobby project? Now as to what the answers to these questions are, I have no idea. Nor do I believe there is a stated answer one way or the other to the fundamental question #1. So the overall answer is a big "Don't know"
When C# compiler is written in C#, will one be able to modify it?
[ "", "c#", ".net", "compiler-construction", "" ]
I'm a decently experienced .net developer for the desktop but this is my first stab at using ASP.NET and i'm stumped almost right away. I've used the VS2008 "New Website" wizard and got a simple page working, codebehind page and all. But my next step of adding a simple static class for some utility methods to be used by all pages is not working out at all. I've tried putting code in App\_Code, I've tried creating a new library project and referencing it... everything always compiles fine in Visual Studio, but when uploaded to the server it simply refuses to find the namespace/class or recognize the library assembly. I've tried messing around with the web.config but haven't been able to find any way to reference the library assembly ("\*" doesn't seem to do it for example). The server pages says: Version Information: Microsoft .NET Framework Version:2.0.50727.3074; ASP.NET Version:2.0.50727.3074 Is there a best practice way for utility methods and how can I get my codebehind pages to recognize any class (or better yet namespace, or even assembly) besides itself? The exact error i'm getting is: CS0246: The type or namespace name 'MyCommon' could not be found (are you missing a using directive or an assembly reference?)
I'm assuming you *do* have a `using` statement that points to the namespace? Something I see from time to time... on the server, have you (in IIS) marked the new folder as an "application"? It should have a cog in IIS. If you haven't, then it'll be looking in the wrong location for App\_Code (the "application" tells it where the local app root is). Right-click, properties, "create application" (or something like that - I don't have a server to hand...)
You are best to ignore the Web Site "projects". They are unique in the Visual Studio world in that they are not projects (no .csproj or other similar file). They will seem very strange and counter-intuitive to any non web site developer. Instead, use File->Add New Project, and choose "ASP.NET Web Application". That will create a web application project, which will work much more as you expect. You can even add classes in whatever folder you like, and they will work as you'd expect them to work.
ASP.NET beginner woes with new Web Site
[ "", "c#", "asp.net", "visual-studio-2008", "vs-web-site-project", "" ]
Is this possible? ``` #include <map> class Example { private: std::map<std::string, std::string, less<std::string>, std::allocator< CustomPair<std::string, std::string> > > myMap; }; ``` In the example above, CustomPair would be a template class holding a key and value. If this is possible, is it that simple or is there anything I should look out for?
One can only speculate what your real intent is here, so I assume you already have a class that contains both key and value. In that case std::set with a custom comparison may be a better choice than a std::map. You then need to provide a comparison that will only compare the key part of your class and the key part must be const (not change over time) as long as the object is in the set. As mentioned in the comment the elements of a set are only accessable as consts, so if you want to change the value of a such element you need to const\_cast the write access or declare the member mutable. In another answer **iain** made another very good suggestion. If you rarely insert into the container and mostly access the container searching for elements then a sorted std::vector and std::binary\_search are a very effective alternative to the set.
I would be more likely to use std::set.
Is it possible to use a custom class in place of std::pair in an STL map?
[ "", "c++", "dictionary", "std-pair", "" ]
I have a problem, i can't figure out a way to get out text between symbols. ``` site.com/hello-world/my-page-title/ ``` i want to get my-page-title only? How? Thanks for your help,
This regex will put "my-page-title" in the second group: ``` ^([^/]*/){2}([^/]*)/$ ``` If you always want the last group you can use: ``` ^.*/([^/]*)/$ ```
This regex always gives you the last URI segment in the first capturing group as long as the URI is terminated with a slash ``` .+/(.+)/ ``` if the slash sometimes misses you can use ``` .+/(.+)/? ```
Get text between symbols, regex?
[ "", "c#", "asp.net", "regex", "" ]
I'm getting some very strange behaviour with HttpWebRequest I hope someone can help me with. I have a console app which does some aggregation work by by using the HttpWebRequest object to retrieve the contents of a target website. Due to the nature of the requirement the app is multithreaded and attempts to make anywhere between 10 and 30 simultaneous connections (I've been experimenting with a range of values). The actual web request is structured as follows: ``` var req = (HttpWebRequest)WebRequest.Create(url); WebResponse resp = req.GetResponse(); Stream s = resp.GetResponseStream(); var sr = new StreamReader(s, Encoding.ASCII); string doc = sr.ReadToEnd(); sr.Close(); resp.Close(); return doc; ``` Anyway, the strange behaviour is that under normal circumstances the app is achieving around 120 requests per minute but if I open up Fiddler it jumps to about 600. Using Windows 7 Resource Monitor I can see the network activity increase accordingly. The TCP connections for the console process now list the remote address as "IPv4 loopback" rather than the target server IP address (expected). I did wonder about the max number of simultaneous HTTP requests allowed by the machine but changing this in the registry does not seem to make a difference. So the question is; what is it about running Fiddler which suddenly increases the throughput five-fold and how can I achieve this natively on the machine without needing to launch another tool? Thanks!
Looks like I've now been able to get the throughput right up (to double that I was getting with Fiddler open actually) by setting the max connections in the App.config: ``` <system.net> <connectionManagement> <add address="*" maxconnection="30" /> </connectionManagement> </system.net> ``` Very happy with the result but am still a little mystified as to why having Fiddler open changed the results so dramatically.
One thing I noticed right away is that you are not implementing using blocks. That adds a randomness factor that might be multiplied by the number of requests, so I suggest you fix that: ``` var req = WebRequest.Create(url); using (WebResponse resp = req.GetResponse()) { using (Stream s = resp.GetResponseStream()) { using (var sr = new StreamReader(s, Encoding.ASCII)) { return sr.ReadToEnd(); } } } ``` Next, FYI, Fiddler acts as a proxy. If your default proxy was set up to use a script to set up the proxy configuration, then I wonder whether having Fiddler running might not remove the time necessary to do the script setup. That might happen only once, rather than on each request.
Why does the performance of the HttpWebRequest object improve while using Fiddler?
[ "", "c#", ".net", "fiddler", "" ]
If I create and start a thread, how does calling Thread.Sleep(x) within that thread affect the ThreadState (if at all)? Thanks!
> ThreadState defines a set of all > possible execution states for threads. > Once a thread is created, it is in at > least one of the states until it > terminates. Threads created within the > common language runtime are initially > in the Unstarted state, while external > threads that come into the runtime are > already in the Running state. An > Unstarted thread is transitioned into > the Running state by calling Start. > Not all combinations of ThreadState > values are valid; for example, a > thread cannot be in both the Aborted > and Unstarted states. > > **Important**: Thread state is only of interest in a few debugging > scenarios. Your code should never use > thread state to synchronize the > activities of threads. ThreadState: **WaitSleepJoin**: The thread is blocked as a result of a call to Wait, Sleep, or Join. From [here](http://msdn.microsoft.com/en-us/library/system.threading.threadstate(VS.80).aspx).
From [MSDN](http://msdn.microsoft.com/en-us/library/system.threading.threadstate.aspx) > **WaitSleepJoin** The thread is blocked. > This could be the result of calling > Thread.Sleep or Thread.Join, of > requesting a lock — for example, by > calling Monitor.Enter or Monitor.Wait > — or of waiting on a thread > synchronization object such as > ManualResetEvent. Short answer is: Yes!
Does Thread.Sleep affect ThreadState?
[ "", "c#", "multithreading", "" ]
I have a situation where I have a pointer to an [STL](https://en.wikipedia.org/wiki/Standard_Template_Library) vector. So like ``` vector<MyType*>* myvector; ``` I have to set this pointer to NULL in the constructor and then lazy load when the property is touched. How can I instantiate this to a new instance of a vector?
> I have to set this pointer to NULL in the constructor and then lazy load when property is touched. > > How can I instantiate this to a new instance of a vector? I'm not sure I understand you all the way. Why not simply leave the vector empty, and set a Boolean that says whether the property was loaded or not? Alternatively, you can use [`boost::optional`](http://www.boost.org/doc/libs/1_39_0/libs/optional/doc/html/index.html): ``` boost::optional< vector<MyType*> > ``` Or ``` boost::optional< vector< shared_ptr<MyType> > > ``` You can then simply receive the object by dereferencing the optional object, and assign a vector to it like usual. I would not use a pointer for this. It complicates the matter, and you have to think about what happens when you copy the object containing the property, ... If you really have to use a pointer, you can do it like this: ``` struct A { A():prop() { } ~A() { delete prop; } vector< MyType *>& get() { if(!prop) prop = new vector< MyType* >(); return prop; } private: // disable copy and assignment. A(A const&); A& operator=(A const&); vector< MyType* > *prop; }; ``` Or use `shared_ptr`, which would be the way to go in my program (but *boost::optional* would still be first option, after which would be the vector-and-Boolean option, after which would be the following) ``` struct A { typedef vector< shared_ptr<MyType> > vector_type; vector_type &get() { if(!prop) { prop.reset(new vector_type); } return *prop; } private: // disable copy and assignment. A(A const&); A& operator=(A const&); shared_ptr< vector_type > prop; }; ``` Copy and assignment are disabled, as they would share the property behind the scene (shallow copy), which should be either clearly documented or disabled by deep copying in these functions.
Assuming you define vector correctly: ``` vector<int>* myvector; // Note vector must be parametrized with a type. // There is no such thing as a a naked vector. ``` Initialize to NULL ``` myclass::myclass() :myvector(NULL) // You can use 0 here but I still like NULL because it {} // gives me more information. Waiting for the new keyword. ``` Instantiate on first use: ``` myvectr = new vector<int>(100); // reserve some space as appropriate ``` But you should not have a *raw* pointer as a member to your class (unless there is a very good reason). You will need to write your own copy constructor and assignment operator. Or alternatively you can wrap 'myvector' with a smart pointer. Or even better make it a normal vector. There is no real need to make it a pointer.
Instantiate a new STL vector
[ "", "c++", "stl", "" ]
I don't have much experience with JavaScript. However I wanted to do a small thing with JavaScript and MySQL. And I could use some help. I have a page in PHP which search for something and it's gives the results based on the search query. For each result it adds 3 images, one which as a URL where you can view the content. Other where you can edit that content. And the third one you can delete. For that I wanted to do something nice. Like, the user clicks the image, a confirmation dialog appears. In that box it asks if you sure you want to delete the data. If yes, it would delete the data. where ID = The ID is printed in the onclick action, inside the JavaScript function in the image using PHP `echo`. If not, we would close the dialog and continue.
OK, so let's assume the following (forgive me for re-clarifying the question): You have a number of rows of some form, with delete links, and you want to confirm that the user actually wants to delete it? Let's assume the following HTML: ``` <tr> <td>Some Item 1</td> <td><a href="?mode=delete&id=1" class="delete-link">Delete</a></td> </tr> <tr> <td>Some Item 2</td> <td><a href="?mode=delete&id=2" class="delete-link">Delete</a></td> </tr> <tr> <td>Some Item 3</td> <td><a href="?mode=delete&id=3" class="delete-link">Delete</a></td> </tr> ``` So I'm assuming the same PHP script can run the delete, picking up on the mode parameter: ``` <?php if($_GET['mode'] == 'delete') { //Check if there is something in $_GET['id']. if($_GET['id']) { //Prevent SQL injection, just to be safe. $query = "DELETE FROM sometable WHERE id='" . mysql_real_escape_string($_GET['id']) . "'"; mysql_query($query); } } ``` I'm going to give two solutions to this on the JavaScript side - the first with an inline, slightly ugly solution, the second using jQuery (<http://jquery.com/>), and unobtrusive JavaScript. Ok, so for the first, I would bind on the onclick event of each link. ``` <tr> <td>Some Item 3</td> <td><a href="?mode=delete&id=3" class="delete-link" onclick="checkDeleteItem();">Delete</a></td> </tr> ``` Then create a JavaScript function: ``` //This will get called when the link is clicked. function checkDeleteItem() { //show the confirmation box return confirm('Are you sure you want to delete this?'); } ``` As I said, I don't like that solution, because it is horribly obtrusive, and also not particularly robust. Now, the jQuery solution: ``` //Do all this when the DOM is loaded $(function() { //get all delete links (Note the class I gave them in the HTML) $("a.delete-link").click(function() { //Basically, if confirm is true (OK button is pressed), then //the click event is permitted to continue, and the link will //be followed - however, if the cancel is pressed, the click event will be stopped here. return confirm("Are you sure you want to delete this?"); }); }); ``` I heartily recommend this solution over the previous one, since it is much more elegant and nice, and is generally best practice.
Can't help you with the php part, but you can use JavaScript's `Confirm`: ``` var ok = confirm('Are you sure you want to delete this row'); //ok is true or false ``` You can bind a function to the click event on your delete buttons. Returning `false` will cause them to ignore the click.
JavaScript - confirmation box. | Yes? > delete data from MySQL / No - do nothing
[ "", "javascript", "mysql", "" ]
I'm new to this whole Template Metaprogramming in C++ mess and I simply can't get this right. The scenario: For example, I've got fractions 2/5, 6/9,... I want to calculate the result of those fractions at compile-time and sort them later using that value at run-time. Is this even possible? Macros maybe? **Edit:** Thanks Naveen, but it doesn't answer the question if it's possible to calculate floats at compile time using templates. Using recursion, for example. I can't find any info on the webs :/
Not sure what you are asking. Do you mean something like this: ``` #include <iostream> using namespace std;; template <int a, int b> struct Fract { double value() const { const double f = a / double(b); return f; } }; int main() { Fract <2,5> f; cout << f.value() << endl; } ``` **Edit:** If you seriously want to get into template programming, meta or otherwise, I strongly suggest getting hold of the book [C++ Templates: The Complete Guide](http://www.josuttis.com/tmplbook/), which is excellent.
You don't require templates for that. Any decent compiler will optimize the calculations when you do something like this: `float f = 2.0/5;` BTW, if all are compile time variables why do you want to sort them at run time?
Calculate float at compile-time using templates
[ "", "c++", "templates", "" ]
I have some code that works like the advised use of TransactionScope, but has an ambient connection instead of an ambient transaction. Is there a way to use a TransactionScope object with an existing connection, or is there an alternative in the .Net framework for this purpose?
In fact, there is one way. ``` connection.EnlistTransaction(Transaction.Current) ``` It works and it doesnt promote transaction to distributed if not necessary (contrary to what documentation says) HTH
To enlist a connection into a TransactionScope, you need to specify `'Enlist=true'` in its connection string and open the connection in the scope of that TransactionScope object. You can use `SqlConnection.BeginTransaction` on an existing connection. **Update**: Can you use `BeginTransaction` like this: ``` using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = connection.CreateCommand(); SqlTransaction transaction; // Start a local transaction. transaction = connection.BeginTransaction("SampleTransaction"); // Must assign both transaction object and connection // to Command object for a pending local transaction command.Connection = connection; command.Transaction = transaction; ... ... } ```
Is there a way to use TransactionScope with an existing connection?
[ "", "c#", "transactions", "transactionscope", "" ]
I just started integrating Hibernate Search with my Hibernate application. The data is indexed by using Hibernate Session every time I start the server. ``` FullTextSession fullTextSession = Search.getFullTextSession(session); Transaction tx = fullTextSession.beginTransaction(); List books = session.createQuery("from Book as book").list(); for (Book book : books) { fullTextSession.index(book); } tx.commit(); //index is written at commit time ``` It is very awkward and the server takes 10 minutes to start. Am I doing the this in right way? I wrote a scheduler which will update the indexes periodically. Will this update the existing index entries automatically, or create duplicate indices?
As detailed in the Hibernate Search guide, section 3.6.1, if you are using annotations (by now the default), the listeners which launch indexing on store are registered by default: > Hibernate Search is enabled out of the > box when using Hibernate Annotations > or Hibernate EntityManager. If, for > some reason you need to disable it, > set > hibernate.search.autoregister\_listeners > to false. An example on how to turn them on by hand: ``` hibConfiguration.setListener("post-update", new FullTextIndexEventListener()); hibConfiguration.setListener("post-insert", new FullTextIndexEventListener()); hibConfiguration.setListener("post-delete", new FullTextIndexEventListener()); ``` All you need to do is annotate the entities which you want to be indexed with the ``` @Indexed(index = "fulltext") ``` annotation, and then do the fine-grained annotation on the fields, as detailed in the user guide. So you should neither launch indexing by hand when storing, neither relaunch indexing whae the application starts, unless you have entities which have been stored before indexing was enabled. You may get performance problems when you are storing an object which say has an "attachment" and so you are indexing that in the same scope of the transaction which is storing the entity. See here: [Hibernate Search and offline text extraction](https://www.hibernate.org/432.html) for a solution that solves this problem.
Provided you are using a FSDirectoryProvider (which is the default) the Lucene index is persisted on disk. This means there is no need to index on very startup. If you have existing database you want of course to create an initial index using the fullTextSession.index() functionality. However, this should not be on application startup. Consider exposing some sort of trigger url, or admin interface. Once you have the initial index I would recommend to use automatic indexing. This means that the Lucene index gets automatically updated if a books get created/updated/deleted. Automatic indexing should also be enabled by default. I recommend you refer to the automatic and manual indexing sections in the online manual - <http://docs.jboss.org/hibernate/stable/search/reference/en/html_single> --Hardy
Indexing data in Hibernate Search
[ "", "java", "hibernate-search", "" ]
I'd like to have some work done in a background thread as simple as creating a Future var for it and then asking later for the calculated value. In pseudo-C#-code: ``` AsyncFuture<int> asyncFuture = new AsyncFuture<int>(FuncToCalculateValue); //do some other work, or draw UI if(asyncFuture.NoErrorsHappened){ int realResult = asyncResult.Value; } ``` I can implement such type by my own, but my question is: isn't that some kind of a known pattern? Is there maybe a name for it, or maybe even a framework implementation? Probably in .NET 4.0? And if it is a pattern, what are the pitfalls associated with it?
Yacoder, I really like [Ayende's two Future implementations](http://ayende.com/Blog/archive/2008/01/02/Its-the-future-now.aspx). There is some [good discussion](http://ayende.com/Blog/archive/2008/01/02/Its-the-future-now.aspx#20529) [from Jon Skeet](http://ayende.com/Blog/archive/2008/01/02/Its-the-future-now.aspx#20542) in the comments on the cons.
Yes, [Futures are part of the Task Parallel Library](http://blogs.msdn.com/pfxteam/archive/2008/02/29/7960146.aspx) which will be in .NET 4.0. In .NET 4.0 Beta 1, it looks like this exists as a [`Task<TResult>`](http://msdn.microsoft.com/en-us/library/dd321424(VS.100).aspx).
"AsyncFuture<T>" or what? Future<T> obtained in a background thread -- is it a pattern?
[ "", "c#", "multithreading", "design-patterns", "" ]
I have a list box with items like **A B C D E**. I also have two buttons **Move UP** and **Move Down** with it. I have already made their properties false in the property window (F4). When a user selects B or all the items below then my Move Up button should get enabled. It should be disabled for A item In the same way my Move Down button should be enabled when the user selects D or all the items above it. It should be disabled for E. Can you please provide me the right part of code to be written here. Thanks....
I am doing a similar thing in my app. It also handles selection of multiple items and also checks if the multiple items that are selected are continuous or not. Here's the code: ``` private bool SelectionIsContiguous(ListBox lb) { for (int i = 0; i < lb.SelectedIndices.Count - 1; i++) if (lb.SelectedIndices[i] < lb.SelectedIndices[i + 1] - 1) return false; return true; } private void SetMoveButtonStates() { if (this.listBox.SelectedIndices.Count > 0) { if (this.listBox.SelectedIndices.Count > 1 && !SelectionIsContiguous(this.listBox)) { this.btnMoveUp.Enabled = false; this.btnMoveDown.Enabled = false; return; } int firstSelectedIndex = this.listBox.SelectedIndices[0]; this.btnMoveUp.Enabled = firstSelectedIndex == 0 ? false : true; int lastIndex = this.listBox.Items.Count - 1; int lastSelectedIndex = this.listBox.SelectedIndices[this.listBox.SelectedIndices.Count - 1]; this.btnMoveDown.Enabled = lastSelectedIndex == lastIndex ? false : true; } } ```
Handle the SelectedIndexChanged event of the ListBox. If the SelectedIndex is greater than 0, enable "move up". If it is lesser than count - 1, enable "move down"
How to find a particular position of a selected item in Listbox making the Buttons Enabled in C#?
[ "", "c#", "button", "listbox", "" ]
In my SPROC a table named #temp1 contains the following columns: ``` #temp1 (StoreId, StoreDesc, ReservedQty, AvgPrice, QtyOnHand) ``` My question is based on the following query ``` INSERT INTO #temp2 (StoreId, StoreDesc, CommittedQty) (SELECT StoreId, StoreDesc, CASE WHEN ReservedQty > QtyOnHand THEN sum(QtyOnHand * AvgPrice) ELSE sum(ReservedQty * AvgPrice) END AS CommittedQty FROM #temp1 GROUP BY StoreId, StoreDesc, QtyOnHand, ReservedQty) ``` A sample result set looks like this: ``` StoreId StoreDesc CommittedQty C4ED0D8B-22CF-40FE-8EF9-7FD764310C94 FramersBranch 0 C4ED0D8B-22CF-40FE-8EF9-7FD764310C94 FarmersBranch 88978 C4ED0D8B-22CF-40FE-8EF9-7FD764310C94 FarmersBranch 0 C4ED0D8B-22CF-40FE-8EF9-7FD764310C94 FarmersBranch 3152 6369D3A6-83BC-4BB0-9A25-86838CD2B7BA Woodlands 5582 6369D3A6-83BC-4BB0-9A25-86838CD2B7BA Woodlands 389 ``` Unfortunatly since I have to `GROUP BY` the `QtyOnHand` & `ReservedQty` columns in my `CASE` statement I get multiple rows for each StoreId. I would like to know if there is a simple way for me to sum the results (again) based on the CommittedQty so that I may get the following result set I desire: ``` StoreId v StoreDesc CommittedQty C4ED0D8B-22CF-40FE-8EF9-7FD764310C94 FramersBranch 92130 6369D3A6-83BC-4BB0-9A25-86838CD2B7BA Woodlands 5971 ``` I realize I could use another temp table but wondered if there was an easier way to accomplish this inside the `SELECT` statement
I wouldn't use a temp table. My guess is that you're already using at least one too many :) You need to put the SUM around your whole CASE statement: ``` SUM(AvgPrice * CASE WHEN ReservedQty > QtyOnHand THEN QtyOnHand ELSE ReservedQty END) ```
``` SELECT StoreId, StoreDesc, SUM( CASE WHEN ReservedQty > QtyOnHand THEN QtyOnHand * AvgPrice ELSE ReservedQty * AvgPrice END ) AS CommittedQty FROM #temp1 GROUP BY StoreId, StoreDesc ```
SQL Sum Column before inserting into #temp
[ "", "sql", "sum", "group-by", "" ]
I have something like this: ``` <!doctype html> <html> <body> <iframe id="someFrame"></iframe> </body> </html> ``` And I would like to use jQuery to write elements such that the full equivalent HTML would be like this: ``` <!doctype html> <html> <body> <iframe id="someFrame"> <!-- inside the iframe's content --> <!-- <html><body> --> <div>A</div> <div>B</div> <div>C</div> <!-- </body></html> --> </iframe> </body> </html> ``` Alternatively, any plain-old-Javascript would be fine. Thanks. **Edit**: After a little more research, it seems I am looking for an IE-equivalent of the contentDocument property of an iframe. "contentDocument" is a W3C standard which FF supports, but IE does not. (surprise surprise)
You can do both, you just have to target differently: ``` var ifrm = document.getElementById('myIframe'); ifrm = ifrm.contentWindow || ifrm.contentDocument.document || ifrm.contentDocument; ifrm.document.open(); ifrm.document.write('Hello World!'); ifrm.document.close(); ```
After some research, and a corroborating answer from Mike, I've found this is a solution: ``` var d = $("#someFrame")[0].contentWindow.document; // contentWindow works in IE7 and FF d.open(); d.close(); // must open and close document object to start using it! // now start doing normal jQuery: $("body", d).append("<div>A</div><div>B</div><div>C</div>"); ```
Write elements into a child iframe using Javascript or jQuery
[ "", "javascript", "jquery", "iframe", "" ]
I'm writing a bookmarklet and I need to be able to prompt the user for a "password". However, I don't want it to be in clear text on screen, so I cannot use prompt. Is there a masked alternative to prompt()? Any other suggestion?
You can create a floating div on the current page, with a form containing a password field.
alternative: let the bookmarlet point to a particular web page. Get the password from the user on that page, and continue. This solution does not use javascript at all, as you may have noticed. If you really insist on using javascript, you will have to create a new window using javascript (`window.open`), add `form` and `input` elements to it, and set the form's `submit` value to your web app backend. you can of course, display a dialog box on the current page, but that will be pretty irritating to the user. Be warned. jrh
javascript prompt for password (i.e. *******)
[ "", "javascript", "bookmarklet", "" ]
I'm currently in the process of designing the database tables for a customer & website management application. My question is in regards to the use of primary keys as functional parts of a table (and not assigning "ID" numbers to every table just because). For example, here are four related tables from the database so far, one of which uses the traditional primary key number, the others which use unique names as the primary key: ``` -- -- website -- CREATE TABLE IF NOT EXISTS `website` ( `name` varchar(126) NOT NULL, `client_id` int(11) NOT NULL, `date_created` timestamp NOT NULL default CURRENT_TIMESTAMP, `notes` text NOT NULL, `website_status` varchar(26) NOT NULL, PRIMARY KEY (`name`), KEY `client_id` (`client_id`), KEY `website_status` (`website_status`), ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- website_status -- CREATE TABLE IF NOT EXISTS `website_status` ( `name` varchar(26) NOT NULL, PRIMARY KEY (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `website_status` (`name`) VALUES ('demo'), ('disabled'), ('live'), ('purchased'), ('transfered'); -- -- client -- CREATE TABLE IF NOT EXISTS `client` ( `id` int(11) NOT NULL auto_increment, `date_created` timestamp NOT NULL default CURRENT_TIMESTAMP, `client_status` varchar(26) NOT NULL, `firstname` varchar(26) NOT NULL, `lastname` varchar(46) NOT NULL, `address` varchar(78) NOT NULL, `city` varchar(56) NOT NULL, `state` varchar(2) NOT NULL, `zip` int(11) NOT NULL, `country` varchar(3) NOT NULL, `phone` text NOT NULL, `email` varchar(78) NOT NULL, `notes` text NOT NULL, PRIMARY KEY (`id`), KEY `client_status` (`client_status`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; -- -- client_status --- CREATE TABLE IF NOT EXISTS `client_status` ( `name` varchar(26) NOT NULL, PRIMARY KEY (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `client_status` (`name`) VALUES ('affiliate'), ('customer'), ('demo'), ('disabled'), ('reseller'); ``` As you can see, 3 of the 4 tables use their 'name' as the primary key. I know that these will always be unique. In 2 of the cases (the \*\_status tables) I am basically using a dynamic replacement for ENUM, since status options could change in the future, and for the 'website' table, I know that the 'name' of the website will always be unique. I'm wondering if this is sound logic, getting rid of table ID's when I know the name is always going to be a unique identifier, or a recipe for disaster? I'm not a seasoned DBA so any feedback, critique, etc. would be extremely helpful. Thanks for taking the time to read this!
There are 2 reasons I would always add an ID number to a lookup / ENUM table: 1. If you are referencing a single column table with the name then you may be better served by using a constraint 2. What happens if you wanted to rename one of the client\_status entries? e.g. if you wanted to change the name from 'affiliate' to 'affiliate user' you would need to update the client table which should not be necessary. The ID number serves as the reference and the name is the description. In the website table, if you are confident that the name will be unique then it is fine to use as a primary key. Personally I would still assign a numeric ID as it reduces the space used in foreign key tables and I find it easier to manage. EDIT: As stated above, you will run into problems if the website name is renamed. By making this the primary key you will be making it very difficult if not impossible for this to be changed at a later date.
When making natural `PRIMARY KEY`'s, make sure their uniqueness is under your control. If you're absolutely sure you will never ever have uniqueness violation, then it's OK to use these values as `PRIMARY KEY`'s. Since `website_status` and `client_status` seem to be generated and used by you and only by you, it's acceptable to use them as a `PRIMARY KEY`, though having a long key may impact performance. `website` name seems be under control of the outer world, that's why I'd make it a plain field. What if they want to rename their `website`? The counterexamples would be `SSN` and `ZIP` codes: it's not you who generates them and there is no guarantee that they won't be ever duplicated.
Database Design and the use of non-numeric Primary Keys
[ "", "sql", "database", "database-design", "primary-key", "primary-key-design", "" ]
I have an integer variable, that can get a value larger than 4294967295. What type should I use for it (long long, or double, or something else)?
There is no portable way of doing this in C++, as the language does not specify the size of integer types (except sizeof char is 1). You need to consult your compiler documentation.
Use `long long` and if possible add a compile-time assertion that this type is wide enough (smth like `sizeof( long long ) >= 8`). `double` is for floating-point, not integer.
What type to use for integers larger than 2^32 in C++?
[ "", "c++", "types", "" ]
What would be a good way to create a dynamic RSS Feed? Currently, I have coded a function that is able to create a static file, but I am just curious what the best method of running this at certain times/days would be? For example, I create an RSS feed that lists all the items that occur today, and I would like it to populate at 12:01 AM. I also have another RSS feed I wrote that lists the next item to occur. Just for clarification, I have already created the function to actually make the Feeds, I am just looking for a good way to schedule this process to run on a regular, determinable basis. I am programming in C# on the .net 3.5 framework in VS 2008. @John - I am using WebForms, and I don't really have a good reason for not just writing it like that, I just created the static feeds because that was what I knew how to do.
How about using [scheduled tasks](http://www.codeproject.com/KB/cs/tsnewlib.aspx) for this?
If you have access to the windows scheduler then create a script for that. If not I would create it when the page is first accessed after 12:01 and then use a caching technique for subsequent calls.
Dynamic RSS Feed in c#
[ "", "c#", "dynamic", "rss", "feed", "" ]
Somebody tasked with creating a "Core" set of libraries created a set of static classes providing all sorts of utilities from logging, auditing and common database access methods. I personally think this stinks because we now have a Core set of libraries that are hard to test because I can't mock / stub these classes or do any injection into their constructors. I suppose I can use TypeMock to stub these out but I'd rather do it for free. What do you think? Edit If you don't think they're hard to test could you give an example of how you would test them. These static classes instantiate other types to do their functions.
Static classes (methods) do not necessarily have to be avoided as long as they have no hidden dependencies. Of course you can pass dependencies into a static method - it just should not be stored internally and modify the behaviour of later calls. There should be no problem to test them in this case, too. But I have a bad feeling about the cases you mentioned, too. I know some of these static "wrapper" utility classes - and in most cases they really stink :) **EDIT:** Maybe I should clarify. I would use static classes/methods only for very small distinguished tasks. When static classes start to initialize dependencies they certainly should be avoided. If you can't test these static classes they already have a too big job to do. In the [first answer of this question](https://stackoverflow.com/questions/205689/class-with-single-method-best-approach#206481) are the arguments against static classes as you mentioned.
How hard would it be to modify those static classes to utilize Dependency Injection? If you make the DI optional (if possible), you can essentially make a situation where you can use the static classes for mocking, just by properly doing the DI, while not changing any of the "normal" behavior.
Should static classes be avoided because it makes Dependency Injection Difficult?
[ "", "c#", "dependency-injection", "mocking", "testability", "" ]
> **Possible Duplicate:** > [PHP: self vs. $this](https://stackoverflow.com/questions/151969/php-self-vs-this) What does `$this->` mean in CakePHP? Please answer this in two parts... What does `$this` refer to? What does `->` refer to? Can someone explain each part explicitly in terms of the statement $this->Post->find('all'); in the Post controller. Why do you need the ->Post part if it is in the Posts controller?
$this refers to the class you want to use. for instance if you see $this->Post->find('all'), you're trying to access the class Post that extends AppModel. Through conventions, the Post Model uses the posts table in your database. $this->Post->find('all') is used because the AppModel has the find() method and the Post model extends AppModel. <http://api.cakephp.org/class/app-model> <http://book.cakephp.org/view/22/CakePHP-Conventions>
It is an [Object reference](http://mjtsai.com/blog/2004/07/15/php-5-object-references/) to the current object.
Meaning of $this-> in CakePHP
[ "", "php", "oop", "cakephp", "" ]
Can anyone post or point me in the direction of a clear example of a **from scratch** implementation of Model 2 architecture? Below is a detailed description of Model 2, taken from [this page](http://www.java-samples.com/showtutorial.php?tutorialid=350). > The Model 2 architecture for designing JSP pages is in reality, Model View Controller (MVC) applied to web applications. Hence the two terms can be used interchangeably in the web world. MVC originated in SmallTalk and has since made its way into Java community. Model 2 architecure and its derivatives are the cornerstones for all serious and industrial strength web applications designed > in the real world. Hence it is essential for you understand this paradigm thoroughly. Figure 1.2 shows the Model 2 (MVC) architecture. > > The main difference between Model 1 and Model 2 is that in Model 2, a controller handles the user request instead of another JSP. The controller is implemented as a Servlet. The following steps are executed when the user submits the request. > > 1. The Controller Servlet handles the user’s request. (This means the hyperlink in the JSP should point to the controller servlet). > 2. The Controller Servlet then instantiates appropriate JavaBeans based on the request parameters (and optionally also based on session attributes). > 3. The Controller Servlet then by itself or through a controller helper communicates with the middle tier or directly to the database to fetch the required data. > 4. The Controller sets the resultant JavaBeans (either same or a new one) in one of the following contexts – request, session or application. > 5. The controller then dispatches the request to the next view based on the request URL. > 6. The View uses the resultant JavaBeans from Step 4 to display data. Note that there is no presentation logic in the JSP. The sole function of the JSP in Model 2 architecture is to display the data from the JavaBeans set in the request, session or application scopes. > [![MVC example](https://i.stack.imgur.com/imowO.jpg)](https://i.stack.imgur.com/imowO.jpg) > (source: [java-samples.com](http://www.java-samples.com/images/model2architecture.jpg))
I like [Bear Bibeault's](http://javaranch.com/journal/200603/Journal200603.jsp#a5) article from a few years ago. High level explanation, but very clear. This is his implementation of an MVC "framework". I learned a lot by going through it: [Bear Bibeault's Frontman](http://www.bibeault.org/frontman/)
I would [download Spring](http://www.springsource.com/download/community?project=Spring%20Framework) and check out some Spring examples too. Also take a look at [this tutorial](http://maestric.com/en/doc/java/spring)
Examples of Java MVC Model 2 architecture?
[ "", "java", "model-view-controller", "web-applications", "servlets", "" ]
I'm trying to encrypt and decrypt a file stream over a socket using RijndaelManaged, but I keep bumping into the exception ``` CryptographicException: Length of the data to decrypt is invalid. at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) at System.Security.Cryptography.CryptoStream.FlushFinalBlock() at System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing) ``` The exception is thrown at the end of the using statement in receiveFile, when the whole file has been transferred. I tried searching the web but only found answers to problems that arise when using Encoding when encrypting and decrypting a single string. I use a FileStream, so I don't specify any Encoding to be used, so that should not be the problem. These are my methods: ``` private void transferFile(FileInfo file, long position, long readBytes) { // transfer on socket stream Stream stream = new FileStream(file.FullName, FileMode.Open); if (position > 0) { stream.Seek(position, SeekOrigin.Begin); } // if this should be encrypted, wrap the encryptor stream if (UseCipher) { stream = new CryptoStream(stream, streamEncryptor, CryptoStreamMode.Read); } using (stream) { int read; byte[] array = new byte[8096]; while ((read = stream.Read(array, 0, array.Length)) > 0) { streamSocket.Send(array, 0, read, SocketFlags.None); position += read; } } } private void receiveFile(FileInfo transferFile) { byte[] array = new byte[8096]; // receive file Stream stream = new FileStream(transferFile.FullName, FileMode.Append); if (UseCipher) { stream = new CryptoStream(stream, streamDecryptor, CryptoStreamMode.Write); } using (stream) { long position = new FileInfo(transferFile.Path).Length; while (position < transferFile.Length) { int maxRead = Math.Min(array.Length, (int)(transferFile.Length - position)); int read = position < array.Length ? streamSocket.Receive(array, maxRead, SocketFlags.None) : streamSocket.Receive(array, SocketFlags.None); stream.Write(array, 0, read); position += read; } } } ``` This is the method I use to set up the ciphers. byte[] init is a generated byte array. ``` private void setupStreamCipher(byte[] init) { RijndaelManaged cipher = new RijndaelManaged(); cipher.KeySize = cipher.BlockSize = 256; // bit size cipher.Mode = CipherMode.ECB; cipher.Padding = PaddingMode.ISO10126; byte[] keyBytes = new byte[32]; byte[] ivBytes = new byte[32]; Array.Copy(init, keyBytes, 32); Array.Copy(init, 32, ivBytes, 0, 32); streamEncryptor = cipher.CreateEncryptor(keyBytes, ivBytes); streamDecryptor = cipher.CreateDecryptor(keyBytes, ivBytes); } ``` Anyone have an idea in what I might be doing wrong?
It looks to me like you're not properly sending the final block. You need to at least `FlushFinalBlock()` the sending `CryptoStream` in order to ensure that the final block (which the receiving stream is looking for) is sent. By the way, [`CipherMode.ECB` is more than likely an epic fail](http://www.codinghorror.com/blog/archives/001267.html) in terms of security for what you're doing. At least use `CipherMode.CBC` (cipher-block chaining) which actually uses the IV and makes each block dependent on the previous one. EDIT: Whoops, the enciphering stream is in read mode. In that case you need to make sure you read to EOF so that the CryptoStream can deal with the final block, rather than stopping after `readBytes`. It's probably easier to control if you run the enciphering stream in write mode. One more note: You cannot assume that bytes in equals bytes out. Block ciphers have a fixed block size they process, and unless you are using a cipher mode that converts the block cipher to a stream cipher, there will be padding that makes the ciphertext longer than the plaintext.
After the comment made by Jeffrey Hantin, I changed some lines in receiveFile to ``` using (stream) { FileInfo finfo = new FileInfo(transferFile.Path); long position = finfo.Length; while (position < transferFile.Length) { int maxRead = Math.Min(array.Length, (int)(transferFile.Length - position)); int read = position < array.Length ? streamSocket.Receive(array, maxRead, SocketFlags.None) : streamSocket.Receive(array, SocketFlags.None); stream.Write(array, 0, read); position += read; } } ``` `->` ``` using (stream) { int read = array.Length; while ((read = streamSocket.Receive(array, read, SocketFlags.None)) > 0) { stream.Write(array, 0, read); if ((read = streamSocket.Available) == 0) { break; } } } ``` And voila, she works (because of the ever so kind padding that I didn't care to bother about earlier). I'm not sure what happens if Available returns 0 even though all data hasn't been transferred, but I'll tend to that later in that case. Thanks for your help Jeffrey! Regards.
Length of the data to decrypt is invalid
[ "", "c#", "cryptography", "rijndaelmanaged", "" ]
I want to build a flexible reporting system for my application. So far I only have a concept in my head and need some tips on implementation. I'm using Crystal Reports to render reports and I know how to load reports dynamically. Now, the idea is that every report will be packaged as a separate assembly (.dll). The reporting framework will be loading every custom report and communicating with it via clearly defined interface like this: ``` public interface IReport { string GetTitle(); string GetDescription(); void SetParameter(); void Print(); } ``` Also, there will be some base implementation (as an abstract class) that will handle some common operations on the reports (like binding to data source, etc.): ``` public abstract class Report { ... } ``` Inside every dll there will be an implementation of concrete class, representing this or that report: ``` public class CustomersReport : Report { ... } ``` Now, I have to figure out the following: 1) How to dynamically locate and load the dll? 2) How to create an instance of concrete class (CustomerReport) and cast it to IReport in order to call necessary methods on it? Have you ever implemented such an extensible system? Could you please share your expertise / code snippets? Thanks in advance. EDIT: While investigating this question I found Jon Skeet's article on [Plug-ins and Cast Exceptions](http://www.yoda.arachsys.com/csharp/plugin.html) that might be helpful.
See this: [Problem with dynamic loading of a dll into my program](https://stackoverflow.com/questions/835551/problem-with-dynamic-loading-of-a-dll-into-my-program) Is doing exactly what you want wihtout all the YAGNI around it.
Have a look at [Mono.Addins](http://www.mono-project.com/Introduction_to_Mono.Addins) (it's MIT license so it's ok with closed software). From your description it does what you need. Basically it uses a dependency tree + plugins based on interfaces. It has it's own manager for loaded .dll-s and its objects are based on the loaded interface, so you don't need any more magic casting to call anything.
Flexible reporting system with dynamically loaded assemblies
[ "", "c#", "dll", "reporting", "add-in", "" ]
I'm trying to write an application in Managed C++, but I cannot work out how to declare an array of strings. > String^ linet[]; throws an error > 'System::String ^' : a native array cannot contain this managed type So I suppose there's a different way to do this for managed data types. What exactly is it?
Do you really mean Managed C++? Not C++/CLI? Assuming you're actually using C++/CLI (because of the error message you posted), there are two ways to do this: ``` array<String^>^ managedArray = gcnew array<String^>(10); ``` will create a managed array, i.e. the same type as string[] in C#. ``` gcroot<String^>[] unmanagedArray; ``` will create an unmanaged C++ array (I've never actually tried this with arrays - it works well with stl containers, so it should work here, too).
<http://www.codeproject.com/KB/mcpp/cppcliarrays.aspx> That should have all the answers you need :) When working with Managed C++ (aka. C++/CLI aka. C++/CLR) you need to consider your variable types in everything you do. Any "managed" type (basically, everything that derives from System::Object) can only be used in a managed context. A standard C++ array basically creates a fixed-size memory-block on the heap, with sizeof(type) x NumberOfItems bytes, and then iterates through this. A managed type can not be guarenteed to stay the same place on the heap as it originally was, which is why you can't do that :)
Arrays of strings in Managed C++
[ "", "c++", "arrays", "managed", "managed-c++", "" ]
I would like to export a ad hoc Select query result sets from SQL Server to be exported directly as Insert Statements. I would love to see a Save As option "Insert.." along with the other current available options (csv, txt) when you right-click in SSMS. I am not exporting from an existing physical table and I have no permissions to create new tables so the options to script physical tables are not an option for me. I have to script either from temporary tables or from the result set in the query window. Right now I can export to csv and then import that file into another table but that's time consuming for repetitive work. The tool has to create proper Inserts and understand the data types when it creates values for NULL values.
take a look at the [SSMS Tools Pack](http://www.ssmstoolspack.com/) add in for SSMS which allows you to do just what you need.
Personally, I would just write a select against the table and generate the inserts myself. Piece of cake. For example: ``` SELECT 'insert into [pubs].[dbo].[authors]( [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract]) values( ''' + [au_id] + ''', ''' + [au_lname] + ''', ''' + [au_fname] + ''', ''' + [phone] + ''', ''' + [address] + ''', ''' + [city] + ''', ''' + [state] + ''', ''' + [zip] + ''', ' + cast([contract] as nvarchar) + ');' FROM [pubs].[dbo].[authors] ``` will produce ``` insert into [pubs].[dbo].[authors]( [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract]) values( '172-32-1176', 'White', 'Johnson', '408 496-7223', '10932 Bigge Rd.', 'Menlo Park', 'CA', '94025', 1); insert into [pubs].[dbo].[authors]( [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract]) values( '213-46-8915', 'Green', 'Marjorie', '415 986-7020', '309 63rd St. #411', 'Oakland', 'CA', '94618', 1); ... etc ... ``` A couple pitfalls: 1. Don't forget to wrap your single quotes 2. This assumes a clean database and is not SQL Injection safe.
Tool to export result set from SQL to Insert statements?
[ "", "sql", "sql-server", "" ]
First off, I realize most of this can also be done using ItemTemplates. If what I'm trying to do simply isn't possible, I will consider using them instead. Here are the basics of my dilemma: I have a GridView in the ASPX page that is loaded in the CodeBehind. Each row contains a couple of buttons that trigger the OnRowCommand event. When someone clicks the "Edit" button, I create a TextBox object and add it to the Controls collection of a particular cell. This works fine. The problem is, when the person clicks the "Save" button, OnRowCommand is triggered again but the cell is registering 0 items in the Controls collection. I'm pretty sure this is happening before a PostBack so I'm not sure why I can't access the TextBox control. I checked after initially adding the TextBox and it shows 1 Control in the cell. Somewhere between loading the page with the textboxes and clicking the button, these controls have gone missing. Google wasn't much help. Any ideas?
You are dynamically creating textboxes so you have to re-bind your grid on each post back, give your textboxes and id (always the same) and re-attach any event handlers.
When the user clicks the edit button, you are in edit mode for the GridView. You need to set that up as well?
GridView cell not registering any controls on RowCommand event
[ "", "c#", "asp.net", "gridview", "rowcommand", "" ]
I have XML that I need to parse but have no control over the creation of. Unfortunately it's not very strict XML and contains things like: ``` <mytag>This won't parse & contains an ampersand.</mytag> ``` The javax.xml.stream classes don't like this at all, and rightly error with: ``` javax.xml.stream.XMLStreamException: ParseError at [row,col]:[149,50] Message: The entity name must immediately follow the '&' in the entity reference. ``` How can I work around this? I can't change the XML, so I guess I need an error-tolerant parser. My preference would be for a fix that doesn't require too much disruption to the existing parser code.
If it's not valid XML (like the above) then no XML parser will handle it (as you've identified). If you know the scope of the errors (such as the above entity issue), then the simplest solution may be to run a correcting process over it (fixing entities such as inserting entities) and then feed it to an existing parser. Otherwise you'll have to code one yourself with built-in support for such anomalies. And I can't believe that's anything other than a tedious and error-prone task.
Use libraries such as `tidy` or `tagsoup`. [TagSoup, a SAX-compliant parser written in Java that, instead of parsing well-formed or valid XML, parses HTML as it is found in the wild: poor, nasty and brutish, though quite often far from short.](http://home.ccil.org/~cowan/XML/tagsoup/)
How to parse badly formed XML in Java?
[ "", "java", "xml", "parsing", "entities", "" ]
I've written and played around with alot of PHP function and variables where the original author has written the original code and I've had to continue on developing the product ie. Joomla Components/Modules/Plugins and I've always come up with this question: How does the '&' symbol attached to a function or a variable affect the outcome? For instance: ``` $variable1 =& $variable2; ``` OR ``` function &usethisfunction() { } ``` OR ``` function usethisfunction(&thisvariable) { { ``` I've tried searching through the PHP manual and other related sources but cannot find anything that specifically addresses my question.
These are known as [references](http://us.php.net/manual/en/language.references.php). Here is an example of some "regular" PHP code: ``` function alterMe($var) { $var = 'hello'; } $test = 'hi'; alterMe($test); print $test; // prints hi $a = 'hi'; $b = $a; $a = 'hello'; print $b; // prints hi ``` And this is what you can achieve using references: ``` function alterMe(&$var) { $var = 'hello'; } $test = 'hi'; alterMe($test); print $test; // prints hello $a = 'hi'; $b &= $a; $a = 'hello'; print $b; // prints hello ``` The nitty gritty details are in the documentation. Essentially, however: > References in PHP are a means to access the same variable content by different names. They are not like C pointers; instead, they are symbol table aliases. Note that in PHP, variable name and variable content are different, so the same content can have different names. The closest analogy is with Unix filenames and files - variable names are directory entries, while variable content is the file itself. References can be likened to hardlinking in Unix filesystem.
``` <?php $a = "hello"; # $a points to a slot in memory that stores "hello" $b = $a; # $b holds what $a holds $a = "world"; echo $b; # prints "hello" ``` Now if we add & ``` $a = "hello"; # $a points to a slot in memory that stores "hello" $b = &$a; # $b points to the same address in memory as $a $a = "world"; # prints "world" because it points to the same address in memory as $a. # Basically it's 2 different variables pointing to the same address in memory echo $b; ?> ```
How does the '&' symbol in PHP affect the outcome?
[ "", "php", "operators", "joomla1.5", "" ]
I am working on a SQl Server Report Services project and the report I am creating requires some custom code. It seems that [all expressions must be in VB.NET](http://msdn.microsoft.com/en-us/library/ms345237.aspx) and I figured if there was an 'easy' way to switch that over to be C#, it would be helpful. EDIT: Well, I decided to move my code to another C# assembly that follows the patterns like [this example.](http://msftrsprodsamples.codeplex.com/Wiki/View.aspx?title=SS2008!File%20Share%20Data%20Processing%20Extension%20Sample)
It's VBA (Visual Basic for Applications) rather than VB.NET, so it's not .NET, it's an embedded scripting language. Therefore I would expect that there's no way to switch to C#.
I believe that the reports are using something more along the lines of VBScript (**Edit**: OregonGhost says VBA which actually makes more sense than VBScript) than VB.NET (and very limited at that). I have not seen any way of switching it over to C#, and I would like to be proven wrong.
Is there a way to do SSRS Expressions in C#
[ "", "c#", "reporting-services", "expression", "ssrs-expression", "" ]
After reading another SO thread ([Should parameters/returns of collections be IEnumerable<T> or T[]?](https://stackoverflow.com/questions/396513/should-parameters-returns-of-collections-be-ienumerablet-or-t)), I am of the opinion that a unit testing 'issue' I'm having is probably related to what the thread refers to as "late evaluation". I am passing three different but related flavors IEnumerables from a presenter class to my UI. The best news is that it works, but I can't seem to find a way to make a unit test that definitively proves that the right IEnumerable is being passed at the right time. I have a facade with the following method: ``` public IEnumerable<DynamicDisplayDto> NonProjectDtos { get { var activities = LeaveTimeActivities.Cast<TimeSheetActivityBase>() .Concat(AdministrativeActivities.Cast<TimeSheetActivityBase>()); return _assembler.ToActivityDtoCollection(activities, _timeSheet); } } ``` In a presenter, I load a widget: ``` private ITimeSheetMatrixWidget _nonProjectActivityMatrix; public ITimeSheetMatrixWidget NonProjectActivityMatrix { set { .. // load the activities _nonProjectActivityMatrix.Load(Facade.NonProjectDtos); ... } } ``` Then the test on a mocked matrix (using Rhino Mocks): ``` [Test] public void SettingTheWidget_TriggersLoad_NonProjectActivities() { var f = _getFacade(); ... // inject the mocked widget & trigger the Load var widget = MockRepository.GenerateMock<ITimeSheetMatrixWidget>(); timeSheetPresenter.ActivityMatrix = widget; widget.AssertWasCalled(x => x.Load(f.NonProjectDtos), mo =>mo.IgnoreArguments()); <-- only way not to fail //widget.AssertWasCalled(x => x.Load(f.NonProjectDtos)); <-- error } ``` If I look in the debugger, I can see that the IEnumerable load arg is evaluating to Domain.TransferObjects.TimeSheetDtoAssembler +d\_\_1, which is also the part of Rhino's message that the method call failed. Is this is related to late evaluation? Is there a reasonably elegant way to test this more rigorously? I would also like to fully understand the intermediate evaluation better, which looks a lot like the method that assembled it (in the facade code above).
Are the Facade objects both the same in the test and in the object under test -- i.e., are you injecting the Facade object as well? If the objects are different, this would cause the problem that you are seeing. If they are the same, then you could either realize the enumeration in the method (use ToList()).
I just want to address your *late evaluation* concern: Both `Cast` and `Concat` (and many `System.Linq.Enumerable` methods) return instances that comply with `IEnumerable<T>`. The actual results of enumerating these instances are deferred. Why are these results deferred and not eagerly determined? ``` List<int> firstThreePrimes = Enumerable.Range(0, 1000000) .Where(i => isPrime(i)) .Take(3) .ToList(); ``` `ToList` enumerates the `IEnumerable<int>` result from `Take(3)`. No numbers are generated by `Range`, filtered by `Where` or limited by `Take` until `ToList` enumerates this result. If the results from Range were eagerly determined, we would generate 1000000 ints. If the results from `Where` were eagerly determined, then the runtime would have to send all of those 1000000 ints to our `isPrime` method. Instead, the call sequence looks like this. ``` Range return from Range Where return from Where Take return from Take ToList GetEnumerator(Take) GetEnumerator(Where) GetEnumerator(Range) return 0 isPrime(0) is false return 1 isPrime(1) is false return 2 isPrime(2) is true 2 is the first result List.Add(2) return 3 isPrime(3) is true 3 is the second result List.Add(3) return 4 isPrime(4) is false return 5 isPrime(5) is true 5 is the third result List.Add(5) break; ``` This is easy to confirm with a debugger. Just step through and watch the calls to `isPrime`. From examining your code, it looks like `_assembler.ToActivityDtoCollection` probably enumerates the result and you probably aren't experiencing deferred execution.
IEnumerable<T> evaluation and unit testing
[ "", "c#", ".net", "linq", "" ]
If we define a abstract class which has a pure virtual destructor, why do we have to give a definition of a destructor in the abstract class?
The destructor for the base class must be called when the object is destroyed, so it needs a definition.
Because the standard says so: > **12.4.7** A destructor can be declared virtual (10.3) or pure virtual (10.4); if any objects of that class or any derived class are created in the program, the destructor shall be defined. The reason for this is that it is called explicitly when an object of a derived class is destroyed. See also the answers to my previous question: [Under what circumstances is it advantageous to give an implementation of a pure virtual function?](https://stackoverflow.com/questions/977543)
Question about pure virtual destructor
[ "", "c++", "virtual-destructor", "" ]
I'm trying to use setuid() and setgid() to set the respective id's of a program to drop privileges down from root, but to use them I need to know the uid and gid of the user I want to change to. Is there a system call to do this? I don't want to hardcode it or parse from /etc/passwd . Also I'd like to do this programmatically rather than using: id -u USERNAME Any help would be greatly appreciated
Have a look at the [getpwnam()](http://linux.die.net/man/3/getpwnam) and [getgrnam()](http://linux.die.net/man/3/getgrnam) functions.
``` #include <sys/types.h> #include <pwd.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> int main() { char *username = ... struct passwd *pwd = calloc(1, sizeof(struct passwd)); if(pwd == NULL) { fprintf(stderr, "Failed to allocate struct passwd for getpwnam_r.\n"); exit(1); } size_t buffer_len = sysconf(_SC_GETPW_R_SIZE_MAX) * sizeof(char); char *buffer = malloc(buffer_len); if(buffer == NULL) { fprintf(stderr, "Failed to allocate buffer for getpwnam_r.\n"); exit(2); } getpwnam_r(username, pwd, buffer, buffer_len, &pwd); if(pwd == NULL) { fprintf(stderr, "getpwnam_r failed to find requested entry.\n"); exit(3); } printf("uid: %d\n", pwd->pw_uid); printf("gid: %d\n", pwd->pw_gid); free(pwd); free(buffer); return 0; } ```
Programmatically getting UID and GID from username in Unix?
[ "", "c++", "c", "unix", "privileges", "system-calls", "" ]
I'm mucking about with daemons, and wondered how feasible (in terms of memory and cpu usage, and reliability) it is to do this using PHP: ``` <?php // Ignore user aborts and allow the script // to run forever ignore_user_abort(true); set_time_limit(0); $fp = fopen('loop.log', 'w'); fwrite($fp, date('Y-m-d H:i:s') . ' Started' . PHP_EOL); while(1) { fwrite($fp, date('Y-m-d H:i:s') . ' Looped' . PHP_EOL); if (file_exists('loop.stop')) { break; } // Sleep for 100 seconds sleep(100); } fwrite($fp, date('Y-m-d H:i:s') . ' Stopped' . PHP_EOL); fclose($fp); ``` This simple example (adapted from the PHP manual for [ignore\_user\_abort](http://www.php.net/manual/en/function.ignore-user-abort.php)) is just the container script. The actual functionality will be placed inside the `while` loop. I've got this script running on my laptop for 7 hours now, and it looks fine, but it doesn't do much. Has anyone else tried this?
I would tend to put the loop into a BASH script, so that any PHP resources are regularly cleaned up. ``` #!/bin/bash clear date php -f doChecksAndAct.php sleep 100 # rerun myself exec $0 ``` If you were doing any particularly heavy-to-setup tasks in the PHP script, you could also put a small(ish) loop in there (say 50-100 iterations, if they were not pausing multiple seconds between them) to reduce the total overhead time between runs. **Addition:** I've blogged on a Bash/PHP (or other language) pairing so that you can very easily loop in the PHP script, then exit to restart immediately, or pause for a while - [Doing the work elsewhere -- Sidebar running the worker](http://www.phpscaling.com/2009/06/23/doing-the-work-elsewhere-sidebar-running-the-worker/).
I recommend against it. There is a bug open 4 years ago which says [Memory allocated for objects created in object methods is not released](http://bugs.php.net/bug.php?id=33487). The devs consider this a *Feature request* but it's very hard to work around it when using long-running processes. I tried to but was extremely relieved when I was able to retire the application.
How feasible is a daemon written in PHP, using ignore_user abort and set_time_limit(0)
[ "", "php", "daemon", "" ]
The scenario is around calling an external SSL SOAP web service from within Mirth. The web service is requires an SSL/TLS connection along with a client certificate. The intention is to use the built-in SOAP Sender Destination to call the remote secure web service, and somehow include that client certificate. I understand that you first need to install that client certificate into the Java runtime. This may be within the Java runtime's certificate store or the Jetty certstore. The platform: * Windows 2003 SP2 * Mirth 1.8 * Java jre1.5.0\_09 **Question**: what configuration steps (Mirth, JRE certificate stores, etc.) would you suggest to successfully have a Mirth SOAP Sender include a client certificate (\*.cer) when calling a web service secured by SSL?
Mirth 1.8 cannot send a client cert when calling a SOAP web service.
The Java runtime, or more specifically, the Sun JSSE provider, will present a client certificate if some system properties are set. You can read details in the [JSSE Reference Guide,](http://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#InstallationAndCustomization) but the important properties are `javax.net.ssl.keyStore` and `javax.net.ssl.keyStorePassword`. There are a few drawbacks to this approach. First, setting the key store password as a system property makes it accessible to any code running in that process—although this can be controlled if a `SecurityManager` is installed. Second, these settings will be used for any SSL sockets created through the "default" `SSLContext`. If you need different credentials for different endpoints, you'll need a Mirth-specific solution. No starting point was specified in the question, but if starting from scratch, the easiest approach is to create a new Java Key Store ("JKS" format) and generate a new key pair and a CSR. After sending the CSR to the CA and getting a certificate back, import it into the same key store. That key store is ready to use. If a certificate is already available, it is likely to be in a stored with its corresponding private key in PKCS #12 format (.p12 or .pfx file). These can be used directly by a Java application, but the `javax.net.ssl.keyStoreType` property will need to be set to `"PKCS12"`
Mirth: calling an SSL SOAP web service with a client certificate
[ "", "java", "web-services", "ssl", "client-certificates", "mirth", "" ]
Testing my app on some WM Std 6.1 I found out that it fails to uninstall. I receive this error: “[app] was not completely removed. Do you want to remove it from the list of installed programs?" Checking my setup.dll I can tell that Uninstall\_Init and Uninstall\_Exit are being called each time but all the files stays (they are not locked, I’ve checked) and its entry doesn’t disappear from the list of installed apps (whether I choose it to stay or not).
There are really only three possible reasons for this: 1. Uninstall\_Init doesn't return continue. 2. Uninstall\_Exit doesn't return continue. 3. The installer engine failed. If you have verified that 1 & 2 then ok then 3 is going to be tough to figure out. Some problems that I have encounted: * Check the DLL dependencies of your setup DLL and try to remove as many as possible. I've found that dependencies to MSXML can cause problems. * Remove any registry setup in your INF file, move it into your setup dll. I've found this to cause the uninstall to fail randomly on random devices because of this. What I needed up doing for existing customers is write a uninstall application to remove our application manually if the uninstall worked. If you do need to write a manual unistall you need to do the following: \* Remove all your registry keys \* Remove all your files \* Remove registry key HKLM\Security\AppInstall{app name} \* In WM6.1 you need to remove a database record from the EDB database "SwMgmtMetadataStore" where the SWT\_INSTALL\_NAME\_TAG property equals your {app name}.
Another thing worth investigating is the install log created by the cab install/uninstall process. You can find this within the \Application Data\Volatile\ directory (usually called setup.log). Copying this file to your desktop PC and opening it in notepad may provide more clues (such as files in use during uninstall) as to why the uninstall did not succeed.
Windows Mobile fails to uninstall
[ "", "c++", "windows-mobile", "installation", "uninstallation", "" ]
What's the easiest way to compute a 3x3 matrix inverse? I'm just looking for a short code snippet that'll do the trick for non-singular matrices, possibly using Cramer's rule. It doesn't need to be highly optimized. I'd prefer simplicity over speed. I'd rather not link in additional libraries.
Why don't you try to code it yourself? Take it as a challenge. :) For a 3×3 matrix [![alt text](https://i.stack.imgur.com/ri7U9.gif)](https://i.stack.imgur.com/ri7U9.gif) (source: [wolfram.com](http://mathworld.wolfram.com/images/equations/MatrixInverse/NumberedEquation3.gif)) the matrix inverse is [![alt text](https://i.stack.imgur.com/ChJRa.gif)](https://i.stack.imgur.com/ChJRa.gif) (source: [wolfram.com](http://mathworld.wolfram.com/images/equations/MatrixInverse/NumberedEquation4.gif)) I'm assuming you know what the determinant of a matrix |A| is. > Images (c) [Wolfram|Alpha](http://www.wolframalpha.com) and > [mathworld.wolfram](http://mathworld.wolfram.com) (06-11-09, > 22.06)
Here's a version of batty's answer, but this computes the *correct* inverse. batty's version computes the transpose of the inverse. ``` // computes the inverse of a matrix m double det = m(0, 0) * (m(1, 1) * m(2, 2) - m(2, 1) * m(1, 2)) - m(0, 1) * (m(1, 0) * m(2, 2) - m(1, 2) * m(2, 0)) + m(0, 2) * (m(1, 0) * m(2, 1) - m(1, 1) * m(2, 0)); double invdet = 1 / det; Matrix33d minv; // inverse of matrix m minv(0, 0) = (m(1, 1) * m(2, 2) - m(2, 1) * m(1, 2)) * invdet; minv(0, 1) = (m(0, 2) * m(2, 1) - m(0, 1) * m(2, 2)) * invdet; minv(0, 2) = (m(0, 1) * m(1, 2) - m(0, 2) * m(1, 1)) * invdet; minv(1, 0) = (m(1, 2) * m(2, 0) - m(1, 0) * m(2, 2)) * invdet; minv(1, 1) = (m(0, 0) * m(2, 2) - m(0, 2) * m(2, 0)) * invdet; minv(1, 2) = (m(1, 0) * m(0, 2) - m(0, 0) * m(1, 2)) * invdet; minv(2, 0) = (m(1, 0) * m(2, 1) - m(2, 0) * m(1, 1)) * invdet; minv(2, 1) = (m(2, 0) * m(0, 1) - m(0, 0) * m(2, 1)) * invdet; minv(2, 2) = (m(0, 0) * m(1, 1) - m(1, 0) * m(0, 1)) * invdet; ```
Simple 3x3 matrix inverse code (C++)
[ "", "c++", "math", "matrix", "matrix-inverse", "" ]
So now that I have a large bit of XML data I'm interested in: <https://blog.stackoverflow.com/2009/06/stack-overflow-creative-commons-data-dump> I'd like to load this into Oracle to play with. How can I directly load a large XML file directly into Oracle? Server-side solutions (where the data file can be opened on the server) and client-side solutions welcomed. Here's a bit of badges.xml for a concrete example. ``` <?xml version="1.0" encoding="UTF-8" ?> <badges> <row UserId="3718" Name="Teacher" Date="2008-09-15T08:55:03.923"/> <row UserId="994" Name="Teacher" Date="2008-09-15T08:55:03.957"/> ... ```
You can access the XML files on the server via SQL. With your data in the /tmp/tmp.xml, you would first declare the directory: ``` SQL> create directory d as '/tmp'; Directory created ``` You could then query your XML File directly: ``` SQL> SELECT XMLTYPE(bfilename('D', 'tmp.xml'), nls_charset_id('UTF8')) xml_data 2 FROM dual; XML_DATA -------------------------------------------------------------------------------- <?xml version="1.0" encoding="UTF-8"?> <badges> [...] ``` To access the fields in your file, you could use the method described in [another SO](https://stackoverflow.com/questions/985894/oracle-pl-sql-loop-through-xmltype-nodes/985985#985985 "Stack Overflow") for example: ``` SQL> SELECT UserId, Name, to_timestamp(dt, 'YYYY-MM-DD"T"HH24:MI:SS.FF3') dt 2 FROM (SELECT XMLTYPE(bfilename('D', 'tmp.xml'), nls_charset_id('UTF8')) xml_data 3 FROM dual), 4 XMLTable('for $i in /badges/row 5 return $i' 6 passing xml_data 7 columns UserId NUMBER path '@UserId', 8 Name VARCHAR2(50) path '@Name', 9 dt VARCHAR2(25) path '@Date'); USERID NAME DT ---------- ---------- --------------------------- 3718 Teacher 2008-09-15 08:55:03.923 994 Teacher 2008-09-15 08:55:03.957 ```
Seems like you're talking about 2 issues -- first, getting the XML document to where Oracle can see it. And then maybe making it so that standard relational tools can be applied to the data. For the first, you or your DBA can create a table with a BLOB, CLOB, or BFILE column and load the data. If you have access to the server on which the database lives, you can define a DIRECTORY object in the database that points to an operating system directory. Then put your file there. And then either set it up as a BFILE or read it in. (CLOB and BLOB store in the database; BFILE stores a pointed to a file on the operating system side). Alternatively , use some tool that will let you directly write CLOBs to the database. Anyway, that gets you to the point where you can see the XML instance document in the database. So now you have the instance document visible. Step 1 is done. Depending on the version, Oracle has some pretty good tools for shredding the XML into relational tables. It can be pretty declarative. While this gets beyond what I've actually done (I have a project where I'll be trying it this fall), you can theoretically load your XML Schema into the database and annotate it with the crosswalk between the relational tables and the XML. Then take your CLOB or BFILE and convert it to an XMLTYPE column with the defined schema and you're done -- the shredding happens automatically, the data is all there, it's all relational, it's all available to standard SQL without the XQUERY or XML extensions. Of course, if you'd rather use XQUERY, then just take the CLOB or BFILE, convert it to an XMLTYPE, and go for it.
Oracle: loading a large xml file?
[ "", "sql", "xml", "oracle", "" ]
I am needing to detect when a user is inactive (not clicking or typing) on the current page for more than 30 minutes. I thinking it might be best to use event blubbling attached to the body tag and then just keep resetting a timer for 30 minutes, but I'm not exactly sure how to create this. I have jQuery available, although I'm not sure how much of this will actually use jQuery. **Edit:** I'm more needing to know if they are actively using the site, therefore clicking (changing fields or position within a field or selecting checkboxes/radios) or typing (in an input, textarea, etc). If they are in another tab or using another program, then my assumption is they are not using the site and therefore should be logged out (for security reasons). **Edit #2:** So everyone is clear, this is not at all for determining if the user is logged in, authenticated or anything. Right now the server will log the user out if they don't make a page request within 30 minutes. This functionality to prevent the times when someone spends >30 minutes filling in a form and then submitting the form only to find out that they haven't been logged out. Therefore, this will be used in combination with the server site to determine if the user is inactive (not clicking or typing). Basically, the deal is that after 25 minutes of idle, they will be presented with a dialog to enter their password. If they don't within 5 minutes, the system automatically logs them out as well as the server's session is logged out (next time a page is accessed, as with most sites). The Javascript is only used as a warning to user. If JavaScript is disabled, then they won't get the warning and (along with most of the site not working) they will be logged out next time they request a new page.
You can watch [mouse movement](http://docs.jquery.com/Events/mousemove#fn), but that's about the best you're going to get for indication of a user still being there without listening to the click event. But there is no way for javascript to tell if it is the active tab or if the browser is even open. (well, you could get the width and height of the browser and that'd tell you if it was minimized)
This is what I've come up with. It seems to work in most browsers, but I want to be sure it will work everywhere, all the time: ``` var timeoutTime = 1800000; var timeoutTimer = setTimeout(ShowTimeOutWarning, timeoutTime); $(document).ready(function() { $('body').bind('mousedown keydown', function(event) { clearTimeout(timeoutTimer); timeoutTimer = setTimeout(ShowTimeOutWarning, timeoutTime); }); }); ``` Anyone see any problems?
How can I detect with JavaScript/jQuery if the user is currently active on the page?
[ "", "javascript", "jquery", "" ]
Im using Python's built in XML parser to load a 1.5 gig XML file and it takes all day. ``` from xml.dom import minidom xmldoc = minidom.parse('events.xml') ``` I need to know how to get inside that and measure its progress so I can show a progress bar. any ideas? minidom has another method called parseString() that returns a DOM tree assuming the string you pass it is valid XML, If I were to split up the file myself into chunks and pass them to parseString one at a time, could I possibly merge all the DOM trees back together at the end?
you usecase requires that you use sax parser instead of dom, dom loads everything in memory , sax instead will do line by line parsing and you write handlers for events as you need so could be effective and you would be able to write progress indicator also I also recommend trying expat parser sometime it is very useful <http://docs.python.org/library/pyexpat.html> for progress using sax: as sax reads file incrementally you can wrap the file object you pass with your own and keep track how much have been read. edit: I also don't like idea of splitting file yourselves and joining DOM at end, that way you are better writing your own xml parser, i recommend instead using sax parser I also wonder what your purpose of reading 1.5 gig file in DOM tree? look like sax would be better here
Did you consider to use other means of parsing XML? Building a tree of such big XML files will always be slow and memory intensive. If you don't need the whole tree in memory, stream based parsing will be *much* faster. It can be a little daunting if you're used to tree based XML manipulation, but it will pay of in form of a huge speed increase (minutes instead of hours). <http://docs.python.org/library/xml.sax.html>
Showing progress of python's XML parser when loading a huge file
[ "", "python", "xml", "pyqt", "" ]
Considering that I want to write python code that would run on Google App Engine and also inside jython, C-extensions are not an option. Amara was a nice library, but due to its C-extensions, I can't use it for either of these platforms.
[ElementTree](http://effbot.org/zone/element-index.htm) is very nice. It's also part of [2.5](http://docs.python.org/library/xml.etree.elementtree.html).
There's also [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) (which may be geared more toward HTML, but it also does XML).
What is the most state-of-the-art, pure python, XML parser available?
[ "", "python", "xml", "google-app-engine", "jython", "" ]
What is a Map? How would I create and use one in C++?
If you mean `std::map`, it stores pairs of values. In each pair, the first value is called the key, and can be used to quickly look up the associated other value. You can write: ``` std::map<std::string, int> ages; ages["Fred"] = 52; ages["Sue"] = 31; std::cout << "Fred's age is " << ages["Fred"] << std::endl; ```
What is a map - it's a data structure that holds pairs of related values. Each pair consists of a key and a value. Every key in a map must be unique, but different keys can have the same values. Maps are often used for caching or implementing lookup tables, much like a dictionary (which is actually what maps are called in some languages). As for how to implement a map in c++, short answer is - you don't. You use std::map or one of its variants.
What is a Map and how would I use one in C++?
[ "", "c++", "std", "" ]
I have this code, and I want to know, if I can replace only groups (not all pattern) in Java regex. Code: ``` //... Pattern p = Pattern.compile("(\\d).*(\\d)"); String input = "6 example input 4"; Matcher m = p.matcher(input); if (m.find()) { //Now I want replace group one ( (\\d) ) with number //and group two (too (\\d) ) with 1, but I don't know how. } ```
Use `$n` (where n is a digit) to refer to captured subsequences in [`replaceFirst(...)`](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#replaceFirst%28java.lang.String%29). I'm assuming you wanted to replace the first group with the literal string *"number"* and the second group with the value of the first group. ``` Pattern p = Pattern.compile("(\\d)(.*)(\\d)"); String input = "6 example input 4"; Matcher m = p.matcher(input); if (m.find()) { // replace first number with "number" and second number with the first // the added group ("(.*)" which is $2) captures unmodified text to include it in the result String output = m.replaceFirst("number$2$1"); // "number example input 6" } ``` Consider `(\D+)` for the second group instead of `(.*)`. `*` is a greedy matcher, and will at first consume the last digit. The matcher will then have to backtrack when it realizes the final `(\d)` has nothing to match, before it can match to the final digit. **Edit** Years later, this still gets votes, and the comments and edits (which broke the answer) show there is still confusion on what the question meant. I've fixed it, and added the much needed example output. The edits to the replacement (some thought `$2` should not be used) actually broke the answer. Though the continued votes shows the answer hits the key point - Use `$n` references within `replaceFirst(...)` to reuse captured values - the edits lost the fact that unmodified text needs to be captured as well, and used in the replacement so that "*only groups (not all pattern)*". The question, and thus this answer, is not concerned with iterating. This is intentionally an [MRE](https://stackoverflow.com/help/minimal-reproducible-example).
You could use [`Matcher#start(group)`](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#start%28int%29) and [`Matcher#end(group)`](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#end%28int%29) to build a generic replacement method: ``` public static String replaceGroup(String regex, String source, int groupToReplace, String replacement) { return replaceGroup(regex, source, groupToReplace, 1, replacement); } public static String replaceGroup(String regex, String source, int groupToReplace, int groupOccurrence, String replacement) { Matcher m = Pattern.compile(regex).matcher(source); for (int i = 0; i < groupOccurrence; i++) if (!m.find()) return source; // pattern not met, may also throw an exception here return new StringBuilder(source).replace(m.start(groupToReplace), m.end(groupToReplace), replacement).toString(); } public static void main(String[] args) { // replace with "%" what was matched by group 1 // input: aaa123ccc // output: %123ccc System.out.println(replaceGroup("([a-z]+)([0-9]+)([a-z]+)", "aaa123ccc", 1, "%")); // replace with "!!!" what was matched the 4th time by the group 2 // input: a1b2c3d4e5 // output: a1b2c3d!!!e5 System.out.println(replaceGroup("([a-z])(\\d)", "a1b2c3d4e5", 2, 4, "!!!")); } ``` Check **[online demo here](http://ideone.com/qVTMqm)**.
Can I replace groups in Java regex?
[ "", "java", "regex", "replace", "regex-group", "" ]
I am trying to cast from a parent class to a child class but I get an InvalidCastException. The child class only has one property of type int. Does anyone know what I need to do?
A simple way to downcast in C# is to serialize the parent and then deserialize it into the child. ``` var serializedParent = JsonConvert.SerializeObject(parentInstance); Child c = JsonConvert.DeserializeObject<Child>(serializedParent); ``` I have a simple console app that casts animal into dog, using the above two lines of code over [here](http://dotnetanalysis.blogspot.com/2012/12/c-cast-parent-to-child-c-downcast.html)
You can't cast a mammal into a dog - it might be a cat. You can't cast a food into a sandwich - it might be a cheeseburger. You can't cast a car into a Ferrari - it might be a Honda, or more specifically, You can't cast a Ferrari 360 Modena to a Ferrari 360 Challange Stradale - there are differnt parts, even though they are both Ferrari 360s.
Unable to Cast from Parent Class to Child Class
[ "", "c#", "" ]
I have a DLL I need to deploy with my C# application. It's not currently included in the installation package when I hit "Publish" so how do I include it? Would the process be any different if I had app.config and other files I wanted to deploy with my application?
If it's referenced it should be included automatically. I've deployed a couple of apps that require a 3rd party dll and they've published OK. Is the dll referenced correctly in your project? That's the only thing I can think of at the moment that might be the problem, but if it wasn't your code wouldn't compile and/or link anyway. To get the xls file to deploy all you need to do is add the file to the solution and then set the "Copy to Output Directory" property on the file.
I take it you are using Visual Studio? If your using Visual Studio 2008 (I have no experience with Visual Studio 2005) under the *Publish* tab in your project properties click on the *Application Files* button. This will bring up a list of all dependencies assembalies required by your project. If you find that required dll is not being published by the Visual Studio publisher tool by default you can go into here and set the **Publish Status** of the offending dll to **Include**. Sometimes in my more complicated projects, depending on the type of dependency, I have to go into this menu and force certain dll's to be included opposed to the default *Prerequsite* setting. ...but this is all under the assumption you have the assembly properly referenced in the required projects and everything is compiling fine.
How can I include files in a C# deployment?
[ "", "c#", "installation", "deployment", "publish", "" ]
What is the best way to get the current logged in user through Java application running on JBoss. The system environment variable System.getProperty("user.name") does not work as JBoss is running as a service. The application is running on a laptop running Windows XP. The application is web-based and accessed using Internet Explorer by particular logged in Windows user. Only 1 Windows user can be logged in at a time. The application needs to know which user has logged in to do a role based menu and security features. So both the client (Internet Explorer) and the server (JBoss) are running on the same laptop. Currently, we determine the logged in user using tasklist /v and then parsing the output to look for certain processes and the user running them. However, need to know if there is a cleaner way of getting the logged in Windows user.
I don't think the question really makes much sense. There may be *no* users logged onto the host - or there may be multiple users. I'd be somewhat wary of a design that really wanted to know this anyway - web applications shouldn't really be interested in that sort of thing, IMO. What are you trying to do?
String uname = System.getenv("user.name") Reference: <http://download.oracle.com/javase/tutorial/essential/environment/sysprop.html>
Java System Environment Variable Current User
[ "", "java", "environment-variables", "" ]
I'm having some trouble using reflection to differentiate between a non-generic and a generic method on a generic class. Here's a test case I'm working with: ``` public class Foo<T> { public string Bar( T value ) { return "Called Bar(T)"; } public string Bar( int value ) { return "Called Bar(int)"; } public static void CallBar<TR>(Foo<TR> foo) { var fooInfo = foo.GetType() .GetMethods() .Where(x => !x.IsGenericMethod && // doesn't filter out Bar(T)! x.Name == "Bar" && x.GetParameters().First().ParameterType == typeof(int)) // !Two identical MethodInfo results, how to choose between them? // Is there a gauranteed canonical ordering? Or is it undefined? .First(); Console.WriteLine(fooInfo.Invoke(foo, new object[]{ 0 })); } } // prints Bar(T)... Foo<int>.CallBar( new Foo<int>() ); ```
Unfortunately System.Reflection doesn't provide a good way to correlate a method on a constructed type with the corresponding method on the generic type definition from which it was constructed. There are two solutions I know of, neither one is perfect: **Solution #1: static TypeBuilder.GetMethod.** There's [a static version of GetMethod on TypeBuilder](http://msdn.microsoft.com/en-us/library/ms145835.aspx) that accepts a generic constructed type and a MethodInfo for a method on a generic type definition, and returns the corresponding method on the specified generic type. In this example, calling `TypeBuilder.GetMethod(Foo<int>, Foo<T>.Bar(T))` will give you `Foo<int>.Bar(T-as-int)` which you can then use to disambiguate between it and `Foo<int>.Bar(int)`. (The above example will not compile, naturally; I've used `Foo<int>` and `Foo<T>.Bar(T)` to mean the respective Type and MethodInfo objects which, which are easily obtainable but would make the example too complex). The bad news is that this only works when the generic type definition is a TypeBuilder, i.e. when you're emitting a generic type. **Solution #2: MetadataToken.** It's a little known fact that type members retain their MetadataToken in the transition from generic type definitions to generic constructed types. So in your example, `Foo<T>.Bar(T)` and `Foo<int>.Bar(T-as-int)` should share the same MetadataToken. That would allow you to do this: ``` var barWithGenericParameterInfo = typeof(Foo<>).GetMethods() .Where(mi => mi.Name == "Bar" && mi.GetParameters()[0].ParameterType.IsGenericParameter); var mappedBarInfo = foo.GetType().GetMethods() .Where(mi => mi.MetadataToken == genericBarInfo.MetadataToken); ``` (This will not compile either, unless I'm extremely lucky and managed to get it right the first time :) ) The problem with this solution is that MetadataToken wasn't meant for that (probably; the documentation is a little skimpy on that) and it feels like a dirty hack. Nevertheless, it works.
When using Foo<int>, the Bar(T) method is typed as Bar(int), making no distinction between it and the method with an int defined as the parameter. To get the correct method definition of Bar(T), you can use typeof(Foo<>) instead of typeof(Foo<int>). This will enable you to tell the difference between the two. Try the following code: ``` public static void CallBar<TR>(Foo<TR> foo) { Func<MethodInfo, bool> match = m => m.Name == "Bar"; Type fooType = typeof(Foo<>); Console.WriteLine("{0}:", fooType); MethodInfo[] methods = fooType.GetMethods().Where(match).ToArray(); foreach (MethodInfo mi in methods) { Console.WriteLine(mi); } Console.WriteLine(); fooType = foo.GetType(); Console.WriteLine("{0}:", fooType); methods = fooType.GetMethods().Where(match).ToArray(); foreach (MethodInfo mi in methods) { Console.WriteLine(mi); } } ``` This will output: System.String Bar(T) System.String Bar(Int32) System.String Bar(Int32) System.String Bar(Int32)
Differentiating between generic and non-generic version of overloaded method using reflection
[ "", "c#", ".net", "generics", "reflection", "overloading", "" ]
I'm trying to use the password reset setup that comes with Django, but the documentation is not very good for it. I'm using Django 1.0 and I keep getting this error: ``` Caught an exception while rendering: Reverse for 'mysite.django.contrib.auth.views.password_reset_confirm' with arguments '()' and keyword arguments ... ``` in my urlconf I have something like this: ``` #django.contrib.auth.views urlpatterns = patterns('django.contrib.auth.views', (r'^password_reset/$', 'password_reset', {'template_name': 'accounts/registration/password_reset_form.html', 'email_template_name':'accounts/registration/password_reset_email.html', 'post_reset_redirect':'accounts/login/'}), (r'^password_reset/done/$', 'password_reset_done', {'template_name': 'accounts/registration/password_reset_done.html'}), (r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'password_reset_confirm', {'template_name': 'accounts/registration/password_reset_confirm.html', 'post_reset_redirect':'accounts/login/', 'post_reset_redirect':'accounts/reset/done/'}), (r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/registration/password_reset_complete.html'}), ) ``` The problem seems to be in this file: ``` password_reset_email.html ``` on line 7 ``` {% url django.contrib.auth.views.password_reset_confirm uidb36=uid, token=token %} ``` I'm at loss as to what's going on, so any help would be appreciated. Thanks
Just wanted to post the solution I came up with. The problem was in this line: ``` {% url django.contrib.auth.views.password_reset_confirm uidb36=uid, token=token %} ``` I'm not really a 100% why either, so I just hard coded the url like this: ``` http://mysite.com/accounts/reset/{{uid}}-{{token}}/ ```
**Edit**: I used your example, and had to change to not use keyword parameters. ``` {% url django.contrib.auth.views.password_reset_confirm uid, token %} ``` Named parameters do work, as long as both uid and token are defined. If either are not defined or blank I get the same error you do: ``` {% url django.contrib.auth.views.password_reset_confirm uidb36=uid, token=token %} ```
Django 1.0, using default password reset
[ "", "python", "django", "" ]
I'm working on an application that may generate thousands of messages in a fairly tight loop on a client, to be processed on a server. The chain of events is something like: 1. Client processes item, places in local queue. 2. Local queue processing picks up messages and calls web service. 3. Web service creates message in service bus on server. 4. Service bus processes message to database. The idea being that all communications are asynchronous, as there will be many clients for the web service. I know that MSMQ can do this directly, but we don't always have that kind of admin capability on the clients to set things up like security etc. My question is about the granularity of the messages at each stage. The simplest method would mean that each item processed on the client generates one client message/web service call/service bus message. That's fine, but I know it's better for the web service calls to be batched up if possible, except there's a tradeoff between large granularity web service DTOs, versus short-running transactions on the database. This particular scenario does not require a "business transaction", where all or none items are processed, I'm just looking to achieve the best balance of message size vs. number of web service calls vs. database transactions. Any advice?
Chatty interfaces (i.e. lots and lots of messages) will tend to have a high overhead from dispatching the incoming message (and, on the client, the reply) to the correct code to process the message (this will be a fixed cost per message). While big messages tend to use the resources in processing the message. Additionally a lot of web service calls in progress will mean a lot of TCP/IP connections to manage, and concurrency issues (including locking in a database) might become an issue. But without some details of the processing of the message it is hard to be specific, other than the general advice against chatty interfaces because of the fixed overheads.
Measure first, optimize later. Unless you can make a back-of-the-envelope estimate that shows that the simplest solution yields unacceptably high loads, try it, establish good supervisory measurements, see how it performs and scales. **Then** start thinking about how much to batch and where. This approach, of course, requires you to be able to change the web service interface after deployment, so you need a **versioning** approach to deal with clients which may not have been redesigned, supporting several WS versions in parallel. But not thinking about versioning almost always traps you in suboptimal interfaces, anyway.
Message Granularity for Message Queues and Service Buses
[ "", "c#", "message-queue", "servicebus", "" ]
I'm stuck with figuring out a good naming convention for the service layer in a spring application. For each class in the service layer I first write the interface it should implement and then the actual class. So for example I have the following interface: ``` public interface UserAccountManager{ public void registerUser(UserAccount newUserAccount); public void resetPassword(UserAccount userAccount); ... } ``` And then the implementation class... What bugs me here is UserAccountManager is a good name for the implementation class so I'm forced into giving it a stupid name like SimpleUserAccountManager or UserAccountDbManager. What are some of the conventions you've used so far? Is it a good idea to put the implementation classes in a different package and give them the same names as the interfaces? Also what are your thoughts on using names ending with Manager over names ending with Service?
Spring itself gives interfaces generic names and then names the classes based on the details of the implementation. This is one example that comes in mind: ``` interface: Controller abstract classes: AbstractController, AbstractCommandController, SimpleFormController, MultiActionController ``` I don't think names like SimpleUserAccountManager or UserAccountDbManager are stupid, since they convey some information regarding the implementation of the manager/service. What I find stupid is the common convention to add the "Impl" suffix at the implementation classes: ``` my/package/UserAccountManager my/package/impl/UserAccountManagerImpl ``` Some people prefer this though.
Here is what we use: * **XxxDAO (Data Access Object)** - Responsible for interacting directly with the EntityManager , JDBC DataSource , file system, etc. Should contain only persistence logic, such as SQL or JPA-QL, but not (or as little as possible) business logic. Should be accessed only from Managers. * **XxxManager** - Manages entites at the business level, usually performs CRUD operations, but adds the required business logic. * **XxxService** - The layer where the business logic resides. Should "speak" in simple objects - Strings, ints, etc. - as much as possible. * **XxxController** - The UI interaction layer. Should speak to Services only. * **XxxUtilities/XxxUtils** - Helper stateless methods, should not depend on any service in the system. If you need such sependency, either convert the utility class to a service or add the service result as a parameter. For the implementation we add the Impl Suffix (XxxServiceImpl), to distinct it from the interface, and if there are several implementations or we want to add additional information we add it as prefix (JdbcXxxDaoImpl, GoogleMapsGeocodingServiceImpl, etc.). The classes names become a bit long this way, but they are very descriptive and self documenting.
What naming convention do you use for the service layer in a Spring MVC application?
[ "", "java", "spring", "naming-conventions", "spring-mvc", "" ]
This is more a gotcha I wanted to share than a question: when printing with `toString()`, Java will detect direct cycles in a Collection (where the Collection refers to itself), but not indirect cycles (where a Collection refers to another Collection which refers to the first one - or with more steps). ``` import java.util.*; public class ShonkyCycle { static public void main(String[] args) { List a = new LinkedList(); a.add(a); // direct cycle System.out.println(a); // works: [(this Collection)] List b = new LinkedList(); a.add(b); b.add(a); // indirect cycle System.out.println(a); // shonky: causes infinite loop! } } ``` This was a real gotcha for me, because it occurred in debugging code to print out the Collection (I was surprised when it caught a direct cycle, so I assumed incorrectly that they had implemented the check in general). There is a question: why? The explanation I can think of is that it is very inexpensive to check for a collection that refers to itself, as you only need to store the collection (which you have already), but for longer cycles, you need to store all the collections you encounter, starting from the root. Additionally, you might not be able to tell for sure what *the* root is, and so you'd have to store every collection in the system - which you do anyway - but you'd also have to do a hash lookup on every collection element. It's very expensive for the relatively rare case of cycles (in most programming). (I think) the only reason it checks for direct cycles is because it so cheap (one reference comparison). OK... I've kinda answered my own question - but have I missed anything important? Anyone want to add anything? --- Clarification: I now realize the problem I saw is specific to **printing** a Collection (i.e. the `toString()` method). There's no problem with cycles *per se* (I use them myself and need to have them); the problem is that Java can't print them. *Edit* Andrzej Doyle points out it's not just collections, but any object whose `toString` is called. Given that it's constrained to this method, here's an algorithm to check for it: * the root is the object that the first `toString()` is invoked on (to determine this, you need to maintain state on whether a toString is currently in progress or not; so this is inconvenient). + as you traverse each object, you add it to an IdentityHashMap, along with a unique identifier (e.g. an incremented index). + but if this object is already in the Map, write out its identifier instead. This approach also correctly renders multirefs (a node that is referred to more than once). The memory cost is the IdentityHashMap (one reference and index per object); the complexity cost is a hash lookup for every node in the directed graph (i.e. each object that is printed).
I think fundamentally it's because while the language tries to stop you from shooting yourself in the foot, it shouldn't really do so in a way that's expensive. So while it's almost free to compare object pointers (e.g. does `obj == this`) anything beyond that involves invoking methods on the object you're passing in. And at this point the library code doesn't know anything about the objects you're passing in. For one, the generics implementation doesn't know if they're instances of `Collection` (or `Iterable`) themselves, and while it could find this out via `instanceof`, who's to say whether it's a "collection-like" object that isn't actually a collection, but still contains a deferred circular reference? Secondly, even if it is a collection there's no telling what it's actual implementation and thus behaviour is like. Theoretically one could have a collection containing all the Longs which is going to be used lazily; but since the library doesn't know this it would be hideously expensive to iterate over every entry. Or in fact one could even design a collection with an Iterator that never terminated (though this would be difficult to use in practice because so many constructs/library classes assume that `hasNext` will eventually return `false`). So it basically comes down to an unknown, possibly infinite cost in order to stop you from doing something that might not actually be an issue anyway.
I'd just like to point out that this statement: > when printing with toString(), **Java will detect** direct cycles in a collection is misleading. **Java** (the JVM, the language itself, etc) is not detecting the self-reference. Rather this is a property of the `toString()` method/override of `java.util.AbstractCollection`. If you were to create your own `Collection` implementation, the language/platform wouldn't automatically safe you from a self-reference like this - unless you extend `AbstractCollection`, you would have to make sure you cover this logic yourself. I might be splitting hairs here but I think this is an important distinction to make. Just because one of the foundation classes in the JDK does something doesn't mean that "Java" as an overall umbrella does it. Here is the relevant source code in `AbstractCollection.toString()`, with the key line commented: ``` public String toString() { Iterator<E> i = iterator(); if (! i.hasNext()) return "[]"; StringBuilder sb = new StringBuilder(); sb.append('['); for (;;) { E e = i.next(); // self-reference check: sb.append(e == this ? "(this Collection)" : e); if (! i.hasNext()) return sb.append(']').toString(); sb.append(", "); } } ```
Why does Java toString() loop infinitely on indirect cycles?
[ "", "java", "collections", "cycle", "infinite-loop", "" ]
I wonder what's the pros/cons of using delegate vs OOP when implementing strategy design pattern? Which one do you recommend to use? or what kind of problem does delegate solve? and why should we use OOP if OOP is better? Thanks! -tep
Both techniques can be powerful and valuable - here are some of my opinions about when to use which. Use an Interface/Implementation approach when the strategy: 2. maintains state 3. needs configuration 4. uses dependency injection 5. needs to be configured by an IoC container (think ConnectionProvider) 6. combines multiple responsibilities (think DataAdapter from ADO.NET) 7. is too complex or long as a single method 8. is likely to be subclassed to create new strategies 9. needs to return state information to the caller 10. needs to access internals of the object is applies to 11. Would require too many direct parameters Otherwise, tend to use delegates based on Func<> or Action<>, especially if 1. There are likely to be a very large variety of strategies (think sort expressions) 2. The strategy is best expressed as as lambda 3. There's an existing method you want to leverage
In favour of delegates: * Delegates are easier to implement in a light-weight way using lambda expressions and dynamic methods * Delegates can be created from "normal" methods with the right signature * Delegates being multi-cast *can* be useful at times (though relatively rarely outside eventing) In favour of interfaces: * An object can implement an interface and still do other things: a delegate is *just* a delegate * An interface can have multiple methods; a delegate just has the one Could go either way: * With interfaces you end up with two names: the interface and the method. With delegates you just have the one. Often I find that single-method interfaces either repeat the same name twice (with variations) or the method name is very bland Personally I'm a big fan of delegates for their flexibility, but it really depends on the situation.
C# Strategy Design Pattern by Delegate vs OOP
[ "", "c#", "design-patterns", "" ]
I'm trying to write a function to generate the full C# declaration for a Type object. My current method involves performing very manual and specific logic on the Type object. Is there some built in way to .Net to generate this declaration? As an example, take this class: ``` namespace My.Code.Here { public class Class1<> { public enum Enum1 { } } } ``` when the function (lets call it getCSharpDec) is called on typeof(Class1<>.Enum1), it would return "My.Code.Here.Class1<>.Enum1".
There are a couple of problems here... * C# and `Type` name nested types differently * C# and `Type` name generic types differently As a minor aside, `Class1<>.Enum1` isn't a closed type, but that shouldn't be an issue... (edit) This gets pretty close - it still retains the outer generics from the type, though: ``` static void Main() { Type t = typeof(My.Code.Here.Class1<>.Enum1); string s = GetCSharpName(t); // My.Code.Here.Class1<T>.Enum1<T> } public static string GetCSharpName<T>() { return GetCSharpName(typeof(T)); } public static string GetCSharpName(Type type) { StringBuilder sb = new StringBuilder(); sb.Insert(0, GetCSharpTypeName(type)); while (type.IsNested) { type = type.DeclaringType; sb.Insert(0, GetCSharpTypeName(type) + "."); } if(!string.IsNullOrEmpty(type.Namespace)) { sb.Insert(0, type.Namespace + "."); } return sb.ToString(); } private static string GetCSharpTypeName(Type type) { if (type.IsGenericTypeDefinition || type.IsGenericType) { StringBuilder sb = new StringBuilder(); int cut = type.Name.IndexOf('`'); sb.Append(cut > 0 ? type.Name.Substring(0, cut) : type.Name); Type[] genArgs = type.GetGenericArguments(); if (genArgs.Length > 0) { sb.Append('<'); for (int i = 0; i < genArgs.Length; i++) { sb.Append(GetCSharpTypeName(genArgs[i])); if (i > 0) sb.Append(','); } sb.Append('>'); } return sb.ToString(); } else { return type.Name; } } ```
This code should work for nested generic types (e.g. `Foo<int>.Bar<string,object>`). ``` public static string GetCSharpTypeName(this Type type, bool getFullName) { StringBuilder sb = new StringBuilder(); if (getFullName && !string.IsNullOrEmpty(type.Namespace)) { sb.Append(type.Namespace); sb.Append("."); } AppendCSharpTypeName(sb, type, getFullName); return sb.ToString(); } private static void AppendCSharpTypeName (StringBuilder sb, Type type, bool fullParameterNames) { string typeName = type.Name; Type declaringType = type.DeclaringType; int declaringTypeArgumentCount = 0; if (type.IsNested) { if (declaringType.IsGenericTypeDefinition) { declaringTypeArgumentCount = declaringType.GetGenericArguments().Length; declaringType = declaringType.MakeGenericType( type.GetGenericArguments().Take(declaringTypeArgumentCount) .ToArray()); } AppendCSharpTypeName(sb, declaringType, fullParameterNames); sb.Append("."); } Type[] genericArguments = type.GetGenericArguments() .Skip(declaringTypeArgumentCount).ToArray(); int stopIndex; if ((type.IsGenericTypeDefinition || type.IsGenericType) && ((stopIndex = type.Name.IndexOf('`')) > 0)) { sb.Append(typeName.Substring(0, stopIndex)); string[] genericArgumentNames = genericArguments .Select(t => GetCSharpTypeName(t, fullParameterNames)).ToArray(); if (genericArgumentNames.Length > 0) sb.AppendFormat("<{0}>", string.Join(",", genericArgumentNames)); } else { sb.Append(typeName); } } ```
How to get full C# declaration for a Type?
[ "", "c#", ".net", "reflection", "types", "" ]
I need to parse a configuration file which looks like this (simplified): ``` <config> <links> <link name="Link1" id="1"> <encapsulation> <mode>ipsec</mode> </encapsulation> </link> <link name="Link2" id="2"> <encapsulation> <mode>udp</mode> </encapsulation> </link> </links> ``` My goal is to be able to change parameters specific to a particular link, but I'm having trouble getting substitution to work correctly. I have a regex that can isolate a parameter value on a specific link, where the value is contained in capture group 1: ``` link_id = r'id="1"' parameter = 'mode' link_regex = '<link [\w\W]+ %s>[\w\W]*[\w\W]*<%s>([\w\W]*)</%s>[\w\W]*</link>' \ % (link_id, parameter, parameter) ``` Thus, ``` print re.search(final_regex, f_read).group(1) ``` prints ipsec The examples in the [regex howto](http://docs.python.org/howto/regex.html) all seem to assume that one wants to use the capture group in the replacement, but what I need to do is replace the capture group itself (e.g. change the Link1 mode from ipsec to udp).
not sure i'd do it that way, but the quickest way would be to shift the captures: ([\w\W]*[\w\W]*<%s>)[\w\W]*([\w\W]*)' and replace with group1 +mode+group2
I have to give you the obligatory: "don't use regular expressions to do this." Check out how very easily awesome it is to do this with [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/documentation.html#Parsing%20XML), for example: ``` >>> from BeautifulSoup import BeautifulStoneSoup >>> html = """ ... <config> ... <links> ... <link name="Link1" id="1"> ... <encapsulation> ... <mode>ipsec</mode> ... </encapsulation> ... </link> ... <link name="Link2" id="2"> ... <encapsulation> ... <mode>udp</mode> ... </encapsulation> ... </link> ... </links> ... </config> ... """ >>> soup = BeautifulStoneSoup(html) >>> soup.find('link', id=1) <link name="Link1" id="1"> <encapsulation> <mode>ipsec</mode> </encapsulation> </link> >>> soup.find('link', id=1).mode.contents[0].replaceWith('whatever') >>> soup.find('link', id=1) <link name="Link1" id="1"> <encapsulation> <mode>whatever</mode> </encapsulation> </link> ``` Looking at your regular expression I can't really tell if this is exactly what you wanted to do, but whatever it is you want to do, using a library like BeautifulSoup is much, much, better than trying to patch a regular expression together. I highly recommend going this route if possible.
Can I use re.sub (or regexobject.sub) to replace text in a subgroup?
[ "", "python", "regex", "regex-group", "" ]
So I have something like this ``` public string? SessionValue(string key) { if (HttpContext.Current.Session[key].ToString() == null || HttpContext.Current.Session[key].ToString() == "") return null; return HttpContext.Current.Session[key].ToString(); } ``` which doesn't compile. How do I return a nullable string type?
String is already a nullable type. Nullable can only be used on ValueTypes. String is a reference type. Just get rid of the "?" and you should be good to go!
As everyone else has said, `string` doesn't need `?` (which is a shortcut for `Nullable<string>`) because all reference types (`class`es) are already nullable. It only applies to value type (`struct`s). Apart from that, you should not call `ToString()` on the session value before you check if it is `null` (or you can get a `NullReferenceException`). Also, you shouldn't have to check the result of `ToString()` for `null` because it should never return `null` (if correctly implemented). And are you sure you want to return `null` if the session value is an empty `string` (`""`)? This is equivalent to what you meant to write: ``` public string SessionValue(string key) { if (HttpContext.Current.Session[key] == null) return null; string result = HttpContext.Current.Session[key].ToString(); return (result == "") ? null : result; } ``` Although I would write it like this (return empty `string` if that's what the session value contains): ``` public string SessionValue(string key) { object value = HttpContext.Current.Session[key]; return (value == null) ? null : value.ToString(); } ```
Returning nullable string types
[ "", "c#", "string", "nullable", "" ]
Been away from C++ for a few years and am getting a linker error from the following code: Gene.h ``` #ifndef GENE_H_INCLUDED #define GENE_H_INCLUDED template <typename T> class Gene { public: T getValue(); void setValue(T value); void setRange(T min, T max); private: T value; T minValue; T maxValue; }; #endif // GENE_H_INCLUDED ``` Gene.cpp ``` #include "Gene.h" template <typename T> T Gene<T>::getValue() { return this->value; } template <typename T> void Gene<T>::setValue(T value) { if(value >= this->minValue && value <= this->minValue) { this->value = value; } } template <typename T> void Gene<T>::setRange(T min, T max) { this->minValue = min; this->maxValue = max; } ``` Using Code::Blocks and GCC if it matters to anyone. Also, clearly porting some GA stuff to C++ for fun and practice.
The template definition (the cpp file in your code) has to be included prior to instantiating a given template class, so you either have to include function definitions in the header, or #include the cpp file prior to using the class (or do explicit instantiations if you have a limited number of them).
Including the cpp file containing the implementations of the template class functions works. However, IMHO, this is weird and awkward. There must surely be a slicker way of doing this? If you have only a few different instances to create, and know them beforehand, then you can use "explicit instantiation" This works something like this: At the top of gene.cpp add the following lines ``` template class Gene<int>; template class Gene<float>; ```
"Undefined symbols" linker error with simple template class
[ "", "c++", "templates", "unsatisfiedlinkerror", "" ]
I have a really simple XML file that I'm trying to read, but I can't seem to get it working. Here is the XML file: ``` <?xml version="1.0"?> <Results><One>45364634</One><Two>-1</Two><Three>B</Three></Results> ``` I am trying to get the contents of two like this: ``` XmlNode node = doc.DocumentElement.SelectSingleNode("/Results/Two"); ``` or ``` XmlNodeList list = doc.GetElementsByTagName("Two"); ``` Neither is working. When I copy paste the XML as a string into the XmlDocument, then it works. However, when I use the string I pull out of the response (where I'm getting the XML from), it doesn't work. I'm wondering if it's something weird like a character issue or not looking at the correct root, but I can't figure it out. Any ideas? Thanks!
Bleh. Turns out I was returning an XML document within an XML document. That's why printing to the screen looked ok but I couldn't pull it out. Thanks guys.
Check the Xml file encoding ... Is it ansi? utf-8 or utf-16? Check if the xml was loaded from the file at all. Check if there is any error, see if the document was populated. I think the document is not being populated when loading from the file.
Problem with node.GetElementsByTagName in C#
[ "", "c#", "xml", "readxml", "" ]
I have a class named Country. It has the public members, 'CountryName' and 'States'. I have declared a list of Countries. Now I want to write a function which accepts a new 'Country' and decides if CountryList already has the 'Country'. I tried writing a function like ``` bool CheckCountry(Country c) { return CountryList.Exists(p => p.CountryName == c.Name && p.States.SequenceEqual(c.States)); } ``` As I want to compare States using the CountryName property of the States, I want to modify my function so that SequenceEqual works based on the CountryName of the states?
Break it down into many simple queries, and then put those queries back together. Let's start by making a sequence of items that match by name: ``` var nameMatches = from item in itemList where item.Name == p.Name select item; ``` We need to compare those items against the sequence of names in p's subitems. What's that sequence? **Write a query:** ``` var pnames = from subitem in p.SubItems select subitem.Name; ``` Now you want to find all the elements from nameMatches where the sequence of names matches. How are you going to get the sequence of names? Well, we just saw how to do that with pnames, so do the same thing: ``` var matches = from item in nameMatches let subitemNames = (from subitem in item.SubItems select subitem.Name) where pnames.SequenceEqual(subitemNames) select item; ``` And now you want to know, are there any matches? ``` return matches.Any(); ``` That should work just fine as is. But if you want to be really buff you can write the whole thing in one big query! ``` return ( from item in itemList let pnames = (from psubitem in p.SubItems select psubitem.Name) let subitemNames = (from subitem in item.SubItems select subitem.Name) where item.Name == p.Name where pnames.SequenceEqual(subitemNames) select item).Any(); ``` And you're done. Easy as pie! Just remember, break it down into small steps, solve each problem individually, and then put the solution together out of the small results.
If i understand you correctly you want a way to compare two items in which you first check the name of the two items then sequentially check each subitem's name. Here's what you want: ``` public override bool Equals(object obj) { return this.Name == (obj as Item).Name; } public override int GetHashCode() { return this.Name.GetHashCode(); } public bool Check(Item obj) { if (this.Name != obj.Name) return false; //if the lists arent of the same length then they //obviously dont contain the same items, and besides //there would be an exception on the next check if (this.SubItems.Count != obj.SubItems.Count) return false; for (int i = 0; i < this.SubItems.Count; i++) if (this.SubItems[i] != obj.SubItems[i]) return false; return true; } ```
Let the SequenceEqual Work for the list
[ "", "c#", "linq", "" ]
I'm working with good group of very sharp developers on one of my client's premises. We are coding correctly around NullPointerException and other exceptions, so we don't have those. But when it comes to business rules we have some mistakes and find issues when already in production. Granted we have very fast paced environment, and deployment to production commanded by management team, not development one. But we passed "green light" with QA and Data Quality teams. What are the best practices to find business related bugs early in software development process.
"What are the best practices to find business related bugs early in software development process." Several things. 1. Use Cases. 2. Overall Tests based on the Use Cases. 3. Unit Tests based on the Use Cases. The important thing is to tie the system -- as a whole -- to real actors, real business value. It's too easy to focus on technical issues. To avoid narrow focus on technical issues, have use cases and test against those.
[User Acceptance Testing](http://en.wikipedia.org/wiki/User_acceptance_testing#User_acceptance_testing) focuses on these sorts of issues.
How to find business related bugs early in software development practices?
[ "", "java", "debugging", "agile", "" ]
I have a jquery script that attaches a click event to every link, running an action when the link is clicked. This has been working great, but I just got some betatester feedback that's foiling me. The user was right-clicking on the link and opening it in a new tab. When she did this, jquery didn't trap the click. BAD USER. I reproduced this with cmd-click as well. Is there a way to trap these gestures, or this an inherent limitation?
So you want to capture every click? Event the right or middle one? Shouldn't the [mousedown event](http://docs.jquery.com/Events/mousedown) do just that? Of course, she could right click a link just to "Copy Link Location"...
See if you can somehow make use of jQuery rightclick plugin: <http://abeautifulsite.net/notebook/68> Usage: ``` $(document).ready( function() { // Capture right click $("#selector").rightClick( function(e) { // Do something }); // Capture right mouse down $("#selector").rightMouseDown( function(e) { // Do something }); // Capture right mouseup $("#selector").rightMouseUp( function(e) { // Do something }); // Disable context menu on an element $("#selector").noContext(); }); ``` As for the cmd-clickie bit, I'm really not sure. In case it's helpful, here's the jQuery hotkeys plugin: <http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/>
How to trap "open in a new tab" clicks in jquery.click
[ "", "javascript", "jquery", "right-click", "" ]
In Java i have abstract class named Operation and three its subclasses called OperationActivation, OperationPayment and OperationSendEmail. ADDED FROM COMMENT: Operation\* objects are EJB Entity Beans so I can't have business logic inside them. No I want to create processor class like this: ``` public class ProcessOperationService { public void processOperation(Operation operation) { out.println("process Operation"); process(operation); } public void process(OperationActivation operationActivation) { out.println("process Activation"); } public void process(OperationPayment operationPayment) { out.println("process Payment"); } public void process(OperationSendEmail operationSendEmail) { out.println("process OperationSendEmail"); } ``` } Processing each operation requires different logic so I want to have three different methods , one for each operation. Of course this code doesn't compile. Am I missing something or it can't be done that way?
Shouldn't your `Operation*` objects be doing the work themselves ? So you can write (say) ``` for (Operation op : ops) { op.process(); } ``` You can encapsulate the logic for each particular operation in its own class, and that way everything related to OperationPayment remains in the OperationPayment class. You don't need a Processor class (and so you don't need to modify a Processor class everytime you add an Operation) There are more complex patterns to enable objects to mediate wrt. what they need to execute, but I'm not sure you need something that complex at this stage.
You are mixing up overloading and polymorphic method handling. When you overload methods based on the parameter type, that is *static* polymorphism. Those methods should be called from code that knows at compile-time what the type is. You could possibly do the following, but it wouldn't be clean object-oriented code: ``` public class ProcessOperationService { public void processOperation(Operation operation) { out.println("process Operation"); if (operation instanceof OperationActivation) process((OperationActivation)operation); else if (operation instanceof OperationPayment) process((OperationPayment)operation); ... } public void process(OperationActivation operationActivation) { out.println("process Activation"); } ... } ``` It would be much better to let the automatic run-time polymorphism work, by doing as Brian Agnew suggested, and making process be a method of each Operation subtype itself.
Java polymorphic methods
[ "", "java", "polymorphism", "" ]
I have an IP Camera that streams out live video to a web site of mine. Problem is, it is powered by an ActiveX control. Even worse, this control is unsigned. To provide a more secure alternative to the people that are using browsers other than IE, or are (rightfully) unwilling to change their security settings, I am tapping into the cameras built in snap-shot script that serves up a 640x480 live JPEG image. The plan was to update the image live on the screen every ~500ms using Javascript without having to reload the entire page. I tried using the Image() object to pre-load the image and update the SRC attribute of the image element when onload fired: ``` function updateCam() { var url = "../snapshot.cgi?t=" + new Date().getTime(); img = new Image(); img.onload = function() { $("#livePhoto").attr("src", url); camTimer = setTimeout(updateCam, 500); } img.src = url; } ``` This worked decently, but it was difficult to determine when the camera had been disabled, which I needed to do in order to degrade gracefully. The internal snapshot script is setup to return an HTTP status code of 204 (No Content) under this circumstance, and of course there is no way for me to detect that using the Image object. Additionally, the onload event was not 100% reliable. Therefore, I am using the jQuery (version 1.2.6) `ajax` function to do a GET request on the URL, and on the `complete` callback I evaluate the status code and set the URL accordingly: ``` function updateCam() { var url = "../snapshot.cgi?t=" + new Date().getTime(); $.ajax({ type: "GET", url: url, timeout: 2000, complete: function(xhr) { try { var src = (xhr.status == 200) ? url : '../i/cam-oos.jpg'; $("#livePhoto").attr("src", src); } catch(e) { JoshError.log(e); } camTimer = setTimeout(updateCam, 500); } }); } ``` And this works beautifully. **But only in IE!** This is the question that I would like to have answered: Why doesn't this work in Firefox or Chrome? The `complete` event does not even fire in Firefox. It does fire in Chrome, but only very rarely does setting the SRC actually load the image that was requested (usually it displays nothing).
Well, I ended up using the [data URI scheme](http://en.wikipedia.org/wiki/Data_URI_scheme) (hat tip to Eric Pascarello) for non-IE browsers. I wrote a HTTP handler (in VB.NET) to proxy the IP camera and base-64 encode the image: ``` Imports Common Imports System.IO Imports System.Net Public Class LiveCam Implements IHttpHandler Private ReadOnly URL As String = "http://12.34.56.78/snapshot.cgi" Private ReadOnly FAIL As String = Common.MapPath("~/i/cam-oos.jpg") Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest Dim Data As Byte() With context.Response .ContentEncoding = Encoding.UTF8 .ContentType = "text/plain" .Write("data:image/png;base64,") Try Using Client As New WebClient() Data = Client.DownloadData(URL) End Using Catch ex As WebException Data = File.ReadAllBytes(FAIL) End Try .Write(Convert.ToBase64String(Data)) End With End Sub End Class ``` Then I just put a little non-IE detection (using the classic document.all check) in order to call the correct URL/set the correct SRC: ``` function updateCam() { var url = (document.all) ? "../snapshot.cgi?t=" : "../cam.axd?t="; url += new Date().getTime(); $.ajax({ type: "GET", url: url, timeout: 2000, complete: function(xhr) { try { var src; if(document.all) src = (xhr.status == 200) ? url : '../i/cam-oos.jpg'; else src = xhr.responseText; $("#livePhoto").attr("src", src); } catch(e) { JoshError.log(e); } camTimer = setTimeout(updateCam, 500); } }); } ``` It's very unfortunate I had to resort to this workaround for. I hate browser detection code, and I hate the additional load that is put on my server. The proxy will not only force me to waste more bandwidth, but it will not operate as efficiently because of the inherent proxy drawbacks and due to the time required to base-64 encode the image. Additionally, it is not setup to degrade *as* gracefully as IE. Although I could re-write the proxy to use HttpWebRequest and return the proper status codes, etc. I just wanted the easiest way out as possible because I am sick of dealing with this! Thanks to all!
Posting a second answer, because the first was just really incorrect. I can't test this solution (because I don't have access to your webcam script), but I would suggest trying to sanitise the response from the camera - since you obviously can't handle the raw image data, try adding the dataFilter setting like so: ``` function updateCam() { var url = "../snapshopt.cgi?t=" + new Date().getTime(); $.ajax({ type: "GET", url: url, timeout: 2000, dataFilter : function(data, type) { return '<div></div>' //so it returns something... }, complete: function(xhr) { try { var src = (xhr.status == 200) ? url : '../i/cam-oos.jpg'; $("#live").attr("src", src); } catch(e) { JoshError.log(e); } camTimer = setTimeout(updateCam, 500); } }); } ``` Like I said, I haven't been able to test this - but it might allow jquery to use the status codes without breaking like crazy.
Dynamically Preloading/Displaying Webcam Snapshots on a Web Page Using AJAX
[ "", "javascript", "jquery", "ajax", "" ]
Using javascript, how can we auto insert the current DATE and TIME into a form input field. I'm building a "Problems" form to keep track of user submitted complaints about a certain service. I'm collecting as much info as possible. I want to save the staff here from having to manually enter the date and time each time they open the form. I have this snippet of code: ``` <input id="date" name="date" value="javascript:document.write(Date()+'.')"/> ``` but it's not working. many thanks for any help.
Javascript won't execute within a value attribute. You could do something like this, though: ``` <input id="date" name="date"> <script type="text/javascript"> document.getElementById('date').value = Date(); </script> ``` You'd probably want to format the date as you prefer, because the default output of Date() looks something like: `Tue Jun 16 2009 10:47:10 GMT-0400 (Eastern Daylight Time)`. See [this SO question](https://stackoverflow.com/questions/986657/how-do-i-format-a-javascript-date) for info about formatting a date.
``` <input type="date" id="myDate" /> <script type="text/javascript"> function SetDate() { var date = new Date(); var day = date.getDate(); var month = date.getMonth() + 1; var year = date.getFullYear(); if (month < 10) month = "0" + month; if (day < 10) day = "0" + day; var today = year + "-" + month + "-" + day; document.getElementById('myDate').value = today; } </script> <body onload="SetDate();"> ``` found here: <http://jsbin.com/oqekar/1/edit?html,js,output>
Auto insert date and time in form input field?
[ "", "javascript", "forms", "date", "automation", "" ]
I have the following class in a common jar: ``` public class Common { public Common(List list) { ... } } ``` I then change the constructor parameter from a `List` to a `Collection` as follows: ``` public class Common { public Common(Collection collection) { ... } } ``` Rebuilding the common jar and running the system causes a `NoSuchMethodError` in any dependent class when it invokes the constructor until I recompile that class. I've got a few ideas what's causing this, along the lines of how the constructor is bound in the bytecode of the dependent class, but I'm not 100% sure. Please can somebody shed some light onto what's going on here? ## Update I've subsequently done a quick test and taken a look at the bytecode: ``` Compiled from "Client.java" public class Client extends java.lang.Object{ public Client(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String[]); Code: 0: new #2; //class ArrayList 3: dup 4: invokespecial #3; //Method java/util/ArrayList."<init>":()V 7: astore_1 8: new #4; //class Common 11: dup 12: aload_1 13: invokespecial #5; //Method Common."<init>":(Ljava/util/List;)V 16: pop 17: return } ``` Like Tom said, and as you can see on line 13, the exact constructor is bound at compile time. You learn something new every day :-)
javac resolves exactly which method or constructor to call at compile time. This does not occur at link time. As the constructor signature has changed, the linking step cannot find the requested method and therefore throws an error. You can fix the error by providing to constructors - one which takes an `Collection` the other `List`. Later a constructor taking an `Iterable` could be added. Note, generic types do not form part of the signature, so those can be changed whilst still keeping binary compatibility. Both parameter and return types form part of the signature for methods (covariant returns cause synthetic bridge methods to be created). There is a [nice big section in the JLS](http://java.sun.com/docs/books/jls/third_edition/html/binaryComp.html) defining exactly what constitutes binary compatible changes.
Are you importing the correct List and Collection classes? i.e. `java.util.List` and `java.util.Collection`?
Changing a constructor param type breaks class in another jar
[ "", "java", "binding", "parameters", "constructor", "binary-compatibility", "" ]
I have some ideas, some that I have accumulated over time, but I really want to know what makes things go smoothly for you when modeling database: 1. Table name matches Primary Key name and description key 2. Schemas are by functional area 3. Avoid composite primary keys where possible (use unique constraints) 4. Camel Case table names and field names 5. Do not prefix tables with tbl\_, or procs with SP\_ (no hungarian notation) 6. OLTP databases should be atleast in BCNF / 4NF
Putting everybody's input together into one list. **Naming Standards** * Schemas are named by functional area (Products, Orders, Shipping) * No Hungarian Notation: No type names in object names (no strFirstName) * Do not use registered keywords for object names * No spaces or any special characters in object names (Alphanumber + Underscore are the only things allowed) * Name objects in a natural way (FirstName instead of NameFirst) * Table name should match Primary Key Name and Description field (SalesType – SalesTypeId, SalesTypeDescription) * Do not prefix with tbl\_ or sp\_ * Name code by object name (CustomerSearch, CustomerGetBalance) * CamelCase database object names * Column names should be singular * Table names may be plural * Give business names to all constraints (MustEnterFirstName) **Data Types** * Use same variable type across tables (Zip code – numeric in one table and varchar in another is not a good idea) * Use nNVarChar for customer information (name, address(es)) etc. you never know when you may go multinational **In code** * Keywords always in UPPERCASE * Never use implied joins (Comma syntax) - always use explicit INNER JOIN / OUTER JOIN * One JOIN per line * One WHERE clause per line * No loops – replace with set based logic * Use short forms of table names for aliases rather than A, B, C * Avoid triggers unless there is no recourse * Avoid cursors like the plague (read <http://www.sqlservercentral.com/articles/T-SQL/66097/>) **Documentation** * Create database diagrams * Create a data dictionary **Normalization and Referential Integrity** * Use single column primary keys as much as possible. Use unique constraints where required. * Referential integrity will be always enforced * Avoid ON DELETE CASCADE * OLTP must be at least 4NF * Evaluate every one-to-many relationship as a potential many-to-many relationship * Non user generated Primary Keys * Build Insert based models instead of update based * PK to FK must be same name (Employee.EmployeeId is the same field as EmployeeSalary.EmployeeId) * Except when there is a double join (Person.PersonId joins to PersonRelation.PersonId\_Parent and PersonRelation.PersonId\_Child) **Maintenance : run periodic scripts to find** * Schema without table * Orphaned records * Tables without primary keys * Tables without indexes * Non-deterministic UDF * Backup, Backup, Backup **Be good** * Be Consistent * Fix errors *now* * Read Joe Celko's SQL Programming Style (ISBN 978-0120887972)
* Name similarly targetted stored procs with the same prefix, for instance if you've got 3 stored procedures for Person. That way everything for person is grouped in one place and you can find them easily without having to look through all your procs to find them. + PersonUpdate + PersonDelete + PersonCreate * Do similar things for tables when you have groups of tables with related data. For instance: + InvoiceHeaders + InvoiceLines + InvoiceLineDetails * If you have the option of schemas within your database, use them. It's much nicer to see: + Invoice.Header + Invoice.Line.Items + Invoice.Line.Item.Details + Person.Update + Person.Delete + Person.Create * Don't use triggers unless there's no other reasonable approach to achieve that goal. * Give field names a meaningful prefix so you can tell what table they come from without someone needing to explain. That way when you see a field name referenced, you can easily tell which table it's from. * Use consistent data types for fields containing similar data, i.e. don't store phone number as numeric in one table and varchar in another. In fact, don't store it as numeric, if I come across a negative phone number I'll be mad. * Don't use spaces or other obscure characters in table/field names. They should be entirely alphanumeric - or if I had my druthers, entirely alphabetic with the exception of the underscore. I'm currently working on an inherited system where table and field names contain spaces, question marks and exclamation marks. Makes me want to kill the designer on a daily basis! * Don't use syntax keywords as object names it'll cause headaches trying to retrieve data from them. I hate having to wrap object names as [index] that's two needless chars I didn't need to type damn you!
What are some of your most useful database standards?
[ "", "sql", "database", "standards", "entity-relationship", "" ]
I am using asp.net ajax control toolkit 1.0 on vs 2005. I am using the collapseablePanel and AlwaysVisibleControlExtender control. When I use these, I notice that it my panel flashes for a few seconds before it is hidden. To avoid this, I have decided to place it in a div to make it hidden. I want it shown when I use the control. Here is what I have: ``` <div id="menuContent" style="display:none"> <asp:Panel ID="pnlAddNewContent" runat="server" Width="300px"> ....//the panel stuff here </asp> </div> ``` and the javascript for this in the header is: ``` function showdiv() { if (document.getElementbyId) { document.getElementbyId('menuContent').style.visibility = 'visible'; } } ``` (its for IE 6 for I don't care about compatability) and body onload=onLoad="showdiv();" It correctly hides upon load, but I cannot get it to show again. Does anyone have solutions?
Basically had to use Visibility hidden and visible attributes as these work best on a collapsePanel
You are trying to show it by setting the visibility but you hid it using display. You actually want something like this: document.getElementbyId('menuContent').style.display = 'block';
Showing/Hiding div
[ "", "c#", "asp.net", "html", "" ]
I am doing a https post and I'm getting an exception of ssl exception Not trusted server certificate. If i do normal http it is working perfectly fine. Do I have to accept the server certificate somehow?
I'm making a guess, but if you want an actual handshake to occur, you have to let android know of your certificate. If you want to just accept no matter what, then use this pseudo-code to get what you need with the Apache HTTP Client: ``` SchemeRegistry schemeRegistry = new SchemeRegistry (); schemeRegistry.register (new Scheme ("http", PlainSocketFactory.getSocketFactory (), 80)); schemeRegistry.register (new Scheme ("https", new CustomSSLSocketFactory (), 443)); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager ( params, schemeRegistry); return new DefaultHttpClient (cm, params); ``` CustomSSLSocketFactory: ``` public class CustomSSLSocketFactory extends org.apache.http.conn.ssl.SSLSocketFactory { private SSLSocketFactory FACTORY = HttpsURLConnection.getDefaultSSLSocketFactory (); public CustomSSLSocketFactory () { super(null); try { SSLContext context = SSLContext.getInstance ("TLS"); TrustManager[] tm = new TrustManager[] { new FullX509TrustManager () }; context.init (null, tm, new SecureRandom ()); FACTORY = context.getSocketFactory (); } catch (Exception e) { e.printStackTrace(); } } public Socket createSocket() throws IOException { return FACTORY.createSocket(); } // TODO: add other methods like createSocket() and getDefaultCipherSuites(). // Hint: they all just make a call to member FACTORY } ``` FullX509TrustManager is a class that implements javax.net.ssl.X509TrustManager, yet none of the methods actually perform any work, get a sample [here](http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e537). Good Luck!
I copied the following code that came from [The Java Developers Almanac](https://web.archive.org/web/20061217061841/http://www.exampledepot.com/egs/javax.net.ssl/TrustAll.html). It simply doesn't check the certificate anymore. > ``` > // always verify the host - dont check for certificate final static > HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { public > boolean verify(String hostname, SSLSession session) { return true; > } }; > > /** * Trust every server - dont check for any certificate */ private > static void trustAllHosts() { // Create a trust manager that does not > validate certificate chains TrustManager[] trustAllCerts = new > TrustManager[] { new X509TrustManager() { public > java.security.cert.X509Certificate[] getAcceptedIssuers() { return > new java.security.cert.X509Certificate[] {}; } > > public void checkClientTrusted(X509Certificate[] chain, > String authType) throws CertificateException { } > > public void checkServerTrusted(X509Certificate[] chain, > String authType) throws CertificateException { } } }; > > // Install the all-trusting trust manager try { SSLContext sc = > SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new > java.security.SecureRandom()); HttpsURLConnection > .setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } } > ``` and > ``` > HttpURLConnection http = null; > > if (url.getProtocol().toLowerCase().equals("https")) { > trustAllHosts(); HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); https.setHostnameVerifier(DO_NOT_VERIFY); http > = https; } else { http = (HttpURLConnection) url.openConnection(); } > ```
Https Connection Android
[ "", "java", "android", "ssl", "" ]
I'm learning to develop apps using Qt Creator. I have built a simple app under Windows, depends on uses mingwm10.dll, QtCore4.dll, QtGui4.dll, QtNetwork4.dll. Out of QtQui4.dll I use only a a couple of widgets, and don't need all of the rest... Is it possible to either shrink the size of QtGui4.dll or do something else to decrease deployment size of application? How about static linking? Will it embed the whole dll, or only parts of it that are used? And also is it possible with Qt to link some dlls staticly and some dynamicly?
It's not possible to shrink the QtGui4.dll by removing some functions. Trolltech is [having a look at this](http://labs.trolltech.com/blogs/2009/04/17/size-matters/), but the good solution seems quite distant: Static linking, I think it is very problematic on windows. Each time I tried, it was a nightmare. So, it looks like you are stuck with the regular DLL. The only thing you can do (which I do for my Qt apps is): * use [UPX](http://upx.sourceforge.net/) to compress your DLL or * use strong compression in your installer If you already UPX your dll, you can not reduce it further with the installer compression, but this can reduce other files.
The best way is to manually configure the Qt library with configure. By issuing ``` configure --help ``` you'll see a number of options that might help reduce both disk and memory footprint. E.g. ``` --no-stl --no-exceptions ``` can both reduce the footprint of your application. You can also modify the mkspec to use more aggressive optimization flags for your compiler.
Decrease Qt GUI application size
[ "", "c++", "qt", "dll", "static-libraries", "" ]
I have to interact with a remote api that forces me to chain requests. Thats a callback-hell in asynchronous mode: ``` // pseudocode: ajax(request_object, callback) ajax(a, function() { ajax(b(a.somedata), function() { ajax(c(b.somedata), function() { c.finish() } }) }) ``` It would be much more readable in sync mode: ``` sjax(a) sjax(b(a.somedata)) sjax(c(b.somedata)) c.finish() ``` But *Sjax* is evil :) How do I do that in a ~~nice~~ not-so-evil and readable way?
Don't use anonymous functions. Give them names. I don't know if you're able to do what I wrote below though: ``` var step_3 = function() { c.finish(); }; var step_2 = function(c, b) { ajax(c(b.somedata), step_3); }; var step_1 = function(b, a) { ajax(b(a.somedata), step_2); }; ajax(a, step_1); ```
You could have a single function which is passed an integer to state what step the request is in, then use a switch statement to figure out what request needs to be make next: ``` function ajaxQueue(step) { switch(step) { case 0: $.ajax({ type: "GET", url: "/some/service", complete: function() { ajaxQueue(1); } }); break; case 1: $.ajax({ type: "GET", url: "/some/service", complete: function() { ajaxQueue(2); } }); break; case 2: $.ajax({ type: "GET", url: "/some/service", complete: function() { alert('Done!'); } }); break; } } ajaxQueue(0); ``` Hope that helps!
How to chain ajax requests?
[ "", "javascript", "jquery", "asynchronous", "" ]
Seems like this should be simple, but I don't find it in a net search. I have an ofstream which is `open()`, and `fail()` is now true. I'd like to know the reason for the failure to open, like with `errno` I would do `sys_errlist[errno]`.
Unfortunately, there is no standard way of finding out exactly why open() failed. Note that sys\_errlist is not standard C++ (or Standard C, I believe).
The [strerror](http://www.cppreference.com/wiki/c/string/strerror) function from `<cstring>` might be useful. This isn't necessarily standard or portable, but it works okay for me using GCC on an Ubuntu box: ``` #include <iostream> using std::cout; #include <fstream> using std::ofstream; #include <cstring> using std::strerror; #include <cerrno> int main() { ofstream fout("read-only.txt"); // file exists and is read-only if( !fout ) { cout << strerror(errno) << '\n'; // displays "Permission denied" } } ```
Detecting reason for failure to open an ofstream when fail() is true
[ "", "c++", "iostream", "" ]
I have a list of dictionaries like so: ``` listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}] ``` I want a list of all the ids from the dictionaries. So, from the given list I would get the list: ``` [1,3,5] ``` It should be one line. I know I've done this before, I've just forgotten the syntax...Thanks
``` >>> listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}] >>> [item["id"] for item in listDict] [1, 3, 5] ```
``` [i['id'] for i in listDict] ```
Getting a list of specific index items from a list of dictionaries in python (list comprehension)
[ "", "python", "" ]
I need to prevent users from starting my Java application (WebStart Swing app) multiple times. So if the application is already running it shouldn't be possible to start it again or show a warning / be closed again. Is there some convenient way to achieve this? I thought about blocking a port or write sth to a file. But hopefully you can access some system properties or the JVM? btw. target platform is Windows XP with Java 1.5
I think your suggestion of opening a port to listen when you start your application is the best idea. It's very easy to do and you don't need to worry about cleaning it up when you close your application. For example, if you write to a file but someone then kills the processes using Task Manager the file won't get deleted. Also, if I remember correctly there is no easy way of getting the PID of a Java process from inside the JVM so don't try and formulate a solution using PIDs. Something like this should do the trick: ``` private static final int PORT = 9999; private static ServerSocket socket; private static void checkIfRunning() { try { //Bind to localhost adapter with a zero connection queue socket = new ServerSocket(PORT,0,InetAddress.getByAddress(new byte[] {127,0,0,1})); } catch (BindException e) { System.err.println("Already running."); System.exit(1); } catch (IOException e) { System.err.println("Unexpected error."); e.printStackTrace(); System.exit(2); } } ``` This sample code explicitly binds to `127.0.0.1` which should avoid any firewall warnings, as any traffic on this address must be from the local system. When picking a port try to avoid one mentioned in the [list of Well Known Ports](http://www.iana.org/assignments/port-numbers). You should ideally make the port used configurable in a file or via a command line switch in case of conflicts.
As the question states that WebStart is being used, the obvious solution is to use [`javax.jnlp.SingleInstanceService`](http://java.sun.com/javase/6/docs/jre/api/javaws/jnlp/javax/jnlp/SingleInstanceService.html). This service is available in 1.5. Note that 1.5 is currently most of the way through its End Of Service Life period. Get with Java SE 6!
How to allow running only one instance of a Java program at a time?
[ "", "java", "java-web-start", "jnlp", "" ]
I saw this years before, but since it was not widely supported, websites are dropping usage of it. I am currently designing a website which will have scrollbars inside the design and wondering whether CSS2 have any specification on styling browser scrollbars because the default colours don't fit. If there's no specification, any reference to specific browser behaviour would be appreciated. If there's no CSS specification on it, I would have to rely on a custom generated scrollbar using JS. References on how to build one is also appreciated.
A JavaScript solution can be found at [<http://www.hesido.com/web.php?page=customscrollbar>](http://www.hesido.com/web.php?page=customscrollbar). Note that you do have to pay for this, but even if you don't want to go that route it shows what is possible. Otherwise a [jQuery solution](http://jscrollpane.kelvinluck.com/) and a [Prototype solution](http://livepipe.net/control/scrollbar) are also available.
I quote myself from [this thread](https://stackoverflow.com/questions/526488/526518#526518), since it's related: From a usability point of view, changing scroll bars is a no-go. The user is familiar with his/her operating system and the visual environment it provides. Changing this does create confusion, especially among those who are new to using computers, old people etc. The majority of users today will probably recognize a scroll bar as long as it has it's basic shape - and many will not even use the bar itself, but just the scroll wheel on the mouse. It's still a thing to think about though. Consider your audience. And whatever you do make sure it actually works on all platforms/in all browsers if you use a custom scroll bar.
Styling Browser Scrollbar
[ "", "javascript", "html", "css", "scrollbar", "" ]
In SQL, is there a way to enforce that only one column out of a group of columns has a value, and the others are null? Maybe a constraint or trigger? This type of thing might be for a lookup table, but are there any alternate table designs that might accomplish this better? For example: ``` ID OtherTable1ID OtherTable2ID OtherTable3ID ----------------------------------------------------- 1 23 NULL NULL 2 NULL 45 NULL 3 33 55 NULL -- NOT ALLOWED ``` The main issue is that these columns are all FKs to other tables, so I can't collapse them down to a single column. I'm using SQL Server, but any answer will do.
@tvanfosson's suggested constraints work OK for three columns, but for generality I prefer ``` (cast(col1 is not null, int) + cast(col2 is not null, int) + cast(col3 is not null, int)) = 1 ``` because it generalizes better to any number of columns with "linearly growing" (instead of "quadratically growing") amount of coding (it's even neater in SQL dialects that don't require explicit casting of boolean aka bit to int, but I'm not sure if SQL Server is one of those).
A constraint such as the following should work: ``` (column1 is null and column2 is null) or (column1 is null and column3 is null) or (column2 is null and column3 is null) ``` This won't force it to contain a non-null column, however. To do that add another constraint: ``` column1 is not null or column2 is not null or column3 is not null ```
SQL: how to enforce that only a single column is set in a group of columns
[ "", "sql", "constraints", "" ]
i want to limit time of exam in the site , after the time is finish , alert popup window with message and redirect the user to another page. the exam contain some pages , the user can turn pages forward and backwards. i want to prevent (how much i possible) to lie.
When they begin the exam, store the time on the server side. For every page they load, start a timer for however much time is left.
I'd say that ensuring only a fixed time window is available to provide input data should be controlled in the backend application, not on the browser. The browser can be manipulated by the user, the backend application can be controlled much more effectively. You might want to provide more information about the technology stack and contraints you're working under to get more specific answers.
How to limit the duration time to finish an exam in my site
[ "", "javascript", "html", "" ]
I am creating a stored procedure in Sql Server 2008 database. I want to return the number of rows affected. Which is a better option SET NOCOUNT OFF or RETURN @@ROWCOUNT? ``` ALTER PROCEDURE [dbo].[MembersActivateAccount] @MemberId uniqueidentifier AS BEGIN -- Should I use this? SET NOCOUNT OFF; UPDATE [dbo].Members SET accountActive = 1 WHERE id = @MemberId; --Or should I SET NOCOUNT ON and use the following line instead? --return @@ROWCOUNT; END ``` I know that both work, but which is a better choice and why? --- After some trying I am coming to a conclusion that SET NOCOUNT is OFF by default inside stored procedures. Is it possible to change this behavior inside my database?
Use @@RowCount. It's explicit and transparent, it is entirely controlled by your code rather than a built-in behaviour. The `NOCOUNT` option can be manually set to default to `ON` (Optons>Query Execution>SQL Server>Advanced). If you set it this way but then declare `SET NOCOUNT OFF` in your stored procedure then that local setting takes precedence.
Don't use RETURN for values. By convention RETURN from stored procedures is for error codes, 0 meaning no error and non-0 meaning some kind of problem. If you need data back, the appropriate way to do it is with an OUTPUT parameter. It's a little counter-intuitive based on other languages' use of return.
SET NOCOUNT OFF or RETURN @@ROWCOUNT?
[ "", "sql", "sql-server", "t-sql", "rowcount", "nocount", "" ]
I would like to create an object array in C# of undefined length and then populate the array in a loop like so... ``` string[] splitWords = message.Split(new Char[] { ' ' }); Word[] words = new Word[]; int wordcount = 0; foreach (string word in splitWords) { if (word == "") continue; words[wordcount] = new Word(word); wordcount++; } ``` However, I get the error... "Array creation must have array size or array initializer" I'm doing a lot more logic in the foreach loop that I've left out for brevity.
What you want to do is create: ``` List<Word> words = new List<Word>(); ``` and then: ``` words.Add(new Word(word)); ``` And finally when the loop is done if you need an array: ``` words.ToArray(); ```
If you're using C# 3.5, you can just do the following. ``` var words = message .Split(new char[]{' '}) .Where(x => x != "") .Select(x => new Word(x)) .ToArray(); ```
Create c# object array of undefined length?
[ "", "c#", "arrays", "" ]
This is related to question [How to generate all permutations of a list in Python](https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python) How to generate all permutations that *match following criteria*: **if two permutations are reverse of each other (i.e. [1,2,3,4] and [4,3,2,1]), they are considered equal and only one of them should be in final result**. Example: ``` permutations_without_duplicates ([1,2,3]) [1, 2, 3] [1, 3, 2] [2, 1, 3] ``` I am permuting lists that contain unique integers. The number of resulting permutations will be high so I'd like to use Python's generators if possible. Edit: I'd like not to store list of all permutations to memory if possible.
I have a marvelous followup to SilentGhost's proposal - posting a separate answer since the margins of a comment would be too narrow to contain code :-) `itertools.permutations` is built in (since 2.6) and fast. We just need a filtering condition that for every (perm, perm[::-1]) would accept exactly one of them. Since the OP says items are always distinct, we can just compare any 2 elements: ``` for p in itertools.permutations(range(3)): if p[0] <= p[-1]: print(p) ``` which prints: ``` (0, 1, 2) (0, 2, 1) (1, 0, 2) ``` This works because reversing the permutation would always flip the relation between first and last element! For 4 or more elements, other element pairs that are symmetric around the middle (e.g. second from each side `p[1] <= p[::-1][1]`) would work too. (This answer previously claimed `p[0] < p[1]` would work but it doesn't — after p is reversed this picks different elements.) You can also do direct lexicographic comparison on whole permutation vs it's reverse: ``` for p in itertools.permutations(range(3)): if p <= p[::-1]: print(p) ``` I'm not sure if there is any more effecient way to filter. `itertools.permutations` guarantees lexicographic order, but the lexicographic position `p` and `p[::-1]` are related in a quite complex way. In particular, just stopping at the middle doesn't work. But I suspect (didn't check) that the built-in iterator with 2:1 filtering would outperform any custom implementation. And of course it wins on simplicity!
If you generate permutations in lexicographical order, then you don't need to store anything to work out whether the reverse of a given permutation has already been seen. You just have to lexicographically compare it to its reverse - if it's smaller then return it, if it's larger then skip it. There's probably a more efficient way to do it, but this is simple and has the properties you require (implementable as a generator, uses O(n) working memory).
How to generate permutations of a list without "reverse duplicates" in Python using generators
[ "", "python", "algorithm", "generator", "combinatorics", "" ]