Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'd like to retrieve a page's content and reformat it to my liking... For example: * Go to example.com * Get content within tags with class "x" * Pass content to specific variables * Spit out the content in some pretty form..array, csv, xml... Not too hard, right? I'm a PHP noob! :)
Try using [PHP Simple HTML DOM Parser](http://simplehtmldom.sourceforge.net/). You can do nice stuff like this: ``` // Create DOM from URL or file $html = file_get_html('http://www.google.com/'); // Find all images foreach($html->find('img') as $element) echo $element->src . '<br>'; // Find all links with class=x foreach($html->find('a[class=x]') as $element) echo $element->href . '<br>'; ```
For getting the data, there are three levels of difficulty: ``` file_get_contents($url); //easy ``` Unfortunately a lot of sites aren't very responsive to the proper user agent. You've got two options, here. One's a little harder than the other. Intermediate is [Zend HTTP Client](http://framework.zend.com/manual/en/zend.http.html#zend.http.client.usage) ``` $client = Zend_Http_Client(); //make sure to include Zend_Http, etc. $client->setConfig($params); // params will include proper user agent $client->setUri($aUrl); $html = $client->request()->getBody(); ``` Option three, which you might not even want to consider unless you really want to keep it more scripting than object-oriented, is to explore PHP's [cURL functionality](https://www.php.net/curl) There are a few PHP-native ways to access HTML data via a DOM object, but my favorite is the [Simple HTML DOM Parser](http://simplehtmldom.sourceforge.net/). It's very similar to jQuery/CSS style DOM navigation. ``` $domObject = new Simple_HTML_Dom($html); foreach ($domobject->find('div#theDataYouWant p') as $sentence) { echo "<h3>{$sentence}</h3>"; } ```
PHP-Retrieve content from page
[ "", "php", "tags", "" ]
How do I create a J2ME app for cellphones with a GUI similar to the menus you see in Java games? I've tried MIDlets with Netbeans but they only show you one GUI element at a time. *(textbox, choice, login, etc)* And which Java IDE would you typically design these GUIs in? Netbeans or Eclipse? and is IntelliJ IDEA usable for this aswell? Do I have to write/get a library that draws GUI controls to screen via bitmap functions .. and keeps track of the keys pressed for focus?
You can also use minime: <http://code.google.com/p/minime/> It's an open source GUI library for j2me. miniME works on canvas level (lowest level in j2me) to draw every control so your UI will look exactly the same whatever the handset it'll be running on. Other advantage are: - miniME uses its own event loop to manage user controlled event (botton pressed, softbar, ..), so you Application will "behave" the same whatever the handset. - miniME support the concept of Views and stack of view, in order to make navigation between different view/screens very easy. Here is an example: A View is what you have on the screen at a given moment (for example the main menu screen), then to go to a sub menu, you create a new view, and by calling a simple API, you push it in the stack of Views. The previous view (the main menu) is still existing, but inactive. When the sub menu view complete his work (for example, user press back, or do a selection), you can just go back to the previous view by calling a pop api.
Try to use LWUIT - nice UI toolkit for j2me: <https://lwuit.dev.java.net/> <http://lwuit.blogspot.com/>
Design a GUI for a J2ME app
[ "", "java", "user-interface", "java-me", "interface", "" ]
How do I make eclipse rebuild the database of classes contained within a project or workspace? This is what it uses to make the "References" menu action work, what it uses for the "Add import" dialog, etc. Basically, it's part of the core usefulness of Eclipse. And now, it's only working for maybe 5% of my project. I've run into this problem multiple times: something happens with eclipse, either through an OutOfMemoryError because I opened some huge file, or because a workspace just has months of hard usage. Right now, I'm using Eclipse Galileo on Win32. However, I've had this problem on MacOS as well as with Europa and Ganymede. In the past, I've trashed my workspace and started again, but today this is not an option. My last workspace backup is from last Friday, but that still means hours of work in restoration. Surely there must be another option? EDIT: I've used eclipse -clean as well as rebuilt my project. This is a corruption problem somewhere in eclipse, not in my project.
This worked: * Export preferences from your current workspace (File->Export->General->Preferences) * Switch workspaces to a new workspace * Import preferences into the current workspace * Import your old project into the new workspace (File->Import->General->Existing Projects into Workspace), choosing "Copy project" That works for getting the references DB fixed. To get SVN (and presumably CVS) to work again: * Right click on project, choose Team, choose "Share project." Choose whichever type of versioning repository you were using and click next. Eclipse should realize that your project was already configured for this and just make you click Finish. * Update your sources with the repository.
First exit Eclipse. Next in your workspace directory, delete the `.metadata/.plugins/org.eclipse.jdt.core/` directory. Next time you launch Eclipse, it will rebuild all of its internal indexes. Often cleaning of projects doesn't force all of that metadata to be rebuilt.
Fix Eclipse java references database corruption?
[ "", "java", "eclipse", "" ]
I was reading and found this code as an aswer to a question ``` public List<T> LoadPlugin<T>(string directory) { Type interfaceType = typeof(T); List<T> implementations = new List<T>(); //TODO: perform checks to ensure type is valid foreach (var file in System.IO.Directory.GetFiles(directory)) { //TODO: add proper file handling here and limit files to check //try/catch added in place of ensure files are not .dll try { foreach (var type in System.Reflection.Assembly.LoadFile(file).GetTypes()) { if (interfaceType.IsAssignableFrom(type) && interfaceType != type) { //found class that implements interface //TODO: perform additional checks to ensure any //requirements not specified in interface //ex: ensure type is a class, check for default constructor, etc T instance = (T)Activator.CreateInstance(type); implementations.Add(instance); } } } catch { } } return implementations; } ``` and it got me wondering what the best way to unit test this code would be?
There are three unrelated things that are done in that one method (see [SRP](http://www.butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod)). Each of them should be separated to their own class, which implements some interface, so that you can mock them for better testability. The tree things are: 1. Finding out the .dll files from the plugin directory. 2. Loading the .dll and getting the types that it contains. This should be a one-liner that calls the API methods. You don't really need to test this (at least not in unit tests), because you can reasonably assume that the programming language's libraries work right. 3. Creating instances of the plugin types. When the algorithm is separated into these three parts, you can unit test parts 1 and 3 in isolation (although technically the tests for part 1 are not unit tests, because it touches the file system, unless C# has some way to mock the file system, like Java 7's NIO2 file system API should be mockable). You can also unit test the code that puts them all together, by mocking part 2.
By refactoring it this way: ``` public List<T> LoadPlugin<T>(Type[] types) { Type interfaceType = typeof(T); List<T> implementations = new List<T>(); //TODO: perform checks to ensure type is valid try { foreach (var type in types) { if (interfaceType.IsAssignableFrom(type) && interfaceType != type) { //found class that implements interface //TODO: perform additional checks to ensure any //requirements not specified in interface //ex: ensure type is a class, check for default constructor, etc T instance = (T)Activator.CreateInstance(type); implementations.Add(instance); } } } catch { } return implementations; } ```
unit test dynamic loading code
[ "", "c#", "unit-testing", "reflection", "" ]
I have a large xml file (40 Gb) that I need to split into smaller chunks. I am working with limited space, so is there a way to delete lines from the original file as I write them to new files? Thanks!
Say you want to split the file into N pieces, then simply start reading from the back of the file (more or less) and repeatedly call [truncate](http://docs.python.org/library/stdtypes.html?highlight=truncate#file.truncate): > Truncate the file's size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed. ... ``` import os import stat BUF_SIZE = 4096 size = os.stat("large_file")[stat.ST_SIZE] chunk_size = size // N # or simply set a fixed chunk size based on your free disk space c = 0 in_ = open("large_file", "r+") while size > 0: in_.seek(-min(size, chunk_size), 2) # now you have to find a safe place to split the file at somehow # just read forward until you found one ... old_pos = in_.tell() with open("small_chunk%2d" % (c, ), "w") as out: b = in_.read(BUF_SIZE) while len(b) > 0: out.write(b) b = in_.read(BUF_SIZE) in_.truncate(old_pos) size = old_pos c += 1 ``` Be careful, as I didn't test any of this. It might be needed to call `flush` after the truncate call, and I don't know how fast the file system is going to actually free up the space.
If you're on Linux/Unix, why not use the split command like [this guy](http://www.techiecorner.com/107/how-to-split-large-file-into-several-smaller-files-linux/) does? ``` split --bytes=100m /input/file /output/dir/prefix ``` EDIT: then use [csplit](http://linux.die.net/man/1/csplit).
Change python file in place
[ "", "python", "file", "" ]
I recently upgraded to GCC 4.4 (MinGW TDM build) and now the follow code produces these warning: > In member function 'void Console::print(const std::string&)': > > warning: array subscript is above array bounds Here's the code: ``` void Console::print( const std::string& str ) { std::string newLine( str ); if( newLine.size() > MAX_LINE_LENGTH ) { sf::Uint32 stringSize = newLine.size(); for( sf::Uint32 insertPos = MAX_LINE_LENGTH; insertPos < stringSize; insertPos += MAX_LINE_LENGTH ) { newLine.insert( insertPos, "\n" ); } } StringList tokens; boost::split( tokens, newLine, boost::is_any_of("\n") ); for( StringList::iterator it = tokens.begin(); it != tokens.end(); ++it ) { addLine( *it ); } } ``` Any ideas? --- It is the optimizations that are doing it... Also it appears to be this line which is causing it: ``` boost::split( tokens, newLine, boost::is_any_of("\n") ); ``` --- Ah yes, I found it, it is the argument for boost::is\_any\_of(), by wrapping it in a string() constructor the warning goes away, thank you all for your help :) ``` boost::split( tokens, newLine, boost::is_any_of( string( "\n" ) ) ); ```
Got the same error. As a workaround I replaced ``` is_any_of(" ") ``` with ``` is_from_range(' ', ' ') ``` which might also be slightly more efficient.
Could have something to do with one or more of these GCC bugs: [GCC bugzilla search results for "Warning: array subscript is above array bounds"](http://gcc.gnu.org/bugzilla/buglist.cgi?query_format=specific&order=relevance+desc&bug_status=__open__&product=&content=warning%3A+array+subscript+is+above+array+bounds) Not all of them are valid, but there are some fixed ones if you search around, too: <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=37861> So I'm pretty sure there's something going on there. Based on the comments, I'd try compiling without optimisation and see if it goes away. I got a spurious bounds warning using one of the standard algorithms (std::remove, I think) and passing iterator parameters: ``` myarray, myarray + sizeof(myarray)/sizeof(*myarray) ``` which I'm pretty sure are in bounds. It was only in toy code, though, so I just bodged around it. If GCC really is throwing dodgy warnings you'll just have to inspect your code extra-carefully until it's fixed.
C++ GCC4.4 warning: array subscript is above array bounds
[ "", "c++", "gcc", "boost", "tdm-mingw", "" ]
Is it possible to specify a library path in a java task? Like the equivalent of: ``` java -Djava.library.path=somedir Whatever ```
[`<propertyset>` and `<syspropertyset>`](http://ant.apache.org/manual/Types/propertyset.html) should be what you are looking for See also [this thread](http://marc.info/?l=ant-user&m=108315111023673&w=2) for instance. --- You can set them one by one within your java ant task: ``` <sysproperty key="test.classes.dir" value="${build.classes.dir}"/> ``` tedious... or you can pass them down as a block of Ant properties: ``` <syspropertyset> <propertyref prefix="test."/> </syspropertyset> ``` You can reference external system properties: ``` <propertyset id="proxy.settings"> <propertyref prefix="http."/> <propertyref prefix="https."/> <propertyref prefix="socks."/> </propertyset> ``` and then use them within your java ant task: This `propertyset` can be used on demand; when passed down to a new process, all current ant properties that match the given prefixes are passed down: ``` <java> <!--copy all proxy settings from the running JVM--> <syspropertyset refid="proxy.settings"/> ... </java> ``` --- I completely missed the fact you were trying to pass `java.library.path` property! As mentioned in [this thread](http://lists.apple.com/archives/java-dev/2005/May/msg00519.html): > if you try to set its value outside of the java task, Ant ignores it. So I put all properties except for that one in my syspropertyset and it works as expected. meaning: ``` <property name="java.library.path" location="${dist}"/> <propertyset id="java.props"> <propertyref name="java.library.path"/> </propertyset> <target name="debug"> <java> <syspropertyset refid="java.props"/> </java> </target> ``` will not work, but the following should: ``` <target name="debug"> <java> <sysproperty key="java.library.path" path="${dist}"/> </java> </target> ``` (although you might try that with the "`fork`" attribute set to true if it does not work) (Note: you [cannot modify its value though](https://stackoverflow.com/questions/422848/ant-how-to-modify-java-library-path-in-a-buildfile))
For **JUnit ant task** set your `java.library.path` in section `<junit>` ``` <target name="test" depends="build-test"> <junit printsummary="yes" fork="true"> <sysproperty key="java.library.path" path="path/where/your/library/is/located"/> <!-- ... --> </junit> </target> ``` See [`ant` manual, page JUnit](https://ant.apache.org/manual/Tasks/junit.html), section `<sysproperty>` for more details. --- The rest of this answer are details for beginners. ## 1. Load your library in your [junit](/questions/tagged/junit "show questions tagged 'junit'") [fixture](/questions/tagged/fixture "show questions tagged 'fixture'") ``` public class MyFeatureTest { @Before public void load_library_xxxxx() { System.loadLibrary("library_name_without_extension"); } @Test public void on_that_case_my_feature_does_this() { // ... } } ``` ## 2. Set the `java.library.path` in your [ant](/questions/tagged/ant "show questions tagged 'ant'") script ``` <?xml version="1.0" encoding="UTF-8" standalone="no"?> <project default="build" name="xxxxxx"> <!-- ... --> <property name="lib_dir" value="path/where/your/library/is/located"/> <!-- ... --> <target name="test" depends="build-test"> <mkdir dir="${test_report_dir}" /> <junit printsummary="yes" fork="true"> <sysproperty key="java.library.path" path="${lib_dir}"/> <classpath> <pathelement location="${antlr}" /> <!-- ... --> </classpath> <formatter type="xml" /> <formatter type="plain" /> <batchtest todir="${test_report_dir}"> <fileset dir="${test_src_dir}"> <include name="**/*Test.java" /> </fileset> </batchtest> </junit> </target> </project> ``` ## 3. Use `ant` option `-v` to check `java.library.path` Search a line like `[junit] '-Djava.library.path=` within your `ant` output to check the presence and value of `java.library.path`. The expression `[...]` represent text that has been removed for clarity. ``` > ant test -v [...] test: [mkdir] Skipping /home/user/my/dir/report because it already exists. [junit] Implicitly adding /usr/share/ant/lib/junit.jar:[...] to CLASSPATH [junit] Executing '/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java' with arguments: [junit] '-Djava.library.path=/home/user/my/project/path/where/your/library/is/located' [junit] '-classpath' [junit] '/home/user/my/project/external/antlr.jar:[...]' [junit] 'org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner' [junit] 'com.example.myproject.myfeature.MyFeatureTest' [junit] 'skipNonTests=false' [junit] 'filtertrace=true' [junit] 'haltOnError=false' [junit] 'haltOnFailure=false' [junit] 'formatter=org.apache.tools.ant.taskdefs.optional.junit.SummaryJUnitResultFormatter' [junit] 'showoutput=false' [junit] 'outputtoformatters=true' [junit] 'logfailedtests=true' [junit] 'threadid=0' [junit] 'logtestlistenerevents=false' [junit] 'formatter=org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter,/home/user/my/dir/report/TEST-com.example.myproject.myfeature.MyFeatureTest.xml' [junit] 'formatter=org.apache.tools.ant.taskdefs.optional.junit.PlainJUnitResultFormatter,/home/user/my/dir/report/TEST-com.example.myproject.myfeature.MyFeatureTest.txt' [junit] 'crashfile=/home/user/my/project/junitvmwatcher4952613017772370651.properties' [junit] 'propsfile=/home/user/my/project/junit3999929381398716397.properties' [junit] [junit] The ' characters around the executable and arguments are [junit] not part of the command. [...] ```
How do I set the Java library path from a Java task?
[ "", "java", "ant", "" ]
I can't find a good clean way to lock a critical section in Django. I could use a lock or semaphore but the python implementation is for threads only, so if the production server forks then those will not be respected. Does anyone know of a way (I am thinking posix semaphores right now) to guarantee a lock across processes, or barring that a way to stop a Django server from forking.
You need a distributed lock manager at the point where your app suddenly needs to run on more than one service. I wrote [elock](http://github.com/dustin/elock) for this purpose. There are [bigger ones](http://hadoop.apache.org/zookeeper/) and others have chosen to ignore every suggestion and done the same with memcached. Please don't use memcached for anything more than light advisory locking. It is designed to forget stuff. I like to pretend like filesystems don't exist when I'm making web apps. Makes scale better.
If you use RDBMS, you can use its "LOCK" mechanism. For example, while one "SELECT FOR UPDATE" transaction locks a row, the other "SELECT FOR UPDATE" transactions with the row must wait. ``` # You can use any Python DB API. [SQL] BEGIN; [SQL] SELECT col_name FROM table_name where id = 1 FOR UPDATE; [Process some python code] [SQL] COMMIT; ```
How to lock a critical section in Django?
[ "", "python", "django", "" ]
In C#, I have a table displayed using a `DataGridView`. The table is significantly smaller than the form in which it appears, and so the table fills only a small portion of the upper-left-hand corner of the form. My question: how can I (programmatically) make either: (1) the table automatically enlarge so that it fills the form, or (2) make the form automatically shrink to the size of the table? (And, are both possible?) ``` using System ; using System.Windows.Forms ; using System.Data ; public class NiftyForm : System.Windows.Forms.Form { private DataGridView myDataGridView ; private System.Data.DataTable myDataTable ; public NiftyForm ( ) { this.Load += new EventHandler ( NiftyFormLoadEventHandler ) ; } private void NiftyFormLoadEventHandler ( System.Object sender, System.EventArgs ea ) { this.Location = new System.Drawing.Point ( 40, 30 ) ; this.Size = new System.Drawing.Size ( 800, 600 ) ; myDataTable = new DataTable ( ) ; DataColumn myDataColumn = new DataColumn ( ) ; myDataColumn.DataType = typeof(string) ; myDataColumn.ColumnName = "Name"; myDataColumn.ReadOnly = true; myDataTable.Columns.Add ( myDataColumn ) ; myDataColumn = new DataColumn ( ) ; myDataColumn.DataType = typeof(int) ; myDataColumn.ColumnName = "Age"; myDataColumn.ReadOnly = true; myDataTable.Columns.Add ( myDataColumn ) ; string [ ] Name = new string [ 5 ] { "Dwight", "Abe", "Cal", "Bill", "Eisenhower" } ; int [ ] Age = new int [ 5 ] { 123, 45, 6, 78, 9 } ; for ( int i = 0 ; i < 5 ; i ++ ) { DataRow myDataRow = myDataTable.NewRow ( ) ; myDataRow [ "Name" ] = Name [ i ] ; myDataRow [ "Age" ] = Age [ i ] ; myDataTable.Rows.Add ( myDataRow ) ; } this.myDataGridView = new DataGridView ( ) ; this.myDataGridView.DataSource = myDataTable ; this.myDataGridView.Dock = DockStyle.Fill ; this.Controls.Add ( this.myDataGridView ) ; } [ STAThreadAttribute ( ) ] static void Main ( ) { Application.Run ( new NiftyForm ( ) ) ; } } ```
``` this.myDataGridView.Dock = DockStyle.Fill; ``` This will make the **DataGrid** fill the entire **Form** You can also use an Anchor like so. ``` this.myDataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; ``` This means that the **DataGrid** will resize when the **Form** resizes.
Play with Dock and Anchor properties of the Grid :) Also, you might want to try AutoSize property of the form to see if it works as you'd like to.
Windows Forms: How to make the Form and a Grid Change Sizes Together?
[ "", "c#", "winforms", "datagridview", "datatable", "" ]
The title is self explanatory. For some reason in the loop in int main(), if the user wants to input another book, the loop skips the input of the first function and goes straight to asking for the author's name. For example: Title: The Lord of the Rings Author: J.R.R. Tolkien Copyright: 1954 Enter ISBN numbered separated by spaces: 1 2 3 x Checked out?(Y or N): Y Are you finished?(Y or N): N // this starts loop over, Y will issue a break Title: // there is actually no space between this line and the next, which there should be Author: // it skips down to this line, not allowing the user to input the title, this cycle continues if the user continues inputting information - always skipping the input for title Code: ``` #include "std_lib_facilities.h" class Book{ public: vector<Book> books; // stores book information Book() {}; // constructor string what_title(); string what_author(); int what_copyright(); void store_ISBN(); void is_checkout(); private: char check; int ISBNfirst, ISBNsecond, ISBNthird; char ISBNlast; string title; string author; int copyright; }; string Book::what_title() { cout << "Title: "; getline(cin,title); cout << endl; return title; } string Book::what_author() { cout << "Author: "; getline(cin,author); cout << endl; return author; } int Book::what_copyright() { cout << "Copyright Year: "; cin >> copyright; cout << endl; return copyright; } void Book::store_ISBN() { bool test = false; cout << "Enter ISBN number separated by spaces: "; while(!test){ cin >> ISBNfirst >> ISBNsecond >> ISBNthird >> ISBNlast; if((ISBNfirst<0 || ISBNfirst>9) || (ISBNsecond<0 || ISBNsecond>9) || (ISBNthird<0 || ISBNthird>9)) error("Invalid entry."); else if(!isdigit(ISBNlast) && !isalpha(ISBNlast)) error("Invalid entry."); else test = true;} cout << endl; } void Book::is_checkout() { bool test = false; cout << "Checked out?(Y or N): "; while(!test){ cin >> check; if(check == 'Y') test = true; else if(check == 'N') test = true; else error("Invalid value.");} cout << endl; } int main() { Book store; char question = '0'; while(true){ store.what_title(); store.what_author(); store.what_copyright(); store.store_ISBN(); store.is_checkout(); store.books.push_back(store); cout << "Are you finished?(Y or N): "; cin >> question; if(question == 'Y') break; else if(question == 'N') cout << endl; else error("Invalid value."); } cout << endl; keep_window_open(); } ``` The header information can be found here if you're interested in functions like keep\_window\_open() and error(), but it doesn't really pertain to this issue. - <http://www.stroustrup.com/Programming/std_lib_facilities.h> Any help would be appreciated - thanks.
The following line: ``` cin >> question; ``` reads in the 'Y' or the 'N' character. When you enter the input, you also type a 'return' or 'enter'. That return/enter is still in the buffer. When you get to getline(cin,title); the second time through the loop, that return/enter that is still in the buffer is read in and interpreted as the entire line. What you need to do is either clear the input buffer with cin.flush(); or you need to read in question as a string and not as a character. Here is what your code should look like ``` int main() { Book store; char question = '0'; while(true){ store.what_title(); store.what_author(); store.what_copyright(); store.store_ISBN(); store.is_checkout(); store.books.push_back(store); cout << "Are you finished?(Y or N): "; cin >> question; if(question == 'Y') break; else if(question == 'N') { cout << endl; cin.flush(); } else error("Invalid value."); } cout << endl; keep_window_open(); } ```
Try ``` std::cin.ignore(INT_MAX);(); ``` So something like this: ``` string Book::what_title() { cout << "Title: "; std::cin.ignore(INT_MAX); getline(cin,title); cout << endl; return title; } ``` If that does not help check out [How do I flush the cin buffer?](https://stackoverflow.com/questions/257091/how-do-i-flush-the-cin-buffer) Reading the full line (using *getline*) as some of the other answers are indicating should also take care of the rogue EOL character in the input stream. *Edit: Removed cin.flush since that as not as standard as I thought.*
first function input being skipped after loop
[ "", "c++", "" ]
When is it run? Does it run for each object to which I apply it, or just once? Can it do anything, or its actions are restricted?
When is the constructor run? Try it out with a sample: ``` class Program { static void Main(string[] args) { Console.WriteLine("Creating MyClass instance"); MyClass mc = new MyClass(); Console.WriteLine("Setting value in MyClass instance"); mc.Value = 1; Console.WriteLine("Getting attributes for MyClass type"); object[] attributes = typeof(MyClass).GetCustomAttributes(true); } } [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { public MyAttribute() { Console.WriteLine("Running constructor"); } } [MyAttribute] class MyClass { public int Value { get; set; } } ``` And what is the output? ``` Creating MyClass instance Setting value in MyClass instance Getting attributes for MyClass type Running constructor ``` So, the attribute constructor is run when we start to examine the attribute. Note that the attribute is fetched from the type, not the instance of the type.
The constructor is run **every time** the `GetCustomAttributes` is invoked, or whenever some other code invokes the constructor directly (not that there's a good reason to do so, but it's not impossible either). Note that at least in .NET 4.0, the attribute instances are **not cached**; a fresh instance is constructed every time `GetCustomAttributes` is called: ``` [Test] class Program { public static int SomeValue; [Test] public static void Main(string[] args) { var method = typeof(Program).GetMethod("Main"); var type = typeof(Program); SomeValue = 1; Console.WriteLine(method.GetCustomAttributes(false) .OfType<TestAttribute>().First().SomeValue); // prints "1" SomeValue = 2; Console.WriteLine(method.GetCustomAttributes(false) .OfType<TestAttribute>().First().SomeValue); // prints "2" SomeValue = 3; Console.WriteLine(type.GetCustomAttributes(false) .OfType<TestAttribute>().First().SomeValue); // prints "3" SomeValue = 4; Console.WriteLine(type.GetCustomAttributes(false) .OfType<TestAttribute>().First().SomeValue); // prints "4" Console.ReadLine(); } } [AttributeUsage(AttributeTargets.All)] class TestAttribute : Attribute { public int SomeValue { get; private set; } public TestAttribute() { SomeValue = Program.SomeValue; } } ``` It is not the best idea to have attributes behave like this, of course. At the very least, note that `GetCustomAttributes` is **not** documented to behave like this; in fact, what happens in the above program is not specified in the documentation.
When is a custom attribute's constructor run?
[ "", "c#", ".net", "vb.net", "constructor", "attributes", "" ]
Say I want a php script the run the function itstime() every hour. Other than setting up a cron job on the server how can I do this? Or is this not possible because php scripts need to be opened to be ran? Thanks. EDIT: I want to write some information to a log file and depending on some variables send it in an email.
Well, I definitely recommend the cron job for the purpose. But theoretically, you could have a PHP script run `itstime()`, sleep for an hour, and loop. This is pretty crazy, though. The script would look like: ``` <?php include('whatever.php'); while(true) { itstime(); sleep(3600); } ?> ``` One would probably run it with `nohup php mycrazyscript.php &` to detach it from your terminal and make it keep running, and using `pkill -f mycrazyscript` to terminate it. The reason this is crazy is that now you've got a sleeping PHP process hanging around doing nothing for 59 minutes out of every hour, and you have to make sure it's both running and running at the right time, both of which cron would take care of for you.
Only appending to chaos' answer, so give him credit. mrlanrat - see [this](http://au.php.net/manual/en/function.sleep.php)
Time based php script
[ "", "php", "time", "" ]
How would I go about detecting whitespace between strings? For example, I have a name string like: "Jane Doe" Keep in mind that I don't want to trim or replace it, just detect if whitespace exists between the first and second string.
Use preg\_match as suggested by Josh: ``` <?php $foo = 'Bob Williams'; $bar = 'SamSpade'; $baz = "Bob\t\t\tWilliams"; var_dump(preg_match('/\s/',$foo)); var_dump(preg_match('/\s/',$bar)); var_dump(preg_match('/\s/',$baz)); ``` Ouputs: ``` int(1) int(0) int(1) ```
You could check for only alphanumerical characters, which whitespace is not. You could also do a strpos for a space. ``` if(strpos($string, " ") !== false) { // error } ```
PHP - detect whitespace between strings
[ "", "php", "regex", "whitespace", "" ]
How do I go about implementing a secure password reset function without sending the user an e-mail? There is another secure bit of information that I store and only the user should know, but it seems insecure to just let the user update a password just because they know a 9 digit number. Note that user data is stored in a simple SQL table due to limitations on real database users on the server I'm working on. Any input would be appreciated. **Update:** After making an attempt at OpenID and remembering that this server doesn't allow PHP (and thus, cURL) to make any external requests, I tried sending mail with PHP again. Apparently all of my previous terrible experiences with mail() on this server have gone away. Thanks for all of your input, I may look into OpenID again in the future.
Punt on the password issue. Switch to OpenID. You don't have to worry about password reset, and the user only needs a new password if they want one. it's a win-win.
Typically, identifying a user as being real on the internet requires an "opt in" model where the user "opts" to have their password reset, and an email is sent confirming that they either want it reset, or that is has been reset and what the new reset password is. Really, the only reasonably safe alternatives are ones that use a similar method. Send an email, sms text message they must reply to, automated phone call where they have to punch in digits, etc. The only method I can think of that doesn't use this system would be a security question. Banks often use these for additional verification when users log in or fail to log in correctly a number of times. They are sometimes also used as a "secret" code for retrieving a password, but even then, it is typically emailed to the user, not displayed on the page.
Secure password reset without sending an e-mail
[ "", "php", "security", "passwords", "" ]
I need to build in click and conversion tracking (more specific and focused than IIS log files) to an existing web site. I am expecting pretty high load. I have investigated using [log4net](http://logging.apache.org/log4net/index.html), specifically the [FileAppender Class](http://logging.apache.org/log4net/release/sdk/log4net.Appender.FileAppender.html), but the docs explicitly state: *"This type is not safe for multithreaded operations."* Can someone suggest a robust approach for a solution for this type of heavy logging? I really like the flexibility log4net would give me. Can I get around the lack of safe multi-threading using `lock`? Would this introduce performance/contention concerns?
While FileAppender itself may not be safe for logging, I'd certainly *expect* the normal access routes to it via log4net to be thread-safe. From the [FAQ](http://logging.apache.org/log4net/release/faq.html): * log4net is thread-safe. In other words, either the main log4net framework does enough locking, or it has a dedicated logging thread servicing a producer/consumer queue of log messages. Any logging framework which wasn't thread-safe wouldn't survive for long.
You could check out the Logging Application Block available in the Microsoft Enterprise Library. It offers a whole host of different types of loggers, as well as a handy GUI configurator that you can point to your app.config\web.config in order to modify it. So there's not need to sift through the XML yourself. Here's a link to a nice tutorial on how to get started with it: <http://elegantcode.com/2009/01/20/enterprise-library-logging-101/>
A method for high-load web site logging to file?
[ "", "c#", "logging", "log4net", "" ]
There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project). The question - how does one decide the parts to put in the same module, and the parts to put in a separate module? Same question for packages.
See [How many Python classes should I put in one file?](https://stackoverflow.com/questions/106896/how-many-python-classes-should-i-put-in-one-file) Sketch your overall set of class definitions. Partition these class definitions into "modules". Implement and test the modules separately from each other. Knit the modules together to create your final application. **Note**. It's almost impossible to decompose a working application that evolved organically. So don't do that. Decompose your design early and often. Build separate modules. Integrate to build an application.
There's a classic paper by David Parnas called "On the criteria to be used in decomposing systems into modules". It's a classic (and has a certain age, so can be a little outdated). Maybe you can start from there, a PDF is available here <http://www.cs.umd.edu/class/spring2003/cmsc838p/Design/criteria.pdf>
Recommended ways to split some functionality into functions, modules and packages?
[ "", "python", "module", "package", "" ]
Anyone out there used MATLAB's `javaObject()` function with a JAR file that uses JNI? I'm trying to get JHDF5 running and it seems like it bombs when it tries to get access using jhdf5.dll so I don't really know what to do next. :( **edit**: I am *NOT* trying to read basic HDF5 files. I have my own custom Java code that does something with HDF5 and needs the JHDF5 library. Also, my first question is just whether anyone has used it successfully at all. If not then I'm probably fighting a losing battle. If so then at least it gives me hope. I'll try to debug, it's very difficult compared to debugging regular Java code under Eclipse. **update**: ok, specifics below. I made a very short test class and it has the same failure modes as my complicated program. It looks like my Java classes can't access the HDF5 static constants for some reason. My MATLAB `javaclasspath` is set to include my `test-hdf5.jar` with Test1.java (below), and the files jhdf5.jar, jhdf5.dll, jhdf5obj.jar, and jhdfobj.jar in the same directory. source file Test1.java: ``` package com.example.test.hdf5; import ncsa.hdf.hdf5lib.H5; import ncsa.hdf.hdf5lib.HDF5Constants; import ncsa.hdf.hdf5lib.exceptions.HDF5LibraryException; import ncsa.hdf.object.FileFormat; import ncsa.hdf.object.h5.H5File; public class Test1 { public Test1 () {} public static void main(String args[]) { Test1 test = new Test1(); if (args.length < 2) { } else if ("h5file".equals(args[0])) { test.testH5File(args[1]); } else if ("h5f".equals(args[0])) { test.testH5F(args[1]); } } public void testH5File(String filename) { H5File file; try { file = (H5File) new H5File().createFile( filename, FileFormat.FILE_CREATE_OPEN); file.close(); } catch (Exception e) { throw new RuntimeException(e); } } public void testH5F(String filename) { try { int id = H5.H5Fopen(filename, HDF5Constants.H5F_ACC_RDONLY, HDF5Constants.H5P_DEFAULT); H5.H5Fclose(id); } catch (HDF5LibraryException e) { throw new RuntimeException(e); } catch (NullPointerException e) { throw new RuntimeException(e); } } } ``` MATLAB error: ``` >> T=javaObject('com.example.test.hdf5.Test1') T = com.example.test.hdf5.Test1@c9a375 >> T.testH5F('c:/tmp/espdf/jj11copy.hdf5') java.lang.UnsatisfiedLinkError: no jhdf5 in java.library.path at java.lang.ClassLoader.loadLibrary(Unknown Source) at java.lang.Runtime.loadLibrary0(Unknown Source) at java.lang.System.loadLibrary(Unknown Source) at ncsa.hdf.hdf5lib.H5.<clinit>(H5.java:276) at ncsa.hdf.hdf5lib.HDF5Constants.<clinit>(HDF5Constants.java:494) at com.example.test.hdf5.Test1.testH5F(Test1.java:46) Jul 23, 2009 10:38:16 AM ncsa.hdf.hdf5lib.H5 <clinit> INFO: HDF5 library: jhdf5 resolved to: jhdf5.dll; NOT successfully loaded from java.library.path ??? Java exception occurred: java.lang.UnsatisfiedLinkError: ncsa.hdf.hdf5lib.H5.H5dont_atexit()I at ncsa.hdf.hdf5lib.H5.H5dont_atexit(Native Method) at ncsa.hdf.hdf5lib.H5.<clinit>(H5.java:288) at ncsa.hdf.hdf5lib.HDF5Constants.<clinit>(HDF5Constants.java:494) at com.example.test.hdf5.Test1.testH5F(Test1.java:46) >> T.testH5F('c:/tmp/espdf/jj11copy.hdf5') ??? Java exception occurred: java.lang.NoClassDefFoundError: Could not initialize class ncsa.hdf.hdf5lib.HDF5Constants at com.example.test.hdf5.Test1.testH5F(Test1.java:46) >> T.testH5File('c:/tmp/espdf/jj11copy.hdf5') ??? Java exception occurred: java.lang.NoClassDefFoundError: Could not initialize class ncsa.hdf.hdf5lib.HDF5Constants at ncsa.hdf.object.h5.H5File.<init>(H5File.java:167) at ncsa.hdf.object.h5.H5File.<init>(H5File.java:106) at com.example.test.hdf5.Test1.testH5File(Test1.java:34) ``` in case it matters, here's the ant build file I'm using. The JHDF5 .jar files and .dll are in my `lib` directory; they get copied to the `dist` directory where my own .jar file is created. ``` <?xml version="1.0"?> <project default="all" name="test-hdf5"> <description>some libraries to use later</description> <property name="srcDir" location="src"/> <property name="buildDir" location="bin"/> <property name="distDir" location="dist"/> <property name="libDir" location="lib"/> <target name="init"> <tstamp/> <mkdir dir="${buildDir}"/> <mkdir dir="${distDir}"/> </target> <path id="antclasspath"> <fileset dir="${libDir}"> <include name="*.jar"/> </fileset> </path> <target name="compile" depends="init"> <javac srcdir="${srcDir}" destdir="${buildDir}" debug="on" target="1.6" classpathref="antclasspath" /> </target> <target name="dist" depends="compile"> <copy todir="${buildDir}"> <fileset dir="${srcDir}"> <include name="*.properties" /> </fileset> </copy> <copy todir="${distDir}"> <fileset dir="${libDir}"> <include name="*.dll" /> <include name="*.jar" /> </fileset> </copy> <jar destfile="${distDir}/test-hdf5.jar" basedir="${buildDir}" includes="**"> <manifest> <attribute name="Built-By" value="${user.name}"/> <attribute name="Main-Class" value="com.example.test.hdf5.Test1" /> <attribute name="Class-Path" value=". ./jhdf5.jar ./jhdfobj.jar ./jdhf5obj.jar" /> </manifest> </jar> </target> <target name="all" depends="dist" /> <target name="clean" > <delete dir="${buildDir}" /> </target> </project> ```
JHDF5 uses some goofy search logic at the Java side for loading the dll. It works, except when it doesn't, which is often. And as with many HDF5 details, the underlying logic is undocumented. I did this: took JHDF5 Java sources, removed the stupid AI that tries to load the jhdf5.dll (it's in ncsa/hdf/hdf5lib/H5.java file, the `static` section in about lines 230-290), and replaced it with an explicit `System.load("full/path/to/the/jhdf5.dll");` statement. Then recompiled the jhdf5.jar. Maybe not beautiful, but works perfectly. Additionally, looking at the source, it seems that if you set an system property called `H5_LIBRARY_NAME_PROPERTY_KEY` to point at the dll, it might get loaded. You can set system properties for instance by starting jvm with a -D switch, something like: ``` java -DH5_LIBRARY_NAME_PROPERTY_KEY=path/to/the/jhdf5.dll -jar yourapp.jar ``` Didn't try it, though.
Matlab is very complicated about this, the above are correct that the classpath is not used for dlls. You may use an envirnomental solution like the above, but a more MATLAB specific variable is available too. The file librarypath.txt is able list folders containing any dll's available to MATLAB. It is executed at startup time, so cannot be added to dynamically. To edit the library path, run `edit librarypath.txt` on the MATLAB command line.
MATLAB + JNI = error?
[ "", "java", "matlab", "java-native-interface", "" ]
I have to write an address book program in C# 2008. It is supposed to ask the user for the person's Name, Email, and Favorite Color (only by the colors in the enumeration). Then it is supposed to save the contacts for future reference. This is the code the produces an error.: ``` class Contact { string Name; //This string represents the person's Name. string Email; //This string represents the person's Email. System.Drawing.KnownColor Favoritecolor { get; } static void Request() // This function requests the user to type in information about the person. { Console.WriteLine("Please enter the person's name, e-mail, and favorite color"); Console.Write; string Name; string Email; ; Console.ReadLine(); } } ``` The error is: ``` 'Lab02.Program.Contact.Favoritecolor': property or indexer must have at least one accessor ```
``` System.Drawing.KnownColor Favoritecolor { get; set; } ``` Right now you have a get on the FavoriteColor property, but no where is it ever set, so it can never return an actual value. If you want to implement an auto property, you need to add a set. Otherwise create a backing field and return that. ``` private System.Drawing.KnownColor _favoriteColor = someValue; System.Drawing.KnownColor Favoritecolor { get { return _favoriteColor; } } ```
Your Favoritecolor property needs to have both a get and a set accessor. Like this: ``` System.Drawing.KnownColor Favoritecolor { get; set; } ``` I think something like this is more what you are going for: ``` class Program { static void Main(string[] args) { Contact contact = new Contact(); Console.WriteLine("Please enter the person's name:"); contact.Name = Console.ReadLine(); Console.WriteLine("Please enter the person's e-mail address:"); contact.Email = Console.ReadLine(); while (contact.Favoritecolor == 0) { Console.WriteLine("Please enter the person's favorite color:"); string tempColor = Console.ReadLine(); try { contact.Favoritecolor = (System.Drawing.KnownColor)(Enum.Parse(typeof(System.Drawing.KnownColor), tempColor, true)); } catch { Console.WriteLine("The color \"" + tempColor + "\" was not recognized. The known colors are: "); foreach (System.Drawing.KnownColor color in Enum.GetValues(typeof(KnownColor))) { Console.WriteLine(color); } } } } class Contact { //This string represents the person's Name. public string Name { get; set; } //This string represents the person's Email. public string Email { get; set; } public System.Drawing.KnownColor Favoritecolor { get; set; } } } ``` You don't even need your Colors enumeration, because you are using System.Drawing.KnownColor as your property type. So you can take that out entirely.
C# Property Accessor Error
[ "", "c#", "" ]
I've just started using jquery and I'm really enjoying using selectors. It occurs to me that the idiom would be a very nice way to traverse object trees (e.g., JSON query results). For example, if I have an object like this: ``` var obj = { 'foo': 1, 'bar': 2, 'child': { 'baz': [3, 4, 5] } }; ``` I would love to be able to write something like $('child baz:last', obj) and get 5. I recognize that chaining wouldn't work, but I'd still love the selection operator. Anyone know if such a beast exists, or what the easiest way would be to write one?
Here's a proof-of-concept implementation for getting jQuery itself work on objects. Through an object wrapper (`FakeNode`), you can trick jQuery into using its built-in selector engine (Sizzle) on plain JavaScript objects: ``` function FakeNode(obj, name, parent) { this.obj = obj; this.nodeName = name; this.nodeType = name ? 1 : 9; // element or document this.parentNode = parent; } FakeNode.prototype = { documentElement: { nodeName: "fake" }, getElementsByTagName: function (tagName) { var nodes = []; for (var p in this.obj) { var node = new FakeNode(this.obj[p], p, this); if (p === tagName) { nodes.push(node); } Array.prototype.push.apply(nodes, node.getElementsByTagName(tagName)); } return nodes; } }; function $$(sel, context) { return $(sel, new FakeNode(context)); } ``` And the usage would be: ``` var obj = { foo: 1, bar: 2, child: { baz: [ 3, 4, 5 ], bar: { bar: 3 } } }; function test(selector) { document.write("Selector: " + selector + "<br>"); $$(selector, obj).each(function () { document.write("- Found: " + this.obj + "<br>"); }); } test("child baz"); test("bar"); ``` Giving the output: ``` Selector: child baz - Found: 3,4,5 Selector: bar - Found: 2 - Found: [object Object] - Found: 3 ``` Of course, you'd have to implement a lot more than the above to support more complex selectors. BTW, have you seen [jLinq](http://www.hugoware.net/)?
The array object has some methods that you can use: ``` last = obj.child.baz.slice(-1)[0]; ``` Some other examples: ``` first = obj.child.baz.slice(0,1)[0]; allExceptFirst = obj.child.baz.slice(1); allExceptLast = obj.child.baz.(0,-1); ```
jquery selectors for plain javascript objects instead of DOM elements
[ "", "javascript", "jquery", "css-selectors", "" ]
Is there a way to tell my code to run as a different user? I am calling NetUserSetInfo via a PInvoke and I need to call it as a different user. Is there a way to do that?
Impersonation requires calling some native APIs (namely, LogonUser) so it's probably not worth posting 3 pages of wrapper code. This page has a complete working sample: <http://platinumdogs.wordpress.com/2008/10/30/net-c-impersonation-with-network-credentials/> Note that impersonation has important security considerations. Make sure you follow best practices.
Probably the best and the cleanest [code](https://stackoverflow.com/a/7250145/2108874) that I have seen so far is this: ``` var credentials = new UserCredentials(domain, username, password); Impersonation.RunAsUser(credentials, logonType, () => { // do whatever you want as this user. }); ``` Just follow [Github](https://github.com/mj1856/SimpleImpersonation) or [Nuget](https://www.nuget.org/packages/SimpleImpersonation).
Run Code as a different user
[ "", "c#", "impersonation", "windows-authentication", "" ]
I'm setting up a custom e-commerce solution, and the payment system I'm using requires me to send HTTPS POSTS. How can I do this using php (and CURL?), is it any different from sending http posts? **UPDATE:** Thanks for your replies, they've been very useful. I assume I will need to purchase an SSL certificate for this to work, and I will obviously do this for the final site, but is there any way for me to test this without buying one? Thanks, Nico
PHP/Curl will handle the https request just fine. What you may need to do, especially when going against a dev server, is turn CURLOPT\_SSL\_VERIFYPEER off. This is because a dev server may be self signed and fail the verify test. ``` $postfields = array('field1'=>'value1', 'field2'=>'value2'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://foo.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_POST, 1); // Edit: prior variable $postFields should be $postfields; curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // On dev server only! $result = curl_exec($ch); ```
You can also use the stream api and [http/https context options](http://php.net/context.http) ``` $postdata = http_build_query( array( 'FieldX' => '1234', 'FieldY' => 'yaddayadda' ) ); $opts = array( 'http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('https://example.com', false, $context); ``` You still need an extension that provides the SSL encryption. That can either be php\_openssl or (*if* compiled that way) php\_curl.
How to send HTTPS posts using php
[ "", "php", "https", "" ]
I know there are a million examples and tutrials on how to reload a DIV in jquery every X amount of seconds, here is the example code I am using right now ``` <script> var auto_refresh = setInterval( function(){ $('#notificationcontainer').load('http://localhost/member/beta_new/notifications.inc.php'). fadeIn("slow"); }, 10000); </script> ``` The above code loads the DIV notificationcontainer My problem is I need to load DIV notificationcontainer on page load and then refresh every X amount of seconds, this code currently makes the page wait X amount of time on initial page load and I need to show the div right away on page load but then also update it every X amount of time, please help
Create a function which loads the DIV, call it once in document.ready and pass it to setInterval function so that will be called periodically. ``` <script> var refreshNotification = function() { $('#notificationcontainer').load('http://localhost/member/beta_new/notifications.inc.php'); fadeIn("slow"); }; $(document).ready( function() { refreshNotification(); var autoRefresh = setInterval(refreshNotification, 10000); } ); </script> ```
Run the function before calling `setInterval`
jquery reload div X amount of seconds problem
[ "", "javascript", "jquery", "ajax", "" ]
I am wondering what the best practices are for creating non-loggable accounts. On StackOverflow, there is a Community Wiki account that I'm assuming can't be logged into. How should I go about scripting for non-loggable accounts? If there is an account that I don't want to be accessible, should I set parameters like you can't log into accounts with IDs less then 0? Or should I just manually define the IDs that cannot be logged into in the configuration ID? or is there a better way?
To me you should use a flag in the account data, in order to set or revoke the logging capability. This capability can be enforced with a query at sql level quite easily. A query like: ``` select wathever from user where loggging=1 and user="aUser" and passwd="password" ``` can do the trick. Answering your comment: Maybe using a colum appears not efficent to you but you have to consider the pro: * You have the information about your users in a single layer, not scattered around beetween database, configuration files, or wathever * You can revoke or grant the logging capability to any account without having to modify configuration files
You can set a "flag" on your user table: ``` loggable int(1) default 1 ``` Then you can check on your script: ``` //... data retrieve login ... if($userRow['loggable'] == 1) { //User can login, do stuff } else { //Tell him that he can't login } ```
Best Practices for Non-loggable Accounts
[ "", "php", "user-accounts", "" ]
My developers and I are having an issue with objects being garbage collected in our application when we don't want them to be. We are using Java with Weblogic 10g3. We are programming a singleton pattern to handle all of our JMS connections. There are two classes involved: ``` public class JMSObject { ... private MessageProducer _producer; private MessageConsumer _consumer; ... // standard get/set procs... etc. } public class JMSFactory { ... // Hashmap sessions with key == ConnectionFactory Name Hashmap<String, List<Session>> _sessions; // Hashmap of JMSObjects with key == ConnectionFactory Name + JMS Queue Name Hashmap<String, List<JMSObject>> _jmsobjects; ... // standard get/set & necessary sington functions } ``` The init method of the Servlets calls the JMSFactory singlton method, any new Sessions are placed in the \_sessions Hashmap and new MessageConsumer/MessageProducers are created as a JMSObject and placed in the \_jmsobjects Hashmap, in the appropriate List. The problem is that when the system is running the JMSObjects in the list get garbage collected after some time (sometimes in 5 minutes other times after a few hours.) We looked at this for a few days but could not find any reason for the JMSObjects to be garbarge collected. Since the JMSFactory has a reference to them why would the gc destroy them? In the end we fixed it by changing the classes as follows(without changing method interfaces): ``` public class JMSObject { ... private List<MessageProducer> _producers; private List<MessageConsumer> _consumers; ... // standard get/set procs... etc. } public class JMSFactory { ... // Hashmap sessions with key == ConnectionFactory Name Hashmap<String, List<Session>> _sessions; // Hashmap of JMSObjects with key == ConnectionFactory Name + JMS Queue Name private Hashmap<String JMSObject> _jmsobjects; ... // standard get/set & necessary sington functions } ``` So far in testing the JMSObjects are not being gc'ed. It has been running for 2 days. Can someone explain why the indirect reference is causing the JMSObject to get gc'ed? And why the Sessions in the \_sessions Hashmap was not getting gc'ed? Does it have anything to do with the fact the Sessions are built in Javax types and the JMSObject is something we wrote?
I think I know what your problem is, it's something I ran into a while back (on WebLogic 6). I believe it has to do with WebLogic's dynamic class reloading, which WebLogic seems to do from time to time, even when you're not in a development environment (I'm guessing the web.xml is somehow getting touched by some service or something). What happened in our case was that like you, we have a single instance of an object that's defined as a static variable of some class, and just like you, it's initialized by a servlet that has it's load-on-startup parameter set. When WebLogic thinks there's a change, it reloads the webapp by garbage collecting the classloader (which is fine) *but* it doesn't re-initialize all the servlets that are marked "load-on-startup" (in our case, and I'm guessing yours, the servlet serves no purpose other than to initialize the static variable, there are no mappings to it, and so it cannot be invoke, the static variable gets GCed, but not-reinitialized, and the server needs to be restarted. In our case, our solution was to initialize the static variable in a static initializer. The original developer used a servlet to initialize the variable because he wanted some servlet context information, which really wasn't necessary. If you need context information, you could try doing your initialization in a [ServletContextListener](http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletContextListener.html).
> Since the JMSFactory has a reference to them why would the gc destroy them? Well, are any objects still holding reference to the JMSFactory at this point? Typical singleton pattern keeps the reference to the singleton object in a static member: ``` public class Singleton { private static Singleton instance = new Singleton(); private Singleton() { //constructor... } public static Singleton getInstance() { return instance; } } ``` Is this not the pattern you are following? It is not possible to tell from the code you provided in your post, as you left out the actual singleton code... (BTW, using Singletons for something like this sounds like it would cause pains, besides being hard to test. See [Singletons Are Pathlogical Liars](http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/))
Why is this being garbage collected
[ "", "java", "jakarta-ee", "garbage-collection", "jms", "weblogic", "" ]
Is there a method using either JavaScript or jQuery to determine what day of the week it is? For instance, if the date a user picks in the box is a Sunday, I can alert them.
``` new Date().getDay(); //0=Sun, 1=Mon, ..., 6=Sat ``` See also: [Javascript Date Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) on MDN. **Word of Caution:** This returns day of week on the browser. Because the earth is not flat, the day of the week for some users might be different from the day of the week for your server. This may or may not be relevant to your project... If you are doing a lot of date work, you may want to look into JavaScript date libraries like [Datejs](http://www.datejs.com/) or [Moment.js](http://momentjs.com/)
# Update I just found my favorite method while adding the hacktastic bonus at the bottom. ``` new Date().toLocaleDateString('en', {weekday:'long'}) // returns "Thursday" new Date().toLocaleDateString('en', {weekday:'short'}) // returns "Thu" new Date().toLocaleDateString('es', {weekday:'long'}) // returns "jueves" new Date().toLocaleDateString('es', {weekday:'short'}) // returns "jue." new Date().toLocaleDateString('fr', {weekday:'long'}) // returns "jeudi" new Date().toLocaleDateString('fr', {weekday:'short'}) // returns "jeu." ``` # Original Answer If you only need this once in your page, keep it simple... ``` ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][(new Date()).getDay()] ``` I didn't think it would be that big a deal to extend, but since I have 3 votes for internationalization in the comments... ``` // dictionary version ({ es: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"], en: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] })['en'][(new Date()).getDay()] // returns "Wednesday" // list version langs=['en','es'] [ ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"], ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] ][langs.indexOf('es')][(new Date()).getDay()] // returns "Miércoles" ``` And finally, the code golf version... ``` ["Sun","Mon","Tues","Wednes","Thurs","Fri","Satur"][(new Date()).getDay()]+"day" ``` Hacktastic Bonus... If you only care about the abbreviation, you can trim everything else. ``` new String(new Date()).replace(/ .*/,'') // or (''+new Date()).split(' ')[0] // or Date().slice(0,3) ```
Use jQuery/JS to determine the DAY OF WEEK
[ "", "javascript", "jquery", "date", "" ]
I'm modeling a database relationship in django, and I'd like to have other opinions. The relationship is kind of a two-to-many relationship. For example, a patient can have two physicians: an attending and a primary. A physician obviously has many patients. The application does need to know which one is which; further, there are cases where an attending physician of one patient can be the primary of another. Lastly, both attending and primary are often the same. At first, I was thinking two foreign keys from the patient table into the physician table. However, I think django disallows this. Additionally, on second thought, this is really a many(two)-to-many relationship. Therefore, how can I model this relationship with django while maintaining the physician type as it pertains to a patient? Perhaps I will need to store the physician type on the many-to-many association table? Thanks, Pete
How about something like this: ``` class Patient(models.Model): primary_physician = models.ForeignKey('Physician', related_name='primary_patients') attending_physicial = models.ForeignKey('Physician', related_name='attending_patients') ``` This allows you to have two foreign keys to the same model; the `Physician` model will also have fields called `primary_patients` and `attending_patients`.
Consider using a many-to-many join table. Use application logic to prevent more than two physicians per patient. ``` Physician Physician_ID ... Patient Patient_ID ... Physician_Patient Physician_ID int not null Patient_ID int not null Type ENUM ('Primary', 'Attending') PRIMARY KEY (Physician_ID, Patient_ID) KEY (Patient_ID) ```
How would you model this database relationship?
[ "", "python", "database", "django", "database-design", "" ]
I want to create a new type of field for django models that is basically a ListOfStrings. So in your model code you would have the following: **models.py:** ``` from django.db import models class ListOfStringsField(???): ??? class myDjangoModelClass(): myName = models.CharField(max_length=64) myFriends = ListOfStringsField() # ``` **other.py:** ``` myclass = myDjangoModelClass() myclass.myName = "bob" myclass.myFriends = ["me", "myself", "and I"] myclass.save() id = myclass.id loadedmyclass = myDjangoModelClass.objects.filter(id__exact=id) myFriendsList = loadedclass.myFriends # myFriendsList is a list and should equal ["me", "myself", "and I"] ``` How would you go about writing this field type, with the following stipulations? * We don't want to do create a field which just crams all the strings together and separates them with a token in one field like [this](http://www.davidcramer.net/code/181/custom-fields-in-django.html). It is a good solution in some cases, but we want to keep the string data normalized so tools other than django can query the data. * The field should automatically create any secondary tables needed to store the string data. * The secondary table should ideally have only one copy of each unique string. This is optional, but would be nice to have. Looking in the Django code it looks like I would want to do something similar to what ForeignKey is doing, but the documentation is sparse. This leads to the following questions: * Can this be done? * Has it been done (and if so where)? * Is there any documentation on Django about how to extend and override their model classes, specifically their relationship classes? I have not seen a lot of documentation on that aspect of their code, but there is [this](http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields). This is comes from this [question](https://stackoverflow.com/questions/1110153/what-is-the-most-efficent-way-to-store-a-list-in-the-django-models).
What you have described sounds to me really similar to the tags. So, why not using [django tagging](http://code.google.com/p/django-tagging/)? It works like a charm, you can install it independently from your application and its API is quite easy to use.
There's some very good documentation on creating custom fields [here](http://docs.djangoproject.com/en/dev/howto/custom-model-fields/). However, I think you're overthinking this. It sounds like you actually just want a standard foreign key, but with the additional ability to retrieve all the elements as a single list. So the easiest thing would be to just use a ForeignKey, and define a `get_myfield_as_list` method on the model: ``` class Friends(model.Model): name = models.CharField(max_length=100) my_items = models.ForeignKey(MyModel) class MyModel(models.Model): ... def get_my_friends_as_list(self): return ', '.join(self.friends_set.values_list('name', flat=True)) ``` Now calling `get_my_friends_as_list()` on an instance of MyModel will return you a list of strings, as required.
How would you inherit from and override the django model classes to create a listOfStringsField?
[ "", "python", "django", "inheritance", "django-models", "" ]
I'm trying to debug an error I got on a production server. Sometimes MySQL gives up and my web app can't connect to the database (I'm getting the "too many connections" error). The server has a few thousand visitors a day and on the night I'm running a few cron jobs which sometimes does some heavy mysql work (Looping through 50 000 rows, inserting and deletes duplicates etc) * The server runs both apache and mysql on the same machine * MySQL has a pretty standard based configuration (max connections) * The web app is using PHP How do I debug this issue? Which log files should I read? How do I find the "evil" script? The strange this is that if I restart the MySQL server it starts working again. Edit: * Different apps/scripts is using different connectors to its database (mostly mysqli but also Zend\_Db)
First, use innotop (Google for it) to monitor your connections. It's mostly geared to InnoDB statistics, but it can bet set to show all connections including those not in a transaction. Otherwise, the following are helpful: Use persistent connections / connection pools in your web apps. Increase your max connections.
It's not necessarily a long-running SQL query. If you open a connection at the start of a page, it won't be released until the PHP script terminates - even if there is no query running. You should add some stats to your pages to find out the slowest ones, and the most-hit ones. Closing the connection early would help, if possible.
Debug MySQLs "too many connections"
[ "", "php", "mysql", "debugging", "cron", "" ]
Doing some refactoring in some legacy code I've found in a project. This is for MSSQL. The thing is, i can't understand why we're using mixed left and right joins and collating some of the joining conditions together. My question is this: doesn't this create implicit inner joins in some places and implicit full joins in others? I'm of the school that just about anything can be written using just left (and inner/full) or just right (and inner/full) but that's because i like to keep things simple where possible. As an aside, we convert all this stuff to work on oracle databases as well, so maybe there's some optimization rules that work differently with Ora? For instance, here's the FROM part of one of the queries: ``` FROM Table1 RIGHT OUTER JOIN Table2 ON Table1.T2FK = Table2.T2PK LEFT OUTER JOIN Table3 RIGHT OUTER JOIN Table4 LEFT OUTER JOIN Table5 ON Table4.T3FK = Table5.T3FK AND Table4.T2FK = Table5.T2FK LEFT OUTER JOIN Table6 RIGHT OUTER JOIN Table7 ON Table6.T6PK = Table7.T6FK LEFT OUTER JOIN Table8 RIGHT OUTER JOIN Table9 ON Table8.T8PK= Table9.T8FK ON Table7.T9FK= Table9.T9PK ON Table4.T7FK= Table7.T7PK ON Table3.T3PK= Table4.T3PK RIGHT OUTER JOIN ( SELECT * FROM TableA WHERE ( TableA.PK = @PK ) AND ( TableA.Date BETWEEN @StartDate AND @EndDate ) ) Table10 ON Table4.T4PK= Table10.T4FK ON Table2.T2PK = Table4.T2PK ```
One thing I would do is make sure you know what results you are expecting before messing with this. Wouldn't want to "fix" it and have different results returned. Although honestly, with a query that poorly designed, I'm not sure that you are actually getting correct results right now. To me this looks like something that someone did over time maybe even originally starting with inner joins, realizing they wouldn't work and changing to outer joins but not wanting to bother changing the order the tables were referenced in the query. Of particular concern to me for maintenance purposes is to put the ON clauses next to the tables you are joining as well as converting all the joins to left joins rather than mixing right and left joins. Having the ON clause for table 4 and table 3 down next to table 9 makes no sense at all to me and should contribute to confusion as to what the query should actually return. You may also need to change the order of the joins in order to convert to all left joins. Personally I prefer to start with the main table that the others will join to (which appears to be table2) and then work down the food chain from there.
`LEFT` and `RIGHT` join are pure syntax sugar. Any `LEFT JOIN` can be transformed into a `RIGHT JOIN` merely by switching the sets. Pre-`9i` `Oracle` used this construct: ``` WHERE table1.col(+) = table2.col ``` , `(+)` here denoting the nullable column, and `LEFT` and `RIGHT` joins could be emulated by mere switching: ``` WHERE table1.col = table2.col(+) ``` In `MySQL`, there is no `FULL OUTER JOIN` and it needs to be emulated. Ususally it is done this way: ``` SELECT * FROM table1 LEFT JOIN table2 ON table1.col = table2.col UNION ALL SELECT * FROM table1 RIGHT JOIN table2 ON table1.col = table2.col WHERE table1.col IS NULL ``` , and it's more convenient to copy the `JOIN` and replace `LEFT` with `RIGHT`, than to swap the tables. Note that in `SQL Server` plans, `Hash Left Semi Join` and `Hash Right Semi Join` are different operators. For the query like this: ``` SELECT * FROM table1 WHERE table1.col IN ( SELECT col FROM table2 ) ``` , `Hash Match (Left Semi Join)` hashes `table1` and removes the matched elements from the hash table in runtime (so that they cannot match more than one time). `Hash Match (Right Semi Join)` hashes `table2` and removes the duplicate elements from the hash table while building it.
Mixing Left and right Joins? Why?
[ "", "sql", "join", "" ]
I am currently evaluating for an eCommerce project. Is there any good Python based webshop software. Are there any personal experiences people can share? Until now I have only found: * <http://www.satchmoproject.com/> Coming from the PHP world finding only ONE project seams akward to me. Does anybody have experience with Satchmo? Are there any good commercial solutions? It's highly important that the webshop software is extendable (and if possible readable/changeable) in every aspect, but it's not required at all to be [OSS](http://en.wikipedia.org/wiki/Open_source_software). Commercial software with support deal is fair enough. Any good recommendations out there?
Satchmo is a great project, mature, and used in live ecommerce sites. The other up-and-coming Django ecommerce app that looks like it will be strong competition for Satchmo is [Lightning Fast Shop](http://www.getlfs.com/start). I haven't used it, but I've looked over the code a few times and like its style.
I also found: * [Plata](http://plata-django-shop.readthedocs.org) (companion to the great FeinCMS) * [Django-Shopkit](https://github.com/dokterbob/django-shopkit) * [Django Shop](https://www.django-shop.org) * [Satchless](http://satchless.com/) * [Cartridge](http://cartridge.jupo.org/) (coupled with Mezzanine CMS) * [Oscar](http://tangentlabs.github.com/django-oscar/) I didn’t try any, was just looking for the right starting point myself (Oscar seems to be the only one that supports split payments, so I guess I'll use that). See also <http://www.readncode.com/blog/the-state-of-ecommerce-in-django/>
What is a good python-based Webshop Software?
[ "", "python", "django", "e-commerce", "webshop", "" ]
Why is a C#/.NET message box not modal? Accidentally, if the message box goes behind our main UI, then the main UI doesn't respond, until we click OK (on our message box). Is there a workaround other than creating a custom message box?
You need to assign the MessageBox owner property to the main UI window (look at the 3rd constructor).
This is a simple C# new Windows-Forms application: ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string message = "You did not enter a server name. Cancel this operation?"; string caption = "No Server Name Specified"; MessageBoxButtons buttons = MessageBoxButtons.YesNo; DialogResult result; // Displays the MessageBox. result = MessageBox.Show(this, message, caption, buttons); if (result == DialogResult.Yes) { // Closes the parent form. this.Close(); } } } } ``` As [Dusty states in his answer](https://stackoverflow.com/questions/1154181/c-sharp-net-messagebox-is-not-modal/1154226#1154226), a message box is a modal dialog. Specify the `owner` property. In this example, the owner is denoted by the keyword `this`.
C# / .NET messagebox is not modal
[ "", "c#", "modal-dialog", "" ]
I am trying to minimize the performance penalty of communicating across AppDomains in the same machine. In my toy example, Class A is loaded in AppDomain 1. It creates an AppDomain 2 and loads there an instance of Class 2 (Class 2 inherits from MarshalByRef) getting back a proxy. Then Class 1 calls repeatedly a method on the proxy that returns no values. I get the following results: 1. No AppDomains, both classes are loaded in the same AppDomain and the first calls repetedly the method on the second (the method has no parameters): **24 million** method calls/sec 2. Two AppDomain as described above, method has no parameters or "bleeding" string parameters: **340.000 methods calls/sec** 3. Two AppDomains as described above, one serializable parameter (array of two strings): **64.000 method calls/sec** Although I understand the performance penalty between 2 and 3 (serialization), I really don't understand **why I am 100 times slower from case 1 to case 2**. To my understanding, once the proxy is created all subsequent method invocations must be really fast since no data are being marshalled from one AppDomain to the other. Does anybody now why communicating across AppDomains is so slow? Am I doing something wrong? PS1. The only tip that I have on this is [here](http://blogs.msdn.com/cbrumme/archive/2003/06/01/51466.aspx): "And the cost of crossing an AppDomain boundary is embarrassing.". I was guessing he refers to serialization... PS2. I don't count the AppDomain or Proxy creation time (my benchmarks start in the first method invocation) PS3. I am using .NET 3.5 in a WinXP SP3 machine. I also tried .NET 4.0 Beta 1 with no significant differences.
If you count lines of IL involved in each scenario, you will see that the CLR is doing much more than 100 times the work when remoting. A direct invocation is just a few opcodes, but with remoting there are multiple classes involved, real/transparent proxies, security checks, serialization, yadda yadda yadda. You will need to address this through design - there is no magic bullet for improving perf through implementation.
Is there any way you can call a single helper method that takes parameters about how many times you want to call the method you need? Cross-AppDomain call performance varies greatly by implementation. I believe it could be significantly better in the CLR 4.0, but I'm not fully versed on the details there. Generally though, you want to avoid the overhead by "batching" the calls through a helper method.
What is the minimum Cross AppDomain communication performance penalty?
[ "", "c#", "performance", "appdomain", "" ]
I have a script which at one point returns an image thumbnail using jquery built in java request. Every time the php function get called, this thumbnail gets updated, but keeps the exact same filename. Problem is that the browser caches the thumbnail and it looks like it never gets updated. Are here any techniques to avoid this?
You may add time() function at the end of the file name. Ex ``` <img src="myImage.jpg?<?php echo time();?>" /> ```
You can set the cache option to false. See the [documentation](http://docs.jquery.com/Ajax/jQuery.ajax).
Force refresh on ajax request?
[ "", "php", "jquery", "ajax", "image", "browser", "" ]
In Java, one of the implementations of queue is "circular array" and the other one is "linked list". What are their differences?
In terms of how they're used, there is virtually no difference at all, except when you get to the size limit of the queue (which I'll explain in a sec...) As for other considerations: * A linked list approach is advantageous because you can dynamically resize the queue with no extra effort - this is fundamental to linked lists. Of course, this can be replicated by reallocating an array, but it's not the easiest way of doing it. * Also, in a linked list, there is no unused memory: in a circular array approach, if the size of the queue is less than the maximum capacity of the array, there will be "empty slots". However, this doesn't mean that linked lists are more memory-efficient, because: * The circular array approach has the advantage that there is no overhead. Each node in a linked list needs to store a reference to the next node - and this adds up if the list gets big. On the other hand, a circular array is just a block of memory which you access by indexing, so there is no overhead. There are pro's and con's to each approach, but really, it comes down to the specific situation it's used in... and unless you're using queues to no end, it probably won't make much of a difference.
Normally the circular array implementation is slightly better at reusing memory, but runs the risk of having to grow if too many items are added to the queue - and possibly holding too much memory if the normal storage and the max storage capacities are too different in practice. The linked list is more flexible, but generally involves more garbage collection. In practice I think I'd be surprised if you found your code bottleneck depended on this choice - use whichever seems most intuitive to you.
What are the differences between the two common implementations of a queue?
[ "", "java", "queue", "collections", "" ]
I'm converting a small MSAccess application to a web-based ASP.NET app, using C# 3.5. I was wondering what's the best way to work with dates in C#, when converting some of this VBA code over to C#. Here is an example of the VBA Code: ``` Coverage1=IIf(IsNull([EffDate1]),0,IIf([CurrDate]<=[EndDate1],[CurrDate]-[EffDate1],[EndDate1]-[EffDate1]+1)) ``` Here is what my current C# code looks like with the errors denoted in the commented code: ``` public DateTime CalculateCoverageOne(DateTime dateEffDateOne, DateTime dateCurrentDate, DateTime dateEndDateOne) { if (dateCurrentDate.Date <= dateEndDateOne.Date) { return null; //Get "cannot convert null to System.DateTime because it is a non-nullable value type" error } else { if (dateCurrentDate.Date <= dateEndDateOne) { return dateCurrentDate.Subtract(dateEffDateOne); //Gets error "cannot implicitly convert system.timepsan to system.datetime } else { return dateEndDateOne.Subtract(dateEffDateOne.AddDays(1)); //Gets error "cannot implicitly convert system.timepsan to system.datetime } } } ```
It looks like your VB is actually returning a time span, presumably in days. Here's the closest direct translation: ``` public TimeSpan CalculateCoverageOne(DateTime EffDate1, DateTime CurrDate, DateTime? EndDate1) { return (EndDate1 == null) ? TimeSpan.Zero : (CurrDate < EndDate1) ? (CurrDate - EffDate1) : (EndDate1.AddDays(1) - EffDate1); } ``` If instead you just wanted a count of days, just return the TimeSpan's Days property: ``` public int CalculateCoverageOne(DateTime EffDate1, DateTime CurrDate, DateTime? EndDate1) { return ((EndDate1 == null) ? TimeSpan.Zero : (CurrDate < EndDate1) ? (CurrDate - EffDate1) : (EndDate1.AddDays(1) - EffDate1)).Days; } ``` And for good measure, this is how I would clean up your final version: ``` public int CalculateCoverageOne(DateTime dateCurrentDate, DateTime dateEffectiveDate, DateTime dateEffDateOne, DateTime dateEndDateOne) { TimeSpan ts; if (dateEffDateOne == DateTime.MinValue) { ts = TimeSpan.Zero; } else if (dateEffectiveDate <= dateEndDateOne) { ts = dateCurrentDate - dateEffDateOne; } else { ts = (dateEndDateOne - dateEffDateOne) + new TimeSpan(1, 0, 0, 0); } return ts.Days; } ```
*cannot convert null to System.DateTime because it is a non-nullable value type" error* The `DateTime` type is a *value type*, which means that it cannot hold a null value. To get around this you can do one of two things; either return `DateTime.MinValue`, and test for that when you want to use the value, or change the function to return `DateTime?` (note the question mark), which is a nullable `DateTime`. The nullable date can be used like this: ``` DateTime? nullable = DateTime.Now; if (nullable.HasValue) { // do something with nullable.Value } ``` *cannot implicitly convert system.timepsan to system.datetime* When you subtract a `DateTime` from another `DateTime`, the result is a [`TimeSpan`](http://msdn.microsoft.com/en-us/library/system.timespan.aspx), representing the amount of time between them. The `TimeSpan` does not represent a specific point in time, but the span itself. In order to get the date, you can use the [`Add`](http://msdn.microsoft.com/en-us/library/system.datetime.add.aspx) method or the [`Subtract`](http://msdn.microsoft.com/en-us/library/ae6246z1.aspx) method overload of a `DateTime` object that accepts a `TimeSpan`. Exactly how that should look I can't say, since I don't know what the different dates in your code represent. In the last case, you can simply use the return value from the AddDays method, but with a negative value (in order to subtract one day, instead of adding one): ``` return dateEffDateOne.AddDays(-1); ```
Convert the TimeSpan datatype to DateTime?
[ "", "c#", ".net", "ms-access", "type-conversion", "" ]
I'm writing a Content Management System in PHP, and I want it to be the smallest one in the world. I'm planning to make it available to everyone, just like Drupal and Joomla. But to make it so ultra-tiny, I change code to smaller code. For example, I change: ``` $info = parse_ini_file("info.scm"); /* to */ $i=parse_ini_file("info.scm"); ``` just to make it smaller. But, I use some functions very often, like preg\_replace();. I use it over 30 times. Should I make a function like: ``` function p($p,$r,$s){preg_replace($p,$r,$s);} //and than just use: p($my_regex, $my_replacement, $my_string); ``` or does this make it all work slower? Notice that my goal is to make it so tiny as possible.
It makes sense when it is code you need to push to a client (JavaScript from a server for example) but when it runs locally on the server, as is the case for php, there is little (if any) performance gain.
What you are attempting to do is known as 'minifying' it has no performance changes, just reduces the size of your program. Yes making that function will reduce the BYTE size of your program. I do suggest though keeping a non minified version in order to make it more maintainable. perhaps write a program to minify it before you release a new version.
Make PHP code as small as possible while not reducing performance?
[ "", "php", "performance", "content-management-system", "" ]
I used to use my Java programs to get free stock data (historical prices, charts, current prices ...) from Yahoo, but recently it stopped working, because Yahoo doesn't seem to welcome people systematically getting data that way. So I wonder if there is any good (reliable and kept up-to-date) open source Java packages that get free stock info, I don't mind the 20 minute delay. PS : After some research, I found this site for anyone who is interested in this topic : <http://www.gummy-stuff.org/Yahoo-data.htm>
I use [WebServiceX](http://www.webservicex.net/WCF/ServiceDetails.aspx?SID=19) and Google Finance.
Google does in fact provide a Java [Finance API](http://code.google.com/apis/finance/developers_guide_java.html). It's talking purely in terms of portfolios and associated positions, but that should get you going. There's also a [Google Data API](http://code.google.com/apis/finance/developers_guide_protocol.html) and even a [Javascript API](http://code.google.com/apis/finance/developers_guide_js.html)
Is there a good and reliable open source Java package to get free stock info?
[ "", "java", "open-source", "stocks", "" ]
How is the performance of a Stored Procedure? Is it worth using them instead of implementing a complex query in a PHP/MySQL call?
Stored procedures will give you a small performance boost, but mostly they are for doing tasks that are difficult or impossible to do with a simple query. Stored procedures are great for simplifying access to data for many different types of clients. Database administrators love them because they control how the database is used as opposed to leaving those details to the developer. Look to indexes and proper table design to get better performance.
Yikes I'd hate for someone to read these answers and get the wrong impression. There are some really important differences between the "Stored Whatever" implementations on "MySQL" vs "SQL server/Oracle". See: <http://www.joinfu.com/2010/05/mysql-stored-procedures-aint-all-that/> > Every person that asks this question assumes something about MySQL’s > stored procedure implementation; they incorrectly believe that stored > procedures are compiled and stored in a global stored procedure cache, > similar to the stored procedure cache in Microsoft SQL Server[1] or > Oracle[2]. > > This is wrong. Flat-out incorrect. > > Here is the truth: Every single connection to the MySQL server > maintains it’s own stored procedure cache. Take a minute to read the rest of the article and comments. It's short and you'll have a much better understanding of the issues.
MySQL Stored Procedure vs. complex query
[ "", "php", "mysql", "performance", "" ]
I am trying to deploy and run my webapplication using maven and its tomcat plugin. I have set it up in project's pom.xml, but when I'm calling it from command line: ``` mvn tomcat:run ``` all that I get is: ``` [root@ovz6022 trunk]# mvn -e tomcat:run + Error stacktraces are turned on. [INFO] Scanning for projects... [INFO] ------------------------------------------------------------------------ [INFO] Building Unnamed - com.gotbrains.breeze:breeze:jar:1.0 [INFO] task-segment: [tomcat:run] [INFO] ------------------------------------------------------------------------ [INFO] Preparing tomcat:run [INFO] [resources:resources {execution: default-resources}] [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory /root/trunk/src/main/resources [INFO] [compiler:compile {execution: default-compile}] [INFO] Nothing to compile - all classes are up to date [INFO] [tomcat:run {execution: default-cli}] [INFO] Skipping non-war project [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------------------ [INFO] Total time: 24 seconds [INFO] Finished at: Thu Jul 23 14:34:31 MDT 2009 [INFO] Final Memory: 7M/14M [INFO] ------------------------------------------------------------------------ ``` And that's all. Tomcat hasn't been launched but I don't see any errors here. Does anybody knows what's happening?
The clue is in the line: ``` [INFO] Skipping non-war project ``` The tomcat:run goal is intended to work with war projects, I'm guessing yours is a jar project. You need to change the packaging of your project to war, you may also need to provide some additional configuration for the war to actually do anything. Note: I'd recommend having a separate war project to your jar projects, then adding the jars as dependencies to the war.
As mentioned before, you should use war packaging. However, if you can't because you're using OSGI or some other reason, you can tell the Tomcat plugin to deploy anyway even if it isn't war packaging by using the ignorePackaging option: ``` <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat6-maven-plugin</artifactId> <version>2.0</version> <configuration> <ignorePackaging>true</ignorePackaging> ```
mvn tomcat:run doesn't start Tomcat
[ "", "java", "tomcat", "maven-2", "" ]
In Javascript OO, when should I use the `this` keyword? Also, if I want to call a method of a class from another method of the same class, should I use `this` or just the name of the function? E.g is this correct? ``` function Foo() { this.bar= function() { alert('bar'); } this.baz= function() { this.bar(); //should I use this.bar() or just bar()? } } ```
When it comes to "object-oriented" JavaScript, here's a nice guide Mark Dickinson here on SO linked to: [Private Members in JavaScript](http://www.crockford.com/javascript/private.html). It does go into detail about some other stuff you don't really need now, but once you understand how JavaScript works, you'll see that it's quite different from your ordinary object-oriented language when it comes to things like what `this` really means. I'd say that in your case, you should definitely use `this`, but maybe your functions should be in the `prototype` part of your "class" (this avoids redefining the function every time a new instance is created.)
I have found [3 Ways to define a javascript class](http://www.phpied.com/3-ways-to-define-a-javascript-class/) helpful.
When to use this in javascript OO?
[ "", "javascript", "oop", "scope", "" ]
I'm using ExtJS to make a form that generates a report from the data in the database in CSV format. After the user chooses a simple range of dates to extract the data and submits, running the following code : ``` var frm = document.createElement('form'); frm.id = 'frmDummy'; frm.name = id; document.body.appendChild(frm); Ext.MessageBox.wait('Generating CSV File ...'); Ext.Ajax.request({ url: 'csv_extract_ajax.php?start_time='+txtDateFieldFrom.getRawValue()+'&end_time='+txtDateFieldTo.getRawValue(), method : 'POST', form: Ext.fly('frmDummy'), isUpload: true, success: function(o, r, n){ Ext.MessageBox.updateProgress(1); Ext.MessageBox.hide(); }, failure: function(o, r, n){ Ext.MessageBox.updateProgress(1); Ext.MessageBox.hide(); }, callback: function(o, r, n){ Ext.MessageBox.updateProgress(1); Ext.MessageBox.hide(); }, scope: this }); ``` The associated php file simple outputs a CSV string, working file. Since the isUpload is true, it seems that the callback is never returned to the user. As soon as I remove it, the callback is called but the file is not uploaded to the client. The problem now, everything is working perfectly but the MessageBox never disappears since the callbacks are never called (success, failure or callback) Any idea ? :P **Additional info:** PHP header : ``` header("Pragma: public"); header("Expires: 0"); header("Cache-Control: private"); header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=$filename"); header("Accept-Ranges: bytes"); ```
This is an excerpt from `Ext.Ajax.request` documentation: > isUpload : Boolean (Optional) True if > the form object is a file upload (will > usually be automatically detected). > File uploads are not performed using > normal "Ajax" techniques, that is they > are not performed using > XMLHttpRequests. Instead the form is > submitted in the standard manner with > the DOM element temporarily > modified to have its target set to > refer to a dynamically generated, > hidden which is inserted into > the document but removed after the > return data has been gathered. The > server response is parsed by the > browser to create the document for the > IFRAME. If the server is using JSON to > send the return object, then the > Content-Type header must be set to > "text/html" in order to tell the > browser to insert the text unchanged > into the document body. The response > text is retrieved from the document, > and a fake XMLHttpRequest object is > created containing a responseText > property in order to conform to the > requirements of event handlers and > callbacks. Be aware that file upload > packets are sent with the content type > multipart/form and some server > technologies (notably Java EE) may require > some custom processing in order to > retrieve parameter names and parameter > values from the packet content. As you can see, upload request is returned via IFRAME and only emulates standard AJAX response, so that callbacks are not called.
> As soon as I remove it, the callback > is called but the file is not uploaded > to the client. Setting `isUpload` to true means you are gonna to upload file from client to server, but this is not your case, I'm afraid.
Ext.Ajax.request callbacks never called when isUpload is true
[ "", "javascript", "ajax", "extjs", "" ]
I have an ASP.NET web application that uses jQuery on client side. On one of the web forms I have a bunch of controls to fill, and an upload control. User can run upload while filling other entries on the form. When user saves the form, all data including file is stored into database . The question is what to do with uploaded file while user fills the form? I have two possible solutions, but don't know which of them is more optimal 1. Cache uploaded file, and later, while saving, retrieve it and store into database with all other data. 2. Save file in temporary folder, and then read it. What is the best solution for this? Thanks in advance.
I think the most appropriate solution will be storing uploaded file in cache. Here is the code ``` var fileKey = Guid.NewGuid(); var fileStream = new Byte[Request.Files[0].ContentLength]; Request.Files[0].InputStream.Read(fileStream, 0, Request.Files[0].ContentLength); Cache[fileKey.ToString()] = fileStream; ``` The fileKey GUID can be stored in ViewState, or sent as the response to client. Later, when whole form will be saved, cached file can be retrieved and stored into database with other data. The good thing about this method is that if user navigates from the page cached file will expire, thus avoiding resource flooding. We can set expiration time using ``` Cache.Add(fileKey, fileStream, null, DateTime.UtcNow.AddMinutes(10), Cache.NoSlidingExpiration, CacheItemPriority.Default, null); ``` function.
How about: 3: Store it in the database but marked as in an incomplete state This could be a separate table, or the same table with a status column.
ASP.NET Uploaded File
[ "", "c#", "asp.net", "file", "file-upload", "" ]
I am looking for a javascript regex for whitespace. I am checking several different string in a loop and I need to locate the strings that have the big white space in them. The white space string is built in a loop, like this... please read this code as `var whitespace = "&nbsp;"` then the loop just concats more non breaking spaces on it. ``` var whitespace = "&nbsp;" for (var x = 0; x < 20; x++) { whitespace += "&nbsp;" } ``` then it is used later on in a string concat. ``` sometext += whitespace + someData; ``` I need to identify the strings that contain whitespace (20 spaces). Or should I just be doing a `contains(whitespace)` or something similar. Any help is appreciated. Cheers, ~ck in San Diego
If you have defined whitespace as 20 spaces, you can do ``` var input = whitespace + someData; if(input.indexOf(whitespace) != -1) { //input contains whitespace. } ``` There is no need to use regex when you can do without it.
For this specific question, Yogi is correct--you don't need regex and you're probably better off without it. For future reference, if anyone else comes looking, regex has a special character for whitespace: ``` \s ``` In JS parlance (where regex literals may be enclosed in forward slashes) if you're looking for 20 spaces (not tabs, line feeds, etc.) you can do this: ``` / {20}/ ``` You'll also want to note that many browser regex engines do not consider the non-breaking space to be whitespace. The unicode representation for the NBSP character is: ``` \u00A0 ``` Combined, looking for any combination of 20 whitespace characters (including tabs, etc.) OR NBSPs in a row (the square brackets denote a 'character class'): ``` /[\s\u00A0]{20}/ ``` **EDIT**: Incorporating thomas' point about NBSP. Give his comment and/or answer an up-vote if you would--I know I have.
javascript regex for whitespace or &nbsp;
[ "", "javascript", "regex", "" ]
I've just finished a web application written in PHP. I thought it was as easy as compressing my .php files and dumping my database in order to decompress those files in the "production" server, creating the database structure and database user, but it doesn't work. Several php files have include directives that are not working, I was using "relative" paths in those directives, I've tried `$_SERVER[DOCUMENT_ROOT]` and fixed the trailing slash issue in that parameter and still is not working. Any suggestions? Maybe you know some "tips" or "instalation-patterns" for PHP web applications.
Check the include\_path on the production server compared to your development machine-- the server may be looking for files in different locations compared to your own box. Regarding deployment there's two projects that I've come across that might be of some help (unfortunately, I've not used either; both are on my ever-growing to-do list): * [Phar](http://www.php.net/manual/en/book.phar.php) are PHP Archives; basically, a way of distributing apps in a .zip file that can be run without being unzipped * [Phing](http://www.phing.info/trac/) is a build tool similar to Apache Ant. It can be used to automate the deployment, say if you need files copied to many different locations.
Are you using the same version of php (and host operating system) on the new server as you were on the old one? PHP can parse your code differently in different version and installations.
PHP web application installation
[ "", "php", "scripting", "installation", "" ]
Using VS .NET 2003. Would like to run the .exe from outside the IDE (i.e. command prompt or double clicking .exe icon in windows) However, still want break points to hit in the IDE. How do I set this up? (Running from outside IDE but IDE seeing it as run from "Debug" -> "Start") Thanks.
On the Debug menu, choose the "Attach to process" option to attach a debugger to your externally-running application.
Visual Studio enables Just In Time Debugging by default. If you haven't turned it off you can call DebugBreak() and you will get a popup allowing you to attach a debugger. If you don't attach a debugger then the program will exit, so you could try wrapping the DebugBreak call in a MessageBox or some other conditional code based on an environment variable or config item.
Run .exe outside IDE but use break points inside IDE
[ "", "c++", "visual-studio", "debugging", "" ]
The actual question is: Is there a way to get XmlWebApplicationContext to load resources using paths relative to the context location? For clarity's sake, let's say "context location" is the location of the first file specified via `setConfigLocation()` method. Detailed explanation is below: I'm using Spring MVC in web tier and Spring IOC in mid tier. Appropriate contexts are defined hierarchically as described in [Spring Documentation](http://static.springsource.org/spring/docs/2.5.x/reference/mvc.html#mvc-servlet): web stuff is defined in `my-servlet.xml` and services et al are defined in `services.xml` that's loaded via `ContextLoaderListener`. Mid tier can be deployed either together with web tier (e.g. the whole thing runs within ServletContainer) or separately (in which case `services.xml` is replaced by `remote-services.xml` defining remote stubs). The whole setup works perfectly except for the following problem: I have certain resources (additional XML files, what have you) located in the same folder as `services.xml` that need to be accessible by said services. Those resources are specified as dependencies in `services.xml` using relative paths. When mid tier is deployed standalone that works fine, but not when it's deployed within servlet container. In the latter case mid tier context gets instantiated as `XmlWebApplicationContext` which loads all resources based of servlet context root meaning I have to prefix everything with **/WEB-INF/** which I'd really like to avoid. Using `PropertyPlaceholderConfigurer` presents a similar problem as well. I know I can work around this somewhat by having resources load from classpath, but that's not ideal either - for standalone deployment it means I need to add configuration folder to classpath and for web deployment it means everything has to be copied under WEB-INF/classes. Any ideas?
I've ended up extending Spring's `XmlWebApplicationContext` to allow relative resource paths. This does what I want, that is allows me to use the same context.xml file no matter whether it's deployed as part of web app or standalone. For anyone interested source is available below. It's published using SOV (Stack Overflow Voting) license :-) which means you're free to do whatever you want with it as long as you upvote this answer :-) ``` import java.io.IOException; import org.springframework.core.io.Resource; import org.springframework.util.StringUtils; import org.springframework.web.context.support.XmlWebApplicationContext; /** * Extends Spring's default web application context to allow relative * resource paths. Resources without explicitly specified URL protocol * and / or leading slash are loaded relative to the first location * from getConfigLocations(). */ public class SpringApplicationContext extends XmlWebApplicationContext { @Override protected Resource getResourceByPath(String path) { path = StringUtils.cleanPath(path); if (path.startsWith("/") || (path.indexOf(':')>0)) { return super.getResourceByPath(path); } try { return super.getResourceByPath(getConfigLocations()[0]) .createRelative(path); } catch (IOException E) { // failed to create relative resource - default to standard implementation return super.getResourceByPath(path); } } // getResourceByPath() } ```
I agree that is rather annoying. I get around this by doing what you suggest, which is putting my spring config on the classpath, so even though I still use fully-qualified imports, they work under any environment. I'm not sure why your classpath config needs to be that complex, though. The files can just under your java source folder alongside the java files, so they get handled the same.
Specifying relative resource path via Spring XmlWebApplicationContext
[ "", "java", "spring", "spring-mvc", "" ]
*If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.* Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this: ``` class DictModel(models.Model): key = models.CharField(20) value = models.CharField(200) DictModel.objects.all().to_dict() ``` ... with the result being a dictionary with the key/value pairs made up of records in the Model? Has anyone else seen this as being useful for them? Thanks. **Update** I just wanted to add is that my ultimate goal is to be able to do a simple variable lookup inside a Template. Something like: ``` {{ DictModel.exampleKey }} ``` With a result of DictModel.objects.get(key\_\_exact=exampleKey).value Overall, though, you guys have really surprised me with how helpful allof your responses are, and how different the ways to approach it can be. Thanks a lot. **Update October 2011:** This question is the top result if you Google "django model\_to\_dict", which is actually pretty awful given that it solves a different problem than what I was asking. What I wanted was to be able to map all of the instances in a queryset into a single dictionary with a specified model field as the key. model\_to\_dict, on the other hand converts a single model instance into a dictionary. Now, my needs at the time were pretty darn specific, and probably extremely rare (I can't even remember the project I needed it for, or why). So I would be pretty surprised that anyone looking for information about model\_to\_dict is going to find my question actually useful. Sorry. model\_to\_dict seems to be a much more common usage case than I had. **Update Dec 2011:** I changed the title to hopefully better reflect my original intent.
Does this need to create an actual dict? could you get by with only something that looked like a dict? ``` class DictModelAdaptor(): def __init__(self, model): self.model = model def __getitem__(self, key): return self.model.objects.get(key=key) def __setitem__(self, key, item): pair = self.model() pair.key = key pair.value = item pair.save() def __contains__(self, key): ... ``` You could then wrap a model in this way: ``` modelDict = DictModelAdaptor(DictModel) modelDict["name"] = "Bob Jones" ``` etc...
You can also rely on django code already written ;). ``` from django.forms.models import model_to_dict model_to_dict(instance, fields=[], exclude=[]) ```
Django: Converting an entire set of a Model's objects into a single dictionary
[ "", "python", "django", "django-models", "dictionary", "" ]
I defined a Java interface to represent the ability of an object to copy itself (no, I don't want to use `Cloneable`, but thanks for the suggestion ;-). It's generic: ``` public interface Copiable<T> { T copy(); } ``` An object will only make copies of its own type: ``` public class Foo implements Copiable<Foo> { Foo copy() { return new Foo(); } } ``` Now, I'm reading `Class<?>` objects from a non-generic API (Hibernate metadata, if that is of interest to anyone), and, if they are `Copiable`, I want to register them with one of my components. The `register` method has the following signature: ``` <T extends Copiable<T>> register(Class<T> clazz); ``` My problem is, how do I cast the class before passing it to the method? What I'm currently doing is: ``` Class<?> candidateClass = ... if (Copiable.class.isAssignableFrom(candidateClass)) { register(candidateClass.asSubclass(Copiable.class)); } ``` This does what I want, but with a compiler warning. And I don't think I'll be able to express the recursive bound in a runtime cast. Is there a way to rework my code to make it typesafe? Thanks
A runtime cast to `<? extends Copiable<?>` fails (in the `register()` call) because there's no way to declare that the first `?` and the second `?` are the same (unknown) thing. The `asSubclass()` call gives you a compiler warning for pretty much the same reason -- because the generics have been erased, there's no way at runtime to prove that a `Copiable` is a `Copiable<AnythingInParticular>`. You've proved that it's a `Copiable`, but you haven't proved that it's a `Copiable<Itself>`. I think the best you can hope for is to localize the warnings to one messy method, and add `@SuppressWarnings("unchecked")` and some comments. Do you know for sure this will work at runtime? I get the feeling the compiler's telling the truth here. Do the classes you're getting from Hibernate actually extend `Copiable`, or do they just happen to declare methods that match the `Copiable` interface? If it's the latter, then -- Java being a strongly typed language -- your `isAssignableFrom()` is always going to return false anyway.
There's no way to cast non-generic API to generic and not get a warning. You can use `@SuppressWarnings("unchecked")` annotation to suppress it. `Class<?>` is rather pointless in this case, too - you can use non-generic `Class candidateClass` instead.
Casting to a recursively bounded type
[ "", "java", "generics", "casting", "" ]
Is there a library for using MS Access database in python? The win32 module is not as easy as the MySQL library. Is there a simpler way to use MS Access with Python?
Depending on what you want to do, [pyodbc](https://github.com/mkleehammer/pyodbc) might be what you are looking for. ``` import pyodbc def mdb_connect(db_file, user='admin', password = '', old_driver=False): driver_ver = '*.mdb' if not old_driver: driver_ver += ', *.accdb' odbc_conn_str = ('DRIVER={Microsoft Access Driver (%s)}' ';DBQ=%s;UID=%s;PWD=%s' % (driver_ver, db_file, user, password)) return pyodbc.connect(odbc_conn_str) conn = mdb_connect(r'''C:\x.mdb''') # only absolute paths! ``` > **Note:** you may download the freely-redistributable [new-driver](https://www.microsoft.com/en-US/download/details.aspx?id=13255), if you don't have *MSOffice* installed.
I don't think win32 is hard. Try use its odbc module. Example of code working with ODBC and PostgreSQL database: ``` import odbc def get_pg_ver(db_alias): connection = odbc.odbc(db_alias) try: cursor = connection.cursor() cursor.execute('SELECT version()') for row in cursor.fetchall(): print row[0] finally: connection.close() get_pg_ver('odbc_name/user/passwd') ``` This is very similar for every db driver I used in Python and Jython (I work with PostgreSQL, Oracle and Informix).
MS Access library for python
[ "", "python", "ms-access", "" ]
Is there a.NET utility class equivalent to [java.util.Arrays.hashCode()](http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#hashCode(int[])) for arrays of intrinsic types such as int[], short[], float[], etc.? Obviously I could write my own utility class but was trying to find one already available in the .NET framework.
In .NET 4.0 arrays will support this via the [IStructuralEquatable](http://msdn.microsoft.com/en-us/library/system.collections.istructuralequatable%28VS.100%29.aspx) interface, but until that point you'll have to do it yourself I'm afraid.
I'm pretty sure there's nothing in the framework itself that does this. There may well be some third-party implementations, but there's nothing built-in (and public).
.NET equivalent to java.util.Arrays.hashCode() function for arrays of intrinsic types?
[ "", "java", ".net", "arrays", "hashcode", "gethashcode", "" ]
A while ago I was poking around with SQLite, trying to port some of my sites to use it instead of MySQL. I got hung up on the lack of a function to count results, like PHP's `mysql_num_rows()`. After searching a little I discovered [this mail list](http://osdir.com/ml/sqlite-users/2009-02/msg00505.html "Re: [sqlite] mysql_num_rows equivalent in SQLite: msg#00505 sqlite-users"), which says (as I understand it) that SQLite doesn't have that functionality because it's inefficient. It states that it is bad form to write code that needs to know how many rows are returned. I generally use `mysql_num_rows` to check for empty return results. For example: ``` $query = "SELECT * FROM table WHERE thing = 'whatever'"; $results = mysql_query($query); if (mysql_num_rows($results)) { while ($row = mysql_fetch_array($results)) { echo "<p>$row[whatever]</p>"; } } else { echo "<p>No results found</p>"; } ``` The vehement distaste for the concept of `mysql_num_rows()` in the SQLite community makes me wonder if it's that terribly efficient for regular MySQL in PHP. Is there a better, more accepted way for checking the size of a MySQL result set in PHP besides `mysql_num_rows()`? EDIT: I'm not just using `mysql_num_rows` to get the count--I would use a `COUNT` query for that. I'm using it to check if there are any results before outputting everything. This is useful for something like displaying search results - it's not always guaranteed that there will be results. In SQLite world, I have to send one `COUNT` query, check if there is something, and then send a `SELECT` query to get everything.
You already have something that is telling you if you've got results in `mysql_fetch_array()`. It returns false if there are no more rows to fetch (from [php.net](https://www.php.net/manual/en/function.mysql-fetch-array.php)). ``` $query = "SELECT * FROM table WHERE thing = 'whatever'"; $results = mysql_query($query); if($results) { $row = mysql_fetch_array($results); if($row) { do { echo "<p>{$row[whatever]}</p>"; } while($row = mysql_fetch_array($results)); } else { echo "<p>No results found</p>"; } } else { echo "<p>There was an error executing this query.</p>"; } ```
Regardless of whether or not you actually use what you **SELECT**ed, all of the rows are still returned. This is terribly inefficient because you're just throwing away the results, but you're still making your database do all of the work for you. If all you're doing is counting, you're doing all that processing for nothing. Your solution is to simply use **COUNT(\*)**. Just swap **COUNT(\*)** in where you would have your **SELECT** statement and you're good to go. However, this mostly applies to people using it as a complete substitute for **COUNT**. In your case, the usage isn't really bad at all. You will just have to manually count them in your loop (this is the preferred solution for SQLite users). The reason being is in the underlying SQLite API. It [doesn't return the whole result set](http://www.nabble.com/row-count-after-a-select-td20341773.html) at once, so it has no way of knowing how many results there are.
Is mysql_num_rows efficient and/or standard practice?
[ "", "php", "mysql", "sqlite", "" ]
If I declare a data structure globally in a C++ application , does it consume stack memory or heap memory ? For eg ``` struct AAA { .../.../. ../../.. }arr[59652323]; ```
Since I wasn't satisfied with the answers, and hope that the sameer karjatkar wants to learn more than just a simple yes/no answer, here you go. Typically a process has **5 different areas of memory allocated** 1. Code - text segment 2. Initialized data – data segment 3. Uninitialized data – bss segment 4. Heap 5. Stack If you really want to learn what is saved where then read and bookmark these: [COMPILER, ASSEMBLER, LINKER AND LOADER: A BRIEF STORY](http://www.tenouk.com/ModuleW.html) (look at Table w.5) [Anatomy of a Program in Memory](http://duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory) [![alt text](https://i.stack.imgur.com/oKcVI.png)](https://i.stack.imgur.com/oKcVI.png)
The problem here is the question. Let's assume you've got a tiny C(++ as well, they handle this the same way) program like this: ``` /* my.c */ char * str = "Your dog has fleas."; /* 1 */ char * buf0 ; /* 2 */ int main(){ char * str2 = "Don't make fun of my dog." ; /* 3 */ static char * str3 = str; /* 4 */ char * buf1 ; /* 5 */ buf0 = malloc(BUFSIZ); /* 6 */ buf1 = malloc(BUFSIZ); /* 7 */ return 0; } ``` 1. This is neither allocated on the stack NOR on the heap. Instead, it's allocated as static data, and put into its own memory segment on most modern machines. The actual *string* is also being allocated as static data and put into a read-only segment in right-thinking machines. 2. is simply a static allocated pointer; room for one address, in static data. 3. has the pointer allocated on the *stack* and will be effectively deallocated when `main` returns. The string, since it's a constant, is allocated in static data space along with the other strings. 4. is actually allocated exactly like at 2. The `static` keyword tells you that it's not to be allocated on the stack. 5. ...but `buf1` is on the stack, and 6. ... the malloc'ed buffer space is on the heap. 7. And by the way., kids don't try this at home. `malloc` has a return value of interest; you should *always* check the return value. For example: ``` char * bfr; if((bfr = malloc(SIZE)) == NULL){ /* malloc failed OMG */ exit(-1); } ```
Global memory management in C++ in stack or heap?
[ "", "c++", "memory-management", "stack", "" ]
Not entirely sure I posed the question in the best way but here goes... I have been playing around with the HTML5 canvas API and have got as far as drawing a shape in the canvas and getting it to move around with the arrow keys. I then tried to move my various variables and functions to a template so I could spawn multiple shapes (that would eventually be controlled by different keys). This is what I have: ``` function player(x, y, z, colour, speed){ this.lx = x; this.ly = y; this.speed = 10; this.playerSize = z; this.colour = colour; } playerOne = new player(100, 100, 10, "#F0F"); function persona(z, colour){ zone.fillStyle = colour; offset = 0 - (z / 2); zone.fillRect(offset, offset, z, z); } function move(x, y){ playerOne.lx = playerOne.lx + x; playerOne.ly = playerOne.ly + y; zone.clearRect(0, 0, 500, 500); zone.save(); zone.translate(playerOne.lx, playerOne.ly); persona(playerOne.playerSize, playerOne.colour); zone.restore(); } window.onkeydown = function() { var direction = this.event.keyCode; var s = playerOne.speed; // Arrow Keys if( direction == 38 && playerOne.ly >= 10){ // Up move(0,-s); } if( direction == 40 && playerOne.ly <= 490){ // Down move(0,s); } if( direction == 37 && playerOne.lx >= 10){ // Left move(-s,0); } if( direction == 39 && playerOne.lx <= 490){ // Right move(s,0); } }; window.onload = function() { zone = document.getElementById('canvas').getContext('2d'); zone.save(); zone.translate(playerOne.lx, playerOne.ly); persona(playerOne.playerSize, playerOne.colour); zone.restore(); }; ``` So what I tried to do was move the persona function into the player template like this: ``` function player(x, y, z, colour, speed){ this.lx = x; this.ly = y; this.speed = 10; function persona(){ zone.fillStyle = colour; var offset = 0 - (z / 2); zone.fillRect(offset, offset, z, z); } } ``` And then where before it said ``` persona(playerOne.playerSize, playerOne.colour); ``` it now just says ``` playerOne.persona(); ``` But this is just totally flaking out and not working and I can't figure out why. I'm probably going about it all the wrong way and I think the problem is that I'm trying to manipulate the canvas.context (call zone in my script) from within a object/template. Perhaps its nothing to do with that at all and I an just not declaring my persona functions properly in the context of the template. Documentation for the canvas API is very thin on the ground and any hint in the right direction will be very much appreciated.
Been hacking away at this for a few more minutes and got the following which is basically what I was trying to achieve from the start. I went in a slightly different direction with this but I would still like any feedback anyone may want to give. ``` function Player(x, y, z, colour, speed){ this.lx = x; this.ly = y; this.speed = speed; this.it = false; this.playerSize = z; this.colour = colour; this.move = move; this.draw = persona; } function move(dx, dy){ this.lx = this.lx + (dx * this.speed); this.ly = this.ly + (dy * this.speed); } function persona(){ zone.fillStyle = this.colour; var offset = 0 - (this.playerSize / 2); zone.fillRect(offset, offset, this.playerSize, this.playerSize); } playerOne = new Player(400,400, 10, "#F0F", 10); playerTwo = new Player(100,100, 10, "#0F0", 10); function drawPlayers(){ zone.clearRect(0, 0, 500, 500); zone.save(); zone.translate(playerOne.lx, playerOne.ly); playerOne.draw(); zone.restore(); zone.save(); zone.translate(playerTwo.lx, playerTwo.ly); playerTwo.draw(); zone.restore(); } window.onkeydown = function() { var direction = this.event.keyCode; // Arrows if( direction == 38 && playerOne.ly >= 10){ // Up playerOne.move(0,-1); } if( direction == 40 && playerOne.ly <= 490){ // Down playerOne.move(0,1); } if( direction == 37 && playerOne.lx >= 10){ // Left playerOne.move(-1,0); } if( direction == 39 && playerOne.lx <= 490){ // Right playerOne.move(1,0); } // WASD if( direction == 87 && playerTwo.ly >= 10){ // Up playerTwo.move(0,-1); } if( direction == 83 && playerTwo.ly <= 490){ // Down playerTwo.move(0,1); } if( direction == 65 && playerTwo.lx >= 10){ // Left playerTwo.move(-1,0); } if( direction == 68 && playerTwo.lx <= 490){ // Right playerTwo.move(1,0); } drawPlayers(); }; window.onload = function() { zone = document.getElementById('canvas').getContext('2d'); drawPlayers(); }; ```
Just commenting that your Player.draw method should be able to handle positioning your sprites on the canvas. This code behaves the same way as your solution, but hopefully is clearer and more compact. ``` function Player(x, y, z, colour, speed){ this.lx = x; this.ly = y; this.speed = speed; this.it = false; this.playerSize = z; this.colour = colour; } Player.prototype = { move: function(dx, dy){ this.lx = this.lx + (dx * this.speed); this.ly = this.ly + (dy * this.speed); }, draw: function(){ var size = this.playerSize, offset = size / 2; zone.fillStyle = this.colour; zone.fillRect(playerTwo.lx - offset, playerTwo.ly - offset, size, size); } }; playerOne = new Player(400,400, 10, "#F0F", 10); playerTwo = new Player(100,100, 10, "#0F0", 10); function drawPlayers(){ zone.clearRect(0, 0, 500, 500); playerOne.draw(); playerTwo.draw(); } ```
Can you declare <canvas> methods within a template in javascript?
[ "", "javascript", "oop", "templates", "canvas", "" ]
Is there a built in (to the .net framework) class or function to resolve a SRV entry to the corresponding records? IE: \_dmsc.\_tcp.network.local to an array of information (host, port, weight, priority)
Open source, BSD licensed library here: <http://dndns.codeplex.com/>
Alternative solution: P/Invoke to the [`DnsQuery`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms682016%28v=vs.85%29.aspx) function and pass [DNS\_TYPE\_SRV](http://msdn.microsoft.com/en-us/library/windows/desktop/cc982162%28v=vs.85%29.aspx). An example can be found in [this excellent post by Ruslan](http://randronov.blogspot.com/2013/03/lookup-srv-record-in-c.html). I reproduce the code below in case the link breaks, but emphasize it is taken directly from his blog. ``` public class nDnsQuery { public nDnsQuery() { } [DllImport("dnsapi", EntryPoint = "DnsQuery_W", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] private static extern int DnsQuery([MarshalAs(UnmanagedType.VBByRefStr)]ref string pszName, QueryTypes wType, QueryOptions options, int aipServers, ref IntPtr ppQueryResults, int pReserved); [DllImport("dnsapi", CharSet = CharSet.Auto, SetLastError = true)] private static extern void DnsRecordListFree(IntPtr pRecordList, int FreeType); public static string[] GetSRVRecords(string needle) { IntPtr ptr1 = IntPtr.Zero; IntPtr ptr2 = IntPtr.Zero; SRVRecord recSRV; if (Environment.OSVersion.Platform != PlatformID.Win32NT) { throw new NotSupportedException(); } ArrayList list1 = new ArrayList(); try { int num1 = nDnsQuery.DnsQuery(ref needle, QueryTypes.DNS_TYPE_SRV, QueryOptions.DNS_QUERY_BYPASS_CACHE, 0, ref ptr1, 0); if (num1 != 0) { if (num1 == 9003) { list1.Add("DNS record does not exist"); } else { throw new Win32Exception(num1); } } for (ptr2 = ptr1; !ptr2.Equals(IntPtr.Zero); ptr2 = recSRV.pNext) { recSRV = (SRVRecord)Marshal.PtrToStructure(ptr2, typeof(SRVRecord)); if (recSRV.wType == (short)QueryTypes.DNS_TYPE_SRV) { string text1 = Marshal.PtrToStringAuto(recSRV.pNameTarget); text1 += ":" + recSRV.wPort; list1.Add(text1); } } } finally { nDnsQuery.DnsRecordListFree(ptr1, 0); } return (string[])list1.ToArray(typeof(string)); } private enum QueryOptions { DNS_QUERY_ACCEPT_TRUNCATED_RESPONSE = 1, DNS_QUERY_BYPASS_CACHE = 8, DNS_QUERY_DONT_RESET_TTL_VALUES = 0x100000, DNS_QUERY_NO_HOSTS_FILE = 0x40, DNS_QUERY_NO_LOCAL_NAME = 0x20, DNS_QUERY_NO_NETBT = 0x80, DNS_QUERY_NO_RECURSION = 4, DNS_QUERY_NO_WIRE_QUERY = 0x10, DNS_QUERY_RESERVED = -16777216, DNS_QUERY_RETURN_MESSAGE = 0x200, DNS_QUERY_STANDARD = 0, DNS_QUERY_TREAT_AS_FQDN = 0x1000, DNS_QUERY_USE_TCP_ONLY = 2, DNS_QUERY_WIRE_ONLY = 0x100 } private enum QueryTypes { DNS_TYPE_A = 0x0001, DNS_TYPE_MX = 0x000f, DNS_TYPE_SRV = 0x0021 } [StructLayout(LayoutKind.Sequential)] private struct SRVRecord { public IntPtr pNext; public string pName; public short wType; public short wDataLength; public int flags; public int dwTtl; public int dwReserved; public IntPtr pNameTarget; public short wPriority; public short wWeight; public short wPort; public short Pad; } } ```
Using DNS SRV records with C#
[ "", "c#", "dns", "service-discovery", "srv", "" ]
I am working on implementing use of the mysql class found [here](http://www.ricocheting.com/scripts/php_mysql_wrapper.php) in an existing script. The script almost always needs to interact with the database, even if there are times when it does not. What is the best practice in this case? Should I open a connection and keep that open until the end of the script or should I open a connection when I need one, closing it when I'm done, to avoid opening a connection when the script does not need it?
Because connections are rather expensive, as others have pointed out, I'd recommend using a "lazy connect" technique in your database layer. If you have structured your application effectively, your application logic should not be concerned with when connections are opened and closed as this would be encapsulated in the database layer. The database layer, when asked to perform a query, would first check to see if it has an active connection and if not, create one. This way you'll avoid opening connections that are never used and you'll also have a nice separation of logic between your application and the database code.
Well, if you are using a class, the connection should be opened automatically when you instantiate the class, or when the first query is performed. If you never use the class, the connection wouldn't be opened. While it is good practice to close it when you don't need it, it doesn't hurt to let it be closed when the request thread dies. This can be bad if you don't have a resource limits set in your php.ini file, the request could possible live forever and never close the connection. If you have a medium-to-high traffic site, you should be thinking about using [mysql\_pconnect](https://www.php.net/manual/en/function.mysql-pconnect.php) anyways so there is always a connection open and you don't need the overhead of opening one on every request.
Where and when to open a database connection
[ "", "php", "mysql", "" ]
Can the API for Google Maps be used to retrieve the latitude and longitude for a given Postal Code or City+Region combination for foreign countries such as The United Kingdon, France, Italy, Japan, Australia etc. ? I am working on a project that requires local search results. For domestic users I retrieve their lat/lon via a U.S Zip Codes Table in our database. It does not involve showing any maps, just results of other users who are in their area via a radius formula based on lat/lon values. For foreign users' local search results: I am just showing results based on matching City Name. At the moment non-U.S users lat/lon is being retrieved via PHP GeoIP data. I'd like to be able to retrieve more accurate values depending on the city+region or postal code the user provides. I am considering getting postal code tables (which have lat/lon fields) for other countries. Or is the Google Map API idea a better solution?
I have found the results from the [Google Maps Geocoder](http://code.google.com/apis/maps/documentation/reference.html#GClientGeocoder) to be pretty good. To test out your foreign postcodes or addresses (without writing any code), just attach the country name to the string and try it out in the [google maps](http://maps.google.com/) search box. Or, you can implement the lookup pretty quickly in Javascript: ``` geo = new GClientGeocoder (); geo.getLatLng("2337, Australia", function (point) { GLog.write(point.lat() + "," point.lng()); }); ```
I've previously used Google Maps for its geocoding, works well and can work for anywhere in the world. Use the GClientGeocoder from google and use the 'setBaseCountryCode(countryCode:String)' method to set it to the countries top-level domain (<http://en.wikipedia.org/wiki/CcTLD>)
Getting the Latitude and Longitude for areas outside the U.S
[ "", "php", "google-maps", "geocoding", "" ]
Looking for an example of connecting via ADODB to Active Directory using C#. My goal is to be able to run a lookup to verify that a user is valid in Active Directory based on one that of that users attributes (user id, email address, etc). [Would like to stress that using ADODB is a requirement for this, using DirectoryServices is not a valid response.] My current approach isn't working (exception at cmd.Execute bit): ``` object parms = null; object recs = null; ADODB.Connection conn = new ADODB.Connection(); ADODB.Command cmd = new ADODB.Command(); ADODB.Recordset rs = new ADODB.Recordset(); conn.Open("Provider=ADsDSOObject",obfsUser,obfsPass,0); cmd.ActiveConnection = conn; cmd.CommandText = "<LDAP://OU=obfsOU,DC=obfsDC,DC=corp,DC=Net>;;name;subtree"; rs = cmd.Execute(out recs, ref parms, 0); ``` I'm not sure if/where I'm supposed to provide the server reference and I'm not really sure what the parameteres passed into the cmd.Execute method by ref should be. Not a ton of documentation out there for connecting to ActiveDirectory from C# via ADODB. conn.State is returning 1 so I believe I am getting an active connection. I think the problem is in the parameters passed to the cmd.Execute() method.
This works. Hope this helps someone else having the same need and problems I had. [Note the lack of an ADODB.Command object and the use of SQL format for the query instead of ADSI format.] ``` object recs; ADODB.Connection conn = new ADODB.Connection(); ADODB.Recordset rs = new ADODB.Recordset(); // You may need to provide user id and password instead of empty strings conn.Open("Provider=ADsDSOObject", "", "", 0); // replace <> elements with your server name and OU/DC tree org string server = "<enter your server name here>"; string start = "OU=<blah>,DC=<blah>,DC=<blah>,DC=<blah>"; string where = "objectClass = '*'"; string qry = string.Format("SELECT cn FROM 'LDAP://{0}/{1}' WHERE {2}", server, start, where); rs = conn.Execute(qry, out recs, 0); for (; !rs.EOF; rs.MoveNext()) { Console.WriteLine(rs.Fields["cn"].Value.ToString()); } ```
The answer by ScottCher works but it has limitations, notably that you cannot deal with the 1000 record result limit. To do that, the *only* way is to use a Command object, and believe me, that is a minefield because there is (a) no good documentation on the C# interfaces, and (b) there is incredibly no full solution that can be Googled as of this writing. I have spent the last bunch of days on this, and have something working that I would like to give back to all the sources I have read with various bits and pieces to the puzzle. First, as noted in a ton of places (sadly with VB examples only!), if you don't do something special then all ADSI queries are limited to 1000 rows of results. The key to avoiding this is to set the "Page Size" property on the Command object. We'll get to that in a sec, but first we need to get the basic query working using a Command. If you use the original code in this thread, you will get an exception on cmd.Execute complaining about parameters mismatching. You would think that passing in null as the ref object would suffice, especially since the LDAP syntax does not (apparently) have parameters. I found the answer to this in two places. First, even though you are not explicitly specifying parameters, it would seem that the ":" in the LDAP SQL syntax is enough to make ADO think that parameters are required. Odd, but seemingly true. Second, the CORRECT way to specify the "no parameters" case is to set the value to Type.Missing, not null, as in: `object parms = Type.Missing;` This was key to getting Execute to not throw an exception. Now with a working Command we can now address the 1000 row limit. This is "simply" by specifying the "Page Size" property on the Command but, as it obvious from the C# interface, it is not the same as a C# property. You need to put it into the Properties collection, but this does not expose a nice collection interface to do that with. After some trial and error, the correct syntax is: `cmd.Properties["Page Size"].Value = 500;` I don't think it is important exactly what the page size is (still playing with that) but setting it to something is enough to tell ADSI to get all the results. And I sincerely hope this helps somebody.
How do I query Active Directory using C# and ADODB?
[ "", "c#", "active-directory", "adodb", "" ]
I have a class library (in C#). I need to encode my data using the HtmlEncode method. This is easy to do from a web application. My question is, how do I use this method from a class library that is being called from a console application?
Import System.Web Or call the System.Web.HttpUtility which contains it You will need to add the reference to the DLL if it isn't there already ``` string TestString = "This is a <Test String>."; string EncodedString = System.Web.HttpUtility.HtmlEncode(TestString); ```
[`System.Net.WebUtility`](https://learn.microsoft.com/en-us/dotnet/api/system.net.webutility) class is available starting from .NET Framework 4.0 — you donʼt need System.Web dependency.
HtmlEncode from Class Library
[ "", "c#", "html-encode", "" ]
There is a reference table that shows the execution cost of every php function? I know that the *time execution* is boundet to many factors and is impossible to determinate an unique value, but im looking for a 'ideological' table. For example, ``` is_dir() = cost 3 is_file() = cost 2 ``` (take it JUST as an example ;) If i dont remember bad, for C there is a table with cpu cycles needed to every operation.. **EDIT**: i read all you comment, and so there are any table for my needs. Anyway, i know that ``` is_dir('/');//is faster than is_dir('/a/very/long/path/to/check/'); ``` But, i have some trouble to accept this situation (that, if i have understood right your words, is possible); ``` $a = '/'; $b = '/a/very/long/path/to/check/'; is_dir($a); //time execution 0.003 is_file($a); //time execution 0.005 //so suppose is_dir is faster than is_file //(still example, function names and number are random ;) is_dir($b); //time execution 0.013 is_file($b); //time execution 0.009 //wow, now is faster is_file()....? ```
Such a chart would not be helpful or accurate. In your example, the timing of the function would depend very much on the details of the local filing system and would quickly become meaningless. The only true way to measure performance is to build your code, then time it. Is for faster than while? Maybe one will be better than the other in one situation, while the other would be faster in another situation, depending on all kinds of factors that would be specific to the code within. Time your code, using a profiler, and get some meaningful data that is accurate for your project on your server environment.
I'm not aware of such a table. The cost of a function will vary a lot depending on the input. A 1000 item array being processed by array\_unique() will take longer than the same function with a 5 item input array. If you're interested in tuning your application you could use microtime to time the execution of each function call. It would look something like this ``` $starttime = microtime(); is_dir('/var/foo'); $stoptime = microtime(); echo "is_dir cost: ".($stoptime-$startime); ```
PHP Function execution cost table
[ "", "php", "execution-time", "micro-optimization", "" ]
I have been using gcc, g++ for my C, C++ application development till now and have found it to be amazing. But browsing through Stack Overflow I found many members stating that error reporting in Comeau compiler is much more than any other compiler. Is this true? I haven't invested in any commercial release of a compiler. Is it really worth spending money on a commercial release of a C/C++ compiler when gcc, g++ are doing the trick?
My experience with writing C++ is that compiling your code with more than one compiler is a great way to find odd corner-cases in your code. In our case, we've used gcc, Apple gcc, and the Visual Studio compiler cl (which is free). When on Windows, I prefer the cl compiler since it compiles faster (around five times faster for us) and it produces better code (around 30% faster last time I checked). Which compiler produces the fastest code is always dependent on the application though. In our particular case the Intel compiler is not so good at producing fast code contrary to popular opinion, so there is no real incentive to use it. If we had the money to spend, compiling with Comeau would be nice to help with additional checking for standards conformance. Apart from that, I'm happy with the compilers we use.
The killer feature of the Comeau compiler is its conformance (including C++03!) and excellent error reporting. There's an online way to try it out too: <http://www.comeaucomputing.com/tryitout/> The Comeau compiler is definitely worth it if these features are worth it to you. Hats off to the Comeau compiler!
Is comeau compiler worth it compared to gcc?
[ "", "c++", "c", "gcc", "compiler-construction", "comeau", "" ]
If I put a control in a .aspx file like this; ``` <asp:TextBox ID="protectedTextBox" runat="server">Some info</asp:TextBox> ``` I get a declared control in the page's .aspx.designer.cs file; ``` protected global::System.Web.UI.WebControls.TextBox protectedTextBox; ``` But I'd like to change the access modifier of the control to `public`. Is there any attribute or similar that I can set to change the access modifier? Here's *why* I want to do it. I am trying to have cross-page postbacks work nice and neatly. I have two pages: ``` FirstPage.aspx MyTextBox : textbox MyButton : button, @PostbackUrl=Secondpage SecondPage.aspx MyLabel : label ``` When the user clicks FirstPage.MyButton, I want to write the value of `FirstPage.MyTextBox.Text` into `SecondPage.MyLabel.Text`. I could do it with Page.FindControl, but this seems like a poor substitute to casting the previous page as a FirstPage object and referring directly to the MyTextBox control on it. Something like this; ``` // on the page_load of SecondPage.aspx; var previousPage = this.PreviousPage as FirstPage; this.MyLabel.Text = previousPage.MyTextBox.Text; ``` Is there any way to change the access modifier?
You can just delete the declaration from the designer and put it in your code behind. The comments around the declaration say to do this. ``` /// To modify move field declaration from designer file to code-behind file. ```
One option I've considered is writing a public property which exposes the original page; ``` public TextBox PublicTextBox { get { return this.MyTextBox; } } ``` Which would get the job done, but seems hacky.
Change the Access Modifiers of ASP.NET controls
[ "", "c#", "asp.net", "controls", "access-modifiers", "" ]
In JavaScript let's say we have the following code ``` var test = 'd'; if (test != 'a' && test != 'b' && test != 'c') alert('were good to go'); ``` This *if* seems rather lengthy to me. I would love to write something like ``` if (test != ('a' && 'b' && 'c') alert('were good to go'); ``` Sadly this doesn't work. What is a more elegant way to write this?
``` var test = 'd'; if (!/[abc]/.test(test)) alert('were good to go'); ```
You can't get do that, but you can get fairly close like this: ``` Array.prototype.contains = function(v) { for (var i = 0; i < this.length; i++) { if (this[i] == v) return true; } return false; } if (!['a', 'b', 'c'].contains('d')) { alert('good to go'); } ``` Most decent JS libs should contains lots of variations on list prototypes like this.
Visually Optimizing JavaScript Conditional Operators that are stringed together
[ "", "javascript", "conditional-operator", "" ]
Ok after reading this article and also some of the examples I am still not clear on what global variables mean. So its say private variables in your class are global? <http://www.c2.com/cgi/wiki?GlobalVariablesAreBad> So can someone explain this to me in simple terms the context. Does this mean even private fields at the top of your class? I'm not clear on the definition of a "global variable" so that I can distinguish if I'm doing something "bad" in my classes.
In C# an example of a global variable would be a public static variable on a public class. The entire program could read/write to it and it would be shared across threads as well.
A private field in your class would generally be called a "class level variable". It isn't global to your application because only your class has access to it. A global variable is a variable that anything in your program can access no matter what scope it's in. An example of a global variable would be something like the `Application` object in ASP.Net (a public static instance of an HttpApplication class). Any object, at any time, in any code-behind file, can have access to the `Application` object to look for that value. Generally, storing values to the `Application` object is a bad idea unless you really know what you're doing, for all the reasons mentioned in the article that you linked.
Global Variables Bad
[ "", "c#", "" ]
I'm trying to test web service calls using an ASP.NET page that creates a form with username and password fields and a "Submit" button. (Both jQuery and the .js file I'm using are included in script tags in the head element.) The "Submit" button calls a function created in the C# code behind file that makes a call to a separate JavaScript file. ``` protected void mSubmit_Click(object sender, EventArgs eventArgs) { String authenticate = String.Format("Authentication(\"{0}\",\"{1}\");", this.mUsername.Text,this.mPassword.Text); Page.ClientScript.RegisterStartupScript(this.GetType(), "ClientScript", authenticate, true); } ``` The JavaScript function, `Authenticate`, makes web service call, using jQuery and Ajax, to a different server, sending JSON parameters and expecting back JSON in response. ``` function Authentication(uname, pwd) { //gets search parameters and puts them in json format var params = '{"Header":{"AuthToken":null,"ProductID":"NOR","SessToken":null,"Version":1},"ReturnAuthentication":true,"Password":"' + pwd + '","Username":"' + uname + '",”ReturnCredentials”:false }'; var xmlhttp = $.ajax({ async: false, type: "POST", url: 'https://myHost.com/V1/Identity/Authenticate', data: params, contentType: 'application/json' }); alert(xmlhttp.statusText); alert(xmlhttp.responseText); return; } ``` However, because the web service I'm calling is on a different server than the ASP.NET, C# and JavaScript files, I'm not getting a `statusText` or `responseText` alert. Somehow, nothing is being sent to the web service and I'm not getting anything back, not even an error. I tried putting a function in the `beforeSend` attribute, but that didn't fire. Is there a special way I need to handle calling an off-server web service? **UPDATE!** At the advice of jjnguy, Janie and Nathan, I'm now trying a server side call to the web service using HttpWebRequest. Using some of jjnguy's code as well as code from [this question](https://stackoverflow.com/questions/575893/why-does-my-c-client-posting-to-my-wcf-rest-service-return-400-bad-request), I've come up with this. ``` public static void Authenticate(string pwd, string uname) { string ret = null; HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://myhost.com/V1/Identity/Authenticate"); request.ContentType = "application/json"; request.Method = "POST"; string data = "{\"Header\":{\"AuthToken\":null,\"ProductID\":\"NOR\",\"SessToken\":null,\"Version\":1},\"ReturnAuthentication\":true,\"Password\":\"" + pwd + "\",\"Username\":\"" + uname + "\",\"ReturnCredentials\":false }'"; byte[] byteData = UTF8Encoding.UTF8.GetBytes(data); request.ContentLength = byteData.Length; using (Stream postStream = request.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (response) { // Get the response stream StreamReader reader = new StreamReader(response.GetResponseStream()); // Console application output ret = reader.ReadToEnd(); } Console.WriteLine(ret); } ``` However, I'm getting a `(400) Bad Request` error from the remote server when I try to get the response from my HttpWebRequest. The value of the Response property of the exception says `{System.Net.HttpWebResponse}` and the value of the Status property is `ProtocolError`. I'm pretty sure this is because the URL is using HTTP SSL protocol. What can I do to get around that, other than having the ASP.NET page URL start with HTTPS (not an option)?
Turns out the code that I posted in my update was correct, I just had a typo and one setting incorrect in the data string. ``` string data = "{\"Header\":{\"AuthToken\":null,\"ProductID\":\"NOR\",\"SessToken\":null,\"Version\":1},\"ReturnAuthentication\":true,\"Password\":\"" + pwd + "\",\"Username\":\"" + uname + "\",\"ReturnCredentials\":true}"; ```
For simplicity's sake, why don't you write the call to the webservice in C# on the Server Side? You have the same abilities to send requests and get responses in C# as you do with Javascript. Here is a crack at your function in C#: ``` public static string Authenticate(string pwd, string uname) { HttpWebRequest requestFile = (HttpWebRequest)WebRequest.Create("https://myHost.com/V1/Identity/Authenticate"); requestFile.ContentType = "application/json"; requestFile.Method = "POST"; StreamWriter postBody = new StreamWriter(requestFile.GetRequestStream()) using (postBody) { postBody.Write("{\"Header\":{\"AuthToken\":null,\"ProductID\":\"NOR\",\"SessToken\":null,\"Version\":1},\"ReturnAuthentication\":true,\"Password\":\"" + pwd + "\",\"Username\":\"" + uname + "\",\"ReturnCredentials\":false }'"); } HttpWebResponse serverResponse = (HttpWebResponse)requestFile.GetResponse(); if (HttpStatusCode.OK != serverResponse.StatusCode) throw new Exception("Url request failed. Connection to the server inturrupted"); StreamReader responseStream = new StreamReader(serverResponse.GetResponseStream()); string ret = null; using (responseStream) { ret = responseStream.ReadLine(); } return ret; } ``` *Disclaimer* This has not been tested.
Call webservice on outside server from javascript using asp.net and C#
[ "", "c#", "web-services", "https", "httpwebrequest", "bad-request", "" ]
For my new Pet-Project I have a question for design, that is decided already, but I want some other opinions on that too. I have two classes (simplified): ``` class MyObject { string name {get;set;} enum relation {get;set;} int value {get;set;} } class MyObjectGroup { string name {get;set;} enum relation {get;set;} int value {get;set;} List<MyObject> myobjects {get;set;} } ``` Later in the Project `MyObjectGroup` and `MyObject` should be used equally. For this I could go two ways: * Create an interface: `IObject` * Create an abstract class: `ObjectBase` I decided to go the way of the interface, that I later in code must not write `ObjectBase` every time but `IObject` just for ease - but what are other positives for this way? And second, what about adding `IXmlSerializable` to the whole story? Let the interface inherit from `IXmlSerializable` or does it have more positives to implement `IXmlSerializable` in abstract base class?
Generally speaking, the approach I use in this kind of situation is to have both an interface and an abstract class. The interfaces defines, well, the interface. The abstract class is merely a helper. You really can't go wrong with this approach. Interfaces give you the flexibility to change implementation. Abstract classes give you boilerplate and helper code that you aren't forced to use, which you otherwise would be if your methods were defined in terms of an abstract class explicitly.
These are some of the differences between Interfaces and Abstract classes. **1A.** A class may inherit (Implement) one or more interfaces. So in C#, interfaces are used to achieve multiple inheritance. **1B.** A class may inherit only one abstract class. **2A.** An interface cannot provide any code, just the signature. **2B.** An abstract class can provide complete, default code and/or just the details that have to be overridden. **3A.** An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public. **3B.** An abstract class can contain access modifiers for the subs, functions, properties. **4A.** Interfaces are used to define the peripheral abilities of a class. For eg. A `Ship` and a `Car` can implement a `IMovable` interface. **4B.** An abstract class defines the core identity of a class and there it is used for objects. **5A.** If various implementations only share method signatures then it is better to use Interfaces. **5B.** If various implementations are of the same kind and use common behaviour or status then abstract class is better to use. **6A.** If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. **6B.** If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly. **7A.** An interface can not have fields defined. **7B.** An abstract class can have fields and constants defined. **8A.** An interface can not have constructor. **8B.** An abstract class can have default constructors implemented. **9A.** An interface can only inherit from other interfaces. **9B.** An abstract class can inherit from interfaces, abstract class, or even class.
Interface or abstract class?
[ "", "c#", "interface", "theory", "abstract", "" ]
I have some properties in an object that I would like to add to the global namespace. In javascript on the browser I could just add it to the `window` object like so: ``` var myObject = { foo : function() { alert("hi"); } // and many more properties }; for (property in myObject) { window[property] = myObject[property]; } // now I can just call foo() foo(); ``` But since rhino doesn't have the global window object I can't do that. Is there an equivalent object or some other way to accomplish this?
You could use `this`, which refers to the global object if the current function is not called as a method of an object.
I found a rather brilliant solution at [NCZOnline](http://www.nczonline.net/blog/2008/04/20/get-the-javascript-global/): ``` function getGlobal(){ return (function(){ return this; }).call(null); } ``` > The key to this function is that the this object always points to the global object anytime you are using `call()` or `apply()` and pass in null as the first argument. **Since a null scope is not valid, the interpreter inserts the global object.** The function uses an inner function to assure that the scope is always correct. Call using: ``` var glob = getGlobal(); ``` `glob` will then return `[object global]` in Rhino.
How can I add an object property to the global object in rhino javascript
[ "", "javascript", "rhino", "" ]
`touch` is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions. How would you implement it as a Python function? Try to be cross platform and complete. (Current Google results for "python touch file" are not that great, but point to [os.utime](http://docs.python.org/library/os.html#os.utime).)
Looks like this is new as of Python 3.4 - [`pathlib`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.touch). ``` from pathlib import Path Path('path/to/file.txt').touch() ``` This will create a `file.txt` at the path. -- > Path.touch(mode=0o777, exist\_ok=True) > > Create a file at this given path. If mode is given, it is combined with the process’ umask value to determine the file mode and access flags. If the file already exists, the function succeeds if exist\_ok is true (and its modification time is updated to the current time), otherwise FileExistsError is raised.
This tries to be a little more race-free than the other solutions. (The `with` keyword is new in Python 2.5.) ``` import os def touch(fname, times=None): with open(fname, 'a'): os.utime(fname, times) ``` Roughly equivalent to this. ``` import os def touch(fname, times=None): fhandle = open(fname, 'a') try: os.utime(fname, times) finally: fhandle.close() ``` Now, to really make it race-free, you need to use [`futimes`](http://www.kernel.org/doc/man-pages/online/pages/man3/lutimes.3.html) and change the timestamp of the open filehandle, instead of opening the file and then changing the timestamp on the filename (which may have been renamed). Unfortunately, Python doesn't seem to provide a way to call `futimes` without going through `ctypes` or similar... --- **EDIT** As noted by [Nate Parsons](https://stackoverflow.com/users/34910/nate-parsons), Python 3.3 will [add](http://bugs.python.org/issue10812) [specifying a file descriptor](http://docs.python.org/dev/library/os.html#path-fd) (when [`os.supports_fd`](http://docs.python.org/dev/library/os.html#os.supports_fd)) to functions such as [`os.utime`](http://docs.python.org/dev/library/os.html#os.utime), which will use the `futimes` syscall instead of the `utimes` syscall under the hood. In other words: ``` import os def touch(fname, mode=0o666, dir_fd=None, **kwargs): flags = os.O_CREAT | os.O_APPEND with os.fdopen(os.open(fname, flags=flags, mode=mode, dir_fd=dir_fd)) as f: os.utime(f.fileno() if os.utime in os.supports_fd else fname, dir_fd=None if os.supports_fd else dir_fd, **kwargs) ```
Implement touch using Python?
[ "", "python", "utility", "" ]
In the following scenario: ``` struct Foo { // ... operator Bar() {... } // implicit cast to Bar } Foo GetFoo() { ... } void CallMeBar(Bar x) { ... } // ... CallMeBar( GetFoo() ); ``` [edit] fixed the cast operator, d'oh[/edit] `GetFoo` returns a temporary object of Type Foo. Does this object survive until after CallMe returns? What does the standard say? I understand that if `CallMe` would accept Foo, the temporary object would not be destroyed until after `CallMe` returns. I am not sure, however, fi the implicit cast changes this, and only the temporary `Bar` is guaranteed to survive. --- A typical case would be Foo = CString, Bar = char \*, i.e. Bar referencing data held by (and freed by) Foo.
Regardless of the cast, the temporary object(s) will "survive" the call to `CallMe()` function because of the C++ standard: 12.2.3 [...] Temporary objects are destroyed as the last step in evaluating the fullexpression (1.9) that (lexically) contains the point where they were created. [...] 1.9.12 A *fullexpression* is an expression that is not a subexpression of another expression.
It will survive, but relying in that fact may be confusing, and may cause clients of your code to reach for the C++ Standard, ask questions on Stack Overflow, etc ;-). For instance what happens when someone does: ``` Bar b = GetFoo(); CallMeBar(b); ``` This time, the Foo has gone before CallMeBar is called, but most programmers would want conversions to create an independent object, and hence for the code to behave the same as: ``` CallMeBar(GetFoo()); ``` This is why `std::string` does not have an implicit cast to `char*`, unlike `CString`'s cast to `LPCTSTR`. Instead, `std::string` has the `c_str()` member function, which has the same constraint but makes it a bit more obvious in calling code that it's not a real conversion: ``` CallMePtr(GetString().c_str()); // OK char* p = GetString().c_str(); // Bad CallMePtr(p); // Badness manifests const string &s = GetString(); // use "the most important const" CallMePtr(s.c_str()); // Best be on the safe side ```
temporary object, function parameters and implicit cast
[ "", "c++", "" ]
I created a costumer's database program. I have a problem in which I create a data module in a DLL and I compile it but then get some error below. My concept is > The data module created in DLL and I insert ADO components in the data module. > This data module is used in another form. I created a db grid in the form but it doesn't > show the records in db grid. I compile it but get an error below. I very thanks to solve my problem... My English is not good but you try to understand........
The main difference between dll usage and packages is the shared memory model. You can simply put a dbconnection in a package. a datamodule in another one. and the best of all is you can load & unload them at your convenience. Then you have access to this elements by unit usage.
TDataModule is just like a form but it's purpose is to be sort of a container form and is invisible to the end user. Although you can create a TDataModule in a DLL, it is not meant to be like that. TDataModules are there for the sake of simplifying your interaction with the whole app. Not to complicate it!! **IMHO, Don't create DataModules in a dll.** From your description, I think that you want a central datastore-like-module that is separate from the app that interacts with the user. May be there are more than one user. If that is the case **try client-server approach**.
Description of datamodule in dll?
[ "", "c++", "delphi", "dll", "" ]
I am frequently having naming conflicts between a namespace and a class within that namespace and would like to know a best practice for handling this when it seems to make sense to use these names in the first place, besides adding random prefixes. It seemed to make sense to have a Models.Technology namespace, with dozens of technology classes (ie. Weapon, Agricultural, Recycling technologies) and some related interfaces in it. I also decided to have a Technology abstract class, in the Technology namespace, from which all technologies derive. However, this is forcing me to use code like this: ``` public Technology.Technology research(Technology.Technology tech) {...} ``` and likewise: ``` public Building.Building build(int count) {...} ``` By the way I did not name my namespace Technologies since I use that term elsewhere as a wrapper for a list of available technologies...
Without more precise indications on when you encounter this problem it's hard to give you some general advice. But I'm gonna suppose you have this problem when you have a base class in your namespace, with others classes inheriting from it. If that's the case you could call your class BaseTechnology (base class) or AbstractBuilding (abstract class) or IAnimal (interface). This even give you more clarity since you specify in the name of your type something important about it.
Well, whether your name your namespaces like that **ns**MyNamespace or you name you class **c**MyClasse. I'm personnaly in favor of naming the namespace, because it's not something you use a lot in code. You can also use TechnologyBase or AbstractTechnology for naming your main abstract class that conflict with the name of your namespace, which is what i recommend to keep the most logical naming convention.
How to avoid having the same name for a class and it's namespace, such as Technology.Technology?
[ "", "c#", "naming-conventions", "namespaces", "" ]
Hej! I am looking for a portable way of periodically dispatching a task in a C++ project. The use of libraries such as boost should be avoided in this particular project. The resolution requirement is not too serious: between 5Hz to 20Hz on an average Netbook. The project uses OpenGL to render the HMI but since I am working on the backend part I am not too familiar with it. Thanks your any advice or suggestions, Arne EDIT: What our 'Task' class actually does is creating a thread using either CreateThread(..) for windows or pthread\_create(..) for linux.
As most straightforward way to achieve this is to use Sleep(100ms) in a cycle, all you need is a portable Sleep. For Linux it can be implemented as follows ``` void Sleep(unsigned long ulMilliseconds) { struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = ulMilliseconds * 1000; select(1, NULL, NULL, NULL, &timeout); } ```
Since you already know the complete set of target systems you can go the [SQLite](http://www.sqlite.org/) way. They have exactly the same problem - many things they use are system-dependent. All system-dependent things are implemented separately for every target system and the right version is compiled depending on preprocessor directives set.
Portable periodic timer for period around 100ms
[ "", "c++", "multithreading", "cross-platform", "" ]
hope everybody is cool.I've been trying to do something with spring-hibernate but it's still a failure.i'm very new to it.i need a little help.supposing a POJO class Users.i want to return an Users object by username.While i had no problem to return Users object by id by doing this ``` return (Users) getHibernateTemplate().get(Users.class, id); ``` it seems to be a challenge for me getting the Users object by username. I've tried this ``` List<Users> users = getHibernateTemplate().find("from Users u where u.username=?",username); return users.get(0); ``` and even this ``` return (Users)getHibernateTemplate().find("from Users u where u.username=?",username).get(0); ``` how should i do it.And what is the proper way to return an array of Users objects and/or List.Thanks for reading this.
maybe you can try this? ``` List l =getHibernateTemplate().find("from Users u where u.username=?",new Object[]{username}); if (l.size() > 0) return (User)l.get(0); else return null; ```
Try this ``` Query q = session.createQuery("select * from Users u where u.username=:username"); q.setString("username", username); ```
working with object with spring and hibernate
[ "", "java", "hibernate", "spring", "jakarta-ee", "" ]
I have several content tables that I want to fill up with random paragraphs of text. In MS Word, I can simply put =rand() and presto! I get three paragraphs of fresh-off-the-press text. Is there a SQL script/command that I can use to generate random dictionary words using t-sql?
``` ; declare @Lorem nvarchar(max), @RowsToGen int, @Factor int select @Lorem = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', @RowsToGen = 200 -- strip punctuations set @Lorem = replace(@Lorem, ',', '') set @Lorem = replace(@Lorem, '.', '') ; with Num1(Pos) as ( select cast(1 as int) union all select cast(Pos + 1 as int) from Num1 where Pos < len(@Lorem) ), Words as ( select substring(@Lorem, Pos, charindex(' ', @Lorem + ' ', Pos) - Pos) as Word from Num1 where Pos <= len(@Lorem) and substring(',' + @Lorem, Pos, 1) = ' ' ), WordsCnt(Factor) as ( select @RowsToGen / count(*) + 1 from Words ), Num2(Pos) as ( select cast(1 as int) union all select cast(Pos + 1 as int) from Num2 cross join WordsCnt where Pos < WordsCnt. Factor ) select top (@RowsToGen) Word from Num2 cross join Words order by newid() option (maxrecursion 0) ```
Here is another version that gives a sentence instead of just a single word per row, as requested by Raj More. ``` ; declare @Lorem nvarchar(max), @SentenceToGen int, @WordsPerSentence int, @Factor int select @Lorem = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', @SentenceToGen = 200, @WordsPerSentence = 10 -- strip punctuations set @Lorem = replace(@Lorem, ',', '') set @Lorem = replace(@Lorem, '.', '') ; with Num1(Pos) as -- number of chars in @Lorem ( select cast(1 as int) union all select cast(Pos + 1 as int) from Num1 where Pos < len(@Lorem) ), Words as ( select lower(substring(@Lorem, Pos, charindex(' ', @Lorem + ' ', Pos) - Pos)) as Word from Num1 where Pos <= len(@Lorem) and substring(',' + @Lorem, Pos, 1) = ' ' ), WordsCnt(Factor) as ( select ceiling(cast(@SentenceToGen * @WordsPerSentence as float) / count(*)) from Words ), Num2(Pos) as -- product of words required, to be divided by number of words found in @Lorem ( select cast(1 as int) union all select cast(Pos + 1 as int) from Num2 cross join WordsCnt where Pos < WordsCnt.Factor ), Sentences as ( select ntile(@SentenceToGen) over (order by newid()) as SentenceId, Word from Num2 cross join Words ), Num3(Pos) as -- list of SentenceId ( select distinct SentenceId from Sentences ) select ( select top (@WordsPerSentence) Word + ' ' from Sentences where Sentences.SentenceId = Num3.Pos for xml path('') ) as Sentence from Num3 option (maxrecursion 0) ```
T-SQL equivalent of =rand()
[ "", "sql", "sql-server", "t-sql", "random", "" ]
Can you measure the width of a string more exactly in WIN32 than using the GetTextMetrics function and using tmAveCharWidth\*strSize?
Try using [GetTextExtentPoint32](http://msdn.microsoft.com/en-us/library/dd144938(VS.85).aspx). That uses the current font for the given device context to measure the width and height of the rendered string in logical units. For the default mapping mode, MM\_TEXT, 1 logical unit is 1 pixel. However, if you've changed the mapping mode for the current device context, a logical unit may not be the same as a pixel. You can read about the different [mapping modes on MSDN](http://msdn.microsoft.com/en-us/library/windows/desktop/dd145045%28v=vs.85%29.aspx). With the mapping mode, you can convert the dimensions returned to you by GetTextExtentPoint32 to pixels.
I don't know for certain, but it seems that: ``` HDC hDC = GetDC(NULL); RECT r = { 0, 0, 0, 0 }; char str[] = "Whatever"; DrawText(hDC, str, strlen(str), &r, DT_CALCRECT); ``` might work.
How to find the width of a String (in pixels) in WIN32
[ "", "c++", "windows", "winapi", "" ]
I have a project in which I'm doing data mining a large database. I currently store all of the data in text files, I'm trying to understand the costs and benefits of storing the data relational database instead. The points look like this: ``` CREATE TABLE data ( source1 CHAR(5), source2 CHAR(5), idx11 INT, idx12 INT, idx21 INT, idx22 INT, point1 FLOAT, point2 FLOAT ); ``` How many points like this can I have with reasonable performance? I currently have ~150 million data points, and I probably won't have more than 300 million. Assume that I am using a box with 4 dual-core 2ghz Xeon CPUs and 8GB of RAM.
MySQL is more than capable of serving your needs as well as Alex's suggestion of PostgreSQL. Reasonable performance shouldn't be difficult to achieve, but if the table is going to be heavily accessed and have a large amount of DML, you will want to know more about the locking used by the database you end up choosing. I believe PostgreSQL can use row level locking out of the box, where MySQL will depend on the storage engine you choose. MyISAM only locks at the table level, and thus concurrency suffers, but storage engines such as InnoDB for MySQL can and will use row-level locking to increase throughput. My suggestion would be to start with MyISAM and move to InnoDB only if you find you need row level locking. MyISAM works well in most situations and is extremely light-weight. I've had tables over 1 billion rows in MySQL using MyISAM and with good indexing and partitioning, you can get great performance. You can read more about storage engines in MySQL at [MySQL Storage Engines](http://dev.mysql.com/doc/refman/5.1/en/storage-engines.html) and about table partitioning at [Table Partitioning](http://mysql.rediris.es/tech-resources/articles/performance-partitioning.html). Here is an article on [partitions in practice on a table of 113M rows](http://dev.mysql.com/tech-resources/articles/testing-partitions-large-db.html) that you may find useful as well. I think the benefits of storing the data in a relational database far outweigh the costs. There are so many things you can do once your data is within a database. Point in time recovery, ensuring data integrity, finer grained security access, partitioning of data, availability to other applications through a common language. (SQL) etc. etc. Good luck with your project.
[PostgreSQL](http://www.postgresql.org/about/) should be able to amply accommodate your data -- up to 32 Terabytes per table, etc, etc. If I understand correctly, you're talking about 5 GB currently, 10 GB max (about 36 bytes/row and up to 300 million rows), so almost any database should in fact be able to accommodate you easily.
Upper Limit for Number of Rows In Open Source Databases?
[ "", "sql", "mysql", "database", "postgresql", "relational-database", "" ]
I'm in the process of creating a [PHP](http://en.wikipedia.org/wiki/PHP) site. It uses multiple PHP classes, which are currently all in one PHP include. However, I am using [Aptana IDE](http://en.wikipedia.org/wiki/Aptana#PHP), and the file is now starting to crash it (it's around 400 lines). So I was wondering whether there would be any negative impact of including all the files seperately. **Current:** main file: ``` include("includes.php"); ``` includes.php: ``` contains php classes ``` **Suggested:** mainfile: main file: ``` include("includes.php"); ``` includes.php: ``` include("class1.php"); include("class2.php") ```
Multiple PHP includes are fine, and 400 lines should not be a big deal. My concern would be with the Aptana IDE before I'd even consider my code to be the problem. Breaking up your code into multiple PHP modules helps you to take a more object-oriented approach and simplifies your code base. I recommend it.
An IDE crashing because of a 400 line file? I'd find a new IDE. However, it is better to separate classes into separate files. Perhaps not strictly one class per file, but only closely related classes in the same file.
Is using multiple PHP includes a bad idea?
[ "", "php", "include", "" ]
Is there ability to read file that is used by another process? Thanks.
If the process holds an exclusive lock on the file then no. If the process holds a shared lock, you can read it.
Depending on the files you want to access, have a look at [Volume Shadow Copy](http://msdn.microsoft.com/en-us/library/bb968832(VS.85).aspx).
Read file that is used by another process
[ "", "c#", "file", ".net", "" ]
Please help. I am trying to figure out how to use DATE or DATETIME for comparison in a linq query. Example: If I wanted all Employee names for those who started before today, I would do something like this in SQL: ``` SELECT EmployeeNameColumn FROM EmployeeTable WHERE StartDateColumn.Date <= GETDATE() //Today ``` But what about linq? ``` DateTime startDT = //Today var EmployeeName = from e in db.employee where e.StartDateColumn <= startDT ``` The above WHERE doesn't work: > Exception Details: System.NotSupportedException: The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
That should work. Are you sure that there isn't another part of the query that triggered the exception? I have several instances of queries of the form ``` var query = from e in db.MyTable where e.AsOfDate <= DateTime.Now.Date select e; ``` in my code.
Use the class `DbFunctions` for trimming the time portion. ``` using System.Data.Entity; var bla = (from log in context.Contacts where DbFunctions.TruncateTime(log.ModifiedDate) == DbFunctions.TruncateTime(today.Date) select log).FirstOrDefault(); ``` Source: <http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/84d4e18b-7545-419b-9826-53ff1a0e2a62/>
How do I perform Date Comparison in EF query?
[ "", "c#", "linq", "datetime", "linq-to-entities", "datetime-comparison", "" ]
example: "`select * from somewhere where x = 1`" I want to find the whitespace-delimited "`where`", but not the "`where`" within "`somewhere`". In the example "where" is delimited by spaces, but it could be carriage returns, tabs etc. Note: I know regex would make it easy to do (the regex equivalent would be "`\bwhere\b`"), but I don't want to add a regex library to my project just to do this.
If you wanted to use the pure MFC method of string manipulation, then this should work: ``` CString strSql = _T("select * from somewhere where x = 1"); int nTokenPos = 0; CString strToken = strSql.Tokenize(_T(" \r\n\t"), nTokenPos); while (!strToken.IsEmpty()) { if (strToken.Trim().CompareNoCase(_T("where")) == 0) return TRUE; // found strToken = strSql.Tokenize(_T(" \r\n\t"), nTokenPos); } return FALSE; // not found ```
I don't know the first thing about MFC and `CString`, but in plain C++ I'd stuff that string into an `std::istringstream` and read from that into a string: ``` std::istringstream iss("select * from somewhere where x = 1"); std::string word; do { iss >> word; if( !iss ) throw "blah blah!"; } while( word != "where" ); ``` I suppose `CString` does have stream operators overloaded with the appropriate semantics, but, as I said, I don't know it.
Best way to find a whitespace-delimited word in a CString
[ "", "c++", "mfc", "" ]
I'm trying to figure out why my web app (I didn't write it, but I'm supposed to debug it) is consistently causing the Tomcat web server to restart. All I see in the logs before the server restarts is: ``` Jul 24, 2009 7:52:15 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent INFO: The Apache Portable Runtime which allows optimal performance in production environments was not found on the java.library.path: /usr/local/jdk1.5.0_09/jre/lib/i386/server:/usr/local/jdk1.5.0_09/jre/lib/i386:/usr/local/jdk1.5.0_09/jre/../lib/i386 Jul 24, 2009 7:52:15 AM org.apache.coyote.http11.Http11BaseProtocol init ``` I can actual do this same processing on other groups of files and it works fine, but doing this one particular group causes the server to restart. Mostly I'm hoping somebody can tell me if that's just a timeout, or if there should be some other log file telling me why it's dying. And if it's a timeout, if there's a way to increase it. **Update**: I tried starting the server with `bin/catalina.sh run` which puts the output to stanadard out instead of catalina.out, and all I get instead of the above is the progress from my app and then "Killed". As an aside, I don't know what's restarting it, but when I try to restart the server with `bin/catalina.sh run`, I get a BindException, so *something* restarted it. **Update 2**: It was using Tomcat 5.5 and Java 5. I installed Tomcat 6 and set it up to use Java 6, and the same thing is happening. Also, if I do an "echo $?" after the "Killed", it gives me "137", which probably indicates the hosting company is killing it off for some reason.
Never mind - it turns out the hosting company was killing my process (with kill -9 no less) because it was taking too much CPU time. Now I have to figure out how to do this incredibly time consuming task without using 90% of their CPU for more than 10 minutes - I tried "nicing" Tomcat and that didn't help, so I may have to add a "sleep(1000)" in the processing loop or something.
AprLifecycleListener's responsibility is to initialize the Apache Portable Runtime, see <http://tomcat.apache.org/tomcat-6.0-doc/apr.html> Could you post the log entries of the shutdown (do you have any, or is the above all you see?)? BTW, you're saying that tomcat restarts, the standard shell scripts only start tomcat once, they just exit when tomcat quits. Do you have any kind of wrapper software (like <http://wrapper.tanukisoftware.org/>) that might be restarting your server?
Why is my Tomcat server restarting and what is org.apache.catalina.core.AprLifecycleListener?
[ "", "java", "tomcat", "" ]
I apologize if this is a really beginner question, but I have not worked with Java in several years. In my application, I need to keep up with a list of files (most, if not all, are txt files). I need to be able to add to this list, remove file paths from the list, and eventually read the contents of the files (though not when the files are initially added to the list). What is the best data structure to use to store this list of files? Is it standard to just save the path to the file as a String, or is there a better way? Thanks very much.
Yes, paths are usually stored as `String` or `File` instances. The list can be stored as an `ArrayList` instance.
It really depends on your requirements * you can store filenames/paths using anything that implements [`Collection`](http://java.sun.com/javase/6/docs/api/java/util/Collection.html) if you have a *small number of files* and/or a flat directory structure * if looking up files is performance critical you should use a data structure that gives you fast search, like a [`HashSet`](http://java.sun.com/javase/6/docs/api/java/util/HashSet.html) * if memory space is an issue (e.g. on mobile devices) and your number of files is high and/or your directory structure deep you should use a data structure that allows for compact storage, like a [trie](http://en.wikipedia.org/wiki/Trie) If the data structure allows, I would store [`File`](http://java.sun.com/javase/6/docs/api/java/io/File.html)s rather than [`String`](http://java.sun.com/javase/6/docs/api/java/lang/String.html)s however because there is no additional overhead and [`File`](http://java.sun.com/javase/6/docs/api/java/io/File.html) obviously offers convenient file handling methods.
How do I store files or file paths in a java application?
[ "", "java", "data-structures", "file", "" ]
So I'm starting to hear more and more about [Web Workers](http://ejohn.org/blog/web-workers/). I think it's absolutely fantastic, but the question I haven't seen anyone really tackle so far is how to support older browsers that do not yet have support for the new technology. The only solution I've been able to come up with so far is to make some sort of wrapper around the web worker functionality that would fall back to some crazy timer based solution that would simulate multi-threaded execution. But even in that case, how does one detect whether web workers is a supported feature of the browser currently executing the javascript? Thanks!
This is the age-old problem of web development: what to do about browsers that don't support what you need. Currently, I only advocate using Web Workers for complex, long-running tasks that can be broken up, and for some reason, can't be done server-side. This way, if you don't have Web Workers, you simply wait longer. Otherwise, you would have to make a mess of your code with wrappers and whatnot that you'll try to avoid later. My degradation strategy happens as soon as the page is loaded. onload function pseudocode: ``` if( window.Worker /*check for support*/ ) someObject.myFunction = function() { /*algorithm that uses Web Workers*/ } else someObject.myFunction = function() { /* sad face */ } ``` You still have to write the algorithm twice, but you would have to do that anyway if you want to support browsers without Web Workers. So that brings up an interesting question: is it worth the time (and money) to write something twice, just so it can go a little faster for some people?
After chewing on this for a few days, I ended up writing an article on my blog: <http://codecube.net/2009/07/cross-platform-javascript-webworker/> The idea is that in cases where WebWorker is not defined, there is a wrapper API that just uses built-in techniques. Although the sample in the article is very simple, it does work in all browsers :-)
Degrading gracefully with Web Workers
[ "", "javascript", "multithreading", "web-worker", "" ]
Is it possible to update an application to a new version without closing it? Or is there a good way to do that without user noticing it was closed?
Typically applications notice on startup that an update is available, then ask the user whether it's okay to update. They then start the update process and exit. The update process replaces the files, then launches the new version. In *some* cases you may be able to get away with updating *some* pieces of an application without a restart - but the added complexity is significant, and frankly it's better not to try in 99% of cases, IMO. Of course, you haven't said what kind of app you're writing - if you could give more information, that would help.
The application needs to be closed before updating it, because updating an application generally means replacing the executable files (.exe, .dlls, etc.) with their newer versions, and this can't be done without closing the application. As [Jon said](https://stackoverflow.com/questions/1165388/updating-an-application-without-closing-it/1165401#1165401), in *some* cases, you can upgrade the application without closing it. But, this is not advisable, as it might cause failure in the updater, and the whole update might rollback. Updater can be another executable which will first close the main application, then download the updates, apply them, start the main application, and exit (An example of this is [Skype](http://www.skype.com/), [FireFox](http://www.getfirefox.com/), etc.)
Updating an application without closing it
[ "", "c#", "auto-update", "" ]
I have an XML file in a string in this format: ``` <item> <name>xxx</name> <id>yyy</id> <view> <name>view1_name</name> <view_attrs> <view_attr> <name>Age</name> <values> <value>18-36</value> <value>55-70</value> </values> </view_attr> <view_attr> <name>Status</name> <values> <value>Single</value> <value>Married</value> </values> </view_attr> </view_attrs> </view> <view> <name>view2_name</name> <view_attrs> <view_attr> <name>Age</name> <values> <value>37-54</value> </values> </view_attr> </view_attrs> </view> <children> <item> ... </item> <item> ... <children> ... </children> </item> </children> </item> ``` What I would like to do for example, is add/delete an item, a child, change values in a specific view\_attr and so on? What's the easiest and simplest method to do so? Thanks in advance. :)
jQuery wraps browser specific XML parsers so you can simply use the following to aquire a document from a string: ``` var xmlDoc = $('<foo><bar1/><bar2/></foo>')[0]; ``` Now you can use standard DOM manipulation to add or delete nodes: ``` var bar2 = xmlDoc.getElementsByTagName('bar2')[0]; var bar3 = document.createElement('bar3'); xmlDoc.appendChild(bar3); xmlDoc.removeChild(bar2); ```
I would convert it to json; I hate working with xml in javascript. There are plugins that will handle the conversion for you. <http://www.fyneworks.com/jquery/xml-to-json/> <http://plugins.jquery.com/project/xmlObjectifier/>
XML string manipulation in JS?
[ "", "javascript", "jquery", "xml", "" ]
Is there a decent USB communication API? Preferably cross-platform (Linux if not, I guess) I don't have a specific use in mind, I just want to learn about using the USB ports for future electronics projects. I realize this is very general, I'll try to refine the question as the answers point me in the right direction. Thanks.
[libusb](http://libusb.wiki.sourceforge.net/) should work for you .. cross platform, user-space USB tools.
Depending on your electronics projects, a USB micro controller might be more what you're looking for. Here is one of my favorite USB devices that do this sort of thing (servo controls, motor controls, LEDs, analog/digital I/O, etc.) [phidgets.com](http://www.phidgets.com/) Cross platform, excellent. For example, setting the position of a servo to halfway I could call to the driver: ``` servo1.setPosition(50); ``` Easy as pie. Good luck!
USB Communication API
[ "", "c++", "c", "linux", "cross-platform", "usb", "" ]
I have two tables. The first is *user*; this consists of *username* and *userid*. The second is *search* which consists of *userid* and *query*. When I select the search table I want user ID to be replaced by username by taking the data from the user table. Is this making sense? | userid | username | | --- | --- | | 1 | foo1 | | 2 | foo2 | | 3 | foo3 | | 4 | foo4 | | userid | query | | --- | --- | | 1 | blah1 | | 2 | blah2 | | 3 | blah2 | | 4 | blah2 | Is there a way to do this with a single query?
You are looking for an [inner join](http://en.wikipedia.org/wiki/Join_(SQL)#Inner_join). This would do it: ``` SELECT s.query, u.username FROM search s INNER JOIN users u ON s.userid = u.userid ```
``` SELECT username, query FROM Users, Queries WHERE Users.userid=Queries.userid; ```
How to combine two tables in a query
[ "", "sql", "mysql", "join", "" ]
I have two functions: ``` def f(a,b,c=g(b)): blabla def g(n): blabla ``` `c` is an optional argument in function `f`. If the user does not specify its value, the program should compute g(b) and that would be the value of `c`. But the code does not compile - it says name 'b' is not defined. How to fix that? Someone suggested: ``` def g(b): blabla def f(a,b,c=None): if c is None: c = g(b) blabla ``` But this doesn't work. Maybe the user intended `c` to be None and then `c` will have another value.
``` def f(a,b,c=None): if c is None: c = g(b) ``` If `None` can be a valid value for `c` then you do this: ``` sentinel = object() def f(a,b,c=sentinel): if c is sentinel: c = g(b) ```
You cannot do it that way. Inside the function, check if c is specified. If not, do the calculation. ``` def f(a,b,c=None): if c == None: c = g(b) blabla ```
Non-Standard Optional Argument Defaults
[ "", "python", "optional-arguments", "" ]
I need to produce multiple HTML report files from an XML data file and I'm using C# (.NET 3.5). I essentially need on HTML report for each of certain child trees in the XML file (but they have to include some parent info). I've decided to use XSLT, because it seems to be the most elegant solution to my problem. I can then use the .NET XslTransform.Transform method to create my HTML files... or can I? From reading on MSDN, it seems that even in .NET 3.5 that XslTransform only supports XSLT 1.0, even though 2.0 has been around for some time. Multiple document output from a single XSLT file only became possible in XSLT 2.0. Is there any workaround for my problem that you can think of?
I would suggest using [AltovaXML](http://www.altova.com/altovaxml.html) to take care of this issue, that is, if you are permitted to use outside class libraries. I personally have nothing but good things to say about it. As for the code for producing multiple documents as output, your XSLT file should look something like this: ``` <xsl:template match="/"> <xsl:for-each select="Item"> <xsl:variable name="filename" select="concat($solutionRoot,'\',$v1,'\',$v2,'.html')" /> <xsl:value-of select="$filename"/> <xsl:result-document href="{$filename}" format="html-format"> --Place document construction code here-- </xsl:result-document> </xsl:for-each> </xsl:template> ``` Essentially turn the name of the file into a variable, creating a new filename with each section of data.
[Saxon](http://www.saxonica.com/) (the .net version) is the gold standard for XSLT 2 implementations. Not only is it the reference implementation for the XSLT 2.0 standard, but it is highly optimized and open source, runs as managed code (via the IKVM libraries), and supports the usual .net interfaces. You can use the `<xsl:result-document>` element there without problems.
XslTransform.Transform to produce multiple output files
[ "", "c#", ".net", "xslt", "" ]
I am currently pretty experienced at PHP, and have wrote multiple applications in it. I know HTML, CSS, MySQL, and Javascript along with PHP. What is the next step in programming? (I know that there are languages like Perl, C, Python, but don't know exactly if they are Web Based, Desktop based, etc) **Updated** My Goals are to learn enough programming that I am able to do program professionally. Let me clear up that I am 15, and have programmed a few complex applications. I have dealt with Object Oriented programming, but have barely touched working with frameworks. Is that something I should go for next?
There is no "next step" in programming; PHP, like the other technologies you mention, are tools we use to solve problems. One useful thing you could do is have a look at how similar problems are solved using other technologies: you seem to be interested in web application development, so similar tools exist like Java/JSP, Ruby/Rails, C#/ASP.NET, and so on. After your edit, this seems to be the most sensible route to take, as platforms like Java and .NET seem to be the way organisations are going, and where skills are used in a lot of jobs in programming. Having spent some time going down those routes, you might be interested in larger systems that make use of enterprise features. Things like JSF, Struts, or futher - J2EE with EJBs make use of web technologies, but in a more enterprise fashion. I'd also suggest you have a look at some open-source web applications to see how tools such as those you mention are used in larger applications with more users. Who knows, perhaps you can join in and help out on a widely-used project!
All I can tell you is my own experience. I learnt PHP/HTML/MySQL/Oracle on UNIX around 12 years ago, and liked it's ease of use and the way you could throw together sites very easily (compared to CGI and C). However, around 6 years ago I reluctantly moved to the "dark side" and had to learn Windows programming for my job. After a horrible period of learning 'Classic ASP' and VB I got into the new, emerging .NET technology, in particular ASP.NET and C#. And I'm *really* glad I did. Learning a "proper" strongly-typed OOP language like C# (or Java) will help improve your programming skill and make you a more disciplined programmer. If you can learn the .NET framework you'll expand your horizons as well as your employability. You will also learn many programming skills that can move you beyond the Web - into application development etc. You'll broaden your outlook and be enriched and rewarded in the process.
What Should I Learn After PHP?
[ "", "php", "" ]
I'm trying to count trailing zeros of numbers that are resulted from factorials (meaning that the numbers get quite large). Following code takes a number, compute the factorial of the number, and count the trailing zeros. However, when the number is about as large as `25!`, numZeros don't work. ``` public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); double fact; int answer; try { int number = Integer.parseInt(br.readLine()); fact = factorial(number); answer = numZeros(fact); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static double factorial (int num) { double total = 1; for (int i = 1; i <= num; i++) { total *= i; } return total; } public static int numZeros (double num) { int count = 0; int last = 0; while (last == 0) { last = (int) (num % 10); num = num / 10; count++; } return count-1; } ``` I am not worrying about the efficiency of this code, and I know that there are multiple ways to make the efficiency of this code BETTER. What I'm trying to figure out is why the counting trailing zeros of numbers that are greater than `25!` is not working. Any ideas?
Your task is not to compute the factorial but the number of zeroes. A good solution uses the formula from <http://en.wikipedia.org/wiki/Trailing_zeros> (which you can try to prove) ``` def zeroes(n): i = 1 result = 0 while n >= i: i *= 5 result += n/i # (taking floor, just like Python or Java does) return result ``` Hope you can translate this to Java. This simply computes [n / 5] + [n / 25] + [n / 125] + [n / 625] + ... and stops when the divisor gets larger than n. DON'T use BigIntegers. This is a bozosort. Such solutions require seconds of time for large numbers.
You only really need to know how many 2s and 5s there are in the product. If you're counting trailing zeroes, then you're actually counting "How many times does ten divide this number?". if you represent n! as q\*(2^a)\*(5^b) where q is not divisible by 2 or 5. Then just taking the minimum of a and b in the second expression will give you how many times 10 divides the number. Actually doing the multiplication is overkill. Edit: Counting the twos is also overkill, so you only really need the fives. And for some python, I think this should work: ``` def countFives(n): fives = 0 m = 5 while m <= n: fives = fives + (n/m) m = m*5 return fives ```
Counting trailing zeros of numbers resulted from factorial
[ "", "java", "correctness", "" ]
I've got a problem with strings that I get from one of my clients over xmlrpc. He sends me utf8 strings that are encoded twice :( so when I get them in python I have an unicode object that has to be decoded one more time, but obviously python doesn't allow that. I've noticed my client however I need to do quick workaround for now before he fixes it. Raw string from tcp dump: ``` <string>Rafa\xc3\x85\xc2\x82</string> ``` this is converted into: ``` u'Rafa\xc5\x82' ``` The best we get is: ``` eval(repr(u'Rafa\xc5\x82')[1:]).decode("utf8") ``` This results in correct string which is: ``` u'Rafa\u0142' ``` this works however is ugly as hell and cannot be used in production code. If anyone knows how to fix this problem in more suitable way please write. Thanks, Chris
``` >>> s = u'Rafa\xc5\x82' >>> s.encode('raw_unicode_escape').decode('utf-8') u'Rafa\u0142' >>> ```
Yow, that was fun! ``` >>> original = "Rafa\xc3\x85\xc2\x82" >>> first_decode = original.decode('utf-8') >>> as_chars = ''.join([chr(ord(x)) for x in first_decode]) >>> result = as_chars.decode('utf-8') >>> result u'Rafa\u0142' ``` So you do the first decode, getting a Unicode string where each character is actually a UTF-8 byte value. You go via the integer value of each of those characters to get back to a genuine UTF-8 string, which you then decode as normal.
Decoding double encoded utf8 in Python
[ "", "python", "string", "utf-8", "decode", "" ]
I would like to replace "." by "," in a String/double that I want to write to a file. Using the following Java code ``` double myDouble = myObject.getDoubleMethod(); // returns 38.1882352941176 System.out.println(myDouble); String myDoubleString = "" + myDouble; System.out.println(myDoubleString); myDoubleString.replace(".", ","); System.out.println(myDoubleString); myDoubleString.replace('.', ','); System.out.println(myDoubleString); ``` I get the following output ``` 38.1882352941176 38.1882352941176 38.1882352941176 38.1882352941176 ``` Why isn't replace doing what it is supposed to do? I expect the last two lines to contain a ",". Do I have to do/use something else? Suggestions?
You need to assign the new value back to the variable. ``` double myDouble = myObject.getDoubleMethod(); // returns 38.1882352941176 System.out.println(myDouble); String myDoubleString = "" + myDouble; System.out.println(myDoubleString); myDoubleString = myDoubleString.replace(".", ","); System.out.println(myDoubleString); myDoubleString = myDoubleString.replace('.', ','); System.out.println(myDoubleString); ```
The original String isn't being modified. The call returns the modified string, so you'd need to do this: ``` String modded = myDoubleString.replace(".",","); System.out.println( modded ); ```
Hints for java.lang.String.replace problem?
[ "", "java", "string", "replace", "" ]
Similar to [this question](https://stackoverflow.com/questions/482912/sql-group-by-year-month-week-day-hour-sql-vs-procedural-performance), I need to group a large number of records into 1-hour "buckets". For example, let's say I've got a typical ORDER table with a datetime attached to each order. And I want to see the total number of orders per hour. So I'm using SQL roughly like this: ``` SELECT datepart(hh, order_date), SUM(order_id) FROM ORDERS GROUP BY datepart(hh, order_date) ``` The problem is that if there are no orders in a given 1-hour "bucket", no row is emitted into the result set. I'd like the resultset to have a row for each of the 24 hour, but if no orders were made during a particular hour, just record the number of orders as O. Is there any way to do this in a single query? See also [Getting Hourly Statistics Using SQL](https://stackoverflow.com/questions/385656/getting-hourly-statistics-using-sql).
You need to have a pre-populated table (or a function returning a table result set) to join with, that contains all the 1-hour slots you want in your result. Then you do a OUTER JOIN with that, and you should get them all. Something like this: ``` SELECT SLOT_HOUR, SUM(order_id) FROM ONEHOURSLOTS LEFT JOIN ORDERS ON DATEPART(hh, order_date) = SLOT_HOUR GROUP BY SLOT_HOUR ```
Some of the previous answers recommend using a table of hours and populating it using a UNION query; this can be better done with a Common Table Expression: ``` ; WITH [Hours] ([Hour]) AS ( SELECT TOP 24 ROW_NUMBER() OVER (ORDER BY [object_id]) AS [Hour] FROM sys.objects ORDER BY [object_id] ) SELECT h.[Hour], o.[Sum] FROM [Hours] h LEFT OUTER JOIN ( SELECT datepart(hh, order_date) as [Hour], SUM(order_id) as [Sum] FROM Orders GROUP BY datepart(hh, order_date) ) o ON h.[Hour] = o.[Hour] ```
Grouping/aggregating SQL results into 1-hour buckets
[ "", "sql", "sql-server", "postgresql", "" ]
I spent a good portion of time last week working on serialization. During that time I found many examples utilizing either the BinaryFormatter or XmlSerializer. Unfortunately, what I did not find were any examples comprehensively detailing the differences between the two. The genesis of my curiosity lies in why the BinaryFormatter is able to deserialize directly to an interface whilst the XmlSerializer is not. [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet) in an answer to "[casting to multiple (unknown types) at runtime](https://stackoverflow.com/questions/619197/casting-to-multiple-unknown-types-at-runtime/619210#619210)" provides an example of direct binary serialization to an interface. [Stan R.](https://stackoverflow.com/users/119929/stan-r) provided me with the means of accomplishing my goal using the XmlSerializer in his answer to "[XML Object Deserialization to Interface](https://stackoverflow.com/questions/1145791/xml-object-deserialization-to-interface/1145800#1145800)." Beyond the obvious of the BinaryFormatter utilizes binary serialization whilst the XmlSerializer uses XML I'd like to more fully understand the fundamental differences. When to use one or the other and the pros and cons of each.
The reason a binary formatter is able to deserialize directly to an interface type is because when an object is originally serialized to a binary stream metadata containing type and assembly information is stuck in with the object data. This means that when the binary formatter deserializes the object it knows its type, builds the correct object and you can then cast that to an interface type that object implements. The XML serializer on the otherhand just serializes to a schema and only serializes the public fields and values of the object and no type information other then that (e.g. interfaces the type implements). Here is a good post, [.NET Serialization](http://www.dotneat.net/2009/03/22/NETSerializationUsingBinaryFormaterSoapFormatterAndXmlSerializer.aspx), comparing the [BinaryFormatter](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter.aspx), [SoapFormatter](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.soap.soapformatter.aspx), and [XmlSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx). I recommend you look at the following table which in addition to the previously mentioned serializers includes the [DataContractSerializer](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx), [NetDataContractSerializer](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.netdatacontractserializer.aspx) and [protobuf-net](https://github.com/mgravell/protobuf-net). ![Serialization Comparison](https://i.stack.imgur.com/FzHRL.png)
Just to weigh in... The obvious difference between the two is "binary vs xml", but it does go a lot deeper than that: * fields (`BinaryFormatter`=bf) vs **public** members (typically properties) (`XmlSerializer`=xs) * type-metadata based (bf) vs contract-based (xs) * version-brittle (bf) vs version-tolerant (xs) * "graph" (bf) vs "tree" (xs) * .NET specific (bf) vs portable (xs) * opaque (bf) vs human-readable (xs) As a discussion of why `BinaryFormatter` can be brittle, [see here](http://marcgravell.blogspot.com/2009/03/obfuscation-serialization-and.html). It is impossible to discuss which is bigger; all the type metadata in `BinaryFormatter` can make it bigger. And `XmlSerializer` can work very with compression like gzip. However, it is possible to take the strengths of each; for example, Google have open-sourced their own data serialization format, "protocol buffers". This is: * contract-based * portable (see [list of implementations](http://code.google.com/p/protobuf/wiki/ThirdPartyAddOns)) * version-tolerant * tree-based * opaque (although there are tools to show data when combined with a .proto) * typically "[contract first](http://code.google.com/apis/protocolbuffers/docs/proto.html)", but some implementations allow implicit contracts based on reflection But importantly, it is very dense data (no type metadata, pure binary representation, short tags, tricks like variant-length base-7 encoding), and very efficient to process (no complex xml structure, no strings to match to members, etc). I might be a little biased; I maintain one of the implementations (including several suitable for C#/.NET), but you'll note I haven't linked to **any** specific implementation; the format stands under its own merits ;-p
What are the differences between the XmlSerializer and BinaryFormatter
[ "", "c#", ".net", "serialization", "xml-serialization", "binary-serialization", "" ]
I have a class with a property which is an enum The enum is ``` /// <summary> /// All available delivery actions /// </summary> public enum EnumDeliveryAction { /// <summary> /// Tasks with email delivery action will be emailed /// </summary> Email, /// <summary> /// Tasks with SharePoint delivery action /// </summary> SharePoint } ``` When I create an instance of this class, NOWHERE in the code, do I specify the value of the enum field, but it seems to default to the first item in the enumlist, and not a null value, is this how enums work? How is it possible to ensure that the enum gets some kind of null value if it is not set, I don't want it defaulting to the first value in the enum.
Default value for `enum` types is `0` (which is by default, the first element in the enumeration). Fields of a class will be initialized to the default value. If you need to represent an *unknown* value in the enum, you can add an element `Unknown` with value 0. Alternatively, you could declare the field as `Nullable<MyEnum>` (`MyEnum?`).
Enums are a value type, like ints. You need to make it nullable so as not to default to the first (or 0-defined) enum member. ``` public class MyClass { public EnumDeliveryAction? DeliveryAction { get; set;} } ```
Initial Value of an Enum
[ "", "c#", "enums", "" ]
I am new to C# and trying to develop a small application which internally opens a command prompt and executes some command here. This is what I have done so far: ``` m_command = new Process(); m_command.StartInfo.FileName = @"cmd.exe"; m_command.StartInfo.UseShellExecute = false; m_command.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; m_command.StartInfo.CreateNoWindow = true; m_command.StartInfo.RedirectStandardInput = true; m_command.StartInfo.RedirectStandardOutput = true; m_command.Start(); m_reader = m_command.StandardOutput; m_writer = m_command.StandardInput; m_writer.WriteLine("Somecommand"); //execute some command ``` As you can see, I have redirected the input and output. My question is how do I execute the "some command" synchronously i.e. I want to read the result of my command using the redirected output. For that I have to wait until the command I invoked using WriteLine to complete. How do I do that?
That really depends on what the command will do. You could wait for the process to exit with `Process.WaitForExit`, while simultaneously reading from `m_reader` in another thread or with `OutputDataReceived`. That will only work if the process is going to quit when the command has finished though. (Note that you *have* to read the output, otherwise it could fill up the output buffer and basically block the process.) The other option is if you'll get a certain bit of output when the command has finished - such as the next command prompt. The trouble is that if your command happens to output the same thing, you'll get it wrong. It feels like launching a command prompt like this isn't a great approach though. Any reason you don't create a separate process each time? Another option: if you can work out what process you've just launched *via* the command line, you could find that as a `Process` and wait for *that* to exit. It's tricky though - I really would try to redesign your solution.
You can call ``` m_command.WaitForExit(); ```
Waiting for the command to complete in C#
[ "", "c#", "" ]
I'm adding multi-currency support to an e-commerce application. The way I approached the problem was to keep the application in it's base currency and have the template call a priceDisplay() function/plugin anytime it displays a price. So the template continues to receive prices in dollar amounts. The priceDisplay function correctly converts the price if needed and adds the correct $ or Euro sign depending on the viewers settings, stored in the session. On order submit, the application will store the order in dollar amount as well as the currencyCode and currencyRate. Additionally we will charge the customer's credit card in their currency to ensure they get billed exactly what was shown on the order screen. Now the issue I am having is when displaying the cart totals in the cart as well as during checkout. As an example, the application sends the template the prices to display in the shopping cart: subtotal: 9.75 ship: 5.95 total: 15.70 The template takes these amounts and calls the priceDisplay function on each item. If the currency rate is 1.1, then we get displayed to the user: subtotal: 10.725 -> 10.73 ship: 6.545 -> 6.55 total: 17.27 You can see that the subtotal + ship = 17.28, but the total converted is 17.27. So couple of options I think could work, though not thought all the way through: 1. Handle all conversion on the application side 2. Where items will be totaled, the template should send all the individual addends and total together in the base currency to the priceDisplay function, which will convert them and ensure that the *converted total* and *sum of addends* match up. In this case, then how do I communicate to the application that the total is not 15.70 but perhaps 15.71 or 15.69 (since we will be storing the order in base currency and multiply by the exchangeRate when processing the payment.) 3. Keep track of dropped/added decimal points as part of the conversions and do something 'smart' with that. So in this example, 10.725, we added 5 thousandths. So when we convert 6.545, we should first drop .005 then convert. Perhaps this is the process that option 2 above does? 4. Your suggestion here. If it makes any difference, application is in PHP and template is Smarty. You can also see the same issue in adding the line totals of the cart items: 3 items x 9.75 each = 29.25 converted: 3 items x 10.73 (10.725) = 32.18 (32.175) but 3 x 10.73 = 32.19 != 32.18
I'm firmly in the 1 camp. Currency conversion is core business logic, and belongs in your models, not your views. Further, although money looks like floating-point numbers, it isn't. Money changes hands in integer quantities of whatever your base unit is. In the US, for example, If gumballs are 10 cents each and I buy ten, then I'm trading 100 pennies for 10 gumballs. Even if I give a dollar bill, from a software perspective, it's best to count that as 100 pennies. For more on this, see Martin Fowler's ["Patterns of Enterprise Application Architecture"](http://www.martinfowler.com/books.html#eaa) and ["Analysis Patterns"](http://www.martinfowler.com/books.html#ap). He talks through all the issues in detail and gives good sample code. You can also find some of that info on the web: * [Quantity](http://martinfowler.com/ap2/quantity.html) (with some money sample code) * [Money](http://www.martinfowler.com/eaaCatalog/money.html) (mainly a pointer into his book) If you need the accounting to work, I'd also talk to the accountant. Currency conversion is often complicated by changing rates, weird fees, and other nonsense, and you can spend a long time chasing pennies to make the books balance if you don't get it right from the get-go.
If you are billing based on the converted currency, you really shouldn't be doing that calculation in your view logic.
Currency Conversion for E-commerce site - Preventing incorrect Total Cart due to rounding
[ "", "php", "e-commerce", "" ]
I'm stuck and I need help. Anyway I have Visual Studio 2008 console program that needs to log a Date, String, Boolean, and an integer for each round of a game. Say the user plays 10 rounds I would have 10 of each. I want to save those records in a data structure (collection i believe) and then after the game is finished loop through them producing a simple console report. I'm stuck. It seems like a simple thing, but I can't find the solution. I imagine that there are multiple ways to accomplish this, but I'm looking for the most simple solution.
**Edit:** I wanted to simplify the answer to this, but perhaps I simplified too much. I've changed the mutable struct below (which is a bad idea, thanks for reminding me [@Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet)), with a class, and properties as well. --- First, create the data type to hold the information: ``` public class RoundInformation { public DateTime Date { get; set; } public String Name { get; set; } public Boolean DidCheat { get; set; } } ``` Then create the list to hold it: ``` public List<RoundInformation> Rounds = new List<RoundInformation>(); ``` Then, for each round, construct a value with the round information data and add it to the list: ``` RoundInformation info = new RoundInformation(); info.Date = DateTime.Now; info.Name = "Bob"; info.DidCheat = true; // Bob always cheats Rounds.Add(info); ``` To loop through: ``` foreach (RoundInformation round in Rounds) { .. dump to console, left as an excercise } ```
Try this: ``` public class GameRound { public DateTime Date {get; set;} public string String {get; set;} public bool Boolean { get; set;} public int Integer { get; set; } } ``` In one part, with the correct variable names. Then, in your console program, add the following line at the top: ``` List<GameRound> rounds = new List<GameRound>(); ``` This makes a "list" of rounds, which can be added to, removed, and "looped" through. Then, when you want to add a round, use code like this: ``` rounds.Add(new GameRound { Date = theDate, String = theString, Boolean = theBool, Integer = theInt }); ``` This makes a new `GameRound` object, and sets all the properties to values. Remember to substitute theDate, etc. for the correct names/values. Finally, to produce the report, try this: ``` foreach ( GameRound round in rounds ) { Console.WriteLine("Date: {0}\nString: {1}\nBoolean: {2}\nInteger: {3}", round.Date, round.String, round.Boolean, round.Integer); } ```
Collections Question (.NET 3.5, C#)
[ "", "c#", ".net-3.5", "collections", "" ]
I'm using dom4j to parse my xml. Let's say I have something like this: ``` <?xml version="1.0" encoding="UTF-8"?> <foo> <bar>&#402;</bar> </foo> ``` When looking at the value of the "bar" node, it gives me back the special character as represented by "& #402;" Is there a way to prevent this and just read in the actual bit of text?
The actual bit of text being `&#402;`? You need to escape ampersand as `&amp;` then.
If the value of the `bar` node were to contain < or > or an & on its own then it would break the parser. In order to protect against this you should escape all data on the way in, and then unescape it on the way out again. This turns your document into: ``` <?xml version="1.0" encoding="UTF-8"?> <foo> <bar>&amp;#402;</bar> </foo> ``` It does suck, but that's XML for you.
dom4j converting text to special characters
[ "", "java", "xml", "dom4j", "" ]
I'm having a small background thread which runs for the applications lifetime - however when the application is shutdown, the thread should exit gracefully. The problem is that the thread runs some code at an interval of 15 minutes - which means it sleeps ALOT. Now in order to get it out of sleep, I toss an interrupt at it - my question is however, if there's a better approach to this, since interrupts generate ThreadInterruptedException. Here's the gist of my code (somewhat pseudo): ``` public class BackgroundUpdater : IDisposable { private Thread myThread; private const int intervalTime = 900000; // 15 minutes public void Dispose() { myThread.Interrupt(); } public void Start() { myThread = new Thread(ThreadedWork); myThread.IsBackground = true; // To ensure against app waiting for thread to exit myThread.Priority = ThreadPriority.BelowNormal; myThread.Start(); } private void ThreadedWork() { try { while (true) { Thread.Sleep(900000); // 15 minutes DoWork(); } } catch (ThreadInterruptedException) { } } } ```
There's absolutely a better way - either use [`Monitor.Wait`](http://msdn.microsoft.com/en-us/library/system.threading.monitor.wait.aspx)/[Pulse](http://msdn.microsoft.com/en-us/library/system.threading.monitor.pulse.aspx) instead of Sleep/Interrupt, or use an [`Auto`](http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx)/[`ManualResetEvent`](http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx). (You'd probably want a `ManualResetEvent` in this case.) Personally I'm a Wait/Pulse fan, probably due to it being like Java's wait()/notify() mechanism. However, there are definitely times where reset events are more useful. Your code would look something like this: ``` private readonly object padlock = new object(); private volatile bool stopping = false; public void Stop() // Could make this Dispose if you want { stopping = true; lock (padlock) { Monitor.Pulse(padlock); } } private void ThreadedWork() { while (!stopping) { DoWork(); lock (padlock) { Monitor.Wait(padlock, TimeSpan.FromMinutes(15)); } } } ``` For more details, see my [threading tutorial](http://www.yoda.arachsys.com/csharp/threads), in particular the pages on [deadlocks, waiting and pulsing](http://www.yoda.arachsys.com/csharp/threads/deadlocks.shtml), the page on [wait handles](http://www.yoda.arachsys.com/csharp/threads/waithandles.shtml). Joe Albahari [also has a tutorial](http://www.albahari.com/threading/) which covers the same topics and compares them. I haven't looked in detail yet, but I wouldn't be surprised if Parallel Extensions also had some functionality to make this easier.
You could use an Event to Check if the Process should end like this: ``` var eventX = new AutoResetEvent(false); while (true) { if(eventX.WaitOne(900000, false)) { break; } DoWork(); } ```
Thread.Interrupt to stop long sleep at app shutdown - Is there a better approach
[ "", "c#", "multithreading", "interrupt", "" ]