Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
i have a statement ``` int A = 10,B=6,C=5; ``` and i want to write a print function such that i pass the int variable to it and it prints me the variable name and the value. eg if i call print(A) it must return "A: 10", and print (B) then it must return "B:6" in short i want to know how can i access the name of the variable and print it to string in c#. DO i have to use reflection? **After reading the answers** Hi all, thanks for the suggestions provided. I shall try them out, however i wanted to know if it is at all possible in .NET 2.0? Nothing similar to ``` #define prt(x) std::cout << #x " = '" << x << "'" << std::endl; ``` macro which is there in C/C++?
The only sensible way to do this would be to use the `Expression` API; but that changes the code yet further... ``` static void Main() { int A = 10, B = 6, C = 5; Print(() => A); } static void Print<T>(Expression<Func<T>> expression) { Console.WriteLine("{0}={1}", ((MemberExpression)expression.Body).Member.Name, expression.Compile()()); } ``` Note: if this is for debugging purposes, be sure to add `[Conditional("DEBUG")]` to the method, as using a variable in this way changes the nature of the code in subtle ways.
You can use lambda expressions: ``` static void Main( string[] args ) { int A = 50, B = 30, C = 17; Print( () => A ); Print( () => B ); Print( () => C ); } static void Print<T>( System.Linq.Expressions.Expression<Func<T>> input ) { System.Linq.Expressions.LambdaExpression lambda = (System.Linq.Expressions.LambdaExpression)input; System.Linq.Expressions.MemberExpression member = (System.Linq.Expressions.MemberExpression)lambda.Body; var result = input.Compile()(); Console.WriteLine( "{0}: {1}", member.Member.Name, result ); } ```
print name of the variable in c#
[ "", "c#", "variables", "printing", "" ]
I would like to have jQuery limit a file upload field to only jpg/jpeg, png, and gif. I am doing backend checking with `PHP` already. I am running my submit button through a `JavaScript` function already so I really just need to know how to check for the file types before submit or alert.
You can get the value of a file field just the same as any other field. You can't alter it, however. So to **superficially** check if a file has the right extension, you could do something like this: ``` var ext = $('#my_file_field').val().split('.').pop().toLowerCase(); if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) { alert('invalid extension!'); } ```
No plugin necessary for just this task. Cobbled this together from a couple other scripts: ``` $('INPUT[type="file"]').change(function () { var ext = this.value.match(/\.(.+)$/)[1]; switch (ext) { case 'jpg': case 'jpeg': case 'png': case 'gif': $('#uploadButton').attr('disabled', false); break; default: alert('This is not an allowed file type.'); this.value = ''; } }); ``` The trick here is to set the upload button to disabled unless and until a valid file type is selected.
How to have jQuery restrict file types on upload?
[ "", "javascript", "jquery", "file-upload", "file-type", "" ]
How do I replace `\n` with empty space? I get an empty literal error if I do this: ``` string temp = mystring.Replace('\n', ''); ```
`String.Replace('\n', '')` doesn't work because `''` is not a valid character literal. If you use the String.Replace(string, string) override, it should work. ``` string temp = mystring.Replace("\n", ""); ```
As replacing "\n" with "" doesn't give you the result that you want, that means that what you should replace is actually not "\n", but some other character combination. One possibility is that what you should replace is the "\r\n" character combination, which is the newline code in a Windows system. If you replace only the "\n" (line feed) character it will leave the "\r" (carriage return) character, which still may be interpreted as a line break, depending on how you display the string. If the source of the string is system specific you should use that specific string, otherwise you should use Environment.NewLine to get the newline character combination for the current system. ``` string temp = mystring.Replace("\r\n", string.Empty); ``` or: ``` string temp = mystring.Replace(Environment.NewLine, string.Empty); ```
String.Replace(char, char) method in C#
[ "", "c#", "string", "" ]
I want to develop an Java application that can detect the user logged on a Windows Domain. These credentials are going to be used to logging on the Java application running on Tomcat. How can I do this? I want to know the remote user accessing my web app. This user is logged on in Active Directory.
This is my solution: Put jcifs-1.2.7.jar on [TOMCAT\_HOME]/common/lib directory. Modify application's web.xml adding the followin text to section webapp: ``` <filter> <filter-name>NtlmHttpFilter</filter-name> <filter-class>jcifs.http.NtlmHttpFilter</filter-class> <init-param> <param-name>jcifs.http.domainController</param-name> <param-value>xx.xx.xx.xxx</param-value> --> Domain Controller IP </init-param> <init-param> <param-name>jcifs.util.loglevel</param-name> <param-value>2</param-value> </init-param> </filter> <filter-mapping> <filter-name>NtlmHttpFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ``` And the you can get the remote user using request.getRemoteUser() whithout prompt. See you.
In general, you can hook into the local authorization service using [Java Authentication and Authorization Service](http://en.wikipedia.org/wiki/Java_Authentication_and_Authorization_Service). That might do what you want. That said, are you sure this is the right way to go? What do you want to accomplish? Are you looking for a single-signon solution for the webapp? Then this: [How to configure Tomcat to use Windows NTLM authentication?](https://stackoverflow.com/questions/439120/how-to-configure-tomcat-to-use-windows-ntlm-authentication) might be what you are looking for, as proposed by Steve Read in the comment above.
Detect user logged on a computer using Java web app
[ "", "java", "tomcat", "active-directory", "" ]
I have several different submit buttons on my JSP in one form tag that all point to the same servlet. I need to know which submit button was clicked. How can I find out which button was clicked?
if request.getParameter("button-name") is not null then this is the button that was pressed
Each Submit button should have a different `name`: ``` <input type="submit" value="This is a submit button" name="submit1"> <input type="submit" value="Another submit button" name="submit2"> <input type="submit" value="Yet another submit button!" name="submit3"> ``` Then, the name of the input should appear in the parameters sent to wherever the form is posting to, something like ``` post.jsp?key=value&submit3=&.... ``` <http://www.w3schools.com/tags/tag_input.asp>
How can I tell which submit button was clicked
[ "", "java", "forms", "jsp", "servlets", "input", "" ]
I'm writing a desktop application to do vector drawing in C++, and considering using sqlite to back my undo/redo feature. Has anybody used sqlite for undo/redo features? How does it work out for you? Clarification: I was aware of the stack approach, I have even implemented one application with that approach. The problem I encountered was that it becomes hard to maintain after a while. What I meant by utilizing sqlite is that I will map my entire in-memory data structure into a sqlite database, and let the sqlite do the diff and revision for me. Speed should not be a issue if I create a in-memory database. That was the idea and I was wondering if that could work.
It makes sense to use SQLite to back undo/redo when an SQLite database is the application's data file format. See [the SQLite website](https://www.sqlite.org/undoredo.html) for an explanation of how to do this with SQLite triggers.
Basically a undo/redo feature can be implemented using a stack: when the user does an operation, you push on the stack an object that represents the delta between the state before and after the operation, and when you undo, you "unroll" the delta. Because every operation the user does creates a new delta object on the stack, it might by that sqlite is not your choice of technology because it might be too slow. I would recommend considering the possibility of just storing the undo/redo information in memory, and linearizing it on the disk only if you want to actually save the undo/redo history.
How to utilize sqlite for undo/redo features?
[ "", "c++", "sqlite", "undo", "undo-redo", "" ]
I am writing an application to sniff some HTTP traffic. I am using WinPcap to access the TCP/IP packets. Is there a library that will help me parse the HTTP messages? I have implemented a basic parser myself, but I would like something more mature: I keep running into new variations (chunked messages, gzip-compression etc.) The .NET framework probably have a HTTP parser, but I can't see any way to use it, when the TCP packets do not come from a direct TCP connection.
Check out HttpMachine | <https://github.com/bvanderveen/httpmachine>
Long shoot, but have you look at [Cassini source code](http://blogs.msdn.com/dmitryr/archive/2005/09/27/474534.aspx)? I also found [HTML Agility](http://www.codeplex.com/htmlagilitypack) in [previous SO question](https://stackoverflow.com/questions/233648/what-is-the-most-useful-net-library-youve-found/233662#233662).
.NET HTTP parser
[ "", "c#", ".net", "http", "parsing", "" ]
How do you find the smallest unused number in a SQL Server column? I am about to import a large number of manually recorded records from Excel into a SQL Server table. They all have a numeric ID (called document number), but they weren't assigned sequentially for reasons that no longer apply, meaning from now on when my web site records a new record, it needs to assign it the smallest possible document number (greater than zero) that has not already been taken. Is there a way to do this through plain SQL or is this a problem for TSQL/code? Thanks! **EDIT** Special thanks to [WW](https://stackoverflow.com/questions/684106/find-the-smallest-unused-number-in-ms-sql/684176#684176) for raising the issue of concurrency. Given that this is a web app, it is multi-threaded by definition and anyone faced with this same problem should consider either a code or DB level lock to prevent a conflict. **LINQ** FYI - this can be accomplished via LINQ with the following code: ``` var nums = new [] { 1,2,3,4,6,7,9,10}; int nextNewNum = ( from n in nums where !nums.Select(nu => nu).Contains(n + 1) orderby n select n + 1 ).First(); ``` nextNewNum == 5
Find the first row where there does not exist a row with Id + 1 ``` SELECT TOP 1 t1.Id+1 FROM table t1 WHERE NOT EXISTS(SELECT * FROM table t2 WHERE t2.Id = t1.Id + 1) ORDER BY t1.Id ``` Edit: To handle the special case where the lowest existing id is not 1, here is a ugly solution: ``` SELECT TOP 1 * FROM ( SELECT t1.Id+1 AS Id FROM table t1 WHERE NOT EXISTS(SELECT * FROM table t2 WHERE t2.Id = t1.Id + 1 ) UNION SELECT 1 AS Id WHERE NOT EXISTS (SELECT * FROM table t3 WHERE t3.Id = 1)) ot ORDER BY 1 ```
If you sort them by numeric ID, the number you are looking for will be the first one for which the ROW\_NUMBER() function doesn't equal the ID.
Find the smallest unused number in SQL Server
[ "", "sql", "sql-server", "gaps-and-islands", "" ]
I am trying to add an existing PDF (created otherwise) to a PDF created with FPDF using FPDI. It seems to work find for most PDFs, but I get the following error: ``` FPDF error: Unable to find xref table. ``` After some testing, I figured out that if I use a PDF version of 1.4 or lower (Acrobat v5 or lower) it seems to work. Looking at the file it seems to be because of a different PDF format. Is there a work around or solution to this? I have probably 10 000+ PDFs uploaded by users, some of the new working, some of them not. It's also annoying that FPDI just dies instead of causing some kind of error or even returning false The only solution I can think of right now is to parse the first line of the PDF file to determine the version and only add the ones that over versions that will work. **Edit:** I also tried this in Zend\_Pdf and it had the following result, using the demo file that comes with the Zend Framework: ``` Fatal error: Uncaught exception 'Zend_Pdf_Exception' with message 'Cross-reference streams are not supported yet.' in /Volumes/Documents/temp/ZendFramework-1.7.7/library/Zend/Pdf/Parser.php:331 Stack trace: #0 /Volumes/Documents/temp/ZendFramework-1.7.7/library/Zend/Pdf/Parser.php(455): Zend_Pdf_Parser->_loadXRefTable('116') #1 /Volumes/Documents/temp/ZendFramework-1.7.7/library/Zend/Pdf.php(297): Zend_Pdf_Parser->__construct('/Volumes/Docume...', Object(Zend_Pdf_ElementFactory_Proxy), true) #2 /Volumes/Documents/temp/ZendFramework-1.7.7/library/Zend/Pdf.php(250): Zend_Pdf->__construct('/Volumes/Docume...', NULL, true) #3 /Volumes/Documents/temp/ZendFramework-1.7.7/demos/Zend/Pdf/demo.php(37): Zend_Pdf::load('/Volumes/Docume...') #4 {main} thrown in /Volumes/Documents/temp/ZendFramework-1.7.7/library/Zend/Pdf/Parser.php on line 331 ``` Is it impossible to parse PDFs greater than 1.4?
I found that using commerical version of [FPDI PDF-Parser](http://www.setasign.de/products/pdf-php-solutions/fpdi-pdf-parser/) solved my problem. I've been using it for a year now and haven't had any PDFs it couln't parse (unless the PDF was corrupt or had something else weird going on).
You can use FPDI with TCPDF, it will generate and read (with FPDI) version 1.7 PDFs. See [TCPDF - PHP class for PDF](http://sourceforge.net/projects/tcpdf/). --- **EDIT** I have recently been challenged with the issue of using various versions and formats of PDF with FPDI and TCPDF, and I can confirm that PDF versions above 1.4 are hit and miss, the interesting thing is that I have a lot of working 1.7 PDFs, and works about 50/50 on 1.5 and 1.6. I worked around the issue by converting all non-workable PDF files to v1.4 using GhostScript which you can `exec` from the command line. Use `ps2pdf14` from the GhostScript `lib` folder.
Is there a way to make FPDF/FPDI or Zend_Pdf support the parsing of PDFs greater than 1.4?
[ "", "php", "zend-framework", "fpdf", "zend-pdf", "fpdi", "" ]
Imagine someone coding the following: ``` string s = "SomeString"; s.ToUpper(); ``` We all know that in the example above, the call to the “ToUpper()” method is meaningless because the returned string is not handled at all. But yet, many people make that mistake and spend time trying to troubleshoot what the problem is by asking themselves “Why aren’t the characters on my ‘s’ variable capitalized”???? So wouldn’t it be great if there was an attribute that could be applied to the “ToUpper()” method that would yield a compiler error if the return object is not handled? Something like the following: ``` [MustHandleReturnValueAttribute] public string ToUpper() { … } ``` If order for this code to compile correctly the user would have to handle the return value like this: ``` string s = "SomeString"; string uppers = s.ToUpper(); ``` I think this would make it crystal clear that you must handle the return value otherwise there is **no point** on calling that function. In the case of the string example this may not be a big deal but I can think of other more valid reasons why this would come in handy. What do you guys think? Thanks.
Does one call a method for its side-effects, for its return value, or for both? "Pure" functions (which have no effects and only serve to compute a return value) would be good to annotate as such, both to eliminate the type of error you describe, as well as to enable some potential optimizations/analyses. Maybe in another 5 years we'll see this happen. (Note that the F# compiler will warn any time you implicitly ignore a return value. The 'ignore' function can be used when you want to explicitly ignore it.)
If you have Resharper it will highlight things like this for you. Cant recommend resharper highly enough, it has lots of useful IDE additions especially around refactoring. <http://www.jetbrains.com/resharper/>
C# Compiler Enhancement Suggestion
[ "", "c#", ".net", "" ]
I am writing a library in VB.NET in which I have added, among others, a class originally written in C# but converted into VB.NET. I don't know much about C# so therefore I have used online C# to VB.NET-converters. Now I am stuck with some code which I believe the online-converter was not able to "translate" properly. When running the code I get the following error: ``` System.IndexOutOfRangeException was unhandled Message="IndexOutOfRangeException" StackTrace: at System.String.get_Chars() ......... ``` I really don't understand the reason for this error. I believe this error might be due either: - to the fact that C# is able to automatically convert an integer variable into a string (while VB.NET needs the "toString-method") - or due to the fact C# is using an incremental operator which is not supported by VB.NET. Here is the original code-snippet in C# where "m\_primaryKey" is a StringBuilder-object: ``` private void addMetaphoneCharacter(String primaryCharacter, String alternateCharacter) { //Is the primary character valid? if (primaryCharacter.Length > 0) { int idx = 0; while (idx < primaryCharacter.Length) { m_primaryKey.Length++; m_primaryKey[m_primaryKeyLength++] = primaryCharacter[idx++]; } } //other code deleted ``` This original code works when using a class-library created in C#. Here is the converted code in VB.NET which gives me the error mentioned earlier: ``` Private Sub addMetaphoneCharacter(ByVal primaryCharacter As String, ByVal alternateCharacter As String) 'Is the primary character valid? If primaryCharacter.Length > 0 Then Dim idx As Integer = 0 While idx < primaryCharacter.Length m_primaryKey.Length += 1 m_primaryKey(System.Math.Max(System.Threading.Interlocked.Increment(m_primaryKeyLength), _ m_primaryKeyLength - 1)) = primaryCharacter _ (System.Math.Max(System.Threading.Interlocked.Increment(idx), idx - 1)) End While End If 'other code deleted ``` The original code may be found [here.](http://www.codeproject.com/KB/recipes/dmetaphone5.aspx "here") I should say that the code in the class is quite advanced for me (I'm a hobby programmer but learning every day) so maybe I don't see obvious things but this is the reason why I am asking you. Can you please give me any hints to sort out this problem? Thank you. EDIT: Here is the complete sub in C#: ``` /** * Appends a metaphone character to the primary, and a possibly different alternate, * metaphone keys for the word. * * @param primaryCharacter * Primary character to append to primary key, and, if no alternate char is present, * the alternate key as well * @param alternateCharacter * Alternate character to append to alternate key. May be null or a zero-length string, * in which case the primary character will be appended to the alternate key instead */ private void addMetaphoneCharacter(String primaryCharacter, String alternateCharacter) { //Is the primary character valid? if (primaryCharacter.Length > 0) { int idx = 0; while (idx < primaryCharacter.Length) { m_primaryKey.Length++; m_primaryKey[m_primaryKeyLength++] = primaryCharacter[idx++]; } } //Is the alternate character valid? if (alternateCharacter != null) { //Alternate character was provided. If it is not zero-length, append it, else //append the primary string as long as it wasn't zero length and isn't a space character if (alternateCharacter.Length > 0) { m_hasAlternate = true; if (alternateCharacter[0] != ' ') { int idx = 0; while (idx < alternateCharacter.Length) { m_alternateKey.Length++; m_alternateKey[m_alternateKeyLength++] = alternateCharacter[idx++]; } } } else { //No, but if the primary character is valid, add that instead if (primaryCharacter.Length > 0 && (primaryCharacter[0] != ' ')) { int idx = 0; while (idx < primaryCharacter.Length) { m_alternateKey.Length++; m_alternateKey[m_alternateKeyLength++] = primaryCharacter[idx++]; } } } } else if (primaryCharacter.Length > 0) { //Else, no alternate character was passed, but a primary was, so append the primary character to the alternate key int idx = 0; while (idx < primaryCharacter.Length) { m_alternateKey.Length++; m_alternateKey[m_alternateKeyLength++] = primaryCharacter[idx++]; } } } ```
The arguments to the second line of the while loop are quite different in the VB.NET version. The Interlocked.Increment calls will be returning the incremented index, whereas the C# post-increment operator returns the original value (before the increment). That second line would probably be better replaced with something like: ``` m_primaryKey(m_primaryKeyLength) = primaryCharacter(idx) m_primaryKeyLength = m_primaryKeyLength + 1 idx = idx + 1 ``` i.e. incrementing the values only after doing the indexing/assignment, as per the C# original.
I might be missing something, but I fail to see the relevance of why the convertor has started using System.Threading.Interlocked.... My manual conversion would look something like this: ``` Private Sub addMetaphoneCharacter(ByVal primaryCharacter As String, ByVal alternateCharacter As String) 'Is the primary character valid? If primaryCharacter.Length > 0 Then Dim idx As Integer = 0 While idx < primaryCharacter.Length m_primaryKey.Length += 1 m_primaryKey(m_primaryKeyLength) = primaryCharacter(idx) m_primaryKeyLength += 1 idx += 1 End While End If 'other code deleted ```
.net - unable to convert code from c# to vb.net due to incremental operator or automatic string conversion (I think)
[ "", "c#", ".net", "vb.net", "" ]
It is pretty standard practice now for desktop applications to be self-updating. On the Mac, every non-Apple program that uses [Sparkle](http://sparkle.andymatuschak.org/) in my book is an instant win. For Windows developers, [this has already been discussed at length](https://stackoverflow.com/questions/232347/how-should-i-implement-an-auto-updater). I have not yet found information on self-updating web applications, and I hope you can help. I am building a web application that is meant to be installed like Wordpress or Drupal - unzip it in a directory, hit some install page, and it's ready to go. In order to have broad server compatibility, I've been asked to use PHP and MySQL -- is that \*\*MP? In any event, it has to be broadly cross-platform. For context, this is basically a unified web messaging application for small businesses. It's not another CMS platform, think webmail. I want to know about self-updating web applications. First of all, (1) is this a bad idea? As of Wordpress 2.7 the automatic update is a single button, which seems easy, and yet I can imagine so many ways this could go terribly, terribly wrong. Also, isn't the idea that the web files are writable by the web process a security hole? (2) Is it worth the development time? There are probably millions of WP installs in the world, so it's probably worth the time it took the WP team to make it easy, saving millions of man hours worldwide. I can only imagine a few thousand installs of my software -- is building self-upgrade worth the time investment, or can I assume that users sophisticated enough to download and install web software in the first place could go through an upgrade checklist? If it's not a security disaster or waste of time, then (3) I'm looking for suggestions from anyone who has done it before. Do you keep a version table in your database? How do you manage DB upgrades? What method do you use for rolling back a partial upgrade in the context of a self-updating web application? Did using an ORM layer make it easier or harder? Do you keep a delta of version changes or do you just blow out the whole thing every time? I appreciate your thoughts on this.
Frankly, it really does depend on your userbase. There are tons of PHP applications that don't automatically upgrade themselves. Their users are either technical enough to handle the upgrade process, or just don't upgrade. I purpose two steps: 1) Seriously ask yourself what your users are likely to really need. Will self-updating provide enough of a boost to adoption to justify the additional work? If you're confident the answer is yes, just do it. Since you're asking here, I'd guess that you don't know yet. In that case, I purpose step 2: 2) Release version 1.0 without the feature. Wait for user feedback. Your users may immediately cry for a simpler upgrade process, in which case you should prioritize it. Alternately, you may find that your users are much more concerned with some other feature. Guessing at what your users want without asking them is a good way to waste a lot of development time on things people don't actually need.
I've been thinking about this lately in regards to database schema changes. At the moment I'm digging into WordPress to see how they've handled database changes between revisions. Here's what I've found so far: `$wp_db_version` is loaded from `wp-includes/version.php`. This variable corresponds to a Subversion revision number, and is updated when `wp-admin/includes/schema.php` is changed. (Possibly through a hook? I'm not sure.) When `wp-admin/admin.php` is loaded, the WordPress option named `db_version` is read from the database. If this number is not equal to `$wp_db_version`, `wp-admin/upgrade.php` is loaded. `wp-admin/includes/upgrade.php` includes a function called `dbDelta()`. `dbDelta()` scans `$wp_queries` (a string of SQL queries that will create the most recent database schema from scratch) and compares it to the schema in the database, altering the tables as necessary so that the schema is brought up-to-date. `upgrade.php` then runs a function called `upgrade_all()` which runs specific `upgrade_NNN()` functions if `$wp_db_version` is less than target values. (ie. `upgrade_250()`, the WordPress 2.5.0 upgrade, will be run if the database version is less than 7499.) Each of these functions run their own data migration and population procedures, some of which are called during the initial database setup script. Nicely cuts down on duplicate code. So, that's one way to do it.
What are best practices for self-updating PHP+MySQL applications?
[ "", "php", "mysql", "security", "upgrade", "" ]
I have a table MyTable with a trigger defined like this: ``` ALTER TRIGGER [MyTableInsertDeleteUpdate] ON [dbo].[MyTable] AFTER INSERT,DELETE,UPDATE AS DECLARE @id int; BEGIN SELECT @id = ins.id FROM inserted ins; IF (@id IS NOT NULL) BEGIN -- insert a new record to audit table PRINT 'inserted/updated id: ' + CAST(@id AS VARCHAR); END END ``` I realize that if more than one rows are updated like this, ``` UPDATE MyTable SET name = 'test rows' WHERE id in (1, 2, 3); ``` the tigger is called only once and only the firstone in [inserted] is updated. Actually, [inserted] may have more than one rows (3 in this case if id 1, 2,3 exist). In order words, the trigger is not fired on each row. Is that right? I am using Microsoft SQL Server 2005.
Yeah the trigger is fired once per statement (not once per row) that makes the changes you are subscripting to. It will even fire if no rows where affected. <http://msdn.microsoft.com/en-us/library/ms189799(SQL.90).aspx>
As Hojou said, your trigger will fire once per statement rather than once per affected row. This is different to databases like Interbase and Firebird, and threw me when I first started using SQL Server. The whole point of the inserted and deleted 'virtual' tables is because the events are record-SET based, not row-based. There are any number of tutorials out there that cover writing sql to process the inserted/deleted tables, but watch out for the shovelware ones. I've seen more than a couple of so-called tutorials that have just been copy/pasted from another database platform and won't actually work in SQL Server as they claim to (one of the top hits for 'SQL Server trigger example' in Google gets it completely wrong for UPDATE statements). [This](http://www.sqlteam.com/article/an-introduction-to-triggers-part-i) is a reasonable introduction to Triggers and the concepts required to make sense of the inserted and deleted tables, with an explanation of why you will be missing events in your own example. The Microsoft docs themselves are reasonably useful once you get past their dull, lifeless structure and writing-style.
Trigger event is fired only once for Microsoft SQL Server 2005 DB if more than one rows updated?
[ "", "sql", "sql-server", "sql-server-2005", "" ]
A time-out occurs during the first RPC call to a server yet subsequest requests succeed. The server times-out on the response because upon first call it loads the libraries needed to handle the request. Due to this delay, some clients time out. Although it is possible to increase the time-out delay in the client, I'd like to minimize the impact that class loading has on the application's responsiveness. How would you preload Java class files so that when the application's `.jar` file is first run class loading does not introduce a delay on the first call?
You could run a load before the server becomes live. You haven't specified how you're loading the server, the classes, and what the environment is, but you can take advantage of the fact that a class static initializer will run when the class is loaded. So, if you're running from a "main" method, your class could look something like this ``` public class Foo { static { //this will be run when the class is loaded try { Class.forName("fully.qualified.class.name.that.i.want.to.Load"); } catch ... } public static void main (string args[]) { //run my server... } } ```
One thing you might want to try is writing a simple client inside of the Java server itself. This client does nothing but call some method in the server when it starts up, forcing the classes to be loaded. After this little client gets a result (or callback), then it puts the server into an "accessible by the outside world" state.
Preloading java classes/libraries at jar startup?
[ "", "java", "jvm", "classloader", "warm-up", "" ]
Lets assume we have a class which will be widely used throughout the (c#) code, for example a Log class. Say the Log writes entries into XML files in a specific directory. Now one attempt to force the user to initialize the class with the required information would be to make the default (parameterless) constructor private and provide one which takes a *logdirectory* parameter. The drawback on this would be, that the user everytime something needs to be written to the log and thus an instance of the Log class is created, the parameter needs to be provided. What other options are available? Thanks in advance for your replies.
Four options (mostly covered, but not explicitly and together): * Just make the calls static, and include static initialization. This is horrible for testing (of classes that depend on it) but very simple. * Use a [singleton](http://pobox.com/~skeet/csharp/singleton.html) as suggested by most other answers. This is potentially better from a testing point of view (you could have internal methods to replace the singleton for test purposes only), and implement an interface for mocking purposes. * Use dependency injection: make everything that needs the dependency take it in a constructor or whatever, and get your DI framework to hook everything up. Much better from a testing perspective, but it's not exactly convenient. * Use a factory - like the singleton, but separating the implementation from the construction. (It may *effectively* end up as a singleton, but without as many assumptions of that.)
I think the term you'll want to search for is the Singleton pattern. I won't fully write it out here -- it's a very google-able term. But basically you initialize a single instance of the object once as the application loads, and then throughout the application you reference that same instance
Design Question: How to deal with initialization?
[ "", "c#", "design-patterns", "initialization", "" ]
I'm looking to run a bit of custom error handling for PHP's parse errors - the type when the syntax is wrong, and you get those white screens of death. (To be clear, the type that would result when running malformed code as so: ``` <?php if () { ?> ``` ) I had a look at setting a custom error handler, but couldn't get anything to happen.
Another idea: If you have an own root server or just want to execute the script on your local PC you could do the following: Put the code to test in a new file, say `failure.php`. In your script (same directory), where you want to check for errors, do it this way: ``` $path_to_test = 'failure.php'; $result = `php -l $path_to_test`; ``` Then you have the parse error messages in `$result`, because the flag `-l` makes PHP only parse the code. It will never execute anything. You can parse the error messages if any on your own and even get the line numbers out of them.
Normally you'd use [`set_error_handler`](https://www.php.net/set-error-handler) for this, but the docs note this: > The following error types cannot be handled with a user defined function: `E_ERROR`, `E_PARSE`, `E_CORE_ERROR`, `E_CORE_WARNING`, `E_COMPILE_ERROR`, `E_COMPILE_WARNING`, and most of `E_STRICT` raised in the file where `set_error_handler()` is called. What you have there is a `PARSE_ERROR` and is not catachble by this. In the "user comment" sections of the `set_error_handler` page there is a plethora of solutions to catch all errors, and some say it works and some say it doesn't, so I suggest just going through them and finding if any in fact work.
How do I run a custom function/bit of code when PHP has a parse error
[ "", "php", "error-handling", "" ]
I have created a wn32 project with **Visual Studio 2008** and **Visual C++** language, it uses the ws2\_32.lib library and then I compiled in **Release mode**. It runs very good in the same computer, but when I copy the exe file to other computer (that doesn't have installed Visual Studio), it doesn't run. The message I see is: *This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.* But, if I compile my application using **DEV C++**, it generates a bigger executable (738KB) compared with the Visual Studio 2008 executable (9.5 KB). However, the DEV C++ executable runs in the other computer. I have add the library ws2\_32.lib to the linker properties of my project, in the **Additional Dependencies** field. How can I fix it to work with Visual Studio 2008? My code is the following: <http://www.stan.com.mx/yupi/udpserver.cpp>
I agree with JaredPar. The application you build with VS2008 is using dynamic linking, whereas the DEV C++ is linking statically, hence the larger size and why one works and not the other. However, if its a plain win32 application project you've got (and you don't want/need to distribute it with a setup), you *may* be able to get it to run on another machine without redistributing the CRT by getting VS2008 to link statically for you (if its just the standard lib you're missing). I don't have a copy of VS2008 to hand, so I'll describe how to do it in VS2005 and hopefully it'll translate across. 1. Bring up configuration properties for the project (right click the project name, then select "properties" from the menu) 2. Expand "Configuration Properties", then "C/C++", then click "Code Generation" 3. Under the "Runtime Library" item, for your particular configuration select the **non-DLL** version of the library i.e. for debug builds you want "Multi-threaded Debug (/MTd) and for release builds you want "Multi-threaded (/MT)" Try and see if that works. You'll obviously get a much bigger final binary now the library is statically linked.
The problem is almost certainly that the other computer does not have version 9 of the C++ CRT installed. The default setting for compiling against the CRT in VS2008 is to dynamically link vs. statically linking. If you want to deploy your program with a real setup project you'll need to include the CRT redistributable. However if you want to do an XCOPY deployment follow the steps on the following page. <http://msdn.microsoft.com/en-us/library/ms235291.aspx>
A C++ Application Compiled With VS2008 Doesn't Run In Other Computer
[ "", "c++", "visual-studio", "visual-studio-2008", "winapi", "visual-c++", "" ]
What is the difference between eventOne (with keyword 'event') and eventTwo (w/o keyword)? ``` class Program { public event EventHandler eventOne; public EventHandler eventTwo; public void RaiseOne() { if (eventOne != null) eventOne(this, EventArgs.Empty); } public void RaiseTwo() { if (eventTwo != null) eventTwo(this, EventArgs.Empty); } static void Main(string[] args) { var p = new Program(); p.eventOne += (s, e) => Console.WriteLine("One"); p.eventTwo += (s, e) => Console.WriteLine("Two"); p.RaiseOne(); p.RaiseTwo(); } } ```
* `eventOne` is a public *event* backed by a private field of type `EventHandler`. * `eventTwo` is a public *field* of type `EventHandler`. Basically an event *only* encapsulates the ideas of "subscribe" and "unsubscribe" in the same way that a property only encapsulates the ideas of "get" and "set" rather than the actual storage. (As far as the CLR is concerned an event can also expose a "raise" method, but C# never uses this. Ignore it.) See [my article on events](http://pobox.com/~skeet/csharp/events.html) ([alternate link](http://csharpindepth.com/Articles/Chapter2/Events.aspx)) for more about the difference between delegates and events.
By using the **event** keyword you tell C# go generate to hidden methods, **add\_XXX** and **remove\_XXX** for your underlying delegate. This makes sure that anyone using your class can only attach and remove delegates to the event. The key point is that nobody outside your class and raise the event, so you've got complete control over when this will happen. If you don't use **event** then you're just exposing a public delegate that anyone can add to, remove from and invoke. It's highly unlikely that you want anyone other than your class to do the invoking.
Is keyword 'event' optional in C#?
[ "", "c#", "events", "compiler-construction", "" ]
I'm using an ASP "classic" server, with JavaScript as the language engine, specified by the directive: ``` <%@LANGUAGE='JAVASCRIPT'%> ``` I've noticed that `import' seems to be a keyword. ``` Technical Information (for support personnel) * Error Type: Microsoft JScript compilation (0x800A03F2) Expected identifier /Default.asp, line 4, column 4 var import = 'whut' ---^ ``` How is the `import' keyword used, if at all?
Like in most programming languages, certain keywords are reserved. Javascript is a bit special since it reserves more keywords than are implemented in the language. Import is one of those words. Other examples are 'private' and 'void', though they are not implemented in the current releases.
From [here](http://www.devguru.com/Technologies/Ecmascript/Quickref/import.html): > The **import** statement allows a script > to import properties, functions and > objects exported by a signed script. > The following code imports the 'wine' > and 'beer' properties of the object > 'drinks' provided they have been made > available by an exporting script > (compare the export statement): > > **Code**: i`mport drinks.beer, drinks.wine;` > > NOTE: Any exported script must be > loaded into a window, frame or layer > before it can be imported and used.
JScript 'import' syntax for ASP classic
[ "", "javascript", "asp-classic", "import", "" ]
How do I split a sentence and store each word in a list? e.g. ``` "these are words" ⟶ ["these", "are", "words"] ``` --- To split on other delimiters, see [Split a string by a delimiter in python](https://stackoverflow.com/questions/3475251). To split into individual characters, see [How do I split a string into a list of characters?](https://stackoverflow.com/questions/4978787).
Given a string `sentence`, this stores each word in a list called `words`: ``` words = sentence.split() ```
To split the string `text` on any consecutive runs of whitespace: ``` words = text.split() ``` To split the string `text` on a custom delimiter such as `","`: ``` words = text.split(",") ``` The `words` variable will be a `list` and contain the words from `text` split on the delimiter.
How do I split a string into a list of words?
[ "", "python", "string", "list", "split", "text-segmentation", "" ]
What is the difference between `Math.random() * n` and `Random.nextInt(n)` where `n` is an integer?
Here is [the detailed explanation](https://community.oracle.com/message/6596485#thread-message-6596485) of why "`Random.nextInt(n)` is both more efficient and less biased than `Math.random() * n`" from the Sun forums post that Gili linked to: > Math.random() uses Random.nextDouble() internally. > > Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its mantissa, so it is uniformly distributed in the range 0 to 1-(2^-53). > > Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX\_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX\_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1. > > Prior to scaling by 6, the output of Math.random() is one of 2^53 possible values drawn from a uniform distribution. > > Scaling by 6 doesn't alter the number of possible values, and casting to an int then forces these values into one of six 'buckets' (0, 1, 2, 3, 4, 5), each bucket corresponding to ranges encompassing either 1501199875790165 or 1501199875790166 of the possible values (as 6 is not a disvisor of 2^53). This means that for a sufficient number of dice rolls (or a die with a sufficiently large number of sides), the die will show itself to be biased towards the larger buckets. > > You will be waiting a very long time rolling dice for this effect to show up. > > Math.random() also requires about twice the processing and is subject to synchronization.
another important point is that Random.nextInt(n) is repeatable since you can create two Random object with the **same** seed. This is not possible with Math.random().
Math.random() versus Random.nextInt(int)
[ "", "java", "random", "" ]
``` Linking... Directory.obj : error LNK2019: unresolved external symbol "public: void __thiscall indexList<class entry,100>::read(class std::basic_istream<char,struct std::char_traits<char> > &)" (?read@?$indexList@Ventry@@$0GE@@@QAEXAAV?$basic_istream@DU?$char_traits@D@std@@@std@@@Z) referenced in function _main ``` Getting this error and others associated with indexList implementation. I have included all the right files, not sure what this means? [indexList.h](http://www2.cs.uregina.ca/%7Emouhoubm/=teaching/=cs170/=indexList/indexList.h) [indexList.cpp](http://www2.cs.uregina.ca/%7Emouhoubm/=teaching/=cs170/=indexList/indexList.cpp) Also, using VS .NET 2003 - They are under the "Source Files" and "Header Files" However, I tested with deleting the indexLish.h and the error doesn't change?
What you have is a class template. This means when the compiler needs to call a function, it will look at your template definition and generate the corresponding code as needed. For example, the following *probably* has a compile-time error in it if tried to call it: ``` template <typename T> void doSomething(const T& x) { x->_this_function_does_not_exist_ever_(); } ``` But as long as you don't call `doSomething` you won't get errors. The problem you have is that your header file tells the compiler "hey, these functions exist", but when the compiler tries to generate them it cannot find any definitions. (You cannot "compile" definitions in a source file and link them in, they must be visible to the caller.) The most common solution is to simply define the entire class template in the `.h` or `.hpp` file.
Are you using visual studio then include both the files into the solution and then run.
Linking error in C++ - implementing a indexList
[ "", "c++", "symbols", "" ]
I've a xml file in which I'm storing some HTML content in an element tag called `<body>`. Now I'm trying to read all the HTML content of body tag using XML DOM in JavaScript. I tried this code: ``` var xmlDoc=loadXMLDoc('QID_627.xml'); var bodytag = xmlDoc.getElementsByTagName("body"); document.write(bodytag); ``` but it is showing [object HTMLCollection] message on the browser screen.
Andrew Hare pointed out that getElementsByTagName() always returns an array, so you have to use bodytag[0] to get the element you want. This is correct, but not complete since even when you do that you'll still get an equally useless "[object *ElementName*]" message. If you're set on using document.write() you can try to serialize out the content of the body tag with ``` document.write(bodytag[0].innerHTML); ``` Better yet would be directly attaching the source DOM nodes into your destination DOM. You'd use something like ``` document.getElementById("destinationNodeId").appendChild(bodytag[0]); ``` There may be some issues with attaching DOM nodes from another document that may require you to copy the nodes, or jump through some other hoops to have it work.
Try this: ``` var xmlDoc=loadXMLDoc('QID_627.xml'); var bodytags = xmlDoc.getElementsByTagName("body"); document.write(bodytags[0]); ``` `getElementsByTagName` returns an array of elements (even if just one is found) so you need to subscript the array to retrieve your element.
How to read all child elements with tag names and their value from a xml file?
[ "", "javascript", "xml", "dom", "" ]
I am attempting to pull ALOT of data from a fox pro database, work with it and insert it into a mysql db. It is too much to do all at once so want to do it in batches of say 10 000 records. What is the equivalent to LIMIT 5, 10 in Fox Pro SQL, would like a select statement like select name, address from people limit 5, 10; ie only get 10 results back, starting at the 5th. Have looked around online and they only make mention of top which is obviously not of much use.
FoxPro does not have direct support for a LIMIT clause. It does have "TOP nn" but that only provides the "top-most records" within a given percentage, and even that has a limitation of 32k records returned (maximum). You might be better off dumping the data as a CSV, or if that isn't practical (due to size issues), writing a small FoxPro script that auto-generates a series of BEGIN-INSERT(x10000)-COMMIT statements that dump to a series of text files. Of course, you would need a FoxPro development environment for this, so this may not apply to your situation...
Take a look at the [RecNo()](http://msdn.microsoft.com/en-us/library/aa978202(VS.71).aspx) function.
LIMIT in FoxPro
[ "", "sql", "limit", "foxpro", "" ]
At work, we've been having a problem with "[PermGen out of memory](http://www.jroller.com/agileanswers/entry/preventing_java_s_java_lang)" exceptions, with the team lead deciding it was a bug in the JVM - something related to hot-deployment of code. Without explaining many details, he pointed out that hot deployment is a "hard problem", so hard that even .NET doesn't do it yet. I found a lot of articles explaining hot deployment from the bird's-eye-view, but always lacking technical details. Could anyone point me to a technical explanation, and explain why hot deployment is "a hard problem"?
When a class is loaded, various static data about the class is stored in PermGen. As long as a live reference to this Class instance exists, the class instance cannot be garbage collected. I believe that part of the problem has to do with whether or not the GC should remove old Class instances from perm gen, or not. Typically, every time you hot deploy, new class instances are added to the PermGen memory pool, and the old ones, now unused, are typically not removed. By default, the Sun JVMs will not run garbage collection in PermGen, but this can be enabled with optional "java" command arguments. Therefore, if you hot deploy enough times, you will eventually exhaust your PermGen space. If your web app does not shut down **completely** when undeployed -- if it leaves a Thread running, for example -- then all of the Class instances used by that web app will be pinned in the PermGen space. You redeploy and now have another whole copy of all of these Class instances loaded into PermGen. You undeploy and the Thread keeps going, pinning ANOTHER set of class instances in PermGen. You redeploy and load a whole net set of copies... and eventually your PermGen fills up. You can sometimes fix this by: * Supplying command arguments to a recent Sun JVM to enable GC in PermGen and of classes. That is: `-XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled` * Using a different JVM that doesn't employ a fixed sized PermGen or that does GC on loaded classes But this will help **only** if your web app shuts down completely and cleanly, leaving no live references to any of the Class instances of any Class loaded by the Class loaders for that Web App. Even this will not necessarily fix the problem, due to class loader leaks. (As well as too many interned strings in some cases.) Check out the following links for more (the two bolded ones have nice diagrams to illustrate part of the problem). * **[Classloader leaks: the dreaded "java.lang.OutOfMemoryError: PermGen space" exception](http://frankkieviet.blogspot.com/2006/10/classloader-leaks-dreaded-permgen-space.html)** * **[The Unknown Generation: Perm](http://dev.eclipse.org/blogs/memoryanalyzer/2008/05/17/the-unknown-generation-perm/)** * [Presenting the Permanent Generation](http://blogs.oracle.com/jonthecollector/entry/presenting_the_permanent_generation) * [Tomcat Wiki: How to Deal With Out Of Memory Errors](http://wiki.apache.org/tomcat/OutOfMemory)
The problem in general terms is the security model of Java that actually attempts to prevent that a class that has already been loaded be loaded again. Of course Java since the beginning has supported dynamic class loading, what it is difficult is class re-loading. It was consider harmful ( and for a good reason ) that a running java application got injected with an new class with malicious code. For instance a java.lang.String cracked implementation comming from the internet , that instead of creating string, deletes some random file hile invoking the method length(). So, they way Java was conceived ( and I presume .NET CLR in consequence, because it was highly "inspired" in JVM's ) was to prevent an already loaded class to load again that same VM. They offered a mechanism to override this "feature". Classloaders, but again the rules for the class loaders was, they should ask permission to the "parent" classloader before attempting to load a new class, if the parent has already loaded the class, the new class is ignored. For instance I have used classloaders that load a classes from LDAP or RDBMS The hot deploy becomes a necessity in the Java world when the application server became mainstream for Java EE ( and also create the need for micro containers like spring to avoid these kind of burden ) . Restarting the whole app server after every compile drives anyone crazy. So app server provider, offer this "custom" class loaders to help hot deployment, and using a configuration file, that behavior, SHOULD be disabled when set in production. But the tradeoff is you have to use tons of memory in development. So the good way to do this is restart every 3 - 4 deployments. This doesn't happen with other languages that were designed from the beginning to load their classes. In Ruby for instance, you can even add methods to a running class, override a method at runtime or even add a single method to an unique specific object. The tradeoff in these kinds of environments is of course memory and speed. I hope this helps. **EDIT** I've found this product some time ago that promises that reload is make as simple as possible. I didn't remember the link when I first wrote this answer, and I do. It is [JavaRebel from ZeroTurnaround](http://www.zeroturnaround.com/javarebel/)
What makes hot deployment a "hard problem"?
[ "", "java", "jvm", "hotdeploy", "" ]
Any suggestions on how to improve this method? I am currently using it to select a single wallpaper from a directory of wallpapers I know your not supposed to use arraylist anymore but i couldnt think of a altrnative also im not sure how to filter for more than just one type of file (ie jpg gif png) in the directory info. any suggestions or tweaks would be fantastic ``` private string getrandomfile(string path) { ArrayList al = new ArrayList(); DirectoryInfo di = new DirectoryInfo(path); FileInfo[] rgFiles = di.GetFiles("*.*"); foreach (FileInfo fi in rgFiles) { al.Add(fi.FullName); } Random r = new Random(); int x = r.Next(0,al.Count); return al[x].ToString(); } ``` Thanks Crash
Changed to use a single instance of the pseudo-random number generator. ``` // Use a class variable so that the RNG is only created once. private Random generator; private Random Generator { get { if (this.generator == null) { this.generator = new Random(); } return this.generator; } } private string getrandomfile(string path) { string file = null; if (!string.IsNullOrEmpty(path)) { var extensions = new string[] { ".png", ".jpg", ".gif" }; try { var di = new DirectoryInfo(path); var rgFiles = di.GetFiles("*.*") .Where( f => extensions.Contains( f.Extension .ToLower() ); int fileCount = rgFiles.Count(); if (fileCount > 0) { int x = this.Generator.Next( 0, fileCount ); file = rgFiles.ElementAt(x).FullName; } } // probably should only catch specific exceptions // throwable by the above methods. catch {} } return file; } ```
Why not use LINQ: ``` var files = Directory.GetFiles(path, "*.*").Where(s => Regex.Match(s, @"\.(jpg|gif|png)$").Success); string randFile = path + files.ToList()[r.Next(0, files.Count())]; ```
select random file from directory
[ "", "c#", ".net", "file", "random", "" ]
I am building a WPF application and I want its background to be filled with **particles** with random: * Opacity/z-order * Size * Velocity * "*Fuzziness*" (blur effect) * Directions (or path) I've found [a really good example](http://www.flashden.net/item/background-animation-blurry-light-cells/21980) of what I'd like it to be, but unfortunately it's in Flash and it's not free... I've tried to implement it but I can't manage to get it **smooth**... So I was wondering if any of you could help me improve it in order to get it to use less CPU and more GPU so it is smoother, even with more particles and in full screen mode. ***Code "Particle.cs"***: the class that defines a Particle with all its properties ``` public class Particle { public Point3D Position { get; set; } public Point3D Velocity { get; set; } public double Size { get; set; } public Ellipse Ellipse { get; set; } public BlurEffect Blur { get; set; } public Brush Brush { get; set; } } ``` ***XAML "Window1.xaml"***: the window's xaml code composed of a radial background and a canvas to host particles ``` <Window x:Class="Particles.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="600" Width="800" Loaded="Window_Loaded"> <Grid> <Grid.Background> <RadialGradientBrush Center="0.54326,0.45465" RadiusX="0.602049" RadiusY="1.02049" GradientOrigin="0.4326,0.45465"> <GradientStop Color="#57ffe6" Offset="0"/> <GradientStop Color="#008ee7" Offset="0.718518495559692"/> <GradientStop Color="#2c0072" Offset="1"/> </RadialGradientBrush> </Grid.Background> <Canvas x:Name="ParticleHost" /> </Grid> </Window> ``` ***Code "Window1.xaml.cs"***: where everything happens ``` public partial class Window1 : Window { // ... some var/init code... private void Window_Loaded(object sender, RoutedEventArgs e) { timer.Interval = TimeSpan.FromMilliseconds(10); timer.Tick += new EventHandler(timer_Tick); timer.Start(); } void timer_Tick(object sender, EventArgs e) { UpdateParticules(); } double elapsed = 0.1; private void UpdateParticules() { // clear dead particles list deadList.Clear(); // update existing particles foreach (Particle p in this.particles) { // kill a particle when its too high or on the sides if (p.Position.Y < -p.Size || p.Position.X < -p.Size || p.Position.X > Width + p.Size) { deadList.Add(p); } else { // update position p.Position.X += p.Velocity.X * elapsed; p.Position.Y += p.Velocity.Y * elapsed; p.Position.Z += p.Velocity.Z * elapsed; TranslateTransform t = (p.Ellipse.RenderTransform as TranslateTransform); t.X = p.Position.X; t.Y = p.Position.Y; // update brush/blur p.Ellipse.Fill = p.Brush; p.Ellipse.Effect = p.Blur; } } // create new particles (up to 10 or 25) for (int i = 0; i < 10 && this.particles.Count < 25; i++) { // attempt to recycle ellipses if they are in the deadlist if (deadList.Count - 1 >= i) { SpawnParticle(deadList[i].Ellipse); deadList[i].Ellipse = null; } else { SpawnParticle(null); } } // Remove dead particles foreach (Particle p in deadList) { if (p.Ellipse != null) ParticleHost.Children.Remove(p.Ellipse); this.particles.Remove(p); } } private void SpawnParticle(Ellipse e) { // Randomization double x = RandomWithVariance(Width / 2, Width / 2); double y = Height; double z = 10 * (random.NextDouble() * 100); double speed = RandomWithVariance(20, 15); double size = RandomWithVariance(75, 50); Particle p = new Particle(); p.Position = new Point3D(x, y, z); p.Size = size; // Blur var blur = new BlurEffect(); blur.RenderingBias = RenderingBias.Performance; blur.Radius = RandomWithVariance(10, 15); p.Blur = blur; // Brush (for opacity) var brush = (Brush)Brushes.White.Clone(); brush.Opacity = RandomWithVariance(0.5, 0.5); p.Brush = brush; TranslateTransform t; if (e != null) // re-use { e.Fill = null; e.Width = e.Height = size; p.Ellipse = e; t = e.RenderTransform as TranslateTransform; } else { p.Ellipse = new Ellipse(); p.Ellipse.Width = p.Ellipse.Height = size; this.ParticleHost.Children.Add(p.Ellipse); t = new TranslateTransform(); p.Ellipse.RenderTransform = t; p.Ellipse.RenderTransformOrigin = new Point(0.5, 0.5); } t.X = p.Position.X; t.Y = p.Position.Y; // Speed double velocityMultiplier = (random.NextDouble() + 0.25) * speed; double vX = (1.0 - (random.NextDouble() * 2.0)) * velocityMultiplier; // Only going from the bottom of the screen to the top (for now) double vY = -Math.Abs((1.0 - (random.NextDouble() * 2.0)) * velocityMultiplier); p.Velocity = new Point3D(vX, vY, 0); this.particles.Add(p); } private double RandomWithVariance(double midvalue, double variance) { double min = Math.Max(midvalue - (variance / 2), 0); double max = midvalue + (variance / 2); double value = min + ((max - min) * random.NextDouble()); return value; } } ``` Thanks a lot!
Erich Mirabal >> I did try HLSL and it was quite fun to learn something new but as I'm a total newbie I did not manage to do a Box/Gaussian blur... Anyway, I found a way that use no CPU at all. Instead of moving Ellipse, I'm moving their Image. I generate an in-memory PNG with **RenderTargetBitmap** and **PngBitmapEncoder** classes and move theses *already-blurred-and-transparent* Images! Thanks a lot to everyone for answering!
I don't think the problem is performance. The app doesn't get anywhere near pegging my CPU, but the frame rate still doesn't appear smooth. I would look at two things. How you're calculating your position update, and how often you're firing the event to do so. ``` timer.Interval = TimeSpan.FromMilliseconds(10); ``` That's 100 frames per second. Choose 30fps instead (every other refresh on your monitor), or 60, etc. You should attempt to do your updates in sync with your monitor, like a video game would. ``` timer.Interval = TimeSpan.FromMilliseconds(33.33); // 30 fps ``` That alone probably won't solve the smoothness. You also shouldn't assume that the time between events is fixed: ``` double elapsed = 0.1; ``` While you are firing a timer to do that update every .01 seconds, that doesn't mean it's actually getting done in a consistent amount of time. Garbage Collection, OS Scheduling, whatever can affect the amount of time it actually takes. Measure the elapsed time since the last update was actually done, and do your calculation based on that number. Good luck!
Fast WPF Particle Background
[ "", "c#", "wpf", "algorithm", "" ]
This [walkthrough](http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-datagrid-feature-walkthrough.aspx) says you can create a WPF datagrid in one line but doesn't give a full example. So I created an example using a generic list and connected it to the WPF datagrid, but it doesn't show any data. What do I need to change on the code below to get it to show data in the datagrid? ## ANSWER: This code works now: **XAML:** ``` <Window x:Class="TestDatagrid345.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit" xmlns:local="clr-namespace:TestDatagrid345" Title="Window1" Height="300" Width="300" Loaded="Window_Loaded"> <StackPanel> <toolkit:DataGrid ItemsSource="{Binding}"/> </StackPanel> </Window> ``` **Code Behind:** ``` using System.Collections.Generic; using System.Windows; namespace TestDatagrid345 { public partial class Window1 : Window { private List<Customer> _customers = new List<Customer>(); public List<Customer> Customers { get { return _customers; }} public Window1() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { DataContext = Customers; Customers.Add(new Customer { FirstName = "Tom", LastName = "Jones" }); Customers.Add(new Customer { FirstName = "Joe", LastName = "Thompson" }); Customers.Add(new Customer { FirstName = "Jill", LastName = "Smith" }); } } } ```
Now remove the Path=Customers from your binding, and it should work :)
Typically in WPF, you would leverage an `ObservableCollection<>` Because then you can just `.Add()` / `.Remove()` elements to/from the source collection, and any controls bound **(Data Binding)** automatically get updated **(Automatic Property Change Notification)**. Those are 2 important concepts in WPF. **Main Window View Model** ``` using System.Collections.Generic; namespace TestDatagrid345.ViewModels { class Window1ViewModel { private ObservableCollection<Customer> _customers = new ObservableCollection<Customer>(); public ObservableCollection<Customer> Customers { Get { return _customers; } } } } ``` **Main Window** ``` using System.Collections.Generic; using System.Windows; namespace TestDatagrid345 { public partial class Window1 : Window { Window1ViewModel _viewModel; public Window1() { InitializeComponent(); _viewModel = (Window1ViewModel)this.DataContext; // @#$% (see XAML) } private void Window_Loaded(object sender, RoutedEventArgs e) { // but this stuff could instead be done on a 'Submit' button click on form: _viewModel.Customers.Add(new Customer { FirstName = "Tom", LastName = "Jones" }); _viewModel.Customers.Add(new Customer { FirstName = "Joe", LastName = "Thompson" }); _viewModel.Customers.Add(new Customer { FirstName = "Jill", LastName = "Smith" }); } } } ``` **Main Window XAML** ``` <Window x:Class="TestDatagrid345.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:TestDatagrid345.ViewModels" Title="Window1" Height="350" Width="525" WindowState="Maximized"> <Window.DataContext> <vm:Window1ViewModel /> <!-- this needs to be here for @#$% --> </Window.DataContext> <Grid> <DataGrid AutoGenerateColumns="True" ItemsSource="{Binding Path=Customers}" AlternatingRowBackground="LightBlue" AlternationCount="2" /> </Grid> </Window> ```
Why isn't my WPF Datagrid showing data?
[ "", "c#", "wpf", "datagrid", "" ]
I need to process XML documents of varying formats into records in a MySQL database on a daily basis. The data I need from each XML document is interspersed with a good deal of data I don't need, and each document's node names are different. For example: source #1: ``` <object id="1"> <title>URL 1</title> <url>http://www.one.com</url> <frequency interval="60" /> <uselessdata>blah</uselessdata> </object> <object id="2"> <title>URL 2</title> <url>http://www.two.com</url> <frequency interval="60" /> <uselessdata>blah</uselessdata> </object> ``` source #2: ``` <object"> <objectid>1</objectid> <thetitle>URL 1</thetitle> <link>http://www.one.com</link> <frequency interval="60" /> <moreuselessdata>blah</moreuselessdata> </object> <object"> <objectid>2</objectid> <thetitle>URL 2</thetitle> <link>http://www.two.com</link> <frequency interval="60" /> <moreuselessdata>blah</moreuselessdata> </object> ``` ...where I need the object's ID, interval, and URL. My ideas for approaches are: 1.) Having a separate function to parse each XML document and iteratively create the SQL query from within that function 2.) Having a separate function parse each document and iteratively add each object to my own object class, and have the SQL work done by a class method 3.) Using XSLT to convert all the documents into a common XML format and then writing a parser for that document. The XML documents themselves aren't all that large, as most will be under 1MB. I don't anticipate their structure changing often (if ever), but there is a strong possibility I will need to add and remove further sources as time goes on. I'm open to all ideas. Also, sorry if the XML samples above are mangled... they're not terribly important, just a rough idea to show that the node names in each document are different.
Using XSLT is an overkill. I like approach (2), it makes a lot of sense. Using Python I'd try to make a class for every document type. The class would inherit from dict and on its `__init__` parse the given document and populate itself with the 'id', 'interval' and 'url'. Then the code in main would be really trivial, just instantiate instances of those classes (which are also dicts) with the appropriate documents and then pass them off as normal dicts.
I've been successfully using variant the third approach. But documents I've been processing were a lot bigger. If it's a overkill or not, well that really depends how fluent you are with XSLT.
Processing XML into MySQL in good form
[ "", "python", "xml", "xslt", "parsing", "" ]
When you create an index on a column or number of columns in MS SQL Server (I'm using version 2005), you can specify that the index on each column be either ascending or descending. I'm having a hard time understanding why this choice is even here. Using binary sort techniques, wouldn't a lookup be just as fast either way? What difference does it make which order I choose?
This primarily matters when used with composite indexes: ``` CREATE INDEX ix_index ON mytable (col1, col2 DESC); ``` can be used for either: ``` SELECT * FROM mytable ORDER BY col1, col2 DESC ``` or: ``` SELECT * FROM mytable ORDER BY col1 DESC, col2 ``` , but not for: ``` SELECT * FROM mytable ORDER BY col1, col2 ``` An index on a single column can be efficiently used for sorting in both ways. See the article in my blog for details: * [**Descending indexes**](http://explainextended.com/2009/04/27/descending-indexes/) **Update:** In fact, this can matter even for a single column index, though it's not so obvious. Imagine an index on a column of a clustered table: ``` CREATE TABLE mytable ( pk INT NOT NULL PRIMARY KEY, col1 INT NOT NULL ) CREATE INDEX ix_mytable_col1 ON mytable (col1) ``` The index on `col1` keeps ordered values of `col1` along with the references to rows. Since the table is clustered, the references to rows are actually the values of the `pk`. They are also ordered within each value of `col1`. This means that that leaves of the index are actually ordered on `(col1, pk)`, and this query: ``` SELECT col1, pk FROM mytable ORDER BY col1, pk ``` needs no sorting. If we create the index as following: ``` CREATE INDEX ix_mytable_col1_desc ON mytable (col1 DESC) ``` , then the values of `col1` will be sorted descending, but the values of `pk` within each value of `col1` will be sorted ascending. This means that the following query: ``` SELECT col1, pk FROM mytable ORDER BY col1, pk DESC ``` can be served by `ix_mytable_col1_desc` but not by `ix_mytable_col1`. In other words, the columns that constitute a `CLUSTERED INDEX` on any table are always the trailing columns of any other index on that table.
For a true single column index it makes little difference from the Query Optimiser's point of view. For the table definition ``` CREATE TABLE T1( [ID] [int] IDENTITY NOT NULL, [Filler] [char](8000) NULL, PRIMARY KEY CLUSTERED ([ID] ASC)) ``` The Query ``` SELECT TOP 10 * FROM T1 ORDER BY ID DESC ``` Uses an ordered scan with scan direction `BACKWARD` as can be seen in the Execution Plan. There is a slight difference however in that currently only `FORWARD` scans can be parallelised. ![Plan](https://i.stack.imgur.com/0RnFz.png) However **it can make a big difference in terms of logical fragmentation**. If the index is created with keys descending but new rows are appended with ascending key values then you can end up with every page out of logical order. This can severely impact the size of the IO reads when scanning the table and it is not in cache. See the fragmentation results ``` avg_fragmentation avg_fragment name page_count _in_percent fragment_count _size_in_pages ------ ------------ ------------------- ---------------- --------------- T1 1000 0.4 5 200 T2 1000 99.9 1000 1 ``` for the script below ``` /*Uses T1 definition from above*/ SET NOCOUNT ON; CREATE TABLE T2( [ID] [int] IDENTITY NOT NULL, [Filler] [char](8000) NULL, PRIMARY KEY CLUSTERED ([ID] DESC)) BEGIN TRAN GO INSERT INTO T1 DEFAULT VALUES GO 1000 INSERT INTO T2 DEFAULT VALUES GO 1000 COMMIT SELECT object_name(object_id) AS name, page_count, avg_fragmentation_in_percent, fragment_count, avg_fragment_size_in_pages FROM sys.dm_db_index_physical_stats(db_id(), object_id('T1'), 1, NULL, 'DETAILED') WHERE index_level = 0 UNION ALL SELECT object_name(object_id) AS name, page_count, avg_fragmentation_in_percent, fragment_count, avg_fragment_size_in_pages FROM sys.dm_db_index_physical_stats(db_id(), object_id('T2'), 1, NULL, 'DETAILED') WHERE index_level = 0 ``` It's possible to use the spatial results tab to verify the supposition that this is because the later pages have ascending key values in both cases. ``` SELECT page_id, [ID], geometry::Point(page_id, [ID], 0).STBuffer(4) FROM T1 CROSS APPLY sys.fn_PhysLocCracker( %% physloc %% ) UNION ALL SELECT page_id, [ID], geometry::Point(page_id, [ID], 0).STBuffer(4) FROM T2 CROSS APPLY sys.fn_PhysLocCracker( %% physloc %% ) ``` ![enter image description here](https://i.stack.imgur.com/HsHcS.png)
SQL Server indexes - ascending or descending, what difference does it make?
[ "", "sql", "sql-server", "optimization", "indexing", "" ]
In a recent project I was working I created a structure in my class to solve a problem I was having, as a colleague was looking over my shoulder he looked derisively at the structure and said "move it into a class". I didn't have any argument for not moving it into a class other than I **only** need it in this class but this kind of falls down because couldn't I make it a nested class? When is it ok to use a structure?
You should check out the value type usage guidelines: <http://msdn.microsoft.com/en-us/library/y23b5415(vs.71).aspx> The article lists several important points but the few that I feel are the most valuable are the following * Is the value immutable? * Do you want the type to have value semantics? If the answer to both questions is yes then you almost certainly want to use a Structure. Otherwise I would advise going with a class. There are issues with using structures with a large amount of members. But I find that if I consider the two points above, rarely do I have more than the recommended number of members / size in my value types.
MSDN has a good [guidelines document](http://msdn.microsoft.com/en-us/library/y23b5415(vs.71).aspx) to cover structure usage. To summarize: * Act like primitive types. * Have an instance size under 16 bytes. * Are immutable. * Value semantics are desirable. Otherwise, use a class.
when is it ok to use a structure rather than a class
[ "", "c#", ".net", "vb.net", "" ]
I am trying to use a set of conditional statements that will set up an enumeration attributed with [Flags]. However, the compiler complains that 'm' is unassigned. How can I rewrite the following to achieve my intended functionality? ``` Media m; if (filterOptions.ShowAudioFiles) m = m | Media.Audio; if (filterOptions.ShowDocumentFiles) m = m | Media.Document; if (filterOptions.ShowImageFiles) m = m | Media.Image; if (filterOptions.ShowVideoFiles) m = m | Media.Video; ```
You need to initialize m. Create a "None" flag that has value 0 then: ``` Media m = Media.None; ``` Then the rest of your code.
You could also write: ``` Media m = default(Media) ``` Useful in cases where you don't know the enum, class, or whether it's a value/reference type.
Flags enum in .NET
[ "", "c#", ".net", "enums", "enum-flags", "" ]
I use Qt 4.4.2 in Visual Studio 2008. When I am writing code, IntelliSense seems to die - it does not show any methods or data members in Qt objects such as QPushButton, does not see the QObject::connect static method, etc. Is it a typical situation or did I do something wrong while installing the library?
Most likely non-standard extensions like `public slots:` etc. There's already a FAQ at the Qt site: [Intellisense does not work for my Qt application. What's wrong?](http://developer.qt.nokia.com/faq/answer/intellisense_does_not_work_for_my_qt_application._whats_wrong)
You need to tell Intellisense about the QT include directories. This can be found by going to Tools -> Options -> Projects and Solutions -> VC++ Directories . Add them to the *Show Directories for: Include Files* list on the right. I don't know if the QT installation does this by default or not. Also, make sure that your VS Project files have the QT include directories as part of the *Additional Include Directories* under C/C++ General settings. (Although you probably have this already if you can successfully compile).
When using Qt in VS2008, IntelliSense does not work properly
[ "", "c++", "visual-studio-2008", "qt", "" ]
If my program is printing to the console, I perform word-wrapping in a certain way according to Console.WindowWidth by inserting newlines - and this works perfectly. However if the output of the program is redirected to a file or another program I would like it to skip the word-wrapping. How can I detect when this is the case? Console.WindowWidth returns the same number in both cases. **Bonus** points if the solution can distinguish redirected Console.Out from redirected Console.Error.
p/invoke `GetFileType(GetStdHandle(STD_OUTPUT_HANDLE))`, or call an innocuous console function like `GetConsoleScreenBufferInfo` to check for invalid handle error. If you want to know about standard error, use `STD_ERROR_HANDLE`. I believe you can even compare handles returned by `GetStdHandle(STD_OUTPUT_HANDLE)` and `GetStdHandle(STD_ERROR_HANDLE)` to detect stuff like `2>&1`.
.NET 4.5 adds `Console.IsOutputRedirected` and `Console.IsErrorRedirected`.
How can I determine whether Console.Out has been redirected to a file?
[ "", "c#", ".net", "console", "" ]
If I had a user logged onto my site, having his id stored in `$_SESSION`, and from his browser he clicked a 'Save' button which would make an AJAX request to the server. Will his `$_SESSION` and cookies be retained in this request, and can I safely rely on the id being present in the `$_SESSION`?
The answer is yes: Sessions are maintained server-side. As far as the server is concerned, there is no difference between an AJAX request and a regular page request. They are both HTTP requests, and they both contain cookie information in the header in the same way. From the client side, the same cookies will always be sent to the server whether it's a regular request or an AJAX request. The Javascript code does not need to do anything special or even to be aware of this happening, it just works the same as it does with regular requests.
If the PHP file the AJAX requests has a `session_start()` the session info will be retained. (baring the requests are within the same domain)
Do AJAX requests retain PHP Session info?
[ "", "php", "ajax", "session", "" ]
I am trying to create a dynamic menu by reading an XML file using jQuery. I have developed the code, and it works fine in Firefox 3 and Chrome, however it just doesn't work for Internet Explorer 7/8. I'm posting my code below. What is the matter with it? ``` var menu =""; $(document).ready(function() { $.ajax({ type: "GET", url: "menu.xml", dataType: "xml", success: parseXml }); }); function parseXml(xml) { $(xml).find('link').each(function(x){ var link = $(this); var title = link.attr("name"); menu += "<div class='AccordionPanel AccordionPanelClosed'>"; menu += "<div class='AccordionPanelTab'><span></span>"; menu += "<a href='javascript:;'>"+title+"</a></div>"; link.find("inLink").each(function(z){ var intitle = $(this).attr("name"); menu += "<div class='AccordionPanelContent'>"; menu += "<ul><li>"; menu += "<a href='"+$(this).attr("ref")+"'>"+intitle+"</a>"; menu += "</li></ul></div>"; }); menu += "</div>"; }); $("#LeftMenu").append(menu); } ``` The XML file has the following structure ``` <links> <link name="Reception" ref="index.html"> <inLink name="Registration" ref="registration.html"/> <inLink name="Inquiry" ref="#"/> </link> <link name="Records" ref="#"> <inLink name="Records" ref="#"/> <inLink name="Records2" ref="#"/> </link> </links> ```
Could you try: ``` $("#LeftMenu").append($(menu)); ``` it's just a thought though.
I had a similar problem parsing an XML AJAX return, it worked fine on FF, but failed on IE. The problem I had was extra nodes between the nodes that you are expecting. IE adds text nodes with whitespace to the XML DOM where there is whitespace in the XML file. I fixed it by changing the generated XML so there was no whitespace between nodes.
jQuery not working in Internet Explorer
[ "", "javascript", "jquery", "xml", "internet-explorer", "" ]
I downloaded a package installer for Python 2.6.1, but when I use the python command in terminal (bash) Apple's shipped 2.3.5 version loads up. How can I get 2.6.1 to load up instead?
I am running Leopard, 10.5.5. The python binary, `/usr/bin/python`, is merely a symlink to the actual binary in the version specific Python folder. For example: ``` $ ls -l /usr/bin/python lrwxr-xr-x 1 root wheel 72 Aug 31 2008 /usr/bin/python -> ../../System/Library/Frameworks/Python.framework/Versions/2.5/bin/python ``` And a look inside that `/Versions` folder reveals this: ``` $ ls -l /System/Library/Frameworks/Python.framework/Versions/ total 8 drwxr-xr-x 7 root wheel 238 Aug 31 2008 2.3 drwxr-xr-x 13 root wheel 442 Nov 22 20:40 2.5 lrwxr-xr-x 1 root wheel 3 Aug 31 2008 Current -> 2.5 ``` With the help of the `ln` command to create symlinks, you will be able to set the `python` in your path to point to the version of python you want to use.
You probably need to edit your ~/.profile file. It contains your PATH variable, which tells the command line where to find things. You can do so like this: ``` export PATH=/path/to/new/python:$PATH ``` That puts your new path as the first place to look.
Upgrading Python on OS X 10.4.11
[ "", "python", "macos", "bash", "terminal", "" ]
How do I use a `ConcurrentLinkedQueue` in Java? Using this `LinkedQueue`, do I need to be worried about concurrency in the queue? Or do I just have to define two methods (one to retrive elements from the list and another to add elements to the list)? Note: obviously these two methods have to be synchronized. Right? --- **EDIT:** What I'm trying to do is this: I have a class (in Java) with one method to retrieve items from the queue and another class with one method to add items to the queue. The items added and retrieved from the list are objects of my own class. One more question: do I need to do this in the remove method: ``` while (queue.size() == 0){ wait(); queue.poll(); } ``` I only have one consumer and one producer.
No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it. First, create your queue: ``` Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>(); ``` Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor): ``` YourProducer producer = new YourProducer(queue); ``` and: ``` YourConsumer consumer = new YourConsumer(queue); ``` and add stuff to it in your producer: ``` queue.offer(myObject); ``` and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it): ``` YourObject myObject = queue.poll(); ``` For more info see [the Javadoc](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html) # EDIT: If you need to block waiting for the queue to not be empty, you probably want to use a [LinkedBlockingQueue](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/LinkedBlockingQueue.html), and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX\_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances. If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using: ``` Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>()); ``` A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock. # Finally: Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff: ``` BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>(); queue.put(myObject); // Blocks until queue isn't full. YourObject myObject = queue.take(); // Blocks until queue isn't empty. ``` Everything else is the same. Put *probably* won't block, because you aren't likely to put two billion objects into the queue.
This is largely a [duplicate of another question](https://stackoverflow.com/questions/435069/java-util-concurrentlinkedqueue/435941#435941). Here's the section of that answer that is relevant to this question: **Do I need to do my own synchronization if I use java.util.ConcurrentLinkedQueue?** Atomic operations on the concurrent collections are synchronized for you. In other words, each individual call to the queue is guaranteed thread-safe without any action on your part. What is **not** guaranteed thread-safe are any operations you perform on the collection that are non-atomic. For example, this is threadsafe without any action on your part: ``` queue.add(obj); ``` or ``` queue.poll(obj); ``` However; non-atomic calls to the queue are not automatically thread-safe. For example, the following operations are **not** automatically threadsafe: ``` if(!queue.isEmpty()) { queue.poll(obj); } ``` That last one is not threadsafe, as it is very possible that between the time isEmpty is called and the time poll is called, other threads will have added or removed items from the queue. The threadsafe way to perform this is like this: ``` synchronized(queue) { if(!queue.isEmpty()) { queue.poll(obj); } } ``` Again...atomic calls to the queue are automatically thread-safe. Non-atomic calls are not.
How to use ConcurrentLinkedQueue?
[ "", "java", "concurrency", "" ]
I have a DataView, which has been sorted in some order. How can I retrieve the values using an index. Something like this: ``` if(dv.rows[0]["name"]=="xxx") { --- do something --- } else --- something else --- ```
Try the following code Move the sorted DataView to DataTable like ``` DataTable dt = dv.ToTable(); ``` Then use ``` if (dt.Rows[0]["name"] == "xxx") { [...] } ``` It will work.
Did you try: ``` DataRowView rowView = dv[index]; ```
Retrieving rows in DataView by its index
[ "", "c#", "dataview", "" ]
How can I programmatically display the last item in a C# listview when there are vertical scrollbars? I've studied every method associated with listviews and can't find anything.
It's not actually easy/possible to scroll the list view. You need to tell the item to make sure it's visible. ``` var items = listView.Items; var last = items[items.Count-1]; last.EnsureVisible(); ```
``` this.listView1.Items[this.listView1.Items.Count - 1].EnsureVisible(); ```
Winforms: How can I programmatically display the last item in a C# listview when there are vertical scrollbars?
[ "", "c#", "winforms", "listview", "scrollbar", "" ]
I am trying to create an ANI lookup table from 2 separate tables, one a table of stores and the other a list of contacts for those stores. I am using MS SQL Server 2005, which, unfortunately, does not support the MERGE INTO syntax... The good stuff: The ANI lookup table has 2 significant columns, StoreID and PhoneNumber. The PhoneNumber column is the (unique) Primary key, as there must be only one StoreID returned for a given PhoneNumber. Store\_Info significant columns: ``` StoreID StorePhone AltPhone ``` There is one record for each StoreID, with possible duplicate phone numbers between stores. And yes, AltPhone could be the same as StorePhone... Store\_Contacts significant columns: ``` StoreID Phone ``` There are multiple entries for StoreID, and possible duplicate phone numbers for one store or across multiple stores. Sample store data ``` StoreID Parent ID StorePhone AltPhone 1 0 402-123-2300 402-123-2345 2 0 202-321-7800 202-321-7890 3 1 202-302-5600 202-302-5600 ``` Sample contacts data: ``` StoreID Title Name Phone 1 Mgr Bob 402-123-2345 1 IT Pat 402-123-2346 1 Reg Mgr Dave 402-321-3213 2 Mgr Ann 202-231-7890 2 IT Mary 202-231-7893 2 A/R Ann 202-231-7890 2 Reg Mgr Dave 402-321-3213 3 Mgr Bob 402-123-2345 3 AsstMgr Pete 402-123-2356 ``` I want to insert phone numbers in the following priority: 1. Main/single store StorePhone 2. Main/single store AltPhone 3. Branch store StorePhone 4. Branch store AltPhone 5. Main/single store contact Phone 6. Branch store contact phone * If a phone number already exists in the destination table, do not add it... So the resulting dataset should be: ``` StoreID Phone 1 402-123-2300 (first pass) 2 202-321-7800 1 402-123-2345 (2nd pass) 2 202-321-7890 3 202-302-5600 (3rd & 4th pass - only add once) 1 402-123-2346 (5th pass - skip dup) 1 402-321-3213 2 202-231-7893 (do not add dups) 3 402-123-2356 (final pass - skip dup) ``` My approach to prioritizing which phone number of the duplicates to choose is to make multiple queries based on other criteria (main store vs branch, for example), inserting the first entry found into the ANI lookup table and skipping subsequent duplicates. How do I do this without using RBAR? I have tried the following with no luck - actually, it works OK until I get to the Store\_Contacts table, where there can be multiple identical phone numbers for a given store: ``` INSERT INTO dbo.Store_PhoneNumbers (StoreID, PhoneNumber) SELECT DISTINCT StoreID, dbo.GetPhoneNumber10(StorePhone) FROM dbo.Store_Info WHERE dbo.IsAniNumber(dbo.GetPhoneNumber10(StorePhone)) = 1 AND ParentID = 0 AND NOT EXISTS (SELECT * FROM dbo.Store_PhoneNumbers WHERE PhoneNumber = dbo.GetPhonenumber10(StorePhone)); ``` ... repeat for AltPhone, then StorePhone where ParentID <> 0 then AltPhone w/ ParentID <> 0 So far so good, then here's where it falls apart: ``` INSERT INTO dbo.Store_PhoneNumbers (StoreID, PhoneNumber) SELECT DISTINCT sc.StoreID, dbo.GetPhoneNumber10(sc.Phone) FROM Store_Contacts sc INNER JOIN Store_Info si ON sc.StoreID = si.StoreID WHERE (dbo.IsAniNumber(dbo.GetPhoneNumber10(sc.Phone)) = 1) AND (si.ParentID = 0) AND NOT EXISTS (SELECT * FROM dbo.Store_PhoneNumbers WHERE PhoneNumber = dbo.GetPhonenumber10(sc.Phone)); ``` ... and repeat for ParentID <> 0 That's where I get the duplicate entries and the insert fails. Thanks for any help you can give me, I'm about to give up and use a cursor, just to get it done... Dave
``` SELECT DISTINCT sc.StoreID, dbo.GetPhoneNumber10(sc.Phone) ``` DISTINCT is wrong. It will allow 2 stores to share the same number. Use GROUP BY to ensure that the second column is unique. ``` INSERT INTO dbo.Store_PhoneNumbers (StoreID, PhoneNumber) SELECT MIN(StoreID), PhoneNumber FROM ( SELECT sc.StoreID as StoreID, dbo.GetPhoneNumber10(sc.Phone) as PhoneNumber FROM Store_Contacts sc INNER JOIN Store_Info si ON sc.StoreID = si.StoreID WHERE (dbo.IsAniNumber(dbo.GetPhoneNumber10(sc.Phone)) = 1) AND (si.ParentID = 0) AND NOT EXISTS (SELECT * FROM dbo.Store_PhoneNumbers WHERE PhoneNumber = dbo.GetPhonenumber10(sc.Phone)) ) sub GROUP BY PhoneNumber ``` The reason you could get away with distinct in the other queries, was that you were working with a single StoreID in them. This query returns multiple StoreIDs.
I see that there's an answer already selected, but I'd be remiss if I didn't point out a simpler, and more general solution. Instead of making the priority implicit in your order of inserting, make it explicit. Your question is basically, "I have several sources of a datum, and I know a priority for each one. For each key, I wish to select the single datum with the highest priority." First select all possible datums (storeid) for your key (phone): ``` create table prioritized_phone( phone char(12), storeid int, priority int); insert into prioritized_phone(phone, storeid, priority) select storephone, storeid, 1 from store_info union select altphone, storeid, 2 from store_info ``` I don't know how you select a branch store's phone, but there's some query that gets that, probably by using parentid in storeinfo, like this: ``` union select b.storephone, a.storeid, 3 from store_info a join storeinfo b on (a.parentid = b,storeid) select b.altphone, a.storeid, 4 from store_info a join storeinfo b on (a.parentid = b,storeid) ``` And then the contact phones: ``` union select distinct phone, storeid, 5 from storecontacts; ``` Once you've done that, for each phone, delete any but the lowest (best) priority: ``` delete from prioritized_phone a where a.priority > (select min( priority) from prioritized_phone b where b.phone = a.phone); ``` Now for each phone we only have its minimum priority row(s). That still may not be unique by store, so we arbitraily select the lowest storeid for the phone with: ``` delete from prioritized_phone a where a.store_id > (select min( store_id ) from prioritized_phone b where b.phone = a.phone); ``` We now have one storeid per phone, but we may still have dupes: ``` create table phone_lookup( phone char(12), storeid int); insert into phone_lookup(phone, storeid) select distinct phone, storeid from prioritized_phone; ``` Why is this solution easier? Because it makes the priority, which was implicit in your solution (implied by order of operations) into an explicit value we can select on.
SQL query to pull unique phone numbers from 2 related tables
[ "", "sql", "" ]
What is your rule for which functions that operate on a class should be member functions vs. nonmember functions? For example, I have a class which represents a maze using a matrix of bools. I am making a function called isConnected which verifies that 2 points in the maze are in the same region (i.e. it is possible to travel from A to B). Should this be member or nonmember? What is a good rule?
When to make it a member function: * when the function is logically coupled with the class (like your maze connectedness example) * when the function needs to access private or protected members, it's better to make it a member than a friend. When to make it a standalone function * when it's a generic function that can be templatized to naturally work on other classes (look at the <algorithms> header for good example)
Herb Sutter says "we want to make them nonmember nonfriends if reasonably possible", and he's smarter than I am. <http://www.gotw.ca/gotw/084.htm>
Member function vs. nonmember function?
[ "", "c++", "oop", "" ]
I'm trying to obfuscate a large amount of data. I've created a list of words (tokens) which I want to replace and I am replacing the words one by one using the StringBuilder class, like so: ``` var sb = new StringBuilder(one_MB_string); foreach(var token in tokens) { sb.Replace(token, "new string"); } ``` It's pretty slow! Are there any simple things that I can do to speed it up? **tokens** is a list of about one thousand strings, each 5 to 15 characters in length.
Instead of doing replacements in a huge string (which means that you move around a lot of data), work through the string and replace a token at a time. Make a list containing the next index for each token, locate the token that is first, then copy the text up to the token to the result followed by the replacement for the token. Then check where the next occurance of that token is in the string to keep the list up to date. Repeat until there are no more tokens found, then copy the remaining text to the result. I made a simple test, and this method did 125000 replacements on a 1000000 character string in 208 milliseconds. Token and TokenList classes: ``` public class Token { public string Text { get; private set; } public string Replacement { get; private set; } public int Index { get; set; } public Token(string text, string replacement) { Text = text; Replacement = replacement; } } public class TokenList : List<Token>{ public void Add(string text, string replacement) { Add(new Token(text, replacement)); } private Token GetFirstToken() { Token result = null; int index = int.MaxValue; foreach (Token token in this) { if (token.Index != -1 && token.Index < index) { index = token.Index; result = token; } } return result; } public string Replace(string text) { StringBuilder result = new StringBuilder(); foreach (Token token in this) { token.Index = text.IndexOf(token.Text); } int index = 0; Token next; while ((next = GetFirstToken()) != null) { if (index < next.Index) { result.Append(text, index, next.Index - index); index = next.Index; } result.Append(next.Replacement); index += next.Text.Length; next.Index = text.IndexOf(next.Text, index); } if (index < text.Length) { result.Append(text, index, text.Length - index); } return result.ToString(); } } ``` Example of usage: ``` string text = "This is a text with some words that will be replaced by tokens."; var tokens = new TokenList(); tokens.Add("text", "TXT"); tokens.Add("words", "WRD"); tokens.Add("replaced", "RPL"); string result = tokens.Replace(text); Console.WriteLine(result); ``` Output: ``` This is a TXT with some WRD that will be RPL by tokens. ``` **Note:** This code does not handle overlapping tokens. If you for example have the tokens "pineapple" and "apple", the code doesn't work properly. Edit: To make the code work with overlapping tokens, replace this line: ``` next.Index = text.IndexOf(next.Text, index); ``` with this code: ``` foreach (Token token in this) { if (token.Index != -1 && token.Index < index) { token.Index = text.IndexOf(token.Text, index); } } ```
OK, you see why it's taking long, right? You have 1 MB strings, and for each token, replace is iterating through the 1 MB and making a new 1 MB copy. Well, not an exact copy, as any token found is replaced with the new token value. But for each token you're reading 1 MB, newing up 1 MB of storage, and writing 1 MB. Now, can we think of a better way of doing this? How about instead of iterating the 1 MB string for each token, we instead walk it once. Before walking it, we'll create an empty output string. As we walk the source string, if we find a token, we'll jump `token.length()` characters forward, and write out the obfuscated token. Otherwise we'll proceed to the next character. Essentially, we're turning the process inside out, doing the for loop on the long string, and at each point looking for a token. To make this fast, we'll want quick loop-up for the tokens, so we put them into some sort of associative array (a set). > I see why it is taking long alright, > but not sure on the fix. For each 1 MB > string on which I'm performing > replacements, I have 1 to 2 thousand > tokans I want to replace. So walking > character by character looking for any > of a thousand tokens doesn't seem > faster In general, what takes longest in programming? New'ing up memory. Now when we create a StringBuffer, what likely happens is that some amount of space is allocated (say, 64 bytes, and that whenever we append more than its current capacity, it probably, say, doubles its space. And then copies the old character buffer to the new one. (It's possible we can can C's realloc, and not have to copy.) So if we start with 64 bytes, to get up to 1 MB, we allocate and copy: 64, then 128, then 256, then 512, then 1024, then 2048 ... we do this twenty times to get up to 1 MB. And in getting here, we've allocated 1 MB just to throw it away. Pre-allocating, by using something analogous to C++'s `reserve()` function, will at least let us do that all at once. But it's still all at once for *each* token. You're at least producing a 1 MB temporary string for *each* token. If you have 2000 tokens, you're allocating about a 2 billion bytes of memory, all to end up with 1 MB. Each 1 MB throwaway contains the transformation of the previous resulting string, with the current token applied. And that's why this is taking so long. Now yes, deciding which token to apply (if any), at each character, also takes time. You may wish to use a regular expression, which internally builds a state machine to run through all possibilities, rather than a set lookup, as I suggested initially. But what's really killing you is the time to allocate all that memory, for 2000 copies of a 1 MB string. Dan Gibson suggests: > Sort your tokens so you don't have to > look for a thousand tokens each > character. The sort would take some > time, but it would probably end up > being faster since you don't have to > search thousands of tokens each > character. That was my reasoning behind putting them into an associative array (e.g, Java HashSet). But the other problem is matching, e.g., if one token is "a" and another is "an" -- if there are any common prefixes, that is, how do we match? This is where Keltex's answer comes in handy: he delegates the matching to a Regex, which is a great idea, as a Regex already defines (greedy match) and implements how to do this. Once the match is made, we can examine what's captured, then use a Java Map (also an associative array) to find the obfuscated token for the matched, unobfuscated one. I wanted to concentrate my answer on the not just how to fix this, but on why there was a problem in the first place.
A better way to replace many strings - obfuscation in C#
[ "", "c#", "optimization", "string", "performance", "obfuscation", "" ]
I have a website which google blocked because it had badware i removed the viruses from the server and its completely clean now, the problem that this virus changed in the html, js asp files in the site and added hidden iframes and strange scripts, i removed all what i found in the diles, but the website is toooo big, so any one have any tool which i can use to remove all the effects of this badware? google gave me this site as a reference to remove the badware from my site <http://www.stopbadware.org/home/security> Thanks,
Upload the latest version of the site from your source control DB. If you dont follow source control, its high time you start doing it. ;-) Find a good search and replace tool. If you are using Dream weaver then you can do a site wide search. The same is applicable to Visual Interdev as well.
Wipe everything from the server, check all the files, and re upload them if they're clean. Only thing you can do.
Do you know any tools to remove badware, malware from my website which google blocks?
[ "", "asp.net", "javascript", "html", "security", "web", "" ]
I have an ASP.NET web application, and I wanted to know how I could display an error message box when an exception is thrown. For example, ``` try { do something } catch { messagebox.write("error"); //[This isn't the correct syntax, just what I want to achieve] } ``` [The message box shows the error] Thank you **Duplicate of** [How to display an error message box in a web application asp.net c#](https://stackoverflow.com/questions/651592/how-to-display-an-error-message-box-in-a-web-application-asp-net-c/651601)
Roughly you can do it like that : ``` try { //do something } catch (Exception ex) { string script = "<script>alert('" + ex.Message + "');</script>"; if (!Page.IsStartupScriptRegistered("myErrorScript")) { Page.ClientScript.RegisterStartupScript("myErrorScript", script); } } ``` But I recommend you to define your custom Exception and throw it anywhere you need. At your page catch this custom exception and register your message box script.
The errors in ASP.Net are saved on the Server.GetLastError property, Or i would put a label on the asp.net page for displaying the error. ``` try { do something } catch (YourException ex) { errorLabel.Text = ex.Message; errorLabel.Visible = true; } ```
How to display an error message in an ASP.NET Web Application
[ "", "c#", "asp.net", "custom-errors", "" ]
After going through hell trying to install the latest version of postgresql and psycopg2 today I'm going for a complete reinstall of Leopard. I've been sticking with macpython 2.5 for the past year but now I'm considering macports even 2.6 For me it's most important for Twisted, PIL and psycopg2 to be working without a problem. Can anyone give some guidelines for what version I should choose, based on experience? Edit: Ok I've decided to go without reinstalling the os. Hacked around to clean up the bad PostgresPlus installation and installed another one. The official python 2.6.1 package works great, no problem installing it alongside 2.5.2. Psycopg2 works. But as expected PIL wont compile. I guess I'll be switching between the 2.5 from macports and the official 2.6 for different tasks, since I know the macports python has it's issues with some packages. Another Edit: I've now compiled PIL. Had to hide the whole macports directory and half the xcode libraries, so it would find the right ones. It wouldn't accept the paths I was feeding it. PIL is notorious for this on leopard.
I wrote something today on this very subject, my recommendation? Run multiple version, and slap virtualenv down to compartmentalize things. <http://jessenoller.com/2009/03/16/so-you-want-to-use-python-on-the-mac/> I also wouldn't both with macports. I don't see a need for it.
You can install them side-by-side. If you've encounter problems just set python 2.5 as the standard python and use e.g. `python26` for a newer version.
Which version of python is currently best for os x?
[ "", "python", "macos", "" ]
I have a function defined in AS3 that's gonna be called from client side via JavaScript. The AS3 functions simply print some value on SWF screen when it's called. It works fine when I set an onclick event handler to a button and call the AS3 function. However I want to call this AS3 function as soon as the page loads. I am using jQuery in the project and I placed the call to the AS3 function inside $(document).ready(), but that gives me the following error in FF2 firebug: getFlashMovie("my\_movie\_name").my\_as3\_function is not a function Then, I tried calling the by setting an onLoad event handler on the , but that also does not work - produces the same error. So, my question is, how do I call an AS3 function automatically once page loads? In my project, I need to pass some client side initialization information to the flash once page loads.
You'll need to have your flash call a function in the page to notify it that the Flash is loaded and initialized, then use that as your entrypoint. In the flash: ``` ExternalInterface.call('flashReady'); ``` In the page: ``` <script> function flashReady() { .. } </script> ```
If you use [swfObject](http://code.google.com/p/swfobject/) to embed your SWF (probably a good idea anyway) then you can use its addDomLoadEvent() function which allows you to do something once the SWF is fully loaded ``` swfobject.addDomLoadEvent(function() { $("#swfobject").get(0).inited('you are loaded!'); }); ```
Calling a flash external interface AS3 function on page load
[ "", "javascript", "flash", "actionscript-3", "" ]
I have this: ``` struct myClass{ multiset<string,binPred<string> > values ; myClass(const char param1, const char param2) : values(less<string>()) { } } ; ``` I need to initialize the **`values`** member with a different functor depending on the values of **`param1`** and **`param2`**. Unfortunately, the logic to decide which functor to use is not so simple and once **`values`** is constructed I cant change its associated comparison functor. So... I would need to put all that decision logic in the member initializaion part, but I dont know how aside using the **`?:`** operator. Is it possible to put more complex statements in there?? (like `switch` staments) If not, is there a way to delay the construction of **`values`** so I can initialize it in the constructor's body?? Thanks.
You can use a static member function that will accept the parameters you have and return a necessary value. This solves the problem completely and allows for clean easily debuggable code.
Call a function: ``` myClass(const char param1, const char param2) : values( MakeComplicatedDecision( xxx ) ) { } ``` and put your logic in the function.
Complex statements in the member initialization part?
[ "", "c++", "member-initialization", "" ]
I'm writing a modal dialog in WPF. How do I set a WPF window to not have a close button? I'd still like for its `WindowState` to have a normal title bar. I found `ResizeMode`, `WindowState`, and `WindowStyle`, but none of those properties allow me to hide the close button but show the title bar, as in modal dialogs.
WPF doesn't have a built-in property to hide the title bar's Close button, but you can do it with a few lines of P/Invoke. First, add these declarations to your Window class: ``` private const int GWL_STYLE = -16; private const int WS_SYSMENU = 0x80000; [DllImport("user32.dll", SetLastError = true)] private static extern int GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll")] private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); ``` Then put this code in the Window's `Loaded` event: ``` var hwnd = new WindowInteropHelper(this).Handle; SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU); ``` And there you go: no more Close button. You also won't have a window icon on the left side of the title bar, which means no system menu, even when you right-click the title bar - they all go together. Important note: **all this does is hide the button.** The user can still close the window! If the user presses `Alt`+`F4`, or closes the app via the taskbar, the window will still close. If you don't want to allow the window to close before the background thread is done, then you could also override `OnClosing` and set `Cancel` to true, as Gabe suggested.
I just got to similar problem and [Joe White's solution](https://stackoverflow.com/a/958980/3195477) seems to me simple and clean. I reused it and defined it as an attached property of Window ``` public class WindowBehavior { private static readonly Type OwnerType = typeof (WindowBehavior); #region HideCloseButton (attached property) public static readonly DependencyProperty HideCloseButtonProperty = DependencyProperty.RegisterAttached( "HideCloseButton", typeof (bool), OwnerType, new FrameworkPropertyMetadata(false, new PropertyChangedCallback(HideCloseButtonChangedCallback))); [AttachedPropertyBrowsableForType(typeof(Window))] public static bool GetHideCloseButton(Window obj) { return (bool)obj.GetValue(HideCloseButtonProperty); } [AttachedPropertyBrowsableForType(typeof(Window))] public static void SetHideCloseButton(Window obj, bool value) { obj.SetValue(HideCloseButtonProperty, value); } private static void HideCloseButtonChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { var window = d as Window; if (window == null) return; var hideCloseButton = (bool)e.NewValue; if (hideCloseButton && !GetIsHiddenCloseButton(window)) { if (!window.IsLoaded) { window.Loaded += HideWhenLoadedDelegate; } else { HideCloseButton(window); } SetIsHiddenCloseButton(window, true); } else if (!hideCloseButton && GetIsHiddenCloseButton(window)) { if (!window.IsLoaded) { window.Loaded -= ShowWhenLoadedDelegate; } else { ShowCloseButton(window); } SetIsHiddenCloseButton(window, false); } } #region Win32 imports private const int GWL_STYLE = -16; private const int WS_SYSMENU = 0x80000; [DllImport("user32.dll", SetLastError = true)] private static extern int GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll")] private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); #endregion private static readonly RoutedEventHandler HideWhenLoadedDelegate = (sender, args) => { if (sender is Window == false) return; var w = (Window)sender; HideCloseButton(w); w.Loaded -= HideWhenLoadedDelegate; }; private static readonly RoutedEventHandler ShowWhenLoadedDelegate = (sender, args) => { if (sender is Window == false) return; var w = (Window)sender; ShowCloseButton(w); w.Loaded -= ShowWhenLoadedDelegate; }; private static void HideCloseButton(Window w) { var hwnd = new WindowInteropHelper(w).Handle; SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU); } private static void ShowCloseButton(Window w) { var hwnd = new WindowInteropHelper(w).Handle; SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) | WS_SYSMENU); } #endregion #region IsHiddenCloseButton (readonly attached property) private static readonly DependencyPropertyKey IsHiddenCloseButtonKey = DependencyProperty.RegisterAttachedReadOnly( "IsHiddenCloseButton", typeof (bool), OwnerType, new FrameworkPropertyMetadata(false)); public static readonly DependencyProperty IsHiddenCloseButtonProperty = IsHiddenCloseButtonKey.DependencyProperty; [AttachedPropertyBrowsableForType(typeof(Window))] public static bool GetIsHiddenCloseButton(Window obj) { return (bool)obj.GetValue(IsHiddenCloseButtonProperty); } private static void SetIsHiddenCloseButton(Window obj, bool value) { obj.SetValue(IsHiddenCloseButtonKey, value); } #endregion } ``` Then in XAML you just set it like this: ``` <Window x:Class="WafClient.Presentation.Views.SampleWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:u="clr-namespace:WafClient.Presentation.Behaviors" ResizeMode="NoResize" u:WindowBehavior.HideCloseButton="True"> ... </Window> ```
How to hide close button in WPF window?
[ "", "c#", "wpf", "xaml", "button", "dialog", "" ]
In a paper about the **Life Science Identifiers** (see [LSID Tester, a tool for testing Life Science Identifier resolution services](http://www.scfbm.org/content/3/1/2)), Dr Roderic DM Page wrote : Given the LSID urn:lsid\*\*:ubio.org\*\*:namebank:11815, querying the DNS for the SRV record for *\_lsid.\_tcp*.**ubio.org** returns animalia.ubio.org:80 as the location of the ubio.org LSID service. I learned that I can link \_lsid.\_tcp.ubio.org to animalia.ubio.org:80 using the **host** command on unix: ``` host -t srv _lsid._tcp.ubio.org _lsid._tcp.ubio.org has SRV record 1 0 80 ANIMALIA.ubio.org ``` How can I do this 'DNS' thing using the Java J2SE API (Without any external java library, I'd like a lightweight solution ) ? Thank you
The JNDI DNS provider can lookup SRV records. You need to do something like: ``` Hashtable env = new Hashtable(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); env.put("java.naming.provider.url", "dns:"); DirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes("_lsid._tcp.ubio.org", new String[] { "SRV" }); ``` The returned attributes are an enumeration of strings that look like "1 0 80 ANIMALIA.ubio.org". The space separated fields are in order: 1. priority 2. weight 3. port 4. server
You can't do this using the standard Java libraries. The `InetAddress` class is only capable of looking up DNS `A` records. To look up `SRV` records (and indeed any other DNS resource record type other than an `A` record) you need a third party library. [`dnsjava`](http://www.dnsjava.org/) is the usual option. I've personally used the 1.6 version on Google Android, it works fine. Version 2.0 and later use the Java `nio` layer, so won't be compatible with earlier JVMs.
Querying the DNS service records to find the hostname and TCP/IP
[ "", "java", "dns", "host", "bioinformatics", "" ]
I'm reading some data that has already been converted to html style υ code. I now need to convert this back to UTF-8 characters for viewing. Unfortunately I can't use a browser to view the string. I've read around about conversion in java and it seems if you have a string of \uxxxx then the compiler will convert for you; However that wont work of course because I want to read in dynamic strings. So can this be done? Many thanks! Dan
You need to use: ``` String StringEscapeUtils.unescapeJava(String str) ``` from the Apache Commons Library. It will find `\uxxxx` sequences in the input string and convert them to a normal Java String.
[native2ascii](http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/native2ascii.html) Use the "-reverse" option.
Convert unicode representations on incoming string to UTF-8?
[ "", "java", "utf-8", "" ]
Two related questions: 1. What are the maximum number of concurrent files that a web page is allowed to open (e.g., images, css files, etc)? I assume this value is different in different browsers (and maybe per file type). For example, I am pretty sure that javascript files can only be loaded one at a time (right?). 2. Is there a way I can use javascript to query this information?
One interesting way to get around the X connections per server limit is to map static resources like scripts and images to their own domains... img.foo.com or js.foo.com. I have only read about this - not actually tried or tested. So please let me know if this doesn't work.
For Internet Explorer see [this MSDN article](http://msdn.microsoft.com/en-us/library/cc304129(VS.85).aspx "MSDN"). Basically, unless the user has edited the registry or run a 'internet speedup' program, they are going to have a maximum of two connections if using IE7 or earlier. IE8 tries to be smart about it and can create up to 6 concurrent connections, depending on the server and the type of internet connection. In JavaScript, on IE8, you can query the property **window.maxConnectionsPerServer**. For Firefox, the default is 2 for FF2 and earlier, and 6 for FF3. See [Mozilla documentation](http://kb.mozillazine.org/Network.http.max-persistent-connections-per-server). I'm not aware of anyway to retrieve this value from JavaScript in FF. Most HTTP servers have little ability to restrict the number of connections from a single host, other than to ban the IP. In general, this isn't a good idea, as many users are behind a proxy or a NAT router, which would allow for multiple connections to come from the same IP address. On the client side, you can artificially increase this amount by requesting resources from multiple domains. You can setup www1, www2, etc.. alias which all point to your same web server. Then mix up where the static content is being pulled from. This will incur a small overhead the first time due to extra DNS resolution.
max number of concurrent file downloads in a browser?
[ "", "javascript", "" ]
Of all the thousands of queries I've written, I can probably count on one hand the number of times I've used a non-equijoin. e.g.: ``` SELECT * FROM tbl1 INNER JOIN tbl2 ON tbl1.date > tbl2.date ``` And most of those instances were probably better solved using another method. Are there any good/clever real-world uses for non-equijoins that you've come across?
Bitmasks come to mind. In one of my jobs, we had permissions for a particular user or group on an "object" (usually corresponding to a form or class in the code) stored in the database. Rather than including a row or column for each particular permission (read, write, read others, write others, etc.), we would typically assign a bit value to each one. From there, we could then join using bitwise operators to get objects with a particular permission.
How about for checking for overlaps? ``` select ... from employee_assignments ea1 , employee_assignments ea2 where ea1.emp_id = ea2.emp_id and ea1.end_date >= ea2.start_date and ea1.start_date <= ea1.start_date ```
Uses of unequal joins
[ "", "sql", "join", "" ]
For quick tasks where I only use an instantiated object once, I am aware that I can do the following: ``` int FooBarResult = (new Foo()).Bar(); ``` I say this is perfectly acceptable with non-disposable objects and more readable than the alternative: ``` Foo MyOnceUsedFoo = new Foo(); int FooBarResult = MyOnceUsedFoo.Bar(); ``` Which do you use, and why? Would you ever use this type of anonymous instantiation in a production app? Preference: with parenthesis "(new Foo()).Bar();" or without "new Foo().Bar();"? (Edited to abstract question away from Random class)
**Side note regarding random numbers:** In fact, no, your specific example (`new Random().Next(0,100)`) is completely unacceptable. The generated random numbers will be far from uniform. --- Other than that, in general, there is not much difference between the two. The compiler will most probably generate the exact same code in either case. You should go with the most readable case (long statements might harm readability; more code will do it too, so you have to make the trade-off in your specific case). By the way, if you chose to go with the single line case, omit the unnecessary parens (`new MyObject().Method()` will do).
You might want to consider the implications of using the code in the debugger. The second case will allow you to inspect the object you've created, whereas the first won't. Granted you can always back out to the second case when you're attempting to debug the code. I've done it both ways and don't really have a preference. I prefer whatever looks more readable, which is highly dependent on the complexity of the class and method being called. BTW -- you might want to pick a different example. I fear that your point might get lost in discussions over the best way to generate random numbers.
Anonymous Instantiation Syntax - Good or Bad?
[ "", "c#", "performance", "syntax", "" ]
Ingredient class: ``` class Ingredient { public String Name { get; set; } public Double Amount { get; set; } } ``` List of Ingredients: ``` var ingredientsList = new List<Ingredient>(); ``` Database layout of my "Ingredients" table: ``` [Ingredients] ( [IngredientsID] [int] IDENTITY(1,1) NOT NULL, [RecipeID] [int] NOT NULL, [IngredientsName] [nvarchar](512) NOT NULL, [IngredientsAmount] [float] NOT NULL ) ``` Am I able to query my `ingredientsList` against my "Ingredients" table, doing a where-clause which goes something like this (pseudo code alert!): ``` SELECT * FROM Ingredients WHERE IngredientsName = ["Name" property on entities in my ingredientsList] AND IngredientsAmount <= ["Amount" property on entities in my ingredientsList] ``` I of course want this to be done with LINQ, and not using dynamically generated SQL queries.
LINQ is composable, but to do this without using UNION you'd have to roll your own `Expression`. Basically, we (presumably) want to create TSQL of the form: ``` SELECT * FROM [table] WHERE (Name = @name1 AND Amount <= @amount1) OR (Name = @name2 AND Amount <= @amount2) OR (Name = @name3 AND Amount <= @amount3) ... ``` where the name/amount pairs are determined at runtime. There is easy way of phrasing that in LINQ; if it was "AND" each time, we could use `.Where(...)` repeatedly. `Union` is a candidate, but I've seen repeated people have problems with that. What we want to do is emulate us writing a LINQ query like: ``` var qry = from i in db.Ingredients where ( (i.Name == name1 && i.Amount <= amount1) || (i.Name == name2 && i.Amount <= amount2) ... ) select i; ``` This is done by crafting an `Expression`, using `Expression.OrElse` to combine each - so we will need to iterate over our name/amount pairs, making a richer `Expression`. Writing `Expression` code by hand is a bit of a black art, but I have a very similar example up my sleeve (from a presentation I give); it uses some custom extension methods; usage via: ``` IQueryable query = db.Ingredients.WhereTrueForAny( localIngredient => dbIngredient => dbIngredient.Name == localIngredient.Name && dbIngredient.Amount <= localIngredient.Amount , args); ``` where `args` is your array of test ingredients. What this does is: for each `localIngredient` in `args` (our local array of test ingredients), it asks us to provide an `Expression` (for that `localIngredient`) that is the test to apply at the database. It then combines these (in turn) with `Expression.OrElse`: --- ``` public static IQueryable<TSource> WhereTrueForAny<TSource, TValue>( this IQueryable<TSource> source, Func<TValue, Expression<Func<TSource, bool>>> selector, params TValue[] values) { return source.Where(BuildTrueForAny(selector, values)); } public static Expression<Func<TSource, bool>> BuildTrueForAny<TSource, TValue>( Func<TValue, Expression<Func<TSource, bool>>> selector, params TValue[] values) { if (selector == null) throw new ArgumentNullException("selector"); if (values == null) throw new ArgumentNullException("values"); // if there are no filters, return nothing if (values.Length == 0) return x => false; // if there is 1 filter, use it directly if (values.Length == 1) return selector(values[0]); var param = Expression.Parameter(typeof(TSource), "x"); // start with the first filter Expression body = Expression.Invoke(selector(values[0]), param); for (int i = 1; i < values.Length; i++) { // for 2nd, 3rd, etc - use OrElse for that filter body = Expression.OrElse(body, Expression.Invoke(selector(values[i]), param)); } return Expression.Lambda<Func<TSource, bool>>(body, param); } ```
The only extent to which you can use a local collection in a LINQ 2 SQL query is with the `Contains()` function, which is basically a translation to the SQL `in` clause. For example... ``` var ingredientsList = new List<Ingredient>(); ... add your ingredients var myQuery = (from ingredient in context.Ingredients where ingredientsList.Select(i => i.Name).Contains(ingredient.Name) select ingredient); ``` This would generate SQL equivalent to "`...where ingredients.Name in (...)`" Unfortunately I don't think that's going to work for you, as you'd have to join each column atomically. And just as an aside, using LINQ 2 SQL *is* a dynamically generated SQL query. You could, of course, do the joining on the client side, but that would require bringing back the entire `Ingredients` table, which could be performance-prohibitive, and is **definitely** bad practice.
LINQ to SQL query against a list of entities
[ "", "c#", "linq-to-sql", "" ]
I'm searching for a Javascript library to create line charts like the ones of Google Analytics. When the mouse is over a point, a box shows you the data. An example is at <http://wikirank.com/en> No Flash or Air, only JS and client-side Canvas... Better if Free...
Edit: If you want a free library, try [Flot](http://code.google.com/p/flot/). [Emprise Charts](http://www.ejschart.com/) is a commercial library that I've seen featured on news sites.
Another option is to use Google's [visualization APIs](http://code.google.com/apis/visualization/documentation/gallery.html).It's pretty easy to use, and they have a several options for displaying data. One thing to keep in mind is some of the visualizations require you to send your data to their server, though none of the canvas/svg ones have this requirement.
JavaScript Charting library - Google Analytics Style
[ "", "javascript", "canvas", "charts", "" ]
I have a comma delimited configuration file. The empty lines are ignored and there need to be errors on invalid lines: > foo,bar > > foo2, bar3 I want to read this file into a `HashMap` where the key (foo) is mapped with a value (bar). What is the best way to do this?
If you can use x = y instead of x, y then you can use the Properties class. If you do need to have x, y then look at the [java.util.Scanner](http://java.sun.com/javase/6/docs/api/java/util/Scanner.html) you can set the delimiter to use as a separator (the javadoc shows examples of doing that). ``` import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; class Main { public static void main(final String[] argv) { final File file; file = new File(argv[0]); try { final Scanner scanner; scanner = new Scanner(file); while(scanner.hasNextLine()) { if(scanner.hasNext(".*,")) { String key; final String value; key = scanner.next(".*,").trim(); if(!(scanner.hasNext())) { // pick a better exception to throw throw new Error("Missing value for key: " + key); } key = key.substring(0, key.length() - 1); value = scanner.next(); System.out.println("key = " + key + " value = " + value); } } } catch(final FileNotFoundException ex) { ex.printStackTrace(); } } } ``` and the Properties version (way simpler for the parsing, as there is none) ``` import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.Properties; class Main { public static void main(final String[] argv) { Reader reader; reader = null; try { final Properties properties; reader = new BufferedReader( new FileReader(argv[0])); properties = new Properties(); properties.load(reader); System.out.println(properties); } catch(final IOException ex) { ex.printStackTrace(); } finally { if(reader != null) { try { reader.close(); } catch(final IOException ex) { ex.printStackTrace(); } } } } } ```
Your best bet is to use the java.util.Scanner class to read in the values in the config file, using the comma as a delimiter. Link here to the Javadoc: <http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html> Example would be: ``` Scanner sc = new Scanner(new File("thing.config")); sc.useDelimiter(","); while (sc.hasNext()) { String token = sc.next(); } ```
What is the best way to read a comma delimited configuration file?
[ "", "java", "file-io", "" ]
I'm currently using ibatis to returns some pojos and everything works great. My question is: I have to return 1 row from a table, just like 3 fields, and I don't want to create a pojo for it. I just want to run the query and get the 3 values. Is there any easy way to do this without create a special java object just for this?
in IBatis.NET we use Hashtable when we need more than one value from a query. ``` <resultMap id="ResultMap1" class="Hashtable"> <result column="FirstName" property="FirstName" type="string" /> <!-- shows up as "FirstName" in the Hashtable --> <result column="LastName" property="LastName" type="string" /> <!-- shows up as "LastName" in the Hashtable --> </resultMap> ```
I'm not aware of any method for doing what you are asking; the specific purpose of iBATIS is to automate the mapping of relational models to classes. I'm not sure what you're trying to do, but if you have meaningful data, you should be able to map to an object of some sort, even if the object will be short-lived. I'm guessing that you need some logic based on the values fetched by your query? If that's the case, create a new POJO, map the query to it and then move the logic into your new POJO instead of wherever it is now. This will make the code much cleaner and easier maintain. If you're just trying to pull back raw data without mapping to a class, you probably need to give your design a second look. (I know that's not the answer you're looking for . . . sorry.)
ibatis return values
[ "", "sql", "ibatis", "" ]
I have an application that needs to work with a vendor-supplied API to do Screen Pops when a call is routed to the user's extension. Another developer worked on getting the API to work and delivered a prototype wrapper class that isn't quite right, and I'm trying to get it right. Because this API can block for several minutes before returning, the developer started the API interface code in a separate thread, like this: ``` // constructor public ScreenPop( ...params... ) { ... t = new Thread( StartInBackground ); t.Start(); ) private void StartInBackground() { _listener = new ScreenPopTelephoneListener(); _bAllocated = true; _listener.Initialize( _address ); _bInitialized = true; _listener.StartListening( _extension ); _bListening = true; } ``` The call to Initialize is the one that could hang, if the phone server was unresponsive. I don't think it was intentional on the part of the developer who did this, but when the API is initialized this way, the thread keeps running, so that now I have to stop the thread before I can clean up when I want to. I also have to use Invoke to get events from the thread, as others so kindly pointed out in my previous question, but that is working now. Anyway, here is the logic used to shut everything down and clean up: ``` public void ShutdownFunc() { try { if ( _bListening ) { _listener.StopListening(); _bListening = false; } if ( _bInitialized ) { _listener.Shutdown(); _bInitialized = false; } if ( _bAllocated ) { _listener = null; _bAllocated = false; } } } ``` Of course, there is a try/catch around the whole mess to prevent unhandled exceptions. My biggest problem is, how do I call the shutdown code when the API interface code is running in a separate thread? I need to clean up in case the user logs off and then logs back on again, as the API gets confused if I don't. Thread.Abort won't work, as it's not in a place to catch the exception, and the "volatile bool" method won't work either, for obvious reasons (most of the time, the API thread is not active). So there seems to be no way to call the shutdown logic if the API interface code is running on a separate thread. Thread.Abort() bypasses all the logic and kills the thread without cleaning up. Calling the shutdown logic from the GUI thread hangs when it calls the Shutdown method. So, what can I do? The IDispose interface just adds another layer of abstraction in the GUI thread, and does nothing to solve the problem here. For now, to get the rest of the code developed, I am eliminating threads completely. But, before I release the app, I need to figure this out. Anybody? Thanks, Dave
With the help of a fellow developer here, I was able to get the code working as desired. What I needed to do was take everything out of the thread except the call to Initialize(), so that the API instance was not running on a separate thread. I then had a different problem, as the status was set from 2 different threads and was not what I expected it to be when I went to clean up. Here is the final solution: ``` // declare a background worker to init the API private BackgroundWorker _bgWorker; // ctor public HiPathScreenPop( ... ) { ... _phoneListener = new ScreenPopTelephoneListener(); _apiState = ApiState.Allocated; _phoneListener.StatusChanged += new _IScreenPopTelephoneListenerEvents_StatusChangedEventHandler( StatusChangedEvent ); _phoneListener.ScreenPop += new _IScreenPopTelephoneListenerEvents_ScreenPopEventHandler( ScreenPopEvent ); _bgWorker = new BackgroundWorker(); _bgWorker.DoWork += new DoWorkEventHandler(StartInBackground); _bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler( bgWorker_RunWorkerCompleted ); _bgWorker.RunWorkerAsync(); } void _bgWorker_DoWork( object sender, DoWorkEventArgs e ) { _phoneListener.Initialize( _strAddress ); } void bgWorker_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e ) { _apiState = ApiState.Initialized; // probably not necessary... _phoneListener.StartListening( _intExtension.ToString() ); _apiState = ApiState.Listening; } ``` Now, the API instance is running in the same thread as the UI and everybody's happy. The call to Shutdwn() no longer hangs, I don't need Invoke() for the callbacks, and the long-running code executes in a background worker thread. What this code does not show are the great ideas presented earlier for how to handle the case where the user shuts down before the call to Initialize() returns. The final code will be a synthesis of these solutions. Thanks to all for the great feedback! Dave
You may further encapsulate initialization logic and check on a ManualResetEvent in the main initialization thread while spawning a worker thread to do the actual initialization. If the ManualResetEvent is set from your main thread while you're still initializing, you can abort the thread doing the actual initialization and do your cleanup, otherwise if the worker thread completes you just stop waiting on the ManualResetEvent. It's kind of dirty and tricky, but should do what it's supposed to ;)
How to handle starting/stopping API interface that may take a long time to start
[ "", "c#", ".net", "multithreading", "dispose", "" ]
My site works fine in Firefox, but it crashes in IE. I am using alot of jQuery in order to fade in content. When the user clicks on one of the above links a few times, it will crash in IE. Here is my site: [Idea Palette](http://www.idea-palette.com/) I have absolutely no idea why the site crashes in IE. I don't even know where to begin to debug my problem. I don't have Visual Studio on my computer, but on my friends computer Visual Studio reads a message of "An unhandled win32 exception occurred in iexplore.exe[####]" Does anyone have any ideas?
Here you go. It has something to do with your DirectX filter (probably what's doing the fades). Here's the stack, and EAX is NULL. Whatever the code is doing is trying to deref EAX: ``` CDXTFilterBehavior::_ClearSurface: 6C8E87E1 mov edi,edi 6C8E87E3 push ebp 6C8E87E4 mov ebp,esp 6C8E87E6 push ecx 6C8E87E7 mov eax,dword ptr [ebp+0Ch] 6C8E87EA mov ecx,dword ptr [eax] <--- EAX is NULL > dxtrans.dll!CDXTFilterBehavior::_ClearSurface() dxtrans.dll!CDXTFilterBehavior::_DrawUnfilteredElementLayers() dxtrans.dll!CDXTFilterBehavior::_DrawElementWithProceduralSurfaces() dxtrans.dll!CDXTFilterBehavior::_ExecuteFilterChain() dxtrans.dll!CDXTFilterBehavior::Draw() mshtml.dll!CPeerHolder::Draw() mshtml.dll!CLayout::DrawClientLayers() mshtml.dll!CDispContainer::DrawSelf() mshtml.dll!CDispNode::Draw() mshtml.dll!CDispContainer::DrawChildren() mshtml.dll!CDispContainer::DrawSelf() mshtml.dll!CDispNode::Draw() mshtml.dll!CDispContainer::DrawChildren() mshtml.dll!CDispContainer::DrawSelf() mshtml.dll!CDispNode::Draw() mshtml.dll!CDispContainer::DrawChildren() mshtml.dll!CDispContainer::DrawSelf() mshtml.dll!CDispNode::Draw() mshtml.dll!CDispContainer::DrawChildren() mshtml.dll!CDispContainer::DrawSelf() mshtml.dll!CDispNode::Draw() mshtml.dll!CDispContainer::DrawChildren() mshtml.dll!CDispContainer::DrawSelf() mshtml.dll!CDispNode::Draw() mshtml.dll!CDispRoot::DrawEntire() mshtml.dll!CDispRoot::DrawRoot() mshtml.dll!CView::RenderView() mshtml.dll!CDoc::OnPaint() mshtml.dll!CServer::OnWindowMessage() mshtml.dll!CDoc::OnWindowMessage() mshtml.dll!CServer::WndProc() user32.dll!_InternalCallWinProc@20() user32.dll!_UserCallWinProcCheckWow@32() user32.dll!_CallWindowProcAorW@24() user32.dll!_CallWindowProcW@20() user32.dll!_InternalCallWinProc@20() user32.dll!_UserCallWinProcCheckWow@32() user32.dll!_DispatchClientMessage@20() user32.dll!___fnDWORD@4() ntdll.dll!_KiUserCallbackDispatcher@12() user32.dll!_NtUserDispatchMessage@4() user32.dll!_DispatchMessageWorker@8() user32.dll!_DispatchMessageW@4() ieframe.dll!CTabWindow::_TabWindowThreadProc() kernel32.dll!@BaseThreadInitThunk@12() ntdll.dll!___RtlUserThreadStart@8() ntdll.dll!__RtlUserThreadStart@8() ``` Perhaps you're removing an element from the DOM while the transform is still operating on it?
I can suggest that you have to follow the "Divide and Conquer Strategy". Remove all your javascript, and try to load it, if it fail the problem is with the code you have removed. Now add again "half" of the code that you have removed, if it didn't crash then the problems isn't in this half, if it crashes again then it is in the half you have added. Now you have to keep adding "half" of the remaining code when it works, or removing half of the code you have added if it fails. If you keep doing this eventually you will led to a piece of code that you can't divide and if added make IE crash. This will not solve your bug but it may give you an idea where the real problem is.
Why does my website crash in IE?
[ "", "javascript", "jquery", "internet-explorer", "crash", "" ]
Sorry for a noobish question but I've stumbled upon some other person's code and he is using `i_tmp2` inside of a `for` loop. When is the `i_tmp2` notation used?
i in i\_tmp2 probably stands for "integer", i.e. telling you it's a variable used for storing whole numbers. tmp2 in i\_tmp2 probably just means it's the second temporary variable created.
Ask the person who actually wrote the code. Every individual programmer has their own reasons for choosing their notation styles for particular types of code.
What does i_tmp2 stand for when used as a variable?
[ "", "php", "" ]
I need a Rolling hash to search for patterns in a file. (I am trying to use the [Rabin-Karp string search algorithm](https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm)). I understand how a good **Hash** works and how a good **Rolling Hash** should work but I am unable to figure out how to efficiently implement the *divide* (or inverse multiplication) when rolling the hash. I also read rsync uses rolling version of *adler32* but that doesn't looks like a random enough hash. Ideally it will be great if you can point me to an optimized C/C++ implementation, but any pointers in the right direction will help.
Cipher's "prime base" idea should work decently - though the solution he posted looks a bit sketchy. I don't think there's any need for inverse multiplication in this method. Here's my solution: Say the string we currently have hashed is "abc", and we want to append "d" and remove "a". Just like Cipher, my basic hash algorithm will be: ``` unsigned hash(const string& s) { unsigned ret = 0; for (int i = 0; i < s.size(); i++) { ret *= PRIME_BASE; //shift over by one ret += s[i]; //add the current char ret %= PRIME_MOD; //don't overflow } return ret; } ``` Now, to implement sliding: ``` hash1 = [0]*base^(n-1) + [1]*base^(n-2) + ... + [n-1] ``` We'd like to add something at the end and remove the first value, so ``` hash2 = [1]*base^(n-1) + [2]*base^(n-2) + ... + [n] ``` First we can add the last letter: ``` hash2 = (hash1 * PRIME_BASE) + newchar; => [0]*base^n + [1]*base^(n-1) + ... + [n-1]*base + [n] ``` Then simply subtract the first character: ``` hash2 -= firstchar * pow(base, n); => [1]*base^(n-1) + ... + [n] ``` An important note: you have to be careful about overflow. You can choose to just let it overflow unsigned int, but I think it's much more prone to collision (but also faster!) Here's my implementation: ``` #include <iostream> #include <string> using namespace std; const unsigned PRIME_BASE = 257; const unsigned PRIME_MOD = 1000000007; unsigned hash(const string& s) { long long ret = 0; for (int i = 0; i < s.size(); i++) { ret = ret*PRIME_BASE + s[i]; ret %= PRIME_MOD; //don't overflow } return ret; } int rabin_karp(const string& needle, const string& haystack) { //I'm using long longs to avoid overflow long long hash1 = hash(needle); long long hash2 = 0; //you could use exponentiation by squaring for extra speed long long power = 1; for (int i = 0; i < needle.size(); i++) power = (power * PRIME_BASE) % PRIME_MOD; for (int i = 0; i < haystack.size(); i++) { //add the last letter hash2 = hash2*PRIME_BASE + haystack[i]; hash2 %= PRIME_MOD; //remove the first character, if needed if (i >= needle.size()) { hash2 -= power * haystack[i-needle.size()] % PRIME_MOD; if (hash2 < 0) //negative can be made positive with mod hash2 += PRIME_MOD; } //match? if (i >= needle.size()-1 && hash1 == hash2) return i - (needle.size()-1); } return -1; } int main() { cout << rabin_karp("waldo", "willy werther warhol wendy --> waldo <--") << endl; } ```
Some pointers for a fast implementation: 1. Avoid modulo n operation (% in C like languages) use mask n - 1, where n is 2^k, include the operations for the hash table lookup. Yes, it's possible to produce good hash with a non-prime moduli. 2. Pick multipliers and exponents with good figures of merit, see [this paper](http://www.ams.org/mcom/1999-68-225/S0025-5718-99-00996-5/S0025-5718-99-00996-5.pdf) for details.
Fast implementation of Rolling hash
[ "", "c++", "hash", "" ]
Using the Magento Ecommerce system, is is possible to remove an item from the Admin Panel Navigation menu? More generally, is there a way to use the config override system to *remove* existing elements from a configuration? I know I can add to the navigation with an override that looks something like this ``` <?xml version="1.0"?> <config> <modules> <Company_Module> <version> 0.1.0 </version> </Company_Module> </modules> <adminhtml> <menu> <cms translate="title" module="cms"> <title>The CMS</title> <sort_order>70</sort_order> <children> <foo translate="title" module="cms"> <title>Foo Item</title> <action>adminhtml/foo</action> </foo> </children> </cms> </menu> </adminhtml> </config> ``` but how would/could I completely suppress the CMS navigation item?
Cleaner way to do this: Add a **adminhtml.xml** (e.g. to an existing modules that keeps all other customization stuff, or create a new module) ``` <?xml version="1.0" ?> <config> <menu> <xmlconnect> <disabled>1</disabled> </xmlconnect> </menu> </config> ```
You could inject a bogus module dependency into the menu item in your config.xml. In your case, ``` <adminhtml> <menu> <cms translate="title" module="cms"> <depends><module>HideMe</module></depends> </cms> </menu> </adminhtml> ```
Removing an Item from Magento's Admin Panel Navigation
[ "", "php", "xml", "magento", "navigation", "overriding", "" ]
I have images displayed in a GridView as in [this tutorial](http://developer.android.com/guide/tutorials/views/hello-gridview.html). I want to be able to click on a single image and do other events and I need to know what image was clicked. Do I have to add imageView.onKeyDown(keyCode, event) in the ImageAdapter class? Here is the code as it currently exists: ``` @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some attributes imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(85, 85)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(8, 8, 8, 8); //does this need imageView.onKeyDown(keyCode, event)? } else { imageView = (ImageView) convertView; } imageView.setImageResource(mThumbIds[position]); return imageView; } ``` How will it indicate what image was clicked? How do I create the proper handler?
For a GridView you can use the setOnItemClickListener method to have an OnItemClickListener listener. That listener will give you a method that you must override with the signature ``` onItemClick(AdapterView<?> parent, View v, int position, long id) ``` where you get the position of the item in the grid that was clicked and the View that is inside the cell of the grid. Is that what you need?
I was able to get the position of the clicked image by making the position final and adding an onClick listener to the imageView. This logs the position of the image that was clicked. ``` @Override public View getView(final int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some attributes imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(85, 85)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(8, 8, 8, 8); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d("onClick","position ["+position+"]"); } }); } else { imageView = (ImageView) convertView; } imageView.setImageResource(mThumbIds[position]); return imageView; } ```
Create a clickable image in a GridView in Android
[ "", "java", "android", "android-gridview", "clickable-image", "" ]
Is there a place to find a list of the possible values for the PHP predefined constant `PHP_OS` ? I'd like to use this value for a system requirements check, but need to know how different operating systems are named in this variable. Through some searching, so far I've compiled the following list: * CYGWIN\_NT-5.1 * Darwin * FreeBSD * HP-UX * IRIX64 * Linux * NetBSD * OpenBSD * SunOS * Unix * WIN32 * WINNT * Windows If anyone has a more complete list, or knows of any additional values I'd love to hear them!
PHP [passes through the uname](https://github.com/php/php-src/blob/0d51ebd1a54af59d915c551a240b56bb3f0e26a6/configure.in#L1300), [except on Windows (`WINNT`)](https://github.com/php/php-src/blob/0d51ebd1a54af59d915c551a240b56bb3f0e26a6/main/main.c#L2022) and [Netware (`Netware`)](https://github.com/php/php-src/blob/0d51ebd1a54af59d915c551a240b56bb3f0e26a6/configure.in#L1292). See [Wikipedia](http://en.wikipedia.org/wiki/Uname#Table_of_standard_uname_output) for a non-exhaustive list of values not mentioned in your question: * CYGWIN\_NT-5.1 * IRIX64 * SunOS * HP-UX * OpenBSD (not in Wikipedia)
I think a better solution to do a 'requirement check' would be to actually use things that you need to know work properly and see what happens. For example, there are constants for directory separators, functions like realpath(), etc to deal with directories on different operating systems. What, specifically, are you trying to do?
Possible Values For: PHP_OS
[ "", "php", "superglobals", "" ]
I'm trying to find a way to display one link to an IE user and another link to all other browsers using javascript or conditional comments (or whatever it takes). Basically... ``` //pseudo code <!--[if IE]> <a href"ie-only.html">click here!</a> <!--[else]> <a href"all-other-browsers.html">click here!</a> <![endif]--> ``` I don't think this is possible with conditional comment tags (which only work in internet explorer). Plus I don't think there is an "else" statement. Is there a way to do this with javascript? Please help! Thanks!
> I don't think this is possible with conditional comment tags (which only work in internet explorer) Sure it is. You just have to leave the content for non-IE browsers in a position such that it's part of a conditional comment clause but not actually inside a <!-- comment -->. Then browsers that don't know about conditional comments will see the content fine. This is known as a [downlevel-revealed](http://msdn.microsoft.com/en-us/library/ms537512(VS.85).aspx#dlrevealed) conditional comment. Unfortunately the markup Microsoft give you there is invalid HTML (and not even well-formed XML). To make it pass muster you just need a few additional ‘--’s: ``` <!--[if IE]> This is IE! <![endif]--> <!--[if !IE]><!--> This ain't IE! <!--<![endif]--> ``` Although I have to echo AnonJr's non-answer, in that it's rare you should need a completely separate link/page for IE compared to other browsers. If you're doing something tricky like complex VML and ActiveX work in IE with Flash on other browsers I guess there could be a reason for it, but usually a few CSS and script hacks over the same basic page should suffice.
This is not going to be the popular answer, but its damn time somebody started posting it - stop with the browser-specific junk. You're only perpetuating future problems when new versions come out. If developers had taken the additional time (yes, it takes time and hard work. If you can't convince your clients you aren't trying hard enough) then we wouldn't have seen IE7 "break the web" and there would have been even less of a brouhaha with IE8. Yes, IE is less standards compliant than the others. But, Fx is also missing certain things that are a part of the standard too. They all suck when it comes to "standards". But they are all getting better. (At different rates, but they are all getting better.) Think first why you are trying to do this, and ask yourself if you really want to deal with this when the next browser version comes out and you have to re-jigger your browser detection and how you handle version X of browser Y. [/rant] **Edit:** To answer some of the comments that point out the obvious fact that I didn't really answer the question, without more information this question makes me wonder if we're not trying to help a person decide to [hammer in a nail with a glass bottle or a shoe...](http://weblogs.asp.net/alex_papadimoulis/archive/2005/05/25/408925.aspx)
How to display browser specific HTML?
[ "", "javascript", "html", "conditional-statements", "browser-detection", "" ]
Ok, so I ended up writing my own game engine based on top of XNA, and I am just wondering what else I need to make a complete engine. This is what's in the engine: * Physics (Farseer Physics) * Particle Engine (Mercury Project) * 2D Cameras * Input Handling * Screen Management (Menus, Pause Screen, etc.) * Sprite ( Animation, Sprite Sheets) * And XNA stuff like Sound. **Am I missing anything that might be crucial to a game engine?**
A theme or market for your engine. If you're doing anything beyond basic your basic graphics engine, you'll want to concentrate on a market for your engine, like RPG, strategy, puzzle, platformer, action, or FPS (ok, not FPS). This will help you point yourself in the direction you need to go in order to make further enhancements to the engine without asking us. An engine like say, the Unreal Engine, can do multiple things, but what it tends to do best is what it's made for, FPS games. Likewise, you should tailor your engine so that it suits a particular field of interest, and therefore is picked up for that type of gameplay. You can make it general to a point, but realize the more generalized your engine is, the harder it is to program, both time wise and skill wise. Other programmers are also less likely to pick up a general engine (unless that's all there is) if a more specific platform is available. Or to just write their own since modifying a generalized engine is about as hard as creating your own.
You're approaching it in an upside-down manner. What should be in your engine is the following: *All the code that turned out to be common between your first and your second game.* First, write a game. Don't write an engine, because, as you have found out, you don't know what it should contain, or how it should be designed. Write a game instead. Once you have that game, write *another* game. Then, when you have done that, examine the second game's code. How much of it was reused from the first game? Anything that was reused should then be refactored out into a separate project. That project is now your game engine. This doesn't mean that you shouldn't plan, or shouldn't try to write nice code. But make sure you're working towards something concrete, something where you can tell a good implementation from a bad one. A good implementation of a game, is one that works, is fun, and doesn't crash. Write your code to achieve those things first. A good implementation of an engine? That's trickier. What's a good implementation of a renderer? Of an AI framework? Of a particle system? Ultimately, the only way to determine whether you have a good engine is by seeing how well it works *in an actual game*. So if you don't have a game, you have no way to evaluate your engine. And if you have no way to evaluate your engine, you have no way of judging whether any of the code you're writing is actually useful.
What Should Be in a 2D Game Engine?
[ "", "c#", "xna", "" ]
I'm playing around with TMP in GCC 4.3.2's half-implementation of C++11, and I was wondering if there was a way to somehow do the following: ``` template <char x, char... c> struct mystruct { ... }; int main () { mystruct<"asdf">::go(); } ``` It obviously won't let me do it just like that, and I thought I'd get lucky by using user-defined literals to transform the "asdf" string during compile-time, but GCC 4.3 doesn't support user-defined literals... Any suggestions? I'd prefer to not do 'a','s','d','f', since this severely hampers my plans for this project.
Sadly, you still have to split it into separate characters, eg: ``` myTemplate<'s','t','r','i','n','g'> ``` In my humble opinion, this is a huge oversight in the new standard. Some other people agreed, and tried to implement the behavior in GCC with pretty good results. You can find that thread [here](http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/9b0edd169ba2ce3c). Edit: Some weird problems with the link, so cut and paste from this: <http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/9b0edd169ba2ce3c>
I solved a problem similar to this. We needed a different type for each name ``` template< const char* the_name > class A { public: const char* name( void ) { return the_name; } }; extern const char g_unique_name[]; // defined elsewhere typedef A<g_unique_name> A_unique; ``` This will gave you compile time access to the name, and unique instantiation. It however will not let you access the individual characters at run time. If you want individual character access the only way to achieve it is with a user defined literal. C++0x will be extended to allow the syntax in your main function above but it will still bind the template to a character pointer not to a compile time array of characters.
Template Meta-programming with Char Arrays as Parameters
[ "", "c++", "templates", "gcc", "c++11", "metaprogramming", "" ]
There are some Delegates predefined in C# I know these: ``` EventHandler // Default event callbacks EventHandler<T> // Default event callbacks with custom parameter (inheriting from EventArgs) Action // Function without return value and without parameter Action<T1, T2, T3, T4> // Function without return value and 1-4 parameters Func<T1, T2, T3, T4, TResult> // Methos with 0-4 parameters and one result type Predicate<T> // equivalent to Func<T, bool> ``` There are many more for special cases and generated form parts of the framework, but these are often good to use in self written code. If you know some more useful add them. Otherwise this is answered.
They're not predefined in C#. They're defined by the *framework*. The `Action` and `Func` delegate families are wider than you've shown - they go up to ``` Action<T1, T2, T3, T4> ``` and ``` Func<T1, T2, T3, T4, TResult> ``` Another common-ish one in .NET 2.0 for list manipulation (before LINQ) is `Predicate<T>`. For working with threads: ``` ThreadStart ParameterizedThreadStart WaitCallback TimerCallback AsyncCallback ```
I like to use `Predicate<T>` which is equivalent to `Func<T, bool>`
Standard delegates in C#
[ "", "c#", "list", "delegates", "" ]
``` $genreList; function directorGen($array) { foreach($array as $value) { $genreList[] = $value; } } //later.. directorGen($title->genres()); ``` This code results in a NULL array. If I replace $genreList[] = $value with echo $value everything prints out like expected. Any ideas?
If `$genreList` is a global variable, there's your problem: it's a scope issue. It can easily be fixed with: ``` $genreList = array(); function directorGen($array) { global $genreList; foreach($array as $value) { $genreList[] = $value; } } ``` **Note:** while not strictly necessary I also initialized it, which I think is good practice. If `directorGen()` is a member function and `$genreList` is a data member then change to: ``` function directorGen($array) { foreach($array as $value) { $this->genreList[] = $value; } } ```
Where is `$genreList` defined? It may just be a function-local variable, in which case it's lost when the function exits. If it's a class-level variable, remember to use `$this->genreList` instead. **Edit** My mistake. If it's a global variable, you need to add this to the top of the function in order for PHP to find it: ``` global $genreList; ```
What's wrong with my PHP array?
[ "", "php", "arrays", "foreach", "" ]
As far as I can tell, these two pieces of javascript behave the same way: **Option A:** ``` function myTimeoutFunction() { doStuff(); setTimeout(myTimeoutFunction, 1000); } myTimeoutFunction(); ``` **Option B:** ``` function myTimeoutFunction() { doStuff(); } myTimeoutFunction(); setInterval(myTimeoutFunction, 1000); ``` Is there any difference between using [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) and [setInterval](https://developer.mozilla.org/en-US/docs/Web/API/setInterval)?
They essentially try to do the same thing, but the `setInterval` approach will be more accurate than the `setTimeout` approach, since `setTimeout` waits 1000ms, runs the function and then sets another timeout. So the wait period is actually a bit more than 1000ms (or a lot more if your function takes a long time to execute). Although one might think that `setInterval` will execute **exactly** every 1000ms, it is important to note that `setInterval` will also delay, since JavaScript isn't a multi-threaded language, which means that - if there are other parts of the script running - the interval will have to wait for that to finish. In [this Fiddle](http://jsfiddle.net/GustvandeWal/295jqqqb/), you can clearly see that the timeout will fall behind, while the interval is almost all the time at almost 1 call/second (which the script is trying to do). If you change the speed variable at the top to something small like 20 (meaning it will try to run 50 times per second), the interval will never quite reach an average of 50 iterations per second. The delay is almost always negligible, but if you're programming something really precise, you should go for a *self-adjusting timer* (which essentially is a timeout-based timer that constantly adjusts itself for the delay it's created)
> Is there any difference? Yes. A Timeout executes a certain amount of time after setTimeout() is called; an Interval executes a certain amount of time after the previous interval fired. You will notice the difference if your doStuff() function takes a while to execute. For example, if we represent a call to setTimeout/setInterval with `.`, a firing of the timeout/interval with `*` and JavaScript code execution with `[-----]`, the timelines look like: ``` Timeout: . * . * . * . * . [--] [--] [--] [--] Interval: . * * * * * * [--] [--] [--] [--] [--] [--] ``` The next complication is if an interval fires whilst JavaScript is already busy doing something (such as handling a previous interval). In this case, the interval is remembered, and happens as soon as the previous handler finishes and returns control to the browser. So for example for a doStuff() process that is sometimes short ([-]) and sometimes long ([-----]): ``` . * * • * • * * [-] [-----][-][-----][-][-] [-] ``` • represents an interval firing that couldn't execute its code straight away, and was made pending instead. So intervals try to ‘catch up’ to get back on schedule. But, they don't queue one on top of each other: there can only ever be one execution pending per interval. (If they all queued up, the browser would be left with an ever-expanding list of outstanding executions!) ``` . * • • x • • x [------][------][------][------] ``` x represents an interval firing that couldn't execute or be made pending, so instead was discarded. If your doStuff() function habitually takes longer to execute than the interval that is set for it, the browser will eat 100% CPU trying to service it, and may become less responsive. > Which do you use and why? Chained-Timeout gives a guaranteed slot of free time to the browser; Interval tries to ensure the function it is running executes as close as possible to its scheduled times, at the expense of browser UI availability. I would consider an interval for one-off animations I wanted to be as smooth as possible, whilst chained timeouts are more polite for ongoing animations that would take place all the time whilst the page is loaded. For less demanding uses (such as a trivial updater firing every 30 seconds or something), you can safely use either. In terms of browser compatibility, setTimeout predates setInterval, but all browsers you will meet today support both. The last straggler for many years was IE Mobile in WinMo <6.5, but hopefully that too is now behind us.
What's the difference between recursive setTimeout versus setInterval?
[ "", "javascript", "setinterval", "" ]
I have a code here and I would like that it will display the first 10 and if I click on that, it will display again the second batch. I tried this first with my first for-code and it work now I'm working with arrays it seems it didn't accept it The one I commented dont work? is this wrong? Thanks ``` long [] potenzen = new long[32]; potenzen[0] = 1; for (int i = 1; i < potenzen.Length; ++i) { potenzen[i] = potenzen[i-1] * 2; //if (potenzen % 10 == 0) // Console.ReadLine(); } foreach (long elem in potenzen) { Console.WriteLine(" " + elem); } ```
``` long [] potenzen = new long[32]; potenzen[0] = 1; for (int i = 1; i < potenzen.Length; ++i) { potenzen[i]=potenzen[i-1]*2; Console.WriteLine(potenzen[i-1]); if (i % 10 == 0) Console.ReadLine(); } ``` is more in line with what you want. An improvement would be to separate your data-manipulation logic from your data display logic. ``` long [] potenzen = new long[32]; potenzen[0] = 1; for (int i = 1; i < potenzen.Length; ++i) potenzen[i]=potenzen[i-1]*2; for (int i = 0; i < potenzen.Length; ++i) { Console.WriteLine(potenzen[i]); if (i % 10 == 0) Console.ReadLine(); } ``` Of course, you could do this without an array ``` long potenzen = 1; for (int i = 1; i < 32; ++i) { Console.WriteLine(potenzen); potenzen = potenzen * 2; if (i % 10 == 0) Console.ReadLine(); } ```
You need: ``` if (i % 10 == 0) ``` and not: ``` if (potenzen % 10 == 0) ```
Modulus (%) in for-loop
[ "", "c#", "arrays", "" ]
I have a controller action that effectively simply returns a JsonResult of my model. So, in my method I have something like the following: ``` return new JsonResult(myModel); ``` This works well, except for one problem. There is a date property in the model and this appears to be returned in the Json result like so: ``` "\/Date(1239018869048)\/" ``` How should I be dealing with dates so they are returned in the format I require? Or how do I handle this format above in script?
Just to expand on [casperOne's answer](https://stackoverflow.com/questions/726334/asp-mvc-jsonresult-date-format/726417#726417). The [JSON spec](http://www.json.org/) does not account for Date values. MS had to make a call, and the path they chose was to exploit a little trick in the javascript representation of strings: the string literal "/" is the same as "\/", and a string literal will *never* get serialized to "\/" (even "\/" must be mapped to "\\/"). See <http://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_topic2> for a better explanation (scroll down to "From JavaScript Literals to JSON") > One of the sore points of JSON is the > lack of a date/time literal. Many > people are surprised and disappointed > to learn this when they first > encounter JSON. The simple explanation > (consoling or not) for the absence of > a date/time literal is that JavaScript > never had one either: The support for > date and time values in JavaScript is > entirely provided through the Date > object. Most applications using JSON > as a data format, therefore, generally > tend to use either a string or a > number to express date and time > values. If a string is used, you can > generally expect it to be in the ISO > 8601 format. If a number is used, > instead, then the value is usually > taken to mean the number of > milliseconds in Universal Coordinated > Time (UTC) since epoch, where epoch is > defined as midnight January 1, 1970 > (UTC). Again, this is a mere > convention and not part of the JSON > standard. If you are exchanging data > with another application, you will > need to check its documentation to see > how it encodes date and time values > within a JSON literal. For example, > Microsoft's ASP.NET AJAX uses neither > of the described conventions. Rather, > it encodes .NET DateTime values as a > JSON string, where the content of the > string is /Date(ticks)/ and where > ticks represents milliseconds since > epoch (UTC). So November 29, 1989, > 4:55:30 AM, in UTC is encoded as > "\/Date(628318530718)\/". A solution would be to just parse it out: ``` value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10)); ``` However I've heard that there is a setting somewhere to get the serializer to output `DateTime` objects with the `new Date(xxx)` syntax. I'll try to dig that out. --- The second parameter of `JSON.parse()` accepts a `reviver` function where prescribes how the value originally produced by, before being returned. Here is an example for date: ``` var parsed = JSON.parse(data, function(key, value) { if (typeof value === 'string') { var d = /\/Date\((\d*)\)\//.exec(value); return (d) ? new Date(+d[1]) : value; } return value; }); ``` See the docs of [JSON.parse()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)
Here's my solution in Javascript - very much like JPot's, but shorter (and possibly a tiny bit faster): ``` value = new Date(parseInt(value.substr(6))); ``` "value.substr(6)" takes out the "/Date(" part, and the parseInt function ignores the non-number characters that occur at the end. EDIT: I have intentionally left out the radix (the 2nd argument to parseInt); see [my comment below](https://stackoverflow.com/questions/726334/asp-net-mvc-jsonresult-date-format/1767558#comment23310086_1767558). Also, please note that ISO-8601 dates are preferred over this old format -- so this format generally shouldn't be used for new development. For ISO-8601 formatted JSON dates, just pass the string into the Date constructor: ``` var date = new Date(jsonDate); //no ugly parsing needed; full timezone support ```
ASP.NET MVC JsonResult Date Format
[ "", "javascript", "asp.net-mvc", "json", "" ]
the [empty selector](http://docs.jquery.com/Selectors/empty) says that: Matches all elements that have no children (including text nodes). Finds all elements that are empty - they don't have child elements or text. What i want is to get elements which has no children but may have text inside., how? **UPDATE:** Example: I want select these elements which has no children but may have text, with syntax like this: ``` $('div:empty, a:empty, span, p:empty, td:empty, img, input').mousemove(myMouseOverHandler); ```
Get any element that doesn't have any other element: ``` $('*:not(:has(*))'); ```
If an element has only text, [`children()`](http://docs.jquery.com/Traversing/children) will have a length of `0`: ``` <div id="test1"> Hello World </div> <div id="test2"> <b>Hey there</b> </div> <script> alert($("#test1").children().length); // alerts 0 alert($("#test2").children().length); // alerts 1 (the bold tag) </script> ``` **EDIT**: In response to your edit, jQuery is awesome enough to let you do custom filters: ``` $.expr[':'].emptyOrText = function(e) { return $(e).children().length == 0; }; ``` So, using the above against the HTML above, you could do this: ``` $('div:emptyOrText'); // will select #test1 ```
How to get elements which have no children, but may have text?
[ "", "javascript", "jquery", "html", "" ]
In Oracle 10i, I'm running the following command: ``` ALTER TABLE jnrvwchnglst ADD ( jnrvwchnglst_userid NUMBER(10) NOT NULL DEFAULT 1 ) ``` Yes `jnrvwchnglst` is an existing table and no `jnrvwchnglst_userid` is not an existing column. The Oracle error message is: ``` ORA-00907: missing right parenthesis ``` What's wrong with this query and why does Oracle think I'm missing a parenthesis?
``` ALTER TABLE jnrvwchnglst ADD ( jnrvwchnglst_userid NUMBER(10) DEFAULT 1 NOT NULL ) ```
"(NOT) NULL" must be the last statement in the "ALTER" syntactically when present, so when Oracle saw that - and that the next char (your "DEFAULT" stmt) wasn't the expected terminating right ")", threw the error.
Why does Oracle think I'm missing a right parenthesis?
[ "", "sql", "oracle", "ora-00907", "" ]
I want to hide all blocks which only contain hidden DIVs (aside from a caption). All elements have to be selected via class names. In detail, I want each "eventBlock" not to show up when all "groupBlocks" underneath are already hidden. The same with "Menu" which should not show up when all child eventBlocks are hidden. Each "Menu" contains multiple eventBlocks, each "eventBlock" contains 1 or more groupBlocks. I am using classes and cannot use IDs because there are lots of groupBlocks, eventBlocks etc. DIVs are hidden using JQuery's "hide()" function, if it's relevant. My HTML basically looks like this: ``` <div class="Menu"> <strong><a name="one">Menu CAPTION</a></strong><br /> <div class="eventBlock event1"> <p class="underlined">eventBlock CAPTION</p> <div class="groupBlock group2"> <strong>name</strong><br /> 4pm - 6pm<br /> </div> <div class="groupBlock group1"> <strong>name</strong><br /> 5pm - 7pm<br /> </div> </div> </div> ```
``` $('eventBlock').each(function() { if ($('.groupBlock:visible', this).length) $(this).show(); else $(this).hide(); }); ``` could be implemented as plugin
This should work: ``` var blocks = jQuery(".groupBlock"); if( blocks.size() == blocks.not(":visible").size() ) { blocks.parents(".eventBlock").hide(); } ``` You can do something similar to hide the menu if all groupBlocks are hidden.
How can I hide elements which only contain hidden DIVs in jQuery?
[ "", "javascript", "jquery", "" ]
I'd like to set up a multidimensional list. For reference, I am working on a playlist analyzer. I have a file/file-list, which my program saves in a standard list. One line from the file in each list entry. I then analyze the list with regular-expressions to find specific lines. Some of the data/results from the lines needs to be put into a new **multidimensional** list; since I don't know how many results/data I'll end up with, I can't use a multidimensional array. Here is the data I want to insert: ``` List ( [0] => List ( [0] => Track ID [1] => Name [2] => Artist [3] => Album [4] => Play Count [5] => Skip Count ) [1] => List ( And so on.... ``` Real Example: ``` List ( [0] => List ( [0] => 2349 [1] => The Prime Time of Your Life [2] => Daft Punk [3] => Human After All [4] => 3 [5] => 2 ) [1] => List ( ``` So yeah, mlist[0][0] would get TrackID from song 1, mlist[1][0] from song 2 etc. But I am having huge issues creating a multidimensional list. So far I have come up with ``` List<List<string>> matrix = new List<List<string>>(); ``` But I haven't really had much more progress :(
Well you certainly *can* use a `List<List<string>>` where you'd then write: ``` List<string> track = new List<string>(); track.Add("2349"); track.Add("The Prime Time of Your Life"); // etc matrix.Add(track); ``` But why would you do that instead of building your own class to represent a track, with Track ID, Name, Artist, Album, Play Count and Skip Count properties? Then just have a `List<Track>`.
As [Jon Skeet](https://stackoverflow.com/questions/665299/is-a-2-multidimensional-lists-possible/665304#665304) mentioned you can do it with a `List<Track>` instead. The Track class would look something like this: ``` public class Track { public int TrackID { get; set; } public string Name { get; set; } public string Artist { get; set; } public string Album { get; set; } public int PlayCount { get; set; } public int SkipCount { get; set; } } ``` And to create a track list as a `List<Track>` you simply do this: ``` var trackList = new List<Track>(); ``` Adding tracks can be as simple as this: ``` trackList.add( new Track { TrackID = 1234, Name = "I'm Gonna Be (500 Miles)", Artist = "The Proclaimers", Album = "Finest", PlayCount = 10, SkipCount = 1 }); ``` Accessing tracks can be done with the indexing operator: ``` Track firstTrack = trackList[0]; ```
Are 2 dimensional Lists possible in c#?
[ "", "c#", "list", "" ]
I am trying to send something to serial port (r232) with PHP. I am using this class: <http://www.phpclasses.org/browse/package/3679.html> The problem is that I am allowed to send only 1 byte. But if I send something like "1", I am actually sending 49 (ASCII for 1). Instead of send("1"), I tried with send(1) but it is no good, because this is integer which has 2 bytes. So is there a way to send a "real" char, not ASCII equivalent?
The [chr()](https://www.php.net/chr) function returns a character given by the integer for the corresponding ascii character.
It looks like the library is expecting characters as input. If you need to send the character which would encode to `0x01`, you just send "\001". The function chr() would convert characters to integer values and would be no use here. One more thing: The byte size of integers depends on the underlying system and is mostly 4 bytes.
Non ASCII char in PHP?
[ "", "php", "serial-port", "char", "ascii", "" ]
I typically code in VB.NET, but I'm going through a tutorial in C# .NET right now. I'm expecting to see a drop down list for selecting methods and properties at the top of the code file, right underneath the tabs for the code files I have open. However, I do not see these. If I open VB code, it works just fine. I've tried to look for an option in Visual Studio that I don't have turned on, but I can't find what I'm missing. Anybody have any ideas?
Go to Tools->Options->Text Editor->C#->General and check "Navigation Bar"
If you want to access the events, you can do it on design mode on upper border of the properties box, there is a "thunder" where you can access them, this part is different from that of VBasic
Can't see Methods, etc. in Visual Studio 2008 C# Code
[ "", "c#", ".net", "visual-studio", "visual-studio-2008", "" ]
I have in a MySQL table a DATE column that represents the date in this format: YYYY-MM-DD. I wanto to retrieve the date from the database using PHP but display it like this: DD Month, YYYY. From '2009-04-13' to '13 April, 2009' for example. Witch is the best way to do it?? ( I know how to get the date from the DB. I only need to know how to convert it) I also need to display the month names in Spanish. There is a way to do it without translating each month using strplc or something like that?? I'm new to programming, please be detailed. Thanks!!!
Refer to [DATE\_FORMAT()](http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format) function in MySQL. I guess that's the best way for you to do it. Also, you can make this: * Fetch your date from DB * Use [strtotime](http://www.php.net/strtotime) in PHP, to convert to unix time * Then format the time using [date](http://www.php.net/date). By using date() you'll be able to get months names in Spanish when you set your locale in PHP with [setlocale](https://www.php.net/manual/en/function.setlocale.php).
Execute following MySQL queries: ``` SET lc_time_names = 'es_ES'; SELECT DATE_FORMAT(t.date,'%e de %M, %Y') FROM your_table t ... ``` With MySQLi it'll be: ``` $mysqli->query("SET lc_time_names = 'es_ES'"); $stmt = $mysqli->prepare("SELECT DATE_FORMAT(t.date,'%e de %M, %Y') FROM your_table t ...where id = ?"); ... ```
PHP/MySQL: Convert from YYYY-MM-DD to DD Month, YYYY?
[ "", "php", "mysql", "datetime", "" ]
Consider i execute a method 'Method1' in C#. Once the execution goes into the method i check few condition and if any of them is false, then the execution of Method1 should be stopped. how can i do this, i.e can the execution of a method when certain conditions are met.? but my code is something like this, ``` int Method1() { switch(exp) { case 1: if(condition) //do the following. ** else //Stop executing the method.** break; case2: ... } } ```
Use the `return` statement. ``` if(!condition1) return; if(!condition2) return; // body... ```
I think this is what you are looking for. ``` if( myCondition || !myOtherCondition ) return; ``` Hope it answered your question. ## Edit: If you want to exit the method due to an error you can throw an exception like this: ``` throw new Exception( "My error message" ); ``` If you want to return with a value, you should return like before with the value you want: ``` return 0; ``` If it is the Exception you need you can catch it with a try catch in the method calling your method, for instance: ``` void method1() { try { method2( 1 ); } catch( MyCustomException e ) { // put error handling here } } int method2( int val ) { if( val == 1 ) throw new MyCustomException( "my exception" ); return val; } ``` MyCustomException inherits from the Exception class.
How to cancel the execution of a method?
[ "", "c#", "" ]
> **Possible Duplicate:** > [Warning: mysql\_fetch\_array(): supplied argument is not a valid MySQL result](https://stackoverflow.com/questions/795746/warning-mysql-fetch-array-supplied-argument-is-not-a-valid-mysql-result) i have an error being drawn with this code: ``` <?php include "config.inc.php"; mysql_query($addClient) or die(mysql_error()); $sth = mysql_query( sprintf( "SELECT c_id,p_id,p_title FROM projects WHERE c_id = %s", mysql_real_escape_string($_GET['id']) ) ); $projects = array(); while($r = mysql_fetch_array($sth)) { $projects[] = array('id' => $r['p_id'], 'name' => $r['p_title']); } print json_encode($projects); exit; ?> ``` I get this error: > **Warning**: mysql\_fetch\_assoc(): supplied argument is not a valid MySQL result resource in **/home/content/g/a/t/gatts316/html/clients/inc/get-projects.php** on line **10** > > []
I assume you changed mysql\_fetch\_assoc to mysql\_fetch\_array for testing... Anyway, the error should still persist. You forgot to enclose the string %s in your query between '': ``` $sth = mysql_query( sprintf( "SELECT c_id,p_id,p_title FROM projects WHERE c_id = '%s'", mysql_real_escape_string($_GET['id']) ) ); ```
Are you sure that is the right code? The error is referring to `mysql_fetch_assoc()` but there is no `mysql_fetch_assoc()` in the code you pasted. Where is `$addClient` defined? Perhaps something inside `config.inc.php` is wrong?
mysql_assoc error - displaying fine
[ "", "php", "" ]
I have an HTML editor widget that I want to appear within an absolutely positioned, fixed-size DIV. However, I don't know the absolute size of the DIV beforehand, and it may change, like if the user resizes the window. The editor, naturally, has controls and an editable area. Each has their own DIV. I want the controls to take up as much space as they need to, and the editable area to fill the rest of the space. If I use tables, this is extremely easy to achieve. I just turn off borders and padding and margins, and throw each DIV into a cell in its own row, and maybe fiddle with max-height on the controls DIV. This is what it looks like: [Base table http://img407.imageshack.us/img407/8435/table1.png](http://img407.imageshack.us/img407/8435/table1.png) [Same table with window resized another way http://img264.imageshack.us/img264/6438/table2p.png](http://img264.imageshack.us/img264/6438/table2p.png) Notice the editable section taking up as much space as possible without causing scrollbars to appear. I've monkeyed with various CSS examples and nothing seems to work without having some JavaScript run on resize to make the editable DIV be the height of the parent minus the height of the controls. Of course, I can make the parent DIV have display:table and the child DIVs wrapped in display:table-row DIVs and themselves have display:table-cell, but...well...in that case it's exactly the same as using TABLE, TR, and TD, but ten times more ugly for the sake of CSS purity. (Why bother?) So, without directly using display:table & friends, nor TABLE/TR/TD, nor JavaScript, is there a pure CSS way of doing this? In other words, is there a pure CSS way of saying, DIV1, take up as little vertical space as possible, and DIV2, take up the remaining vertical space within the parent element? If there isn't, I'm quite ready to stop subscribing to the "pure CSS" mentality. It's caused me enough grief with very little developer or end-user benefit.
You only have so many options. If you want table-like behavior without using a table then use display:table and give yourself the option of changing your mind later. That way, while uglier in the markup (subjective), makes more sense to me: you'll end up with a few more elements, but you won't be locked in to a specific layout. If you don't care about the markup then pull the trigger and use a table. This will be easier in the short-term. My question: If you don't want to use JavaScript, how will you be implementing your editor controls?
This question speaks to a problem I see a lot of people faced with lately: obey the "only use tables for tabular data" rule, or just use tables and do 1/3 the work. The fact that this is even a difficult decision is a demonstration of how standards-crazy we've all become. Forget the standards, use tables, get it done cleanly and simply. If W3C has a problem with that, they can complain right after they create a better alternative.
Pure CSS minimized-height header, maximized-height body within an absolutely positioned DIV
[ "", "javascript", "html", "css", "css-tables", "" ]
What's the best way to achieve Rails-like flash messages such as "Update successful" <http://api.rubyonrails.org/classes/ActionController/Flash.html>) in the Java world? I'm using Spring MVC.
I would recommend implementing this as a session-wide HashTable, with string keys mapping to custom FlashItem objects. The FlashItem will simply contain the object or string you're storing plus a boolean value, possibly called IsNew, which should be set to true when you insert a new item into the HashTable. On each page load you then iterate the HashTable, set any IsNew = true items to false, and delete any items where IsNew is already false. That should give you a work-alike to Rails's flash feature.
I have done just that in Spring MVC with a **session scoped** bean. ``` public class FlashImpl implements Flash, Serializable{ private static final long serialVersionUID = 1L; private static final String ERROR = "error"; private static final String WARNING = "warning"; private static final String NOTICE = "notice"; private String message; private String klass; public void message(String klass, String message) { this.klass = klass; this.message = message; } public void notice(String message) { this.message(NOTICE, message); } public void warning(String message) { this.message(WARNING, message); } public void error(String message) { this.message(ERROR, message); } public boolean isEmptyMessage() { return message == null; } public void clear() { this.message = null; this.klass = null; } public String getMessage() { String msg = message; this.clear(); return msg; } public void setMessage(String message) { this.message = message; } public String getKlass() { return klass; } public void setKlass(String klass) { this.klass = klass; }} ``` The trick is in consumming the message once it's been read for the first time. This way it can survive to a redirect after post. I am assuming that there will be only one type of message for request!. If you don't want this you could create a hashmap as already suggested. I inject this bean in my controllers (actually I inject it in a base controller inherited by all the others). In your JSP you have to add some code like this: ``` <c:if test="${!flash.emptyMessage}" > <div class="${flash.klass}">${fn:escapeXml(flash.message)}</div> </c:if> ```
Rails flash messages in Java
[ "", "java", "ruby-on-rails", "ruby", "spring-mvc", "" ]
Can anyone tell me why my redirect helper does not work the way I'd expect it to? I'm trying to redirect to the index method of my main controller, but it takes me `www.example.com/index/provider1/` when it should route to `www.example.com/provider1`. Does this make sense to anyone? I have index page in config set to blank, although I don't think that it is the issue. Does anyone have advice on how to fix this issue? **Controller**: ``` if($provider == '') { redirect('/index/provider1/', 'location'); } ``` **.htaccess**: ``` RewriteEngine on RewriteCond %{REQUEST_URI} !^(index\.php|files|images|js|css|robots\.txt|favicon\.ico) RewriteCond %{HTTP_HOST} ^example.com/ttnf/ RewriteRule (.*) http://www.example.com/ttnf/$1 [R=301,L] RewriteBase /ttnf/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] php_flag display_errors On ```
# redirect() ### URL Helper --- The redirect statement in code igniter sends the user to the specified web page using a redirect header statement. This statement resides in the URL helper which is loaded in the following way: ``` $this->load->helper('url'); ``` The redirect function loads a local URI specified in the first parameter of the function call and built using the options specified in your config file. The second parameter allows the developer to use different HTTP commands to perform the redirect "location" or "refresh". According to the Code Igniter documentation: "Location is faster, but on Windows servers it can sometimes be a problem." Example: ``` if ($user_logged_in === FALSE) { redirect('/account/login', 'refresh'); } ```
If your directory structure is like this, ``` site application controller folder_1 first_controller.php second_controller.php folder_2 first_controller.php second_controller.php ``` And when you are going to redirect it in same controller in which you are working then just write the following code. ``` $this->load->helper('url'); if ($some_value === FALSE/TRUE) //You may give 0/1 as well,its up to your logic { redirect('same_controller/method', 'refresh'); } ``` And if you want to redirect to another control then use the following code. ``` $this->load->helper('url'); if ($some_value === FALSE/TRUE) //You may give 0/1 as well,its up to your logic { redirect('folder_name/any_controller_name/method', 'refresh'); } ```
Redirect with CodeIgniter
[ "", "php", "codeigniter", "redirect", "urlhelper", "" ]
I'm looking for a resource in python or bash that will make it easy to take, for example, mp3 file X and m4a file Y and say "copy X's tags to Y". Python's "mutagen" module is great for manupulating tags in general, but there's no abstract concept of "artist field" that spans different types of tag; I want a library that handles all the fiddly bits and knows fieldname equivalences. For things not all tag systems can express, I'm okay with information being lost or best-guessed. (Use case: I encode lossless files to mp3, then go use the mp3s for listening. Every month or so, I want to be able to update the 'master' lossless files with whatever tag changes I've made to the mp3s. I'm tired of stubbing my toes on implementation differences among formats.)
I needed this exact thing, and I, too, realized quickly that mutagen is not a distant enough abstraction to do this kind of thing. Fortunately, the authors of mutagen needed it for their media player [QuodLibet](http://code.google.com/p/quodlibet/). I had to dig through the QuodLibet source to find out how to use it, but once I understood it, I wrote a utility called **sequitur** which is intended to be a command line equivalent to **ExFalso** (QuodLibet's tagging component). It uses this abstraction mechanism and provides some added abstraction and functionality. If you want to check out the source, [here's a link to the latest tarball](http://jeremycantrell.com/files/python-qlcli.tar.gz). The package is actually a set of three command line scripts and a module for interfacing with QL. If you want to install the whole thing, you can use: ``` easy_install QLCLI ``` One thing to keep in mind about exfalso/quodlibet (and consequently sequitur) is that they actually implement audio metadata properly, which means that all tags support multiple values (unless the file type prohibits it, which there aren't many that do). So, doing something like: ``` print qllib.AudioFile('foo.mp3')['artist'] ``` Will not output a single string, but will output a list of strings like: ``` [u'The First Artist', u'The Second Artist'] ``` The way you might use it to copy tags would be something like: ``` import os.path import qllib # this is the module that comes with QLCLI def update_tags(mp3_fn, flac_fn): mp3 = qllib.AudioFile(mp3_fn) flac = qllib.AudioFile(flac_fn) # you can iterate over the tag names # they will be the same for all file types for tag_name in mp3: flac[tag_name] = mp3[tag_name] flac.write() mp3_filenames = ['foo.mp3', 'bar.mp3', 'baz.mp3'] for mp3_fn in mp3_filenames: flac_fn = os.path.splitext(mp3_fn)[0] + '.flac' if os.path.getmtime(mp3_fn) != os.path.getmtime(flac_fn): update_tags(mp3_fn, flac_fn) ```
Here's some example code, a script that I wrote to copy tags between files using Quod Libet's music format classes (not mutagen's!). To run it, just do `copytags.py src1 dest1 src2 dest2 src3 dest3`, and it will copy the tags in sec1 to dest1 (after deleting any existing tags on dest1!), and so on. Note the blacklist, which you should tweak to your own preference. The blacklist will not only prevent certain tags from being copied, it will also prevent them from being clobbered in the destination file. To be clear, Quod Libet's format-agnostic tagging is not a feature of mutagen; it is implemented *on top of* mutagen. So if you want format-agnostic tagging, you need to use `quodlibet.formats.MusicFile` to open your files instead of `mutagen.File`. Code can now be found here: <https://github.com/DarwinAwardWinner/copytags> If you also want to do transcoding at the same time, use this: <https://github.com/DarwinAwardWinner/transfercoder> One critical detail for me was that Quod Libet's music format classes expect QL's configuration to be loaded, hence the `config.init` line in my script. Without that, I get all sorts of errors when loading or saving files. I have tested this script for copying between flac, ogg, and mp3, with "standard" tags, as well as arbitrary tags. It has worked perfectly so far. As for the *reason* that I didn't use QLLib, it didn't work for me. I suspect it was getting the same config-related errors as I was, but was silently ignoring them and simply failing to write tags.
abstracting the conversion between id3 tags, m4a tags, flac tags
[ "", "python", "bash", "mp3", "m4a", "" ]
I am trying to insert values from one table in to the other, with an additonal parameter that is required. For instance: ``` INSERT INTO table1(someInt, someOtherInt, name, someBit) SELECT someInt, someOtherInt, name FROM table2 ``` someBit is not allowed to be null, and I need to set it to False, but I am not quite sure how use it in the same INSERT statement. (Im using SQL 2005 if it matters) edit: Ouch...looks like i threw out filet mignon to lions :-)
Maybe ``` INSERT INTO table1(someInt, someOtherInt, name, someBit) SELECT someInt, someOtherInt, name, 0 FROM table2 ```
Perhaps `INSERT INTO table1(someInt, someOtherInt, name, someBit) SELECT someInt, someOtherInt, name, 0 FROM table2` ?
inserting value in to SQL table and use SELECT statement
[ "", "sql", "sql-server", "" ]
I am using Spring MVC 2.5, and I am trying to get a JSTL form object to load from a GET request. I have Hibernate POJOs as my backing objects. There is one page directing to another page with a class id (row primary key) in the request. The request looks like "newpage.htm?name=RowId". This is going into a page with a form backing object, The newpage above, loads the fields of the object into editable fields, populated with the existing values of the row. The idea is, that you should be able to edit these fields and then persist them back into the database. The view of this page looks something like this ``` <form:form commandName="thingie"> <span>Name:</span> <span><form:input path="name" /></span> <br/> <span>Scheme:</span> <span><form:input path="scheme" /></span> <br/> <span>Url:</span> <span><form:input path="url" /></span> <br/> <span>Enabled:</span> <span><form:checkbox path="enabled"/></span> <br/> <input type="submit" value="Save Changes" /> </form:form> ``` The controller has this in it, ``` public class thingieDetailController extends SimpleFormController { public thingieDetailController() { setCommandClass(Thingie.class); setCommandName("thingie"); } @Override protected Object formBackingObject(HttpServletRequest request) throws Exception { Thingie thingieForm = (Thingie) super.formBackingObject(request); //This output is always null, as the ID is not being set properly logger.debug("thingieForm.getName(): [" + thingieForm.getName() + "]"); //thingieForm.setName(request.getParameter("name")); SimpleDAO.loadThingie(thingieForm); return thingieForm; } @Override protected void doSubmitAction(Object command) throws Exception { Thingie thingie = (Thingie) command; SimpleDAO.saveThingie(thingie); } } ``` As you can see from the commented code, I've tried manually setting the object id (name is this case) from the request. However Hibernate complains about the object being desynched when I try and persist the data in the form. ``` org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) ``` This error seems to do something to the entire session, which stops working for my entire web application, continually throwing the Stale Object State Exception seen above. If anyone familiar with Spring MVC can help me with this or suggest a workaround, I would really appreciate it. **EDIT:** Session factory code. ``` private static final SessionFactory sessionFactory; private static final Configuration configuration = new Configuration().configure(); static { try { // Create the SessionFactory from standard (hibernate.cfg.xml) // config file. sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); } catch (Throwable ex) { // Log the exception. System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } ```
One of the major flaws with using Spring MVC + hibernate is that the natural approach is to use the hibernate domain object as the backing object for the form. Spring will bind anything in the request based on name by DEFAULT. This inadvertently includes things like ID or name (usually the primary key) or other hibernate managed properties being set. This also makes you vulnerable to form injection. In order to be secure under this scenario you must use something like: ``` protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { String[] allowedFields = {"name", "birthday"} binder.setAllowedFields(allowedFields); } ``` and EXPLICITLY set the ALLOWED fields to only those in your form, and exclude the primary key or you will end up with a mess!!!
To answer your immediate question, the problem you are having with Hibernate has to do with the following sequence of events: 1. One Hibernate session is opened (let's call it session A) in `formBackingObject` 2. Using session A, you load a Thingie object in `formBackingObject` 3. You return the Thingie object as the result of `formBackingObject` 4. When you return the Thingie object, session A is closed, but Thingie is still linked to it 5. When `doSubmitAction` is called, the same instance of the `Thingie` backing object is passed as the command 6. A new Hibernate session (call it session B) is opened 7. You attempt to save the Thingie object (originally opened with session A) using session B Hibernate doesn't know anything about session A at this point, because it's closed, so you get an error. The good news is that you shouldn't be doing it that way, and the correct way will bypass that error completely. The `formBackingObject` method is used to populate a form's command object with data, prior to showing the form. Based on your updated question, it sounds like you are simply trying to display a form populated with information from a given database row, and update that database row when the form is submitted. It looks like you already have a model class for your record; I'll call that the `Record` class in this answer). You also have DAO for the `Record` class, which I will call `RecordDao`. Finally, you need a `UpdateRecordCommand` class that will be your backing object. The `UpdateRecordCommand` should be defined with the following fields and setters/getters: ``` public class UpdateRecordCommand { // Row ID of the record we want to update private int rowId; // New name private int String name; // New scheme private int String scheme; // New URL private int String url; // New enabled flag private int boolean enabled; // Getters and setters left out for brevity } ``` Then define your form using the following code: ``` <form:form commandName="update"> <span>Name:</span> <span><form:input path="name" /></span><br/> <span>Scheme:</span> <span><form:input path="scheme" /></span><br/> <span>Url:</span> <span><form:input path="url" /></span><br/> <span>Enabled:</span> <span><form:checkbox path="enabled"/></span><br/> <form:hidden path="rowId"/> <input type="submit" value="Save Changes" /> </form:form> ``` Now you define your form controller, which will populate the form in `formBackingObject` and process the update request in `doSubmitAction`. ``` public class UpdateRecordController extends SimpleFormController { private RecordDao recordDao; // Setter and getter for recordDao left out for brevity public UpdateRecordController() { setCommandClass(UpdateRecordCommand.class); setCommandName("update"); } @Override protected Object formBackingObject(HttpServletRequest request) throws Exception { // Use one of Spring's utility classes to cleanly fetch the rowId int rowId = ServletRequestUtils.getIntParameter(request, "rowId"); // Load the record based on the rowId paramrter, using your DAO Record record = recordDao.load(rowId); // Populate the update command with information from the record UpdateRecordCommand command = new UpdateRecordCommand(); command.setRowId(rowId); command.setName(record.getName()); command.setScheme(record.getScheme()); command.setUrl(record.getUrl()); command.setEnabled(record.getEnabled()); // Returning this will pre-populate the form fields return command; } @Override protected void doSubmitAction(Object command) throws Exception { // Load the record based on the rowId in the update command UpdateRecordCommand update = (UpdateRecordCommand) command; Record record = recordDao.load(update.getRowId()); // Update the object we loaded from the data store record.setName(update.getName()); record.setScheme(update.getScheme()); record.setUrl(update.getUrl()); record.setEnabled(update.setEnaled()); // Finally, persist the data using the DAO recordDao.save(record); } } ```
Spring MVC, generating a form backing object from a request?
[ "", "java", "hibernate", "spring-mvc", "" ]
I was writing some code in C#, and I found myself writing: ``` return new MyClass(... ``` when I noticed that both the `return` and the `new` were both C# keywords. So I wondered what is the longest legal sequence of keywords in C#. All I could think of is: ``` internal static override void MyFunc(... ``` Where `internal static override void` are all keywords. Can you think of a longer sequence of keywords? Note: There's really no point to the question. I'm just hoping to pour more some fun on the fire :-)
For 6: ``` new protected internal unsafe virtual decimal Foo() {...} ``` Edit for 7: ``` new protected internal unsafe virtual extern decimal Foo(); ``` If we allow brackets and braces... (**edited** the "lock", "new object()", "as" and "string" were contributed by others; see comments) ``` decimal Bar() { lock (new object() as string) { if (true) { checked { unsafe { try { do { return default(decimal); unchecked {break;} continue; } while (false); } catch { throw; } finally { } } } } } } ```
I guess it's infinite: ``` return null as string as string as string as string as string.... ```
What is the longest legal statement block you can make with only C# keywords?
[ "", "c#", "keyword", "" ]
For a user control with internal data structures that must be disposed, is the correct place to add that code to the Dispose method in the .designer.cs file, or is there an event or something we're meant to use instead? **Edit**: This is a winforms user control.
If you're talking about WinForms I usually take one of two approaches to solve this problem. **Approach 1** Open the Form.Designer.cs file. Inside the generated dispose method I add a call to DisposeCore. I then go back to Form.cs and add a DisposeCore method that will now be called during dispose. I add all of my dispose logic into this method. Editing the designer file is technically not supported. However I've found that this particular edit will not be washed away when the designer regenerates code. **Approach 2** Add a event handler to Form.Disposed and do my dispose logic in the handler. This is the preferable way because it's a supported operation and won't be affected by some designer generation you have yet to encounter.
Could you clarify what kind of controls? ASP.NET, WinForms? In ASP.NET you could: ``` protected override void OnUnload(EventArgs e){ base.OnUnload(e); //Unload here... } ```
Dispose on user controls, really meant to edit the .designer.cs file?
[ "", "c#", "controls", "dispose", "idisposable", "" ]
For a project I am considering building a Boggle type game in PHP. All of the solutions I have seen online have used some sort of tree or hash based approach. Are there any similar data structures built into PHP? Any advice on how to handle figuring out what words are present on a current board of letters?
PHP does have hash data structures built into the language. They are generally called associative arrays, though. [This website](http://www.bellaonline.com/articles/art31316.asp) has a very brief explanation of them.
Do you really need to figure out what words are available with the letters? A simple method would be to simply let the user guess a word, check that the correct letters exist on the board, then check that the word is a real word. This would be simple, however you would not be able to tell the user how many words are remaining.
PHP Boggle game
[ "", "php", "boggle", "" ]
I am writing a library of utility classes, many of which are singletons. I have implemented them as such using inheritance: ``` template <class T> class Singleton { public: T& getInstance() { if(m_instance == 0) { m_instance = new T; } return m_instance; } private: static T* m_instance; }; class SomeClass : public Singleton<SomeClass> { public: SomeClass() {} virtual ~SomeClass() {} void doSomething() {;} }; ``` Obviously this is a simple example, not an actual class. Anyways, I am finding that using code such as: ``` SomeClass::getInstance().doSomething(); ``` Will create more than one instance of SomeClass. I am thinking this may be due to the fact that it is being used outside my library (.a) file as well as internally. For example, I am using a UI library not written by myself which is separately compiled and to which I am making additions. Some of these additions utilize singletons which are also being used in my .a library. Is the separate compilation causing this? Something else? The only way I have managed to get around the issue is to create a global object in my main.cpp file which I initialize with any singletons I will need. Then all code accesses this common global object with calls such as: ``` GlobalObject::getSomeClass().doSomething() ``` I hate having to add an additional method to this object every time I create another singleton. Plus the syntax seems clearer and more familiar using the first access method: ``` SomeClass::getInstance().doSomething(); ``` Please let me know if you have any thoughts, opinions, etc. Thanks.
Your problem is that your template is going to be instantiated in more than one compilation unit as it is completely inline. Therefore in every compilation unit that uses the template you will end up creating one singleton (per compilation unit). What you would need is to force global linkage, so that all compilation units reference the same template instantiation. The upcoming C++ standard will support this via [extern template](http://en.wikipedia.org/wiki/C++0x#Extern_template). What you can do now is to disable automatic instantiation in your project and manually instantiate the templates that you use explicitly. This way when you use the template in any compilation unit you will generate an unknown reference to the implementation which can then be satisfied by the linker from the (one) compilation unit where you do the explicit instantiation.
Are multiple threads accessing getInstance at the same time? That could cause multiple instances to be created. Consider: 1. Thread 1 executes the "`if (m_instance==0)`" and finds it true 2. Thread 2 executes the "`if (m_instance==0)`" and finds it true 3. Thread 1 allocates a new T 4. Thread 2 allocates a new T Then one of them overwrites the other, and returns either one of the instances or the other (depending on compiler optimizations, etc.)
Multiple Singleton Instances
[ "", "c++", "singleton", "code-separation", "" ]
How can I get an InputStream from a BufferedImage object? I tried this but ImageIO.createImageInputStream() always returns NULL ``` BufferedImage bigImage = GraphicsUtilities.createThumbnail(ImageIO.read(file), 300); ImageInputStream bigInputStream = ImageIO.createImageInputStream(bigImage); ``` The image thumbnail is being correctly generated since I can paint *bigImage* to a *JPanel* with success.
If you are trying to save the image to a file try: ``` ImageIO.write(thumb, "jpeg", new File(....)); ``` If you just want at the bytes try doing the write call but pass it a ByteArrayOutputStream which you can then get the byte array out of and do with it what you want.
From <http://usna86-techbits.blogspot.com/2010/01/inputstream-from-url-bufferedimage.html> It works very fine! > Here is how you can make an > InputStream for a BufferedImage: > > ``` > URL url = new URL("http://www.google.com/intl/en_ALL/images/logo.gif"); > BufferedImage image = ImageIO.read(url); > ByteArrayOutputStream os = new ByteArrayOutputStream(); > ImageIO.write(image, "gif", os); > InputStream is = new ByteArrayInputStream(os.toByteArray()); > ```
How to get an InputStream from a BufferedImage?
[ "", "java", "image-processing", "javax.imageio", "" ]
How do you change the day part of a `DateTime` structure? I have a `DateTime` with the value of 3/31/2009 8:00:00 AM and would like to change it to any other date but the time should be same. I don't need a solution to add day(s), I need to replace it with any arbitrary date. How do I achieve this?
``` day = 1 month = 4 year = 2009 Date2 = new DateTime(day,month,year,Date1.Hours,Date1.Minute,Date1.Seconds) ```
To construct a DateTime from two other DateTimes, one of which contains the date and one of which contains the time, you can use: ``` DateTime result = date.Date + time.TimeOfDay; ```
Replace date in a DateTime with another date
[ "", "c#", "" ]
There was some code like this: ``` // Convenience to make things more legible in the following code const float & x = some.buried.variable.elsewhere; // Go on to use x in calculations... ``` I have been told that the "const float &" is "bad" and should just be a plain float or const float. I, however, could not think of a compelling reason other than "you don't have to type '&'". In fact, it seems to me that in some cases the original could be better, since compiler might not allocate extra stack space to the variable. In other words, originally I could validly say: ``` assert(&x == &some.buried.variable.elsewhere) ``` Whereas in the second case I cannot. Also, the original seems to communicate intent better, in my view, since the whole point of a reference is to make an alias to another value. Can anyone give me examples of where the "const float &" version is worse than a plain "float" or "const float" in some tangible way?
I can't think of a reason why `const float &` would be better than `const float`. References make sense if you're either worried about copies being made (which is irrelevant with a primitive type like `float`) or you want to be able to update a value across all instances that share the reference (which is irrelevant with `const` members). On top of that, references in members are a huge pain in the neck\* when it comes to initialization, and so they'd have to offer a significant advantage of the alternatives in order to be useful, and it's clearly not the case with `const float`. --- `*` The [FQA on references](http://yosefk.com/c++fqa/ref.html#fqa-8.6) is always amusing and thought provoking
You should only use references in the following cases: (If I didn't forgot one) 1. The type being referred is not small and causes performance problems. 2. You want your local alias to update when the value being referred to is updated. Or: You don't want to make a copy. 3. You want the ability to update the other value. (In case it is not constant) So in this case the float is small enough, you probably don't want it to update when the value being referenced to updates (causing problems in your calculations) and since you are using constants you don't want it to update. So, you would want: ``` const float x = some.buried.variable.elsewhere; ```
const float & x = something; // considered harmful?
[ "", "c++", "reference", "" ]
I've got a query like this: ``` update table set status = 1 where status = 2; ``` but I'd only like to do this to the top 400. I tried adding a 'limit 0, 400' (like I would in a query) but that didn't work. I did some searching and mysql doesn't seem to support the TOP(n) command as sql server does. Any idea how I'd do this? edit: for future reference, I was using the following style for selects, which worked fine: ``` select * from table where ... limit 0, 400; ``` but in the update it wouldn't work with the "0, " for whatever reason. I would consider this inconsistent and ambiguous behaviour, but oh well.
``` UPDATE table SET status = 1 WHERE status = 2 ORDER BY id LIMIT 400 ``` Checked in `MySQL 5.2.0-falcon-alpha-community-nt-log`, confirmed working. In your case it's `0` in `LIMIT 0, 400` that does not work. You cannot use the lower bound in `UPDATE`'s `LIMIT`.
Try this: ``` update table set status = 1 where status = 2 LIMIT 400 ``` You can also put an order by clause ``` update table set status = 1 where status = 2 ORDER BY id LIMIT 400 ```
mysql + update top n
[ "", "mysql", "sql", "sql-update", "" ]
How can I compile java code from an arbitrary string (in memory) in Java 5 and Java 6, load it and run a specific method on it (predefined)? Before you flame this, I looked over existing implementations: * Most rely on Java 6 Compiler API. * Those that don't, rely on tricks. * Yes, I checked out commons-jci. Either I'm too dense to understand how it works, or it just doesn't. * I could not find how to feed the compiler my current class path (which is quite huge). * On the implementation that worked (in Java 6), I could not find how to correctly load inner classes (or inner anonymous classes). * I'd quite like it if the entire thing was in-memory, as the thing runs on multiple environments. I'm sure this has been solved before, but I can't find anything that looks even half-production quality on google (except jci, which, as I've said before, I haven't managed to use). Edit: * I looked over JavaAssist - I need inner classes, Java 5.0 language level support and compiling with the entire classpath. Also, I'd like to create new classes on the fly. I might be mistaken, but I couldn't find how to do this with JavaAssit. * I'm willing to use a file-system based solution (calling javac) but I don't know how to divine the classpath, nor how to later load the files (which are not in my classpath) with a special classloader that can be recycled for multiple invocations. While I do know how to research it, I'd prefer a ready solution. Edit2: For now, I'm content with BeanShell "evaluate". Apparently it does everything I need it to (get a string, evaluate it in the context of the 'current' classpath. It does miss some of Java 5 features, but it can use enums (not define) and compiled 'generic' (erased) classes, so it should be enough for what I want. ~~I don't want to mark the answer as accepted yet since I do hope for a better solution to come up.~~ Edit3: Accepted the beanshell suggestion - it really works wonderfully.
If you're not completely tied to compiling, solutions like Beanshell, groovy and the other scripting languages are easily embedded (in-fact, java has built-in support for plugging in a scripting language so your code doesn't even know what language the script is written in) Beanshell should run any 100% java code IIRC, and I believe Groovy can run most java code--possibly all.
JCI looks fine. This code snippet should be your base: ``` JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse"); MemoryResourceReader mrr = new MemoryResourceReader(); mrr.add("resource name string", yourJavaSourceString.getBytes()); MemoryResourceStore mrs = new MemoryResourceStore(); CompilationResult result = compiler.compile(sources, mrr, mrs); // don't need the result, unless you care for errors/warnings // the class should have been compiled to your destination dir ``` Any reason this should not work? --- **Edit:** added a `MemoryResourceStore` to send the compiled class output to memory, like requested. Also, setting `javac` settings, like classpath in your case, can be done via [`setCustomArguments(String[] pCustomArguments)`](http://commons.apache.org/jci/apidocs/org/apache/commons/jci/compilers/JavacJavaCompilerSettings.html#setCustomArguments(java.lang.String[])) in `JavacJavaCompilerSettings` class.
On-the-fly, in-memory java code compilation for Java 5 and Java 6
[ "", "java", "compiler-construction", "runtime", "compilation", "runtime-compilation", "" ]
I want an easy way to create multiple directories in C++ on Linux. For example, I want to save a file lola.file in the directory: ``` /tmp/a/b/c ``` but if the directories are not there I want them to be created automagically. A working example would be perfect.
Easy with Boost.Filesystem: [`create_directories`](http://www.boost.org/doc/libs/1_57_0/libs/filesystem/doc/reference.html#create_directories) ``` #include <boost/filesystem.hpp> //... boost::filesystem::create_directories("/tmp/a/b/c"); ``` Returns: `true` if a new directory was created, otherwise `false`.
With C++17 or later, there's the standard header `<filesystem>` with function [`std::filesystem::create_directories`](https://en.cppreference.com/w/cpp/filesystem/create_directory) which should be used in modern C++ programs. The C++ standard functions do not have the POSIX-specific explicit permissions (mode) argument, though. However, here's a C function that can be compiled with C++ compilers. ``` /* @(#)File: mkpath.c @(#)Purpose: Create all directories in path @(#)Author: J Leffler @(#)Copyright: (C) JLSS 1990-2020 @(#)Derivation: mkpath.c 1.16 2020/06/19 15:08:10 */ /*TABSTOP=4*/ #include "posixver.h" #include "mkpath.h" #include "emalloc.h" #include <errno.h> #include <string.h> /* "sysstat.h" == <sys/stat.h> with fixup for (old) Windows - inc mode_t */ #include "sysstat.h" typedef struct stat Stat; static int do_mkdir(const char *path, mode_t mode) { Stat st; int status = 0; if (stat(path, &st) != 0) { /* Directory does not exist. EEXIST for race condition */ if (mkdir(path, mode) != 0 && errno != EEXIST) status = -1; } else if (!S_ISDIR(st.st_mode)) { errno = ENOTDIR; status = -1; } return(status); } /** ** mkpath - ensure all directories in path exist ** Algorithm takes the pessimistic view and works top-down to ensure ** each directory in path exists, rather than optimistically creating ** the last element and working backwards. */ int mkpath(const char *path, mode_t mode) { char *pp; char *sp; int status; char *copypath = STRDUP(path); status = 0; pp = copypath; while (status == 0 && (sp = strchr(pp, '/')) != 0) { if (sp != pp) { /* Neither root nor double slash in path */ *sp = '\0'; status = do_mkdir(copypath, mode); *sp = '/'; } pp = sp + 1; } if (status == 0) status = do_mkdir(path, mode); FREE(copypath); return (status); } #ifdef TEST #include <stdio.h> #include <unistd.h> /* ** Stress test with parallel running of mkpath() function. ** Before the EEXIST test, code would fail. ** With the EEXIST test, code does not fail. ** ** Test shell script ** PREFIX=mkpath.$$ ** NAME=./$PREFIX/sa/32/ad/13/23/13/12/13/sd/ds/ww/qq/ss/dd/zz/xx/dd/rr/ff/ff/ss/ss/ss/ss/ss/ss/ss/ss ** : ${MKPATH:=mkpath} ** ./$MKPATH $NAME & ** [...repeat a dozen times or so...] ** ./$MKPATH $NAME & ** wait ** rm -fr ./$PREFIX/ */ int main(int argc, char **argv) { int i; for (i = 1; i < argc; i++) { for (int j = 0; j < 20; j++) { if (fork() == 0) { int rc = mkpath(argv[i], 0777); if (rc != 0) fprintf(stderr, "%d: failed to create (%d: %s): %s\n", (int)getpid(), errno, strerror(errno), argv[i]); exit(rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE); } } int status; int fail = 0; while (wait(&status) != -1) { if (WEXITSTATUS(status) != 0) fail = 1; } if (fail == 0) printf("created: %s\n", argv[i]); } return(0); } #endif /* TEST */ ``` The macros `STRDUP()` and `FREE()` are error-checking versions of `strdup()` and `free()`, declared in `emalloc.h` (and implemented in `emalloc.c` and `estrdup.c`). The `"sysstat.h"` header deals with broken versions of `<sys/stat.h>` and can be replaced by `<sys/stat.h>` on modern Unix systems (but there were many issues back in 1990). And `"mkpath.h"` declares `mkpath()`. The change between v1.12 (original version of the answer) and v1.13 (amended version of the answer) was the test for `EEXIST` in `do_mkdir()`. This was pointed out as necessary by [Switch](https://stackoverflow.com/users/205938/switch) — thank you, Switch. The test code has been upgraded and reproduced the problem on a MacBook Pro (2.3GHz Intel Core i7, running Mac OS X 10.7.4), and suggests that the problem is fixed in the revision (but testing can only show the presence of bugs, never their absence). The code shown is now v1.16; there have been cosmetic or administrative changes made since v1.13 (such as use `mkpath.h` instead of `jlss.h` and include `<unistd.h>` unconditionally in the test code only). It's reasonable to argue that `"sysstat.h"` should be replaced by `<sys/stat.h>` unless you have an unusually recalcitrant system. *(You are hereby given permission to use this code for any purpose with attribution.)* This code is available in my [SOQ](https://github.com/jleffler/soq) (Stack Overflow Questions) repository on GitHub as files `mkpath.c` and `mkpath.h` (etc.) in the [src/so-0067-5039](https://github.com/jleffler/soq/tree/master/src/so-0067-5039) sub-directory.
How can I create a directory tree in C++ on Linux?
[ "", "c++", "linux", "directory", "" ]
Are there any in-memory/caching solutions for java that allow for a form of Querying for specific attributes of objects in the Cache? I realize this is something that a full blown database would be used for, but I want to be able to have the speed/performance of a cache with the Querying ability of a database.
Nowadays the answer should be updated to [Infinispan](http://www.jboss.org/infinispan/), the successor of JBoss Cache and having much improved Search technology.
JBoss Cache has search functionality. It's called JBossCacheSearchable. From the site: > This is the integration package > between JBoss Cache and Hibernate > Search. > > The goal is to add search capabilities > to JBoss Cache. We achieve this by > using Hibernate Search to index user > objects as they are added to the cache > and modified. The cache is queried by > passing in a valid Apache Lucene query > which is then used to search through > the indexes and retrieve matching > objects from the cache. Main JBoss Cache page: <http://www.jboss.org/jbosscache/> JBossCacheSearch: <http://www.jboss.org/community/docs/DOC-10286>
Caching solutions and Querying
[ "", "java", "caching", "jakarta-ee", "jboss", "glassfish", "" ]
Is there any way in MySQL to put the name of the database into a variable? For example, when I have a database called 'db1', can I do something like this: ``` set @db= 'db1'; select * from @db.mytable; ``` EDIT: There is another example of what I want to do: ``` set @dbfrom= 'db1'; set @dbto= 'db2'; insert into @dbto.mytable (col1,col2,col3) select col2,col1,col3 from @dbfrom.mytable; ```
With considerable effort, yes. ``` SET @db = 'db1'; SET @q = CONCAT('SELECT * FROM ', @db, '.mycol'); PREPARE stmt FROM @q; EXECUTE stmt; DEALLOCATE PREPARE stmt; ```
Using [Chaos' 'Prepare Statement' solution](https://stackoverflow.com/a/701007/662581) I managed to create a Stored Procedure which uses a variable database name. Works like a charm for migrating data from one database to another with a Stored Procedure. This way the code isn't pinned to a single database. ``` DELIMITER $$ DROP PROCEDURE IF EXISTS `SampleProcedure` $$ CREATE PROCEDURE `SampleProcedure`(IN HubDatabaseName VARCHAR(255)) BEGIN SET @db = HubDatabaseName; SET @q = CONCAT(' /* Import data from Hub database to local database */ INSERT INTO `table_name_in_local_database` SELECT * FROM ', @db ,'.`tablename` '); PREPARE stmt FROM @q; EXECUTE stmt; DEALLOCATE PREPARE stmt; END $$ DELIMITER ; ```
variable database name
[ "", "sql", "mysql", "" ]