Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a whole bunch of string that are supposed to represent MIME types. However, some of these string have bad/invalid MIME types. Is there a way in the .NET framework to get a list of valid MIME types?
Check out [this stack overflow post](https://stackoverflow.com/questions/234526/can-i-setup-a-iis-mime-type-in-net) about adding custom mime types. You should be able to do something like ``` using (DirectoryEntry mimeMap = new DirectoryEntry("IIS://Localhost/MimeMap")) { PropertyValueCollection propValues = mimeMap.Properties["MimeMap"]; foreach(IISOle.MimeMap mimeType in propValues) //must cast to the interface and not the class { //access mimeType.MimeType to get the mime type string. } } ```
IANA have a list [here](http://www.iana.org/assignments/media-types/). I would think that is more of an authority than most lists you can find.
How can I know if a string represents a valid MIME type?
[ "", "c#", ".net", "mime-types", "" ]
I want to have a map with duplicate keys. I know there are many map implementations (Eclipse shows me about 50), so I bet there must be one that allows this. I know it's easy to write your own map that does this, but I would rather use some existing solution. Maybe something in commons-collections or google-collections?
You are searching for a multimap, and indeed both commons-collections and Guava have several implementations for that. Multimaps allow for multiple keys by maintaining a collection of values per key, i.e. you can put a single object into the map, but you retrieve a collection. If you can use Java 5, I would prefer Guava's [`Multimap`](https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/Multimap.html) as it is generics-aware.
We don't need to depend on the Google Collections external library. You can simply implement the following Map: ``` Map<String, ArrayList<String>> hashMap = new HashMap<String, ArrayList>(); public static void main(String... arg) { // Add data with duplicate keys addValues("A", "a1"); addValues("A", "a2"); addValues("B", "b"); // View data. Iterator it = hashMap.keySet().iterator(); ArrayList tempList = null; while (it.hasNext()) { String key = it.next().toString(); tempList = hashMap.get(key); if (tempList != null) { for (String value: tempList) { System.out.println("Key : "+key+ " , Value : "+value); } } } } private void addValues(String key, String value) { ArrayList tempList = null; if (hashMap.containsKey(key)) { tempList = hashMap.get(key); if(tempList == null) tempList = new ArrayList(); tempList.add(value); } else { tempList = new ArrayList(); tempList.add(value); } hashMap.put(key,tempList); } ``` Please make sure to fine tune the code.
Map implementation with duplicate keys
[ "", "java", "duplicates", "guava", "multimap", "" ]
I'm using match() in JavaScript to parse a dates from an RSS feed, I just can't get my head around the correct regular expression to find the date format. Here's the date: ``` 2009-05-11 16:59:20 ``` And the regular expression so far: ``` if (dateToParse.match(/^\d\d\d\d-\d\d-\d\d/)) { dateTimeSeparator = " "; monthIndex = 0; dayIndex = 1; yearIndex = 2; } ```
``` /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/ ``` This puts the date in the first to third groups, and the time in the forth to sixth groups.
Hopefully this helps: ``` var digitpattern = /\d+/g, datetime = '2009-05-11 16:59:20', matches = datetime.match(digitpattern); console.log ('year = ' + matches[0]); console.log ('month = ' + matches[1]); console.log ('day = ' + matches[2]); console.log ('hour = ' + matches[3]); console.log ('minutes = ' + matches[4]); console.log ('seconds = ' + matches[5]); ``` Or, you might like to use something like [DateJS](http://www.datejs.com/).
Date parsing with regular expressions in JavaScript
[ "", "javascript", "regex", "datetime", "parsing", "" ]
I have a following items displayed on an asp.net page (C#). 1 Welcome 2 Whats New 2.1 Gifts 2.2 Ideas 2.3 Others 2.3.1 Novelty 2.3.2 Boats 2.4 Vehicals 2.5 Fruits Now the user can remove any child items ( not root for ex user can remove item 2.1 gifts or item 2.3.1 novelty) Once user remove the item, i need to re-nunmber the structure using C#. I am looking for any suggestion / ideas / code to accomplish this task. 1 Welcome 2 Whats New 2.1 Gifts(remove) 2.2 Ideas 2.3 Others 2.3.1 Novelty(remove) 2.3.2 Boats 2.4 Vehicals 2.5 Fruits Result should be - 1 Welcome 2 Whats New 2.1 Ideas 2.2 Others 2.2.1 Novelty(remove) 2.2.2 Boats 2.3 Vehicals 2.4 Fruits
Not a very smart solution, but the following code renumbers a list of lines given as input. It splits each line at the space separating the numbering from the rest, determines the nesting level by counting the number of dots in the numbering, and uses this information together with the nesting level of the last line to update a list with the current numbering for each nesting level. Finally the current numbering stored in the list is joined with the text and outputed. ``` List<Int32> numbering = new List<Int32>(); Int32 lastNestingLevel = -1; foreach (String line in lines) { String[] parts = line.Split(new Char[] { ' ' }, 2); Int32 currentNestingLevel = parts[0].Count(c => c == '.'); if (currentNestingLevel > lastNestingLevel) { // Start a new nesting level with number one. numbering.Add(1); } else if (currentNestingLevel == lastNestingLevel) { // Increment the number of the current nesting level. numbering[currentNestingLevel] += 1; } else if (currentNestingLevel < lastNestingLevel) { // Remove the deepest nesting level... numbering.RemoveAt(numbering.Count - 1); // ...and increment the numbering of the current nesting level. numbering[currentNestingLevel] += 1; } lastNestingLevel = currentNestingLevel; String newNumbering = String.Join(".", numbering .Select(n => n.ToString()) .ToArray()); Console.WriteLine(newNumbering + " " + parts[1]); } ``` For the following input ``` List<String> lines = new List<String>() { "1 Welcome", "2 Whats New", //"2.1 Gifts", "2.2 Ideas", "2.3 Others", //"2.3.1 Novelty", "2.3.2 Boats", "2.4 Vehicals", "2.5 Fruits" }; ``` the output is the following. ``` 1 Welcome 2 Whats New 2.1 Ideas 2.2 Others 2.2.1 Boats 2.3 Vehicals 2.4 Fruits ``` **UPDATE** Here is a variant using a dictionary - it simplifies the update, but complicates the generation of the new numbering a bit. ``` Dictionary<Int32, Int32> numbering = new Dictionary<Int32, Int32>(); Int32 lastNestingLevel = -1; foreach (String line in lines) { String[] parts = line.Split(new Char[] { ' ' }, 2); Int32 currentNestingLevel = parts[0].Count(c => c == '.'); if (currentNestingLevel > lastNestingLevel) { numbering[currentNestingLevel] = 1; } else { numbering[currentNestingLevel] += 1; } lastNestingLevel = currentNestingLevel; String newNumbering = String.Join(".", numbering .Where(n => n.Key <= currentNestingLevel) .OrderBy(n => n.Key) .Select(n => n.Value.ToString()) .ToArray()); Console.WriteLine(newNumbering + " " + parts[1]); } ``` This variant also fixes a bug in the first version. If the nesting level drops by more than one at once, the first variant will produce false outputs. ``` 2.3.2.1 Vehicals 2.5 Fruits <= nesting level drops by two ``` I assume an input where the nesting level raises by more than one at once is not valid or at least a more precise definition how to handle this case is required, but both variants may have problems with that kind of inputs.
Is the number purely "optical" sugar for the user? If yes, I'd number them on the fly while writing the output, without keeping the number stored anywhere.
Optimized way to re-order numbering using C#
[ "", "c#", "algorithm", "" ]
I have an HTTP Handler that is the entry point for 90% of our app. Basically it gets a request, process a lot of data and returns a very specific file depending on the client & web page it is embedded on, etc. I have setup the **Application Mappings** so that all **.kab** extensions point to *C:\Windows...\aspnet\_isapi.dll*. I added my HttpHandler DLL to the BIN directory for my website. When I try to browse to the test page the iFrame displays a 404. **Did I miss something in my setup of the HttpHandler?** As far as debugging my code, I’ve tried attaching but I keep getting a 404 error on the page and it never steps into my code. **What is the best practice method for tying into the project in debug mode?** --- Basic setup for test (all local on one machine): * **IIS 5.1 on Windows XP Pro** – running a plain Jane default.aspx: > <body> > <form id="form1" runat="server"> > <iframe style="border-width: 2px; z-index: > 100; overflow: hidden; width: 500px; > height: 423px;" > src="http://localhost/barrows.kab?client=33ee472yaaM24a"> > </form> > </body> * VS2005 running in attached mode to the INETINFO.EXE Process.
You also need to map .cab extension to your handler class in the web.config file. See [here](http://msdn.microsoft.com/en-us/library/bya7fh0a.aspx). e.g. ``` <httpHandlers> <add verb="*" path="*.cab" type="My.Assembly,My.Assembly.Handler, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=whatever" validate="false"/> .... ```
Go back to Application Mappings and make sure the checkbox for "Verify File Exists" is un-checked. This will make anything with .kab be handled by .NET.
C#, Debugging an HTTPHandler
[ "", "c#", "debugging", "httphandler", "" ]
I have a table in my database which has duplicate records that I want to delete. I don't want to create a new table with distinct entries for this. What I want is to delete duplicate entries from the existing table without the creation of any new table. Is there any way to do this? ``` id action L1_name L1_data L2_name L2_data L3_name L3_data L4_name L4_data L5_name L5_data L6_name L6_data L7_name L7_data L8_name L8_data L9_name L9_data L10_name L10_data L11_name L11_data L12_name L12_data L13_name L13_data L14_name L14_data L15_name L15_data ``` see these all are my fields : id is unique for every row. L11\_data is unique for respective action field. L11\_data is having company names while action is having name of the industries. So in my data I'm having duplicate name of the companies in L11\_data for their respective industries. What I want is to have is unique name and other data of the companies in the particular industry stored in action. I hope I have stated my problem in a way that you people can understand it.
Yes, assuming you have a unique ID field, you can delete all records that are the same except for the ID, but don't have "the minimum ID" for their group of values. Example query: ``` DELETE FROM Table WHERE ID NOT IN ( SELECT MIN(ID) FROM Table GROUP BY Field1, Field2, Field3, ... ) ``` Notes: * I freely chose "Table" and "ID" as representative names * The list of fields ("Field1, Field2, ...") should include all fields except for the ID * This may be a slow query depending on the number of fields and rows, however I expect it would be okay compared to alternatives EDIT: In case you don't have a unique index, my recommendation is to simply add an auto-incremental unique index. Mainly because it's good design, but also because it will allow you to run the query above.
``` ALTER IGNORE TABLE 'table' ADD UNIQUE INDEX(your cols); ``` Duplicates get NULL, then you can delete them
Deleting duplicate rows from a table
[ "", "mysql", "sql", "duplicates", "" ]
I really confused in understanding where the tomcat actually runs. Is it execute inside the JVM, which execute servlets. Or it has it's own VM in executing servlet or JSP. Thanks in advance.
Tomcat will run within the JVM, and servlets execute within the Tomcat process (in the same JVM). Running catalina.sh (or .bat) will start up a new JVM for Tomcat to run in. You can load/run Tomcat programatically within an existing JVM if you require a webserver as part of a bigger application.
Java provides the JVM to run any Java application. Tomcat is essentially a Java program which implements the Servlet container specification and acts as a Servlet Container. It also means you need (atleast) the Java JRE to run Tomcat.
Tomcat and VM
[ "", "java", "tomcat", "servlets", "" ]
I just started a new project with the Dojo toolkit, and no sooner did I drop my dojo.js script tag in than firebug started telling me ``` Could not load 'dojo._firebug.firebug'; last tried './_firebug/firebug.js' ``` I know dojo has a reputation for bad debugging messages, but this is ridiculous.... If anyone has any ideas about this I would appreciate it.
You need to put it on a web server, per [this thread](http://www.nabble.com/newbie-question-td19229349.html) -- probably a local web server that only serves to your own machine, of course, for development purposes.
It is possible to work without a web server. go through the below mentioned steps. <http://www.dojotoolkit.org/support/faq/why-does-dojo-fail-load-file-urls-firefox-3> Set Security.fileuri.strict origin policy to false and retry.
Dojo and Firebug
[ "", "javascript", "dojo", "firebug", "" ]
Since I'm using jQuery, any solution via that would work too. Ideally, I'd like to know both, though. I already have the arrow keys bound to another function on my page (using jQuery), but having them cause the page to scroll in addition to that, causes me problems. I may have known this at one time, but I don't remember it anymore.
Adding document level keypress handler does the trick! ``` var ar=new Array(33,34,35,36,37,38,39,40); $(document).keydown(function(e) { var key = e.which; //console.log(key); //if(key==35 || key == 36 || key == 37 || key == 39) if($.inArray(key,ar) > -1) { e.preventDefault(); return false; } return true; }); ```
Under some circumstances, eg. when you don't actualy have an element you focus on, just some area you had to click, you might not have too much control over the handler and preventing the event at the global level can be a little flaky at best (as I found out the hard way). The simplest solution in those cases is to bind on the click even of the control button and focus on a empty input element which you position -9000px to the left. You can then reliably block the event via keydown and also dont have to worry about blocking default behavior or other global listeners since the default behavior on the input element will just move the cursor to the left and right.
How do I prevent scrolling with arrow keys but NOT the mouse?
[ "", "javascript", "jquery", "scroll", "arrow-keys", "" ]
I'm curious if there are any Java abstractions that are similar to .Net's AppDomain. In particular, I'm curious because I've found that with our Coldfusion/J2EE server we need to restart it every few days due to a slow memory leak that we haven't been able to easily track down yet. This can wreck our long-running processes and we'd really like a way to slowly just push people to new JVMs as they age past a certain time period/memory threshold. From my limited .Net experience I'm pretty sure that this is one situation that IIS and AppDomains are able to manage fairly seamlessly by recycling AppDomains that come under memory pressure. Please let me know if I'm way off on AppDomains helping in this scenario. Any suggestions?
I think Yiannis's answer here is a little misleading. Simply saying "no, you can't" is not the whole story. The question is focused on unloading Java classes in a server process to remove leaky code from the JVM process without a process restart. The OP is not asking for the process-like memory isolation feature that an AppDomain gives, but the ability to unload classes in a running JVM. I say process-like, since under the hood an AppDomain is not a process, but enjoys some of the isolation aspects that a first-class process is afforded by the operating system. The isolate JSR mentioned is referring to this 'process-like' isolation. Unloading java ClassLoaders and thus classes, without cycling the OS process hosting the JVM is possible. A couple of methods are mentioned here: [SO 148681](https://stackoverflow.com/questions/148681/unloading-classes-in-java). It is not trivial, or elegant to do this in Java, but it is possible.
Unfortunately, no. The analogous concept in the Java world is the Isolate, that appeared first in the JSR 121. This was an API for a future JVM feature that would allow safe separation and communication between different applications running in the same JVM. After the JSR was published (around 2004) one research team in Sun worked in the Barcelona project. This project tried to implement the Isolation API in Sun's HotSpot 1.5 VM. After two years, they released a prototype for SPARC/Solaris. Windows/Linux versions were never released due to stability problems. Recently, SUN has introduced a limited version of the Isolation API to J2ME, focusing of offering "multiple processes" in environments that didn't actively offer them. Recently, we also asked Sun for their status in implementing the Isolate API to standard JVMs and their response was that they plan to release a JVM with limited support. They plan to offer the ability to load/unload Isolates but without the ability to communicate between them. Also, there has been an old reserach efford to build an Isolates-compatible JVM version, called JanosVM (java 1.1) but I doubt that it can be of any use today. Hope this helps...
Java AppDomain like abstraction?
[ "", "java", ".net", "jakarta-ee", "coldfusion", "appdomain", "" ]
How can I click a Button in one form and update text in a TextBox in another form?
If you're attempting to use WinForms, you can implement a custom event in your "child" form. You could have that event fire when the button in your "child" form was clicked. Your "parent" form would then listen for the event and handle it's own TextBox update. ``` public class ChildForm : Form { public delegate SomeEventHandler(object sender, EventArgs e); public event SomeEventHandler SomeEvent; // Your code here } public class ParentForm : Form { ChildForm child = new ChildForm(); child.SomeEvent += new EventHandler(this.HandleSomeEvent); public void HandleSomeEvent(object sender, EventArgs e) { this.someTextBox.Text = "Whatever Text You Want..."; } } ```
Roughly; the one form must have a reference to some underlying object holding the text; this object should fire an event on the update of the text; the TextBox in another form should have a delegate subscribing to that event, which will discover that the underlying text has changed; once the TextBox delegate has been informed, the TextBox should query the underlying object for the new value of the text, and update the TextBox with the new text.
Propagating events from one Form to another Form in C#
[ "", "c#", ".net", "events", "event-handling", "" ]
I was trying to figure out if a for loop was faster than a foreach loop and was using the System.Diagnostics classes to time the task. While running the test I noticed that which ever loop I put first always executes slower then the last one. Can someone please tell me why this is happening? My code is below: ``` using System; using System.Diagnostics; namespace cool { class Program { static void Main(string[] args) { int[] x = new int[] { 3, 6, 9, 12 }; int[] y = new int[] { 3, 6, 9, 12 }; DateTime startTime = DateTime.Now; for (int i = 0; i < 4; i++) { Console.WriteLine(x[i]); } TimeSpan elapsedTime = DateTime.Now - startTime; DateTime startTime2 = DateTime.Now; foreach (var item in y) { Console.WriteLine(item); } TimeSpan elapsedTime2 = DateTime.Now - startTime2; Console.WriteLine("\nSummary"); Console.WriteLine("--------------------------\n"); Console.WriteLine("for:\t{0}\nforeach:\t{1}", elapsedTime, elapsedTime2); Console.ReadKey(); } } } ``` **Here is the output:** ``` for: 00:00:00.0175781 foreach: 00:00:00.0009766 ```
Probably because the classes (e.g. Console) need to be JIT-compiled the first time through. You'll get the best metrics by calling all methods (to JIT them (warm then up)) first, then performing the test. As other users have indicated, 4 passes is never going to be enough to to show you the difference. Incidentally, the difference in performance between for and foreach will be negligible and the readability benefits of using foreach almost always outweigh any marginal performance benefit.
1. I would not use DateTime to measure performance - try the `Stopwatch` class. 2. Measuring with only 4 passes is never going to give you a good result. Better use > 100.000 passes (you can use an outer loop). Don't do `Console.WriteLine` in your loop. 3. Even better: use a profiler (like Redgate ANTS or maybe NProf)
Why does the second for loop always execute faster than the first one?
[ "", "c#", "winforms", "performance", "diagnostics", "" ]
I have a php script that backup my table in .sql format and I want to save the file in gzip format using PHP. How can I do that.
You can also use [a filter](http://nl.php.net/manual/en/filters.compression.php). From the manual page: ``` <?php $params = array('level' => 6, 'window' => 15, 'memory' => 9); $original_text = "You SQL queries here..."; $fp = fopen('yourfile.sql.gz', 'w'); stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, $params); fwrite($fp, $original_text); fclose($fp); ?> ```
Use the Zlib functions. Read the [documentation](http://www.php.net/manual/en/zlib.examples.php) for details An example taken straight from the linked page: ``` <?php $filename = tempnam('/tmp', 'zlibtest') . '.gz'; $s = "Only a test, test, test, test, test, test, test, test!\n"; /***** WRITING THE FILE *****/ // open file for writing with maximum compression $zp = gzopen($filename, "w9"); // write string to file gzwrite($zp, $s); // close file gzclose($zp); /***** READING IT *****/ // open file for reading $zp = gzopen($filename, "r"); // read 3 char echo gzread($zp, 3); // output until end of the file and close it. gzpassthru($zp); gzclose($zp); /***** ANOTHER WAY TO READ (and print) IT *****/ // open file and print content (the 2nd time). if (readgzfile($filename) != strlen($s)) { echo "Error with zlib functions!"; } ?> ``` Hope that helps.
GZIP compression in PHP
[ "", "php", "gzip", "" ]
The simplest way to deal with python package installations, so far, to me, has been to check out the source from the source control system and then add a symbolic link in the python dist-packages folder. Clearly since source control provides the complete control to downgrade, upgrade to any branch, tag, it works very well. Is there a way using one of the Package installers (easy\_install or pip or other), one can achieve the same. easy\_install obtains the tar.gz and install them using the setup.py install which installs in the dist-packages folder in python2.6. Is there a way to configure it, or pip to use the source version control system (SVN/GIT/Hg/Bzr) instead.
Using [pip](http://pip.openplans.org/) this is quite easy. For instance: ``` pip install -e hg+http://bitbucket.org/andrewgodwin/south/#egg=South ``` Pip will automatically clone the source repo and run "setup.py develop" for you to install it into your environment (which hopefully is a [virtualenv](http://pypi.python.org/pypi/virtualenv)). Git, Subversion, Bazaar and Mercurial are all supported. You can also then run "pip freeze" and it will output a list of your currently-installed packages with their exact versions (including, for develop-installs, the exact revision from the VCS). You can put this straight into a requirements file and later run ``` pip install -r requirements.txt ``` to install that same set of packages at the exact same versions.
If you download or check out the source distribution of a package — the one that has its "setup.py" inside of it — then if the package is based on the "setuptools" (which also power easy\_install), you can move into that directory and say: ``` $ python setup.py develop ``` and it will create the right symlinks in dist-packages so that the .py files in the source distribution are the ones that get imported, rather than copies installed separately (which is what "setup.py install" would do — create separate copies that don't change immediately when you edit the source code to try a change). As the other response indicates, you should try reading the "setuptools" documentation to learn more. "setup.py develop" is a really useful feature! Try using it in combination with a virtualenv, and you can "setup.py develop" painlessly and without messing up your system-wide Python with packages you are only developing on temporarily: ``` http://pypi.python.org/pypi/virtualenv ```
Python package install using pip or easy_install from repos
[ "", "python", "svn", "version-control", "easy-install", "pip", "" ]
I am php page everything was working fine till today morning. Now the page is not uploading any selected file. All that I keep getting is the following error message: > Warning: move\_uploaded\_file(upload/BrainStream\_2009\_06\_25\_23041.zip) [function.move-uploaded-file]: failed to open stream: No such file or directory in C:\xampp\htdocs\vectorization\admin\jobs\_edit.php on line 146 > > Warning: move\_uploaded\_file() [function.move-uploaded-file]: Unable to move 'C:\Documents and Settings\Admin\Local Settings\Temp\php1B2.tmp' to 'upload/BrainStream\_2009\_06\_25\_23041.zip' in C:\xampp\htdocs\vectorization\admin\jobs\_edit.php on line 146 > File could not be uploaded. Please select a valid file. > File Name:BrainStream.zip I have written following code: ``` $uplfile = $_FILES['uploadfile']['name']; $upltmp = $_FILES["uploadfile"]["tmp_name"]; if(!empty($uplfile)) { $ext = explode(".", $uplfile); $upload_date = date("Y_m_d"); //use this variable to change file name to avoid conflict with same name files $upload_dir = "upload/"; $file_name=$ext[0]."_".$upload_date."_".rand(0, getrandmax()).".".$ext[1]; (move_uploaded_file($upltmp,$upload_dir.$file_name)) } ``` I have XAMPP stack installed on my PC which is running WinXP, has 3 GB RAM and ample of Hard disk space. No matter which size file I select it always give error. What must be wrong in this code?
Interesting syntax in the last line. The error indicates the problem is in that line and either the source file or destination directory is missing. Since the first one is automatically generated, make sure that `C:\xampp\htdocs\vectorization\admin\upload` exists and is writable.
@phihag, Thanks for the hint. One of the new developer while studying the source had by mistake remove (../) in the $upload\_dir variable assignment. ``` $upload_dir = "upload/"; //this is wrong ``` Actually it was set as ``` $upload_dir = "../upload/"; //this works but accidentally edited by another developer ``` What a lamer I am. I could not spot the problem. Anyways thanks once one for your help to solve my problem.
Error when trying to upload file in PHP
[ "", "php", "upload", "file-upload", "" ]
I've never used these functions before but after reading a lot about sprintf(), I decided I should get to know it. So I went ahead and did the following. ``` function currentDateTime() { list($micro, $Unixtime) = explode(" ",microtime()); $sec= $micro + date("s", $Unixtime); $sec = mb_ereg_replace(sprintf('%d', $sec), "", ($micro + date("s", $Unixtime))); return date("Y-m-d H:i:s", $Unixtime).$sec; } sprintf(currentDateTime()); ``` It prints nothing. Using the printf() function on the other hand: ``` printf(currentDateTime()); ``` It prints the result just fine. So what's the difference between these 2 functions and how do I properly use the sprintf() function?
`sprintf()` returns a string, `printf()` displays it. The following two are equal: ``` printf(currentDateTime()); print sprintf(currentDateTime()); ```
`sprintf()` prints the result to a string. `printf()` prints it to standard output ie: ``` printf(currentDateTime()); ``` is equivalent to: ``` echo sprintf(currentDateTime()); ```
Why doesn't sprintf() output anything?
[ "", "php", "printf", "" ]
I have a button that I trigger `OnClick` whenever there is a click on that button. I would like to know which Mouse button clicked on that button? When I use the `Mouse.LeftButton` or `Mouse.RightButton`, both tell me "*realsed*" which is their states after the click. I just want to know which one clicked on my button. If I change `EventArgs` to `MouseEventArgs`, I receive errors. **XAML:** `<Button Name="myButton" Click="OnClick">` ``` private void OnClick(object sender, EventArgs e) { //do certain thing. } ```
If you're just using the Button's Click event, then the only mouse button that will fire it is the primary mouse button. If you still need to know specifically whether it was the left or right button, then you can use the SystemInformation to obtain it. ``` void OnClick(object sender, RoutedEventArgs e) { if (SystemParameters.SwapButtons) // Or use SystemInformation.MouseButtonsSwapped { // It's the right button. } else { // It's the standard left button. } } ``` **Edit:** The WPF equivalent to SystemInformation is SystemParameters, which can be used instead. Though you can include System.Windows.Forms as a reference to obtain the SystemInformation without adversely effecting the application in any way.
You can cast like below: ``` MouseEventArgs myArgs = (MouseEventArgs) e; ``` And then get the information with: ``` if (myArgs.Button == System.Windows.Forms.MouseButtons.Left) { // do sth } ``` The solution works in VS2013 and you do not have to use MouseClick event anymore ;)
How can I determine which mouse button raised the click event in WPF?
[ "", "c#", "wpf", "mouseevent", "" ]
Some data is displayed in a datagridview (Winform). I have a requirement to mail the table represented in the datagridview in a similar format (Rows, Columns etc). What is the easiest was I can do it? How to convert that to html table with Column headers and preserving the column width.
Quick Google Search yielded this: [How to send DataGridView contents by email](http://www.codeproject.com/KB/grid/Send_DataGridView_Mail.aspx). It covers converting the DGV to an HTML table and mailing it.
I don't know if there is any framework level conversion that can take place. But it should be a pretty simple matter to iterate through the grids rows, and cells, and recreate it in HTML with the Width's in place. *Written off the cuff, please excuse its incompleteness and any simple mistakes, but I think you can get the basic idea here.* ``` StringBuilder sb = new SringBuilder(); sb.AppendLine("<table>"); sb.AppendLine(" <tr>"); foreach(DataGridViewColumn column in grid.Columns) { sb.AppendLine(" <td>" + column.HeaderText + "</td>"); } sb.AppendLine(" </tr>"); foreach(DataGridViewRow row in grid.Rows) { sb.AppendLine(" <tr>"); foreach(DataGridViewCell cell in row.Cells) { sb.AppendLine(" <td width=\"" + cell.Width + "px\">" + cell.Value + "</td>"); } sb.AppendLine(" </tr>"); } sb.AppendLine("</table>"); ```
DataGridView data of C# WinForm to html
[ "", "c#", "" ]
I have a system sitting on a "Master Server", that is periodically transferring quite a few chunks of information from a MySQL DB to another server in the web. Both servers have a MySQL Server and an Apache running. I would like an easy-to-use solution for this. Currently I'm looking into: * XMLRPC * RestFul Services * a simple POST to a processing script * socket transfers The app on my master is a TurboGears app, so I would prefer "pythonic" aka less ugly solutions. Copying a dumped table to another server via FTP / SCP or something like that might be quick, but in my eyes it is also very (quick and) dirty, and I'd love to have a nicer solution. Can anyone describe shortly how you would do this the "best-practise" way? This doesn't necessarily have to involve Databases. Dumping the table on Server1 and transferring the raw data in a structured way so server2 can process it without parsing too much is just as good. One requirement though: As soon as the data arrives on server2, I want it to be processed, so there has to be a notification of some sort when the transfer is done. Of course I could just write my whole own server sitting on a socket on the second machine and accepting the file with own code and processing it and so forth, but this is just a very very small piece of a very big system, so I dont want to spend half a day implementing this. Thanks, Tom
Server 1: Convert rows to JSON, call the RESTful api of second with JSON data Server 2: listens on a URI e.g. POST /data , get json data convert back to dictionary or ORM objects, insert into db sqlalchemy/sqlobject and simplejson is what you need.
If the table is small and you can send the whole table and just delete the old data and then insert the new data on remote server - then there can be an easy generic solution: you can create a long string with table data and send it via webservice. Here is how it can be implemented. Note, that this is far not perfect solution, just an example how I transfer small simple tables between websites: ``` function DumpTableIntoString($tableName, $includeFieldsHeader = true) { global $adoConn; $recordSet = $adoConn->Execute("SELECT * FROM $tableName"); if(!$recordSet) return false; $data = ""; if($includeFieldsHeader) { // fetching fields $numFields = $recordSet->FieldCount(); for($i = 0; $i < $numFields; $i++) $data .= $recordSet->FetchField($i)->name . ","; $data = substr($data, 0, -1) . "\n"; } while(!$recordSet->EOF) { $row = $recordSet->GetRowAssoc(); foreach ($row as &$value) { $value = str_replace("\r\n", "", $value); $value = str_replace('"', '\\"', $value); if($value == null) $value = "\\N"; $value = "\"" . $value . "\""; } $data .= join(',', $row); $recordSet->MoveNext(); if(!$recordSet->EOF) $data .= "\n"; } return $data; } // NOTE: CURRENTLY FUNCTION DOESN'T SUPPORT HANDLING FIELDS HEADER, SO NOW IT JUST SKIPS IT // IF NECESSARRY function FillTableFromDumpString($tableName, $dumpString, $truncateTable = true, $fieldsHeaderIncluded = true) { global $adoConn; if($truncateTable) if($adoConn->Execute("TRUNCATE TABLE $tableName") === false) return false; $rows = explode("\n", $dumpString); $startRowIndex = $fieldsHeaderIncluded ? 1 : 0; $query = "INSERT INTO $tableName VALUES "; $numRows = count($rows); for($i = $startRowIndex; $i < $numRows; $i++) { $row = explode(",", $rows[$i]); foreach($row as &$value) { if($value == "\"\\N\"") $value = "NULL"; } $query .= "(". implode(",", $row) .")"; if($i != $numRows - 1) $query .= ","; } if($adoConn->Execute($query) === false) { return false; } return true; } ``` If you have large tables, then I think that you need to send only new data. Ask your remote server for the latest timestamp, and then read all newer data from your main server and send the data either in generic way (as I've shown above) or in non-generic way (in this case you have to write separate functions for each table).
Best Practise for transferring a MySQL table to another server?
[ "", "python", "web-services", "database-design", "" ]
Trying to get the highest and lowest value from an array that I know will contain only integers seems to be harder than I thought. ``` var numArray = [140000, 104, 99]; numArray = numArray.sort(); console.log(numArray) ``` I'd expect this to show `99, 104, 140000`. Instead it shows `104, 140000, 99`. So it seems the sort is handling the values as strings. Is there a way to get the sort function to actually sort on integer value?
By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) - ``` var numArray = [140000, 104, 99]; numArray.sort(function(a, b) { return a - b; }); console.log(numArray); ``` Documentation: Mozilla [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) recommends this compare function for arrays that don't contain Infinity or NaN. (Because `Infinity - Infinity` is NaN, not 0). Also examples of sorting objects by key.
Just building on all of the above answers, they can also be done in one line like this: ``` var numArray = [140000, 104, 99]; numArray = numArray.sort(function (a, b) { return a - b; }); //outputs: 99, 104, 140000 ```
How to sort an array of integers correctly
[ "", "javascript", "arrays", "sorting", "numbers", "" ]
**Extended problem** I would like to add a new problem in addition to the original problem specified below. One of the user controls in the application contains a list of objects that I need to access from another user control. How can this be done? (I don't believe the division into controls is very well performed, but I'd rather not change it..) Should I do it by events as with the original problem, or should I get hold of the parent Form, and use it to find the instance of the control, and expose it as a property? --- **Original problem** I have two user controls in a form that I want to be able to communicate with each other. Usercontrol A should be able to start an operation on B. What is the preferred way of solving this? Should the form wait for an Event from A, and then start the operation on B? Any design pattern for this? Or is it an even easier solution? Thanks in advance! :)
The two user controls should not have any knowledge of each other. If you want to always deal with them as a pair, consider creating a third user control to house them. > Should the form wait for an Event from A, and then start the operation on B? Yes, this is the only good way to handle this. The extended (bonus?) problem is a bit trickier. I would handle this by having the form pass the user control a delegate to a method on the other user control to retrieve the data. The user control can then invoke the delegate method to call the method on the other control without having any knowledge of its implementation.
1. Expose the data it as a property. 2. Create a property on the other user control that the parent form will populate with the reference to the control with the data. Pseudo code: ``` public UserControlA uca { get; set; } ... var items = uca.Items; ```
Best practice when you need two user controls (winforms) to communicate
[ "", "c#", "winforms", "design-patterns", "user-controls", "" ]
It's probably just the vocabulary I am missing to find out how to do this: A job scheduled to run regularly every 5 mins, however keeping track that there are never two instances of it running at the same time, i.e. the next instance would be postponed or skipped if the prior runs longs than 5 mins. What is the easiest/most elegant way to achieve this?
`DBMS_JOB` takes care of that. Just use it.
From the Oracle 10g administrators guide: "The DBMS\_JOB package has been superseded by the [DBMS\_SCHEDULER](http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_sched.htm#CIHHBGGI) package. In particular, if you are administering jobs to manage system load, you should consider disabling DBMS\_JOB by revoking the package execution privilege for users." DBMS\_SCHEDULER is Oracle's recommended way to do this now. One advantage it has is that you can manage your jobs via Enterprise Manager/Grid Control if you're using this.
How to create a "singleton" scheduled job in oracle?
[ "", "sql", "oracle", "plsql", "dbms-scheduler", "dbms-job", "" ]
If I were to have 2 tables, call them TableA and TableB. TableB contains a foreign key which refers to TableA. I now need to add data to both TableA and TableB for a given scenario. To do this I first have to insert data in TableA then find and retrieve TableA's last inserted primary key and use it as the foreign key value in TableB. I then insert values in TableB. This seems lika a bit to much of work just to insert 1 set of data. How else can I achieve this? If possible please provide me with SQL statements for SQL Server 2005.
That sounds about right. Note that you can use `SCOPE_IDENTITY()` on a per-row basis, or you can do set-based operations if you use the INSERT/OUTPUT syntax, and then join the the set of output from the first insert - for example, here we only have 1 INSERT (each) into the "real" tables: ``` /*DROP TABLE STAGE_A DROP TABLE STAGE_B DROP TABLE B DROP TABLE A*/ SET NOCOUNT ON CREATE TABLE STAGE_A ( CustomerKey varchar(10), Name varchar(100)) CREATE TABLE STAGE_B ( CustomerKey varchar(10), OrderNumber varchar(100)) CREATE TABLE A ( Id int NOT NULL IDENTITY(51,1) PRIMARY KEY, CustomerKey varchar(10), Name varchar(100)) CREATE TABLE B ( Id int NOT NULL IDENTITY(1123,1) PRIMARY KEY, CustomerId int, OrderNumber varchar(100)) ALTER TABLE B ADD FOREIGN KEY (CustomerId) REFERENCES A(Id); INSERT STAGE_A VALUES ('foo', 'Foo Corp') INSERT STAGE_A VALUES ('bar', 'Bar Industries') INSERT STAGE_B VALUES ('foo', '12345') INSERT STAGE_B VALUES ('foo', '23456') INSERT STAGE_B VALUES ('bar', '34567') DECLARE @CustMap TABLE (CustomerKey varchar(10), Id int NOT NULL) INSERT A (CustomerKey, Name) OUTPUT INSERTED.CustomerKey,INSERTED.Id INTO @CustMap SELECT CustomerKey, Name FROM STAGE_A INSERT B (CustomerId, OrderNumber) SELECT map.Id, b.OrderNumber FROM STAGE_B b INNER JOIN @CustMap map ON map.CustomerKey = b.CustomerKey SELECT * FROM A SELECT * FROM B ```
If you work directly with SQL you have the right solution. In case you're performing the insert from code, you may have higher level structures that help you achieve this (LINQ, Django Models, etc).
How to add data to two tables linked via a foreign key?
[ "", "sql", "sql-server", "database", "sql-server-2005", "foreign-keys", "" ]
Quick question ... Using J2ME (CLDC 1.1, MIDP-2.1) is it possible to sleep the Midlet for a period of time (not using threads)... For example: ``` public class myMidlet extends MIDlet{ public void startApp() { /* Sleep for 10 seconds */ /* The answer was: */ try { Thread.sleep(time_ms); } catch (Exception e) {} } ... ``` I don't use Java all that much, and don't want to program threads just for a simple sleep. **Thanks in advance** **Answer Summary** My lack of Java knowledge. Examples I saw using Thread.sleep() led me to believe it was only usable in a thread object spawned by the Midlet ... not the midlet itself. I didn't want to have to spool off the midlet logic into a thread to sleep it ... But now I know the midlet runs in the default thread :) **Going to find that Java book I never read because I didn't think I would use the language ever**
I didn't understand whether you mean putting midlet in paused state or just stopping execution for specified time. If it's the latter, actually I don't undesrtand, why you don't want to use Threads, this is no big deal. You just insert three following lines wherever you need: ``` try { Thread.sleep(10000); } catch (Exception ex) {} ``` That's all, nothing too complicating.
I don't know the exact answer, but I also don't understand what's the problem with calling static method Thread.sleep(milliseconds) that "Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds" . Do you call this programming threads?
Making a J2ME Midlet sleep without threads?
[ "", "java", "java-me", "scheduling", "midlet", "midp", "" ]
I'm searching for a fast (really fast) way to test changes to hibernate queries. I have a huge application with thousands of different HQL queries (in XML files) and 100+ mapped classes and i dont want to redeploy the whole application to just test one tiny change to a query. How would a good setup look like to free me from redeployment and enable a fast query check?
With Intellij IDEA 8.1.3 the mechnism of choice is called 'Facet'. To instantly test HQL queries: 1. create a data source Tools -> Data Source, Add Data Source, define driver, username and password of yor development db 2. in case you dont have already a hibernate.cfg or you configure your session factory in a different way than via xml: create a hibernate.cfg file referencing all XML mapping's (define a name for the session factory, just for easier handling) 3. in 'Project Structure' add Facet to your module of choice and assign the recently defined data source to the new facet 4. switch to Java EE View 5. Open Hibernate Facets - Node 6. Right click Session factory and choose "Open HQL Console" 7. enter HQL query in console ...and your're done. sorry for this RTFM question.
You can use [hibernate tools in eclipse](http://www.hibernate.org/subprojects/tools.html) to run queries. This will allow you to run HQL whenever you want to try something. If you're using IntelliJ, there is [Hibero](http://www.betosoftware.com/hibero/). There is a [standalone editor](https://hqe.dev.java.net/) from sun, but I haven't tried it.
How to test HQL queries?
[ "", "java", "hibernate", "testing", "hql", "environment", "" ]
I have something like this: ``` var Something = function(){ this.render = function(){}; $(window).resize(function(){ this.render(); }); } ``` The trouble is that inside the anonymous function 'this' refers to the window object. I know I could do something like: ``` var Something = function(){ this.render = function(){}; var tempThis = this; $(window).resize(function(){ tempThis.render(); }); } ``` but is there a better way? This doesn't look very elegant.
The solution you found is the the one most people use. The common convention is to call your tempThis variable "that." ``` var Something = function(){ this.render = function(){}; var that = this; $(window).resize(function(){ that.render(); }); }; ```
That looks like your best option, I don't think there's a better way. (someone correct my if I'm wrong).
How can I keep the context of 'this' in jquery
[ "", "javascript", "jquery", "this", "" ]
How can I open a new window through javascript when popup is blocked in IE and Firefox. Below is the code: ``` <%@ Page language="c#" AutoEventWireup="false" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <html> <head> <title>SessionRedirect</title> <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name=vs_defaultClientScript content="JavaScript"> <meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5"> </head> <body MS_POSITIONING="GridLayout"> <form method="post" name="frmRedirect"> <input type="hidden" name="email" value="<%=Session["Email"].ToString() %>" /> <input type="hidden" name="pass" value="<%= Session["PWD"].ToString() %>" /> <input type="hidden" name="User" value="<%= Session["User"].ToString() %>" /> </form> <script type="text/javascript"> if(frmRedirect.User.value == "P") { window.open("", "Partner", "height=650,width=1075,left=100,top=100,status=1,scrollbars=1,location=1,toolbar=1;resizable=1"); frmRedirect.target="Partner"; frmRedirect.action = "http://pli.cmsstag/partnerzone/index.aspx"; document.frmRedirect.submit(); location.replace("index.aspx"); } else { window.open("", "Student", "height=650,width=1075,left=100,top=100,status=1,scrollbars=1,location=1,toolbar=1;resizable=1"); frmRedirect.target="Student"; frmRedirect.action = "http://pli.cmsstag/studentzone/index.aspx"; document.frmRedirect.submit(); location.replace("index.aspx"); } </script> <% Session.Remove("registration"); Session.Remove("User"); Session.Remove("UserId"); Session.Remove("UserLoggedIn"); Session.Remove("AgentCode"); Session.Abandon(); %> </body> </html> ``` all the above code is working fine, until the browser has blocked the popup. I am trying to open new window through window.open, please see the above code. I want the window should open in any case, if there is pop up blocker it should also open. Please help!
Pop ups created by window.open can get blocked by pop up blockers. You can add a new div layer that acts like a pop up to solve this. [Javascript Modal Dialog](http://luke.breuer.com/tutorial/javascript-modal-dialog.aspx) Some of the problems with div pop ups are . dropdown lists come in the way of these pop ups. . on window resize the position has to be changed etc In the above page many of the issues with a div pop up has been solved.
Popup blockers only block unintended popups. If your popup is displayed while handling a click event from the user, your popup might not be blocked by the popup blocker. So as long as your user clicks on a button or a link to open the popup, it will be ok with current popup blockers.
how to open new window through javascript when pop up is blocked
[ "", "javascript", "popup", "" ]
I would like to develop an application (that runs at all times in the background I guess) to track the usage of applications (msword, excel, powerpoint, \*.exe, etc.). I can handle posting the data to a database but don't exactly know where to start with monitoring running applications (when they start, when they stop). Anyone have any clues?
You can periodically poll a list of the running processes using `System.Diagnostics.Process.GetProcesses()`. This following code outputs information about starting and exiting processes. Exiting system processes won't be recognized. ``` class Program { struct ProcessStartTimePair { public Process Process { get; set; } public DateTime StartTime { get; set; } public DateTime ExitTime { get { return DateTime.Now; // approximate value } } public ProcessStartTimePair(Process p) : this() { Process = p; try { StartTime = p.StartTime; } catch (System.ComponentModel.Win32Exception) { StartTime = DateTime.Now; // approximate value } } } static void Main(string[] args) { List<ProcessStartTimePair> knownProcesses = new List<ProcessStartTimePair>(); while (true) { foreach (Process p in Process.GetProcesses()) { if (!knownProcesses.Select(x => x.Process.Id).Contains(p.Id)) { knownProcesses.Add(new ProcessStartTimePair(p)); Console.WriteLine("Detected new process: " + p.ProcessName); } } for (int i = 0; i < knownProcesses.Count; i++) { ProcessStartTimePair pair = knownProcesses[i]; try { if (pair.Process.HasExited) { Console.WriteLine(pair.Process.ProcessName + " has exited (alive from {0} to {1}).", pair.StartTime.ToString(), pair.ExitTime.ToString()); knownProcesses.Remove(pair); i--; // List was modified, 1 item less // TODO: Store in the info in the database } } catch (System.ComponentModel.Win32Exception) { // Would have to check whether the process still exists in Process.GetProcesses(). // The process probably is a system process. } } Console.WriteLine(); System.Threading.Thread.Sleep(1000); } } } ``` You probably can simply ignore system processes that don't let you read the HasExited property. **Edit** Here's a .net 2.0 version: ``` static void Main(string[] args) { List<ProcessStartTimePair> knownProcesses = new List<ProcessStartTimePair>(); while (true) { foreach (Process p in Process.GetProcesses()) { if (!ProcessIsKnown(knownProcesses, p.Id)) { knownProcesses.Add(new ProcessStartTimePair(p)); Console.WriteLine("Detected new process: " + p.ProcessName); } } for (int i = 0; i < knownProcesses.Count; i++) [...] } } static bool ProcessIsKnown(List<ProcessStartTimePair> knownProcesses, int ID) { foreach (ProcessStartTimePair pstp in knownProcesses) { if (pstp.Process.Id == ID) { return true; } } return false; } ``` Note that the code could be improved and only shows the concept.
You could poll all top-level windows periodically and record the Window title text; and based on that do some conclusions as to which program are running. Or you could do it via process name, or a combination. For enumerating windows, see <http://msdn.microsoft.com/en-us/library/ms633497(VS.85).aspx>, and [here is how to use it in managed code](http://www.pinvoke.net/default.aspx/user32/EnumWindows.html). For enumerating processes, use the Process.GetProcesses method or see <http://www.codeproject.com/KB/threads/enumprocess.aspx>
How to track application usage?
[ "", "c#", "" ]
Personally I like the many features that it offers. I have seen some questions but they are old, so want to gather some response from people who used it or planning to use it. If you are planning to use, how did you arrive at this framework?
It all depends. What's the point of the project? If it's to become more attractive to employers, figure out what teams in your area are using, and use that framework. Cake and Zend seem to be popular with small and big shops, respectively. If it's to learn about PHP, you're much better off writing your own code from scratch. This forces you to really understand what you're doing at every turn. I'd suggest writing your code test-first. If you just need to get some work done, use the tools you know best, if they're suitable for the problem at hand. IMO, I'd use Yii if I were interested in trying yet another framework. After browsing the source for a minute or two, Yii seems to have pretty nice tests and test coverage, which both makes me trust the code more, and provides working examples of how to use the APIs.
Personally, I'm tired of seeing so many new frameworks. The tendency for the PHP community to develop YAF is reaching the level of absurdity - how many are there now - over two dozen? I understand that people may want the challenge of working on a framework project, or don't like what's currently available, so they embark to create a new one. But you know what? I think it's time to stop creating new frameworks - and instead pick one of [the](http://framework.zend.com/) [well](http://www.symfony-project.org) [established](http://kohanaphp.com/) [frameworks](http://cakephp.org/) and become a contributor. Sorry, I know this really doesn't answer your question, but I'm unashamedly stealing space in your question to have a mini rant ;)
How is Yii Framework doing in PHP world? Any good or bad recent experiences
[ "", "php", "frameworks", "" ]
I have to warn you: the question may be rather silly, but I can't seem to wrap my head around it right now. I have two managed beans, let's say A and B: ``` class A { private Date d8; // ...getters & setters public String search() { // search by d8 } } class B { private Date d9; //...getters & setters public String insert() { // insert a new item for date d9 } } ``` and then I have two JSP pages, **pageA.jsp** (the search page) and **pageB.jsp** (the input page). What I would like to do is placing a **commandbutton** in **pageB** so to open the search page **pageA** passing the parameter **d9** somehow, or navigating to **pageA** directly after **b.insert()**. What I would like to do is showing the search result after the insertion. Maybe it's just that I can't see the clear, simple solution, but I'd like to know what the best practice might be here, also... I though of these possible solutions: 1. including \*\*A\*\* in \*\*B\*\* and linking the command button with \*\*b.a.search\*\* 2. passing \*\*d9\*\* as a \*\*hiddenInput\*\* and adding a new method \*\*searchFromB\*\* in \*\*A\*\* (ugly!) 3. collapsing the two beans into one
You should configure the navigation flow in faces-config.xml. In ideal scenario you would return a "status" message which would decide the flow. Read more at following link: <http://www.horstmann.com/corejsf/faces-config.html> <http://publib.boulder.ibm.com/infocenter/rtnlhelp/v6r0m0/index.jsp?topic=/com.businessobjects.integration.eclipse.doc.devtools/developer/JSF_Walkthrough8.html> As far as passing the values from one page to another is concerned you can use backing beans. More about backing beans here: <http://www.netbeans.org/kb/articles/jAstrologer-intro.html> <http://www.coderanch.com/t/214065/JSF/java/backing-beans-vs-managed-beans> Hope i have understood and answered correctly to your question **Way to share values between beans** ``` FacesContext facesContext = FacesContext.getCurrentInstance(); Application app = facesContext.getApplication(); ExpressionFactory elFactory = app.getExpressionFactory(); ELContext elContext = facesContext.getELContext(); ValueExpression valueExp = elFactory.createValueExpression(elContext, expression, Object.class); return valueExp.getValue(elContext); ``` In above code "expression" would be something like `#{xyzBean.beanProperty}` Since JSF uses singleton instances, you should be able to access the values from other beans. If you find more details on this technique, I am sure you'll get what you are looking for.
JSF 1.1/1.2 raw doesn't provide an easy way to do this. Seam/Spring both have ways around this and there are a couple of things you can do. JSF 2 should also have solutions to this once it is released. Probably the easiest and most expedient would be to collapse the two beans into one and make it session scoped. The worry, of course, is that this bean will not get removed and stay in session until the session times out. Yay Memory leaks! The other solution would be to pass the date on as a GET parameter. For instance, you action method could call the ``` FacesContext.getCurrentInstance().getExternalContext().redirect("pageB?d9=" + convertDateToLong(d9)); ``` and then get the parameter on the other side.
JSF: navigation
[ "", "java", "jsf", "navigation", "" ]
I have a class like so... ``` class Container { public: class Iterator { ... }; ... }; ``` Elsewhere, I want to pass a Container::Iterator by reference, but I don't want to include the header file. If I try to forward declare the class, I get compile errors. ``` class Container::Iterator; class Foo { void Read(Container::Iterator& it); }; ``` Compiling the above code gives... ``` test.h:3: error: ‘Iterator’ in class ‘Container’ does not name a type test.h:5: error: variable or field ‘Foo’ declared void test.h:5: error: incomplete type ‘Container’ used in nested name specifier test.h:5: error: ‘it’ was not declared in this scope ``` How can I forward declare this class so I don't have to include the header file that declares the Iterator class?
This is simply not possible. You cannot forward declare a nested structure outside the container. You can only forward declare it within the container. You'll need to do one of the following * Make the class non-nested * Change your declaration order so that the nested class is fully defined first * Create a common base class that can be both used in the function and implemented by the nested class.
I don't believe forward declaring inner class of on an incomplete class works (because without the class definition, there is no way of knowing if there actually *is* an inner class). So you'll have to include in the definition of Container, a forward declared inner class: ``` class Container { public: class Iterator; }; ``` Then in the corresponding source file, implement Container::Iterator: ``` class Container::Iterator { }; ``` Then #include only the container header (or not worry about forward declaring and just include both)
How do I forward declare an inner class?
[ "", "c++", "forward-declaration", "" ]
I have 2 strings: ``` string d = "09/06/24"; string t = "13:35:01"; ``` I want to take the strings and combine them to make a datetime variable: ``` newDT = Convert.ToDateTime(d + t); ``` Compiles but when it hits that line it fails..........any ideas?
DateTime.Parse(d + " " + t) should do it, the problem you were probably having is the lack of space inbetween the two variables, you were trying to parse: "09/06/2413:35:01" As you can see, this is not a valid date format.
does this work? ``` DateTime.Parse(d + " " + t); ```
C# Convert strings to DateTime
[ "", "c#", "datetime", "" ]
Each of our users is assigned to a primary organizational unit (OU) based on which global office they are in. So the "Chicago" OU contains all the associates in our Chicago office. Using c# and .net 3.5, my task is to extract all of these users. Unless the users are in a satellite or home office, their street address, city, state, etc. are empty, but the OU contains these details. When in Windows' Active Directory interface, right clicking on the OU and selecting properties gives a place to put all of this information just as on a user. However, when I try to access these properties like I do a user, I get an object reference error, suggesting these attributes do not exist the same way for an OU that they do for a user. How do/can I access these location parameters from an OU object? Here is a sample of the code I am using, showing streetaddress as an example, the statement trying to assign the value of streetaddress from the OU fails, where the assignment from associate succeeds. ``` foreach (SearchResult subOU in results) { ResultPropertyValueCollection subColl = subOU.Properties["distinguishedname"]; string subPath = subColl[0].ToString(); DirectoryEntry subEntry = new DirectoryEntry("LDAP://" + subPath); DirectorySearcher userSearcher = new DirectorySearcher(subEntry); userSearcher.SearchScope = SearchScope.OneLevel; userSearcher.Filter = "(objectClass=user)"; foreach (SearchResult user in userSearcher.FindAll()) { ResultPropertyValueCollection userColl = user.Properties["distinguishedname"]; string userPath = userColl[0].ToString(); DirectoryEntry userEntry = new DirectoryEntry("LDAP://" + userPath); PropertyCollection associateProperties = userEntry.Properties; PropertyCollection ouProperties = subEntry.Properties; string streetAddress = string.Empty; if (associateProperties["streetaddress"].Value == null) { streetAddress = ouProperties["streetaddress"].Value.ToString(); } else { streetAddress = associateProperties["streetaddress"].Value.ToString(); } } } ```
If you change the Street-field on the General-tab in Active Directory Users & Computers for a user the value is stored in the streetAddress-attribute in the directory. If however you change the same field for an OU that value is stored in the street-attribute of that OU in the directory. This is because OU objects are not (as defined in the Active Directory default schema) permitted to contain the streetAddress-attribute. So (not having analyzed your code further) if you change `ouProperties["streetaddress"]` to `ouProperties["street"]` you'll might get the result you're looking for.
To avoid the ObjectReference exception you should check the collection contains the required attribute using the Contains(string) method. See [here](http://msdn.microsoft.com/en-us/library/system.directoryservices.propertycollection_members.aspx) I believe that AD will only stored valued attributes on an object, if a particular attribute has never been assigned a value it won't be available.
How to get streetaddress property of an organizational unit in windows active directory with LDAP in C#.Net
[ "", "c#", ".net", "active-directory", "ldap", "" ]
I want to create a Web app which would allow the user to upload some C code, and see the results of its execution (the code would be compiled on the server). The users are untrusted, which obviously has some huge security implications. So I need to create some kind of sandbox for the apps. At the most basic level, I'd like to restrict access to the file system to some specified directories. I cannot use chroot jails directly, since the web app is not running as a privileged user. I guess a suid executable which sets up the jail would be an option. The uploaded programs would be rather small, so they should execute quickly (a couple of seconds at most). Hence, I can kill the process after a preset timeout, but how do I ensure that it doesn't spawn new processes? Or if I can't, is killing the entire pgid a reliable method? What would be the best way to go about this - other than "don't do it at all"? :) What other glaring security problems have I missed? FWIW, the web app will be written in Python.
Along with the other sugestions you might find this useful. <http://www.eelis.net/geordi/> This is from <http://codepad.org/about>, [codepad.org](http://codepad.org)'s about page.
The few details you provide imply that you have administrative control over the server itself, so my suggestion makes this assumption. I'd tackle this as a batch system. The web server accepts an upload of the source file, a process polls the submission directory, processes the file, and then submits the result to another directory which the web application polls until it finds the result and displays it. The fun part is how to safely handle the execution. My OS of choice is FreeBSD, so I'd set up a pre-configured jail (not to be confused with a vanilla chroot jail) that would compile, run, and save the output. Then, for each source file submission, launch a pristine copy of the jail for each execution, with a copy of the source file inside. Provided that the jail's /dev is pruned down to almost nothing, system resource limits are set safely, and that the traffic can't route out of the jail (bound to unroutable address or simply firewalled), I would personally be comfortable running this on a server under my care. Since you use Linux, I'd investigate User Mode Linux or Linux-VServer, which are very similar in concept to FreeBSD jails (I've never used them myself, but have read about them). There are several other such systems listed [here](http://en.wikipedia.org/wiki/Operating_system-level_virtualization). This method is much more secure than a vanilla chroot jail, and it is much more light-weight than using full virtualization such as qemu/kvm or VMware. I'm not a programmer, so I don't what kind of AJAX-y thing you could use to poll for the results, but I'm sure it could be done. As an admin, I would find this a fun project to partake in. Have fun. :)
Sandboxing in Linux
[ "", "python", "c", "linux", "security", "sandbox", "" ]
I have a number of CSV files of data that I want to Union together into a single table in MS Excel. All the CSV files have the same names and number of columns. In a relational database like Access or SQL I could use a Union Query, but this has to be in Excel. How can I quickly merge all of these files into one in Excel?
You can write a macro in VBA to handle doing this. Just have something that imports the CSV file into a temporary worksheet, then cuts and pastes it into place below the last final worksheet values, and deletes the newly imported, temporary worksheet.
Create a batch file with following text `@echo off for %%1 in (*.csv) do findstr /v "a,b,c" %%1` Here "a,b,c" is the column headers. After the batch file is created (assume the name of the batch file is test.bat), you could run the following on Command Prompt. `test.bat > combined.txt` This runs the batch file & pipes the output to a new file (combined.txt). You will have to open the combined.txt file and paste the header ("a,b,c") at the top. Hope this helps.
SQL Union in MS Excel 2007
[ "", "sql", "excel", "union", "" ]
My web application is using Java, Hibernate's JPA implementation (EntityManager) and Spring. What are my logger choices and what would you recommend. Ideally the configuration would be simple (one config file for Hibernate, Spring and my code).
When building applications out of various frameworks you often need to wrap existing loggers, be they log4j or JUL or JULI or whatever. The standard application for this is the [Simple Logging Facade for Java (SLF4J)](http://www.slf4j.org/). Even if your app doesn't need SLF4J now you may later want to add a library that does need it, and it's your best hope for one config file in the long run. With that in mind you should stick to logging packages that SLF4J supports, but usually it boils down to java.util.logging (JUL) or Apache's log4j. This has been a [subject for debate](http://java.sys-con.com/node/48541?page=0,0) for some time and you can find many opinions on both sides. Personally, I think it's unfortunate that Java logging is in [this situation](https://stackoverflow.com/questions/354837/whats-up-with-logging-in-java), and I'll use whatever gives me the least pain for the situation.
[log4j](http://logging.apache.org/log4j/1.2/index.html) is the standard logger that I use. You can configure logging levels and log files by package so Hibernate, Spring and your code can each go to the own log files.
Recommended logger for use with Java, Hibernate and Spring
[ "", "java", "hibernate", "spring", "logging", "jpa", "" ]
I am practicing over the summer to try and get better and I am a little stuck on the following: <http://www.javabat.com/prob/p123384> > Given a string, return a new string where the first and last chars have been exchanged. --- ### Examples: ``` frontBack("code") → "eodc" frontBack("a") → "a" frontBack("ab") → "ba" ``` --- ### Code: ``` public String frontBack(String str) { String aString = ""; if (str.length() == 0){ return ""; } char beginning = str.charAt(0); char end = str.charAt(str.length() - 1); str.replace(beginning, end); str.replace(end, beginning); return str; } ```
Rather than using the [`String.replace`](http://java.sun.com/javase/6/docs/api/java/lang/String.html#replace(char,%20char)) method, I'd suggest using the [`String.substring`](http://java.sun.com/javase/6/docs/api/java/lang/String.html#substring(int,%20int)) method to get the characters excluding the first and last letter, then concatenating the `beginning` and `end` characters. Furthermore, the `String.replace` method will replace all occurrences of the specified character, and returns a new `String` with the said replacements. Since the return is not picked up in the code above, the `String.replace` calls really don't do much here. This is because `String` in Java is immutable, therefore, the `replace` method cannot make any changes to the original `String`, which is the `str` variable in this case. --- Also to add, this approach won't work well with `String`s that have a length of 1. Using the approach above, a call to `String.substring` with the source `String` having a length of 1 will cause a `StringIndexOutOfBoundsException`, so that will also have to be taken care of as a special case, if the above approach is taken. Frankly, the approach presented in [indyK1ng's answer](https://stackoverflow.com/questions/1028095/how-can-i-exchange-the-first-and-last-characters-of-a-string-in-java/1028124#1028124), where the `char[]` is obtained from the `String` and performing a simple swap of the beginning and end characters, then making a `String` from the modified `char[]` is starting to sound much more pleasant.
Strings can be split into an array of chars and can be made with an array of chars. For more details on String objects, go to the [Java API](http://java.sun.com/javase/6/docs/api/) and click on String in the lower left pane. That pane is sorted alphabetically. Edit: Since some people are being more thorough, I think I'll give additional details. Create a char array using String's .toCharArray() method. Take the first element and store it in a char, swap the first element with the last, and place the element you stored in a char into the last element into the array, then say: ``` String temp = new String(charArray); ``` and return that. This is assuming that charArray is your array of chars.
How can I exchange the first and last characters of a string in Java?
[ "", "java", "" ]
It amazes me that JavaScript's Date object does not implement an add function of any kind. I simply want a function that can do this: ``` var now = Date.now(); var fourHoursLater = now.addHours(4); function Date.prototype.addHours(h) { // How do I implement this? } ``` I would simply like some pointers in a direction. * Do I need to do string parsing? * Can I use setTime? * How about milliseconds? Like this: ``` new Date(milliseconds + 4*3600*1000 /* 4 hours in ms */)? ``` This seems really hackish though - and does it even work?
JavaScript itself has terrible Date/Time API's. Nonetheless, you can do this in pure JavaScript: ``` Date.prototype.addHours = function(h) { this.setTime(this.getTime() + (h*60*60*1000)); return this; } ```
``` Date.prototype.addHours= function(h){ this.setHours(this.getHours()+h); return this; } ``` Test: ``` alert(new Date().addHours(4)); ```
How to add hours to a Date object?
[ "", "javascript", "datetime", "" ]
Im currently working with an API which requires we send our collection details in xml to their server using a post request. Nothing major there but its not working, so I want to output the sent xml to a txt file so I can look at actually whats being sent!! Instead of posting to the API im posting to a document called target, but the xml its outputting its recording seems to be really wrong. Here is my target script, note that the posting script posts 3 items, so the file being written should have details of each post request one after the other. ``` <?php error_reporting(E_ALL); ini_set('display_errors', 1); // get the request data... $payload = ''; $fp = fopen('php://input','r'); $output_file = fopen('output.txt', 'w'); while (!feof($fp)) { $payload .= fgets($fp); fwrite($output_file, $payload); } fclose($fp); fclose($output_file); ?> ``` I also tried the following, but this just recorded the last post request so only 1 collection item was recorded in the txt file, instead of all 3 ``` output_file = fopen('output.txt', 'w'); while (!feof($fp)) { $payload .= fgets($fp); } fwrite($output_file, $payload); fclose($fp); fclose($output_file); ``` I know im missing something really obvious, but ive been looking at this all morning!
Change ``` $output_file = fopen('output.txt', 'w'); ``` to ``` $output_file = fopen('output.txt', 'a'); ``` Also, change ``` $payload .= fgets($fp); ``` to ``` $payload = fgets($fp); ```
you should probably use curl instead to fetch the content and then write it via fwrite
Using PHP to store results of a post request
[ "", "php", "http-post", "file-writing", "" ]
Given a URL in a string: ``` http://www.example.com/test.xml ``` What's the easiest/most succinct way to download the contents of the file from the server (pointed to by the url) into a string in C#? The way I'm doing it at the moment is: ``` WebRequest request = WebRequest.Create("http://www.example.com/test.xml"); WebResponse response = request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); ``` That's a lot of code that could essentially be one line: ``` string responseFromServer = ????.GetStringFromUrl("http://www.example.com/test.xml"); ``` Note: I'm not worried about asynchronous calls - this is not production code.
Given that, at the time of this writing, `HttpClient` is the *only* remaining, *valid* .Net mechanism for performing this function, and, in any case where you're *"not worried about asynchronous calls"* (which appear to be unavoidable with `HttpClient`), I think that this function should get you what you're after: ``` public static class Http { ///<remarks>NOTE: The <i>HttpCLient</i> class is <b>intended</b> to only ever be instantiated once in any application.</remarks> private static readonly HttpClient _client = new(); /// <summary>Used to retrieve webserver data via simple <b>GET</b> requests.</summary> /// <param name="url">A string containing the complete web <b>URL</b> to submit.</param> /// <returns>Whatever <i>HttpClient</i> returns after attempting the supplied query (as a <i>Task&lt;string&gt;</i> value).</returns> /// <exception cref="InvalidOperationException">Returned if the supplied <i>url</i> string is null, empty or whitespace.</exception> private static async Task<string> HttpClientKludge( string url ) { if ( string.IsNullOrWhiteSpace( url ) ) throw new InvalidOperationException( "You must supply a url to interrogate for this function to work." ); Uri uri; try { uri = new Uri( url ); } catch ( UriFormatException e ) { return $"{e.Message}\r\n{url}"; } return await _client.GetStringAsync( uri ); } /// <summary>Attempts to interrogate a website via the supplied URL and stores the result in a <i>string</i>.</summary> /// <param name="url">A string containing a fully-formed, proper URL to retrieve.</param> /// <param name="captureExceptions">If <b>TRUE</b>, any Exceptions generated by the operation will be suppressed with their Message returned as the result string, otherwise they're thrown normally.</param> /// <returns>The result generated by submitting the request, as a <i>string</i>.</returns> public static string Get( string url, bool captureExceptions = true ) { string result; try { result = HttpClientKludge( url ).Result; } catch (AggregateException e) { if (!captureExceptions) throw; result = e.InnerException is null ? e.Message : e.InnerException.Message; } return result; } } ``` With that in place, anytime you want to interrogate a website with a simple URL+GET inquiry, you can simply do: ``` string query = "/search?q=Easiest+way+to+read+from+a+URL+into+a+string+in+.NET", siteResponse = Http.Get( $"https://www.google.com{query}" ); // Now use 'siteResponse' in any way you want... ```
Important: this was correct when written, but in `$current_year$`, please see the `HttpClient` answer below --- ``` using(WebClient client = new WebClient()) { string s = client.DownloadString(url); } ```
Easiest way to read from a URL into a string in .NET
[ "", "c#", "http", "networking", "" ]
I have method which gets a POJO as it's parameter. Now I want to programmatically get all the attributes of the POJO (because my code may not know what are all the attributes in it at run time) and need to get the values for the attributes also. Finally I'll form a string representation of the POJO. I could use [ToStringBuilder](http://commons.apache.org/lang/api-release/org/apache/commons/lang/builder/ToStringBuilder.html), but I want build my output string in certain format specific to my requirement. Is it possible to do so in Beanutils !? If yes, any pointers to the method name? If no, should I write my own reflection code?
Have you tried [ReflectionToStringBuilder](http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/builder/ReflectionToStringBuilder.html)? It looks like is should do what you describe.
I know this is a year old question, but I think it can be useful for others. I have found a partial solution using this LOC ``` Field [] attributes = MyBeanClass.class.getDeclaredFields(); ``` Here is a working example: ``` import java.lang.reflect.Field; import org.apache.commons.beanutils.PropertyUtils; public class ObjectWithSomeProperties { private String firstProperty; private String secondProperty; public String getFirstProperty() { return firstProperty; } public void setFirstProperty(String firstProperty) { this.firstProperty = firstProperty; } public String getSecondProperty() { return secondProperty; } public void setSecondProperty(String secondProperty) { this.secondProperty = secondProperty; } public static void main(String[] args) { ObjectWithSomeProperties object = new ObjectWithSomeProperties(); // Load all fields in the class (private included) Field [] attributes = object.getClass().getDeclaredFields(); for (Field field : attributes) { // Dynamically read Attribute Name System.out.println("ATTRIBUTE NAME: " + field.getName()); try { // Dynamically set Attribute Value PropertyUtils.setSimpleProperty(object, field.getName(), "A VALUE"); System.out.println("ATTRIBUTE VALUE: " + PropertyUtils.getSimpleProperty(object, field.getName())); } catch (Exception e) { e.printStackTrace(); } } } } ```
How to get the list of all attributes of a Java object using BeanUtils introspection?
[ "", "java", "reflection", "introspection", "apache-commons-beanutils", "" ]
I would like to know about how NULL values affect query performance in SQL Server 2005. I have a table similar to this (simplified): ``` ID | ImportantData | QuickPickOrder -------------------------- 1 | 'Some Text' | NULL 2 | 'Other Text' | 3 3 | 'abcdefg' | NULL 4 | 'whatever' | 4 5 | 'it is' | 2 6 | 'technically' | NULL 7 | 'a varchar' | NULL 8 | 'of course' | 1 9 | 'but that' | NULL 10 | 'is not' | NULL 11 | 'important' | 5 ``` And I'm doing a query on it like this: ``` SELECT * FROM MyTable WHERE QuickPickOrder IS NOT NULL ORDER BY QuickPickOrder ``` So the QuickPickOrder is basically a column used to single out some commonly chosen items from a larger list. It also provides the order in which they will appear to the user. NULL values mean that it doesn't show up in the quick pick list. I've always been told that NULL values in a database are somehow evil, at least from a normalization perspective, but is it an acceptable way to filter out unwanted rows in a WHERE constraint? Would it be better to use specific number value, like -1 or 0, to indicate items that aren't wanted? Are there other alternatives? **EDIT:** The example does not accuratly represent the ratio of real values to NULLs. An better example might show at least 10 NULLs for every non-NULL. The table size might be 100 to 200 rows. It is a reference table so updates are rare.
`SQL Server` indexes `NULL` values, so this will most probably just use the `Index Seek` over an index on `QuickPickOrder`, both for filtering and for ordering.
Another alternative would be two tables: ``` MyTable: ID | ImportantData ------------------ 1 | 'Some Text' 2 | 'Other Text' 3 | 'abcdefg' 4 | 'whatever' 5 | 'it is' 6 | 'technically' 7 | 'a varchar' 8 | 'of course' 9 | 'but that' 10 | 'is not' 11 | 'important' QuickPicks: MyTableID | QuickPickOrder -------------------------- 2 | 3 4 | 4 5 | 2 8 | 1 11 | 5 SELECT MyTable.* FROM MyTable JOIN QuickPicks ON QuickPickOrder.MyTableID = MyTable.ID ORDER BY QuickPickOrder ``` This would allow updating QuickPickOrder without locking anything in MyTable or logging a full row transaction for that table. So depending how big MyTable is, and how often you are updating QuickPickOrder, there may be a scalability advantage. Also, having a separate table will allow you to add a unique index on QuickPickOrder to ensure no duplication, and could be more easily scaled later to allow different kinds of QuickPicks, having them specific to certain contexts or users, etc.
Query Performance with NULL
[ "", "sql", "sql-server", "database", "performance", "" ]
I'm making a Django web-app which allows a user to build up a set of changes over a series of GETs/POSTs before committing them to the database (or reverting) with a final POST. I have to keep the updates isolated from any concurrent database users until they are confirmed (this is a configuration front-end), ruling out committing after each POST. My preferred solution is to use a per-session transaction. This keeps all the problems of remembering what's changed (and how it affects subsequent queries), together with implementing commit/rollback, in the database where it belongs. Deadlock and long-held locks are not an issue, as due to external constraints there can only be one user configuring the system at any one time, and they are well-behaved. However, I cannot find documentation on setting up Django's ORM to use this sort of transaction model. I have thrown together a minimal monkey-patch (ew!) to solve the problem, but dislike such a fragile solution. Has anyone else done this before? Have I missed some documentation somewhere? (My version of Django is 1.0.2 Final, and I am using an Oracle database.)
Multiple, concurrent, session-scale transactions will generally lead to deadlocks or worse (worse == livelock, long delays while locks are held by another session.) This design is not the best policy, which is why Django discourages it. The better solution is the following. 1. Design a **Memento** class that records the user's change. This could be a saved copy of their form input. You may need to record additional information if the state changes are complex. Otherwise, a copy of the form input may be enough. 2. Accumulate the sequence of **Memento** objects in their session. Note that each step in the transaction will involve fetches from the data and validation to see if the chain of mementos will still "work". Sometimes they won't work because someone else changed something in this chain of mementos. What now? 3. When you present the 'ready to commit?' page, you've replayed the sequence of **Mementos** and are pretty sure they'll work. When the submit "Commit", you have to replay the **Mementos** one last time, hoping they're still going to work. If they do, great. If they don't, someone changed something, and you're back at step 2: what now? This seems complex. Yes, it does. However it does not hold any locks, allowing blistering speed and little opportunity for deadlock. The transaction is confined to the "Commit" view function which actually applies the sequence of **Mementos** to the database, saves the results, and does a final commit to end the transaction. The alternative -- holding locks while the user steps out for a quick cup of coffee on step n-1 out of n -- is unworkable. For more information on **Memento**, see [this](http://en.wikipedia.org/wiki/Memento_pattern).
In case anyone else ever has the exact same problem as me (I hope not), here is my monkeypatch. It's fragile and ugly, and changes private methods, but thankfully it's small. Please don't use it unless you really have to. As mentioned by others, any application using it effectively prevents multiple users doing updates at the same time, on penalty of deadlock. (In my application, there may be many readers, but multiple concurrent updates are deliberately excluded.) I have a "user" object which persists across a user session, and contains a persistent connection object. When I validate a particular HTTP interaction is part of a session, I also store the user object on django.db.connection, which is thread-local. ``` def monkeyPatchDjangoDBConnection(): import django.db def validConnection(): if django.db.connection.connection is None: django.db.connection.connection = django.db.connection.user.connection return True def close(): django.db.connection.connection = None django.db.connection._valid_connection = validConnection django.db.connection.close = close monkeyPatchDBConnection() def setUserOnThisThread(user): import django.db django.db.connection.user = user ``` This last is called automatically at the start of any method annotated with @login\_required, so 99% of my code is insulated from the specifics of this hack.
Per-session transactions in Django
[ "", "python", "django", "transactions", "" ]
I'm doing an override for a third party class and I want to suppress all checks for it (since I'm only keeping it around until the patch is accepted). Is there a way to suppress all checks for a file? I tried using "\*" but that fails.
Don't know whether you're using command line or in an IDE, but you'll basically need a suppresions file. If you're manually editing the Checkstyle config file, add a new module to it: ``` <module name="SuppressionFilter"> <property name="file" value="mysuppressions.xml" /> </module> ``` Your `mysuppression.xml` can be something like: ``` <?xml version="1.0"?> <!DOCTYPE suppressions PUBLIC "-//Puppy Crawl//DTD Suppressions 1.1//EN" "http://www.puppycrawl.com/dtds/suppressions_1_1.dtd"> <suppressions> <suppress files="TheClassToIgnore\.java" checks="[a-zA-Z0-9]*"/> </suppressions> ``` The value for "`files`" attribute is basically a regex for your source files, and the value for the "`checks`" attribute is regex for what checks to skip ("`[a-zA-Z0-9]*`" basically means skip everything). This is the pattern you're looking for I guess?
I was able to suppress the checks in a file by adding the SuppressionCommentFilter tag in my checks.xml: First, I added the FileContentHolder tag as a child of TreeWalker tag (this step is *not* needed since version 8.1 of com.puppycrawl.tools:checkstyle): ``` <module name="TreeWalker"> ... <module name="FileContentsHolder"/> ... </module> ``` Then I added the SuppressionCommentFilter in the checks.xml (since version 8.1 of com.puppycrawl.tools:checkstyle - under "TreeWalker" node): ``` <module name="SuppressionCommentFilter"/> ``` In each file that I wanted to suppress the checks I inserted the following comment in the first line of the file: ``` // CHECKSTYLE:OFF ```
How to suppress all checks for a file in Checkstyle?
[ "", "java", "checkstyle", "" ]
Right now I can use this URL to request a Google Static Maps image successfully: ``` http://maps.google.com/staticmap?center=37.687,-122.407&zoom=8&size=450x300&maptype=terrain&key=[my key here]&sensor=false ``` However, the second I use JQuery or any direct javascript to set an image's src to the above url, Google passes back a Error 400: "Your client has issued a malformed or illegal request." I've read that this is usually from the key being incorrect, but my key is clearly being passed. This is how I'm setting the image dynamically: ``` document.getElementById('my-image-id').src = "http://maps.google.com/staticmap?center=37.687,-122.407&zoom=8&size=450x300&maptype=terrain&key=[my key here]&sensor=false" ``` I've replaced [my key here] with my correct key, and it still doesn't work. When I request the same url through the browser, it's fine. I've confirmed that the correct referrers are getting passed as well. Any ideas?
Does this code work for you (it works for me -- be sure to insert your key)? ``` <html> <head> <script language="javascript"> function swap() { document.getElementById('my-image-id').src = "http://maps.google.com/staticmap?center=37.687,-122.407&zoom=8&size=450x300&maptype=terrain&key=&sensor=false" } </script> </head> <body> <img src="http://www.google.com/intl/en_ALL/images/logo.gif" width="450" height="300" onClick="swap();" id="my-image-id" /> </body> </html> ```
You have a possible typo with the g on the end here: ``` &key=[my key here]g ```
How to load a Google Static Maps Image using Javascript
[ "", "javascript", "google-maps", "" ]
Looks like no built-in Library/API in C# to unzip a zip file. I am looking for a free (better open source) library/API which could work with .Net 3.5 + VSTS 2008 + C# to unzip a zip file and extract all files into a specific folder. Any recommended library/API or samples?
The GPL <http://www.icsharpcode.net/OpenSource/SharpZipLib/> OR the less restrictive Ms-PL <http://www.codeplex.com/DotNetZip> To complete this answer the .net framework has [ZipPackage](http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx) I had less success with it.
If all you want to do is unzip the contents of a file to a folder, and you know you'll only be running on Windows, you can use the Windows Shell object. I've used `dynamic` from Framework 4.0 in this example, but you can achieve the same results using `Type.InvokeMember`. ``` dynamic shellApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application")); dynamic compressedFolderContents = shellApplication.NameSpace(sourceFile).Items; dynamic destinationFolder = shellApplication.NameSpace(destinationPath); destinationFolder.CopyHere(compressedFolderContents); ``` You can use [FILEOP\_FLAGS](http://www.pinvoke.net/default.aspx/Enums/FILEOP_FLAGS.html) to control behaviour of the `CopyHere` method.
recommend a library/API to unzip file in C#
[ "", "c#", ".net", "zip", "" ]
I ran an update statement on a large PostgreSQL table through the phpPgAdmin interface. This timed out as it ran for too long. I can now update some rows from that table but not all. Trying to update some rows will hang. Are the rows locked? How can I allow these rows to be updated?
What version of PostgreSQL are you running? The following assumes 8.1.8 or later (it may apply to earlier versions too, I don't know). I presume that you mean that phpPgAdmin timed out -- the PostgreSQL backend will take as long as it takes to complete a query/update. In that case, it's possible that the original session is still alive and the UPDATE query is still running. I suggest running the following query (taken from [chapter 24 of the PostgreSQL docs](http://www.postgresql.org/docs/8.1/interactive/monitoring.html)) on the machine that hosts the PostgreSQL server process, to see whether the session is still alive: ``` ps auxwww|grep ^postgres ``` Several rows should appear: 1 for the `postmaster` master process, and 1 each for "writer", "stats buffer", and "stats collector" processes. Any remaining lines are for processes serving DB connections. These lines will contain the username and database name. Hopefully, from that you can see whether the session you performed the original UPDATE in is still hanging around. Although in theory you could find more detailed info by `SELECT`ing from the system view `pg_stat_activity`, by default PostgreSQL is not set up to populate the most useful fields (such as `current_query` and `query_start`). See chapter 24 for how to enable this in the future. If you see the session is still there, kill it. You will need to be logged in as the user running the process (usually `postgres`) or root to do so -- if you don't run the server yourself, get your DBA to do this for you. One more thing: for updating rows in a table, PostgreSQL avoids using locks. Instead, it allows every writing transaction to create a new "version" of the DB, which becomes the "current version" when the transaction is committed, provided it doesn't conflict with updates made in the meantime by other transactions. So I suspect the "hanging" you're seeing is caused by something else -- though what, I'm not sure. (Have you checked the obvious things, like whether the disk partition containing the DB is full?)
It's possible to see the locks. Here is a view to make it a bit easier than using pg\_locks directly: ``` CREATE OR REPLACE VIEW public.active_locks AS SELECT t.schemaname, t.relname, l.locktype, l.page, l.virtualtransaction, l.pid, l.mode, l.granted FROM pg_locks l JOIN pg_stat_all_tables t ON l.relation = t.relid WHERE t.schemaname <> 'pg_toast'::name AND t.schemaname <> 'pg_catalog'::name ORDER BY t.schemaname, t.relname; ``` Then you just select from the view: ``` SELECT * FROM active_locks; ``` And kill it with: ``` SELECT pg_cancel_backend('%pid%'); ``` Other solutions: <http://wiki.postgresql.org/wiki/Lock_Monitoring>
How to release possible Postgres row locks?
[ "", "sql", "database", "postgresql", "locking", "" ]
So I've been reading a lot about encryption in PHP. So much that I am not sure exactly what's a really good method to securely store login information. However, the following function is what I came up with: ``` function loginHash($username, $password){ $salt = str_split($password,(strlen($password)/2)+1); $hash = hash('whirlpool', $username.$salt[0].'centerSalt'.$salt[1]); return $hash; } ``` Am I doing it the right way? It's used for authenticating a password combined with a username, and the ability to compare the generated hash with the one stored in a database to verify a login.
Encrypting != Hashing. They both are generally accepted to be in the category of Cryptography, but when something can be encrypted, it can be decrypted, which is not the case in Hashing. Hashing is just hashing, and that's it. The salt is indeed not properly constructed. It should be x-bytes read from /dev/urandom with a fopen() call. For example, 16 bytes of salt is what I personally use. This prevents rainbow table attacks effectively. To make things more secure, use a secret key, too. For example: ``` $hashedPassword = hash_hmac('whirlpool',$password.$salt,$key); ``` The $key is simply random data. You could generate a 64 kB file, for instance, that is called "key.bin" in a hidden folder above the document root and use file\_get\_contents() before the hash process. Why to use secret keys? If you store the hashes and salts in a database and the key in the filesystem, then this prevents anyone from cracking your hash if they get their hands on your stored hashes and salts. So, an attacker would need to crack into both the database and the filesystem to crack your hashes, but notice that it's pointless for anyone to crack your hashes anymore if they have already cracked your whole application, which implies that your hashing scheme is good.
My advise is to never, never, never write your own encryption and hash functions. Even experts do it wrong all the time, so dont try it yourself. Ive heared that [phpass (Openwall)](http://www.openwall.com/phpass/) is a nice hashing framework, i'd suggest you use that. They use salts in their hashes and have quite some parameters to tweak the hash.
Is my authentication encryption any good?
[ "", "php", "authentication", "encryption", "hash", "salt", "" ]
Is there a way of determining the name of a constant from a given value? For example, given the following: public const uint ERR\_OK = 0x00000000; How could one obtain "ERR\_OK"? I have been looking at refection but cant seem to find anything that helps me.
In general, you can't. There could be any number of constants with the same value. If you know the class which declared the constant, you could look for all public static fields and see if there are any with the value 0, but that's all. Then again, that might be good enough for you - is it? If so... ``` public string FindConstantName<T>(Type containingType, T value) { EqualityComparer<T> comparer = EqualityComparer<T>.Default; foreach (FieldInfo field in containingType.GetFields (BindingFlags.Static | BindingFlags.Public)) { if (field.FieldType == typeof(T) && comparer.Equals(value, (T) field.GetValue(null))) { return field.Name; // There could be others, of course... } } return null; // Or throw an exception } ```
I may be late.. but i think following could be the answer ``` public static class Names { public const string name1 = "Name 01"; public const string name2 = "Name 02"; public static string GetName(string code) { foreach (var field in typeof(Names).GetFields()) { if ((string)field.GetValue(null) == code) return field.Name.ToString(); } return ""; } } ``` and following will print "**name1**" ``` string result = Names.GetName("Name 01"); Console.WriteLine(result ) ```
Determine the name of a constant based on the value
[ "", "c#", ".net", "reflection", "constants", "" ]
I have created two beans ``` class BackPageBean{ String backPage = null; : : : } class InformationMessageBean{ String informationMessage = null; : : : } ``` Now, if a class is backpage aware then it will extend backPageBean, or if it need to show some kind of message then it extends InformationMessageBean. ``` class BackPageAware extends backPageBean{ } class InfoMessAware extends InformationMessageBean{ } someFunction () { if ( theObject instanceOf backPageBean ) { prepareTheBackPage ( theObject.getBackPage() ); } if ( theObject instanceOf InformationMessageBean ) { showtheInformation ( theObject.getMessage() ); } } ``` --- Now the problem is, if i want to have a bean which is both BackPageAware as well as InformationAware then, as we don't have multiple inheritance, what should be the approach?
Just to clarify my comment. > Just like Darth Eru says you create > the two interfaces and the two default > implementations. When you have a bean > that needs both of the behaviours you > have that class implement the two > interfaces but you also create > variables of the default > implementations. This way you still > dont need to duplicate any code. ``` interface InfoMessAware { String getMessage(); } interface BackPageAware { String getBackPage(); } class DefaultInfoMessAware { String getMessage() { return "message"; } } class DefaultBackPageAware { String getBackPage() { return "backPage"; } } class MyBean implements InfoMessAware, BackPageAware { private InfoMessAware messAware = new DefaultInfoMessAware(); private BackPageAware backPageAware = new DefaultBackPageAware(); String getMessage() { return messAware.getMessage(); } String getBackPage() { return backPageAware.getBackPage(); } } ```
use interfaces: ``` interface InfoMessAware { String getMessage(); } interface BackPageAware { String getBackPage(); } class MyBean implements InfoMessAware, BackPageAware { String getMessage() { return "message"; } String getBackPage() { return "backPage"; } } ``` then replace **instanceof** with standard method calls.
Alternative of Multiple inheritance in Java
[ "", "java", "multiple-inheritance", "" ]
I have an iPhone application that emails my GPS coordinates to an email account. I have some code ([here](https://stackoverflow.com/questions/1003678/error-using-cmail-dll/1003959#1003959)) that I'm using to search that account for emails that contain the GPS coordinates. I wanted a Windows Forms application that would allow me to store the date, time, latitude, longitude and res information of the emails into some sort of rudimentary database that would just be either part of the program or just a file that accompanied the program. I could probably use a [CSV](http://en.wikipedia.org/wiki/Comma-separated_values) file but I wanted to do things the right way so I'll put it before the court of better programmers. What is the best way to store this data to be queried against later? Some ideas are to make a heat map of how often a certain location is occupied. Another idea is to create a path of "bread crumbs" that I can use later. Thanks for any advice you can give.
If you don't want a full fledged database server, I'd recommend using [SQLite](http://www.sqlite.org).
You can use [SQLite](http://www.sqlite.org) and store the data for each GPS fix you get. Then you can use normal SQL queries to combine and slice the data in what ever ways you want. SQLite can be used from with in an iPhone app as well as .net languages, so you can store the data directly to a SQLite database on your iPhone instead of emailing the data then searching the emails.
Beginner question for a simple database
[ "", "c#", "database", "" ]
My background is C and C++. I like Python a lot, but there's one aspect of it (and other interpreted languages I guess) that is really hard to work with when you're used to compiled languages. When I've written something in Python and come to the point where I can run it, there's still no guarantee that no language-specific errors remain. For me that means that I can't rely solely on my runtime defense (rigorous testing of input, asserts etc.) to avoid crashes, because in 6 months when some otherwise nice code finally gets run, it might crack due to some stupid typo. Clearly a system should be tested enough to make sure all code has been run, but most of the time I use Python for in-house scripts and small tools, which ofcourse never gets the QA attention they need. Also, some code is so simple that (if your background is C/C++) you know it will work fine as long as it compiles (e.g. getter-methods inside classes, usually a simple return of a member variable). So, my question is the obvious - is there any way (with a special tool or something) I can make sure all the code in my Python script will "compile" and run?
Look at [PyChecker](http://pychecker.sourceforge.net/) and [PyLint](http://www.logilab.org/857). Here's example output from pylint, resulting from the trivial program: ``` print a ``` As you can see, it detects the undefined variable, which py\_compile won't (deliberately). ``` in foo.py: ************* Module foo C: 1: Black listed name "foo" C: 1: Missing docstring E: 1: Undefined variable 'a' ... |error |1 |1 |= | ``` Trivial example of why tests aren't good enough, even if they cover "every line": ``` bar = "Foo" foo = "Bar" def baz(X): return bar if X else fo0 print baz(input("True or False: ")) ``` EDIT: PyChecker handles the ternary for me: ``` Processing ternary... True or False: True Foo Warnings... ternary.py:6: No global (fo0) found ternary.py:8: Using input() is a security problem, consider using raw_input() ```
Others have mentioned tools like PyLint which are pretty good, but the long and the short of it is that it's simply not possible to do 100%. In fact, you might not even want to do it. Part of the benefit to Python's dynamicity is that you can do crazy things like insert names into the local scope through a dictionary access. What it comes down to is that if you want a way to catch type errors at compile time, you shouldn't use Python. A language choice always involves a set of trade-offs. If you choose Python over C, just be aware that you're trading a strong type system for faster development, better string manipulation, etc.
How can I make sure all my Python code "compiles"?
[ "", "python", "parsing", "code-analysis", "" ]
I am trying to make my own user control and have almost finished it, just trying to add some polish. I would like the option in the designer to "Dock in parent container". Does anyone know how to do this I can't find an example. I think it has something to do with a Docking Attribute.
I order to achieve this you will need to implement a couple of classes; first you will need a custom [ControlDesigner](http://msdn.microsoft.com/en-us/library/system.windows.forms.design.controldesigner.aspx) and then you will need a custom [DesignerActionList](http://msdn.microsoft.com/en-us/library/system.componentmodel.design.designeractionlist.aspx). Both are fairly simple. The ControlDesigner: ``` public class MyUserControlDesigner : ControlDesigner { private DesignerActionListCollection _actionLists; public override System.ComponentModel.Design.DesignerActionListCollection ActionLists { get { if (_actionLists == null) { _actionLists = new DesignerActionListCollection(); _actionLists.Add(new MyUserControlActionList(this)); } return _actionLists; } } } ``` The DesignerActionList: ``` public class MyUserControlActionList : DesignerActionList { public MyUserControlActionList(MyUserControlDesigner designer) : base(designer.Component) { } public override DesignerActionItemCollection GetSortedActionItems() { DesignerActionItemCollection items = new DesignerActionItemCollection(); items.Add(new DesignerActionPropertyItem("DockInParent", "Dock in parent")); return items; } public bool DockInParent { get { return ((MyUserControl)base.Component).Dock == DockStyle.Fill; } set { TypeDescriptor.GetProperties(base.Component)["Dock"].SetValue(base.Component, value ? DockStyle.Fill : DockStyle.None); } } } ``` Finally, you will need to attach the designer to your control: ``` [Designer("NamespaceName.MyUserControlDesigner, AssemblyContainingTheDesigner")] public partial class MyUserControl : UserControl { // all the code for your control ``` **Brief explanation** The control has a `Designer` attribute associated with it, which points out our custom designer. The only customization in that designer is the `DesignerActionList` that is exposed. It creates an instance of our custom action list and adds it to the action list collection that is exposed. The custom action list contains a `bool` property (`DockInParent`), and creates an action item for that property. The property itself will return `true` if the `Dock` property of the component being edited is `DockStyle.Fill`, otherwise `false`, and if `DockInParent` is set to `true`, the `Dock` property of the component is set to `DockStyle.Fill`, otherwise `DockStyle.None`. This will display the little "action arrow" close to the upper right corner of the control in the designer, and clicking the arrow will pop up the task menu.
I would also suggest looking at the [DockingAttribute](http://msdn.microsoft.com/en-us/library/system.windows.forms.dockingattribute%28v=vs.80%29.aspx). ``` [Docking(DockingBehavior.Ask)] public class MyControl : UserControl { public MyControl() { } } ``` This also displays the 'action arrow' on the upper right corner of the control. This option is available as far back as .NET 2.0, and it is far simpler if all you're looking for is the 'Dock/Undock in Parent Container' function. The Designer classes are massive overkill in that case. It also gives the options of `DockingBehavior.Never` and `DockingBehavior.AutoDock`. `Never` does not display the arrow and loads the new control at it's default `Dock` behavior, while `AutoDock` displays the arrow but automatically docks the control in as `Fill`. > *PS: Sorry about necromancing a thread. I was looking for a similar solution, and this was the first thing that popped up on Google. The > Designer attributes gave me an idea, so I started digging around and > found DockingAttribute, which seemed far cleaner than the accepted > solution with the same requested results. Hopefully this will help > someone in the future.*
User Control Docking Attribute
[ "", "c#", "winforms", "user-controls", "attributes", "docking", "" ]
I have a class Employee. I want to be able to Validate() it before I save it to make sure all the fields have been populated with valid values. The user of the class may call Validate() before they call Save() or they may call Save() directly and Save() will then call Validate() and probably throw an Exception if validation fails. Now, my (main) question is this; If my Validate() function returns a simple bool then how do I tell the user of the class what is wrong, i.e. "Email not filled in", "ID not unique" etc. For the purposes of this I just want the error strings to pass to the human user, but the principle is the same if I wanted a list of error codes (except that makes the use of a bitmap more logical). * I could use an Out paramater in my Validate function but I understand this is frowned upon. * Rather than returning a bool, I could return a string array from my function and just test if it was empty (meaning no errors) - but that seems messy and not right. * I could create a Struct just to return from this method, including a bool and a string array with error messages, but just seems clunky. * I could return a bitmap of error codes instead of a bool and look it up, but that seems rather excessive. * I could create a public property "ValidationErrors" on the object which would hold the errors. However, that would rely on me calling Validate() before reading it or explicitly calling Validate from the Property() which is a bit wasteful. My specific program is in C# but this looks like a fairly generic "best practice" question and one I am sure I should know the answer to. Any advice gratefully received.
I would probably go for the bitmap-option. Simply ``` [Flags] public enum ValidationError { None = 0, SomeError = 1, OtherError = 2, ThirdError = 4 } ``` ...and in the calling code, simply: ``` ValidationError errCode = employee.Validate(); if(errCode != ValidationError.None) { // Do something } ``` Seems nice and compact to me.
> I could create a Struct just to return from this method, including a bool and a string array with error messages, but just seems clunky. Why does it seem clunky? Creating an appropriate type to encapsulate the information is perfect. I wouldn't necessarily use a string to encode such information, though. An enum may be better suited. An alternative would be to subclass the return type and provide an extra child class for every case – if this is appropriate. If more than one failures may be signalled, an array is fine. But I would encapsulate this in an own type as well. The general pattern could look like this: ``` class ValidationInfo { public bool Valid { get; private set; } public IEnumerable<Failure> Failures { get; private set; } } ```
Best practice for giving back extra information from a Validate function
[ "", "c#", "" ]
I've got some legacy code in C++ here that does some things I don't understand. I'm running it in Visual C++ 2008 Express Edition on a machine running Windows XP. The code uses some Windows functions: [GetAdaptersInfo](http://msdn.microsoft.com/en-us/library/aa365917(VS.85).aspx) and GetAdaptersAddressess. I realize that the final parameter for both of these is a pointer to the size of the buffer and since it's in\_out, it can be changed within the function. My question is: are these functions supposed to change the buffer length? In the code I have, every time these functions are called the buffer length variable is initialized to zero, and after the function is called, it's still 0.
Your code needs to look something like this: ``` // First get the desired size. unsigned long outBufLen = 0; DWORD dwResult = GetAdaptersInfo(NULL, &outBufLen); if (dwResult == ERROR_BUFFER_OVERFLOW) // This is what we're expecting { // Now allocate a structure of the requried size. PIP_ADAPTER_INFO pIpAdapterInfo = (PIP_ADAPTER_INFO) malloc(outBufLen); dwResult = GetAdaptersInfo(pIpAdapterInfo, &outBufLen); if (dwResult == ERROR_SUCCESS) { // Yay! ``` **Edit:** See also Jeremy Friesner's answer for why this code isn't quite enough.
Of course, the example code in [@RichieHindle's answer](https://stackoverflow.com/questions/1070351/getadaptersinfo-and-getadaptersaddressess-bufferlength-param/1070481#1070481) contains a race condition.... if the size of the structure Windows wants to return grows after the first call to GetAdaptersInfo() but before the second call to GetAdaptersInfo(), the second call to GetAdaptersInfo() will fail with ERROR\_BUFFER\_OVERFLOW as well, and your function won't work. Yes, that does happen in real life -- I've had it happen to me. If you want the code to be reliable, you need to call GetAdaptersInfo() in a loop, increasing your buffer's size as many times as necessary until the call succeeds. There has to be a less error-prone way to construct an API... unfortunately Microsoft hasn't yet found it. :^P
GetAdaptersInfo and GetAdaptersAddressess BufferLength Param
[ "", "c++", "windows", "visual-c++", "windows-xp", "" ]
Typically the default implementation of `Object.hashCode()` is some function of the allocated address of the object in memory (though this is not mandated by the Java Language Specification). Given that the VM shunts objects about in memory, why does the value returned by `System.identityHashCode()` never change during the object's lifetime? If it is a "one-shot" calculation (the object's `hashCode` is calculated once and stashed in the object header or something), then does that mean it is possible for two objects to have the same `identityHashCode` (if they happen to be first allocated at the same address in memory)?
Modern JVMs save the value in the object header. I believe the value is typically calculated only on first use in order to keep time spent in object allocation to a minimum (sometimes down to as low as a dozen cycles). The common Sun JVM can be compiled so that the identity hash code is always 1 for all objects. Multiple objects can have the same identity hash code. That is the nature of hash codes.
In answer to the second question, irrespective of the implementation, it is possible for multiple objects to have the same identityHashCode. See [bug 6321873](https://bugs.java.com/bugdatabase/view_bug?bug_id=6321873) for a brief discussion on the wording in the javadoc, and a program to demonstrate non-uniqueness.
How does the JVM ensure that System.identityHashCode() will never change?
[ "", "java", "jvm", "hashcode", "heap-memory", "" ]
I am having some trouble with Python giving me a result I do not expect. Here is a sample code : ``` number = re.search(" [0-9] ", "test test2 test_ 2 333") print number.groups() number = re.search(" [[:digit:]] ", "test test2 test_ 2 333") print number.groups() ``` In the first block I get an object returned but with nothing in it. Where I think I should get the string "2". In the second block I don't even get an object, where I am expection the string "2". While when I do this in bash everything looks fine : ``` echo "test test2 test_ 2 333" | grep " [[:digit:]] " echo "test test2 test_ 2 333" | grep " [0-9] " ``` Can somebody help me please?
The groups() method returns the capture groups. It does *not* return group 0, in case that's what you were expecting. Use parens to indicate capture groups. eg: ``` >>> number = re.search(" ([0-9]) ", "test test2 test_ 2 333") >>> print number.groups() ('2',) ``` For your second example, Python's re module doesn't recognize the "[:digit:]" syntax. Use `\d`. eg: ``` >>> number = re.search(r" (\d) ", "test test2 test_ 2 333") >>> print number.groups() ('2',) ```
You are missing the () which capture the contents for use with the groups() (and other) function(s). ``` number = re.search(" ([0-9]) ", "test test2 test_ 2 333") print number.groups() ``` This however won't work because python does not support the [[:number:]] notation ``` number = re.search(" ([[:digit:]]) ", "test test2 test_ 2 333") print number.groups() ```
Python regular expression with [:numeric:]
[ "", "python", "regex", "bash", "" ]
I am trying to load views for a set of 'modules' for a user who has selected any number of available 'modules'. I can get the name of the modules, or any column from the database. ``` load->view($name . '_view'); ``` I can't seem to figure a way to load the data for the view based on the 'module' name though. ``` //Loads the rows (selected modules) I need for this user into an array $modules['modulearr'] = $this->module_model->getModuleUser(); for($i = 0; $i < count($modules['modulearr']); $i++){ //Get the variable from the array $name = $modules['modulearr'][$i]->mod_name; //The below works. $this->load->view($name.'_view'); //The below would not work. (this is the crux of my problem) $data = $this->$name.'_model'->get(); $this->load->view($name.'_view', $data); } ``` There is also an issue with loading the models in the controller based on the fact I can't change `$this->load->THIS_PART` dynamically. I am new to everything, so there may be a basic concept I am not grasping. If you could point me in the right direction; that would be awesome. I could do a whole bunch of if statements, but that seems messy. Surely there is a better way. Thanks in advance!
It was a capitalization issue: The fields from the database (in array form) ``` $name = $modules['modulearr'][$i]->mod_name; ``` were sometimes in capitals. I fixed it by using ``` $name = strtolower($name); $nameMod = $name.'_model'; ``` then ``` //it doesn't seem to like combinations of things where nameMod is below. $data[$name.'_result'] = $this->$nameMod->get() $this->load->view($name.'_view', $data); ``` I don't know why it originally worked in the view loading part and not the loading data by calling model function part, but it does now. I am using it for a main landing (after sign up or login) page function that selects and displays the modules added by each user to their profile, I am probably going about this in a completely gammy way, but I am learning heaps by making mistakes, Thanks for the help answerers you definitely put me on the right track
maybe you wanted ``` $data = $this->$name.'_model'->get(); ``` you forgot to concatenate the strings
Loading 'modules' Data Into Views on a Per User Basis Dynamically From One Controller Using CodeIgniter
[ "", "php", "codeigniter", "dynamic", "" ]
This may seem like an odd question, but I need to find a closed-source alternative to Quartz.NET. I have been using quartz in a windows service application I am writing, and recently discovered that my employer will not allow me to use open-source controls in my project (funny, since there is plenty of UNIX stuff running here as well...sheesh). Anyone have any suggestions on a control that I can use? Thanks!
It appears as though I have talked the superiors into allowing me to use Quartz (as long as I don't mention that I am using it, hehe). Thanks for the help everyone!
Keeping in mind that closed source usually means you have to pay, here is a solution that might fit your needs: 1. [PortSight Task Scheduler for .NET](http://www.portsight.com/Products.aspx?AliasPath=Products/Task%20Scheduler/Task%20Scheduler&CultureAlias=en-US)
Closed-source alternative to Quartz.NET
[ "", "c#", "quartz-scheduler", "" ]
I am writing a file to disk in stages. As I write it I need to know the line numbers that I am writing to use to build an index. The file now has 12 million lines so I need to build the index on the fly. I am doing this in four steps, with four groupings of the value that I am indexing on. Based on some examples I found elsewhere on SO I decided that to keep my functions as clean as possible I would get the linesize of the file before I start writing so I can use that count to continue to build my index. So I have run across this problem, theoretically I don't know if I am adding the first chunk or the last chunk to my file so I thought to get the current size I would ``` myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt','a') try: num_lines=sum(1 for line in myFile) except IOError: num_lines=0 ``` When I do this the result is always 0-even if myFile exists and has a num\_lines >0 If I do this instead: ``` myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt') try: num_lines=sum(1 for line in myFile) except IOError: num_lines=0 ``` I get the correct value iff myFile exists. byt if myFile does not exist, if I am on the first cycle, I get an error message. As I was writing out this question it occurred to me that the reason for the value num\_lines=0 on every case the file exists is because the file is being opened for appending to so the file is opened at the last line and is now awaiting for lines to be delivered. So this fixes the problem ``` try: myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt') num_lines=sum(1 for line in myFile) except IOError: num_lines=0 ``` My question is whether or not this can be done another way. The reason I ask is because I have to now close myFile and reopen it for appending: That is to do the work I need to do now that I have the ending index number for the data that is already in the file I have to ``` myFile.close() myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt','a') ``` Now, here is where maybe I am learning something- given that I have to open the file twice then maybe getting the starting index (num\_lines) should be moved to a function ``` def getNumbLines(myFileRef): try: myFile=open(myFileRef) num_lines=sum(1 for line in myFile) myFile.close() except IOError: num_lines=0 return num_lines ``` It would be cleaner if I did not have to open/handle the file twice. Based on Eric Wendelin's answer I can just do: ``` myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt','a+') num_lines=sum(1 for line in myFile) ``` Thanks
You can open a file for reading AND writing: ``` myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt','r+') ``` Try that. **UPDATE: Ah, my mistake since the file might not exist. Use 'a+' instead of 'r+'.**
I assume you are writing the file, in that case why don't you maintain a separate track of how many lines you have already written? to me it looks very wasteful that you have to read whole file line by line just to get line number.
Can I avoid handling a file twice if I need the number of lines and I need to append to the file?
[ "", "python", "file", "" ]
I would like to develop a application (i prefer c++), which will take C header file with lot of nested structures as input and generate a html page where the data will be presented as Hierarchial tree structures, which can be collapsed.. ## file.h ``` struct level1 { struct level2 { struct level3 { } } }; ``` ## file.html [+] level1 I can collapse the level1 as below ``` [-] level1 [-] level2 [+] level3 ``` Its for Learning purpose..and i am not sure where to start. Few pointers will be really helpful.
The hardest part will be parsing the C header files. [GCCXML](http://www.gccxml.org/HTML/Index.html) will do that for you, outputting an XML structure that's then trivial to parse.
You might want to checkout **ctags** and **DOxygen** because they create HTML from various source code files for documentation purposes. Probably has what you need, and ctags I am sure will have C++ bindings.
Generate HTML Pages from C Structures
[ "", "c++", "" ]
I have created a [jQuery content switcher](http://pmck.net/jq-switcher/). Generally, it works fine, but there is one problem with it. If you click the links on the side multiple times, multiple pieces of content sometimes become visible. The problem most likely lies somewhere within the click event. Here is the code: ``` $('#tab-list li a').click( function() { var targetTab = $(this).attr('href'); if ($(targetTab).is(':hidden')) { $('#tab-list li').removeClass('selected'); var targetTabLink = $(this).parents('li').eq(0); $(targetTabLink).addClass('selected'); $('.tab:visible').fadeOut('slow', function() { $(targetTab).fadeIn('slow'); } ); } return false; } ); ``` I have tried adding a lock to the transition so that further clicks are ignored as the transition is happening, but to no avail. I have also tried to prevent the transition from being triggered if something is already animating, using the following: ``` if ($(':animated')) { // Don't do anything } else { // Do transition } ``` But it seems to always think things are being animated. Any ideas how I can prevent the animation being triggered multiple times?
One idea would be to remove the click event at the start of your function, and then add the click event back in when your animation has finished, so clicks during the duration would have no effect. If you have the ability to execute code when the animation has finished this should work.
Add a variable to use as a lock rather than is(:animating). On the click, check if the lock is set. If not, set the lock, start the process, then release the lock when the fadeIn finishes. ``` var blockAnimation = false; $('#tab-list li a').click( function() { if(blockAnimation != true){ blockAnimation = true; var targetTab = $(this).attr('href'); if ($(targetTab).is(':hidden')) { $('#tab-list li').removeClass('selected'); var targetTabLink = $(this).parents('li').eq(0); $(targetTabLink).addClass('selected'); $('.tab:visible').fadeOut('slow', function() { $(targetTab).fadeIn('slow', function(){ blockAnimation=false; }); } ); } } return false; } ); ```
Prevent click event in jQuery triggering multiple times
[ "", "javascript", "jquery", "" ]
I want to create a dialog that contains some kind of text element (JLabel/JTextArea etc) that is multi lined and wrap the words. I want the dialog to be of a fixed width but adapt the height depending on how big the text is. I have this code: ``` import static javax.swing.GroupLayout.DEFAULT_SIZE; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class TextSizeProblem extends JFrame { public TextSizeProblem() { String dummyString = ""; for (int i = 0; i < 100; i++) { dummyString += " word" + i; //Create a long text } JLabel text = new JLabel(); text.setText("<html>" + dummyString + "</html>"); JButton packMeButton = new JButton("pack"); packMeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { pack(); } }); GroupLayout layout = new GroupLayout(this.getContentPane()); getContentPane().setLayout(layout); layout.setVerticalGroup(layout.createParallelGroup() .addComponent(packMeButton) .addComponent(text) ); layout.setHorizontalGroup(layout.createSequentialGroup() .addComponent(packMeButton) .addComponent(text, DEFAULT_SIZE, 400, 400) //Lock the width to 400 ); pack(); } public static void main(String args[]) { SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new TextSizeProblem(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } ``` When running the program it looks like this: [![alt text](https://i.stack.imgur.com/39zyR.png)](https://i.stack.imgur.com/39zyR.png) (source: [lesc.se](http://lesc.se/stackoverflow/multiline_size_1.png)) But I would like the dialog to look like this (as when you press the pack-button): [![alt text](https://i.stack.imgur.com/elKLc.png)](https://i.stack.imgur.com/elKLc.png) (source: [lesc.se](https://web.archive.org/web/20141025154731/http://lesc.se/stackoverflow/multiline_size_2.png)) I'm guessing that the problem is that the layout manager had not been able to determine the proper height of the text before displaying it to the screen. I have tried various validate(), invalidate(), validateTree() etc but have not succeed.
I found a solution to my problem. By replacing the JLabel with a JTextArea: > ``` > JTextArea text = new JTextArea(); > text.setText(dummyString); > text.setLineWrap(true); > text.setWrapStyleWord(true); > ``` And calling pack() followed by an invocation to the layout manager to layout the components again followed by another pack: > ``` > pack(); > layout.invalidateLayout(this.getContentPane()); > pack(); > ``` This will cause the layout manager to adapt to the width. The complete code: ``` import static javax.swing.GroupLayout.DEFAULT_SIZE; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class TextSizeProblem3 extends JFrame { public TextSizeProblem3() { String dummyString = ""; for (int i = 0; i < 100; i++) { dummyString += " word" + i; //Create a long text } JTextArea text = new JTextArea(); text.setText(dummyString); text.setLineWrap(true); text.setWrapStyleWord(true); JButton packMeButton = new JButton("pack"); packMeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { pack(); } }); GroupLayout layout = new GroupLayout(this.getContentPane()); getContentPane().setLayout(layout); layout.setVerticalGroup(layout.createParallelGroup() .addComponent(packMeButton) .addComponent(text) ); layout.setHorizontalGroup(layout.createSequentialGroup() .addComponent(packMeButton) .addComponent(text, DEFAULT_SIZE, 400, 400) //Lock the width to 400 ); pack(); layout.invalidateLayout(this.getContentPane()); pack(); } public static void main(String args[]) { SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new TextSizeProblem3(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } ``` (you can add some customization (border, color etc) so it looks just like the JLabel but I have omitted that)
Here is an adaptation of your code, doing what you want. But it needs a little trick to calculate the size of the label and set its preferred Size. [I found the solution here](http://forums.sun.com/thread.jspa?messageID=10579575) ``` import static javax.swing.GroupLayout.DEFAULT_SIZE; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import javax.swing.text.View; public class TextSizeProblem extends JFrame { public TextSizeProblem() { String dummyString = ""; for (int i = 0; i < 100; i++) { dummyString += " word" + i; // Create a long text } JLabel text = new JLabel(); text.setText("<html>" + dummyString + "</html>"); Dimension prefSize = getPreferredSize(text.getText(), true, 400); JButton packMeButton = new JButton("pack"); packMeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { pack(); } }); GroupLayout layout = new GroupLayout(this.getContentPane()); getContentPane().setLayout(layout); layout.setVerticalGroup(layout.createParallelGroup().addComponent(packMeButton) .addComponent(text,DEFAULT_SIZE, prefSize.height, prefSize.height)); layout.setHorizontalGroup(layout.createSequentialGroup().addComponent(packMeButton) .addComponent(text, DEFAULT_SIZE, prefSize.width, prefSize.width) // Lock the width to 400 ); pack(); } public static void main(String args[]) { SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new TextSizeProblem(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } private static final JLabel resizer = new JLabel(); /** * Returns the preferred size to set a component at in order to render an html string. You can * specify the size of one dimension. */ public static java.awt.Dimension getPreferredSize(String html, boolean width, int prefSize) { resizer.setText(html); View view = (View) resizer.getClientProperty(javax.swing.plaf.basic.BasicHTML.propertyKey); view.setSize(width ? prefSize : 0, width ? 0 : prefSize); float w = view.getPreferredSpan(View.X_AXIS); float h = view.getPreferredSpan(View.Y_AXIS); return new java.awt.Dimension((int) Math.ceil(w), (int) Math.ceil(h)); } } ```
Get height of multi line text with fixed width to make dialog resize properly
[ "", "java", "swing", "layout-manager", "" ]
PHP's `rand()` function doesn't give good random numbers. So I started to use `mt_rand()` which is said to give better results. But how good are these results? Are there any methods to improve them again? My idea: ``` function rand_best($min, $max) { $generated = array(); for ($i = 0; $i < 100; $i++) { $generated[] = mt_rand($min, $max); } shuffle($generated); $position = mt_rand(0, 99); return $generated[$position]; } ``` This should give you "perfect" random numbers, shouldn't it?
[Pseudorandom number generators](http://en.wikipedia.org/wiki/Pseudorandom_number_generator) (PRNG) are very complex beast. There are no real "perfect" random number generators -- in fact the best that can be done from mathematical functions are pseudorandom -- they seem random enough for most intents and purposes. In fact, performing any additional actions from a number returned by a PRNG doesn't really increase its randomness, and in fact, the number can become less random. So, my best advice is, don't mess around with values returned from a PRNG. Use a PRNG that is good enough for the intended use, and if it isn't, then find a PRNG that can produce better results, if necessary. And frankly, it appears that the [`mt_rand`](http://www.php.net/manual/en/function.mt-rand.php) function uses the [Mersenne twister](http://en.wikipedia.org/wiki/Mersenne_twister), which is a pretty good PRNG as it is, so it's probably going to be good enough for most casual use. However, **Mersenne Twister is not designed to be used in any security contexts**. See [this answer](https://stackoverflow.com/a/31443898) for a solution to use when you need randomness to ensure security. **Edit** There was a question in the comments why performing operations on a random number can make it less random. For example, some PRNGs can return more consistent, less random numbers in different parts of the bits -- the high-end can be more random than the low-end. Therefore, in operations where the high-end is discarded, and the low end is returned, the value can become less random than the original value returned from the PRNG. I can't find a good explanation at the moment, but I based that from the Java documentation for the [`Random.nextInt(int)`](http://java.sun.com/javase/6/docs/api/java/util/Random.html#nextInt(int)) method, which is designed to create a fairly random value in a specified range. That method takes into account the difference in randomness of the parts of the value, so it can return a better random number compared to more naive implementations such as `rand() % range`.
**Quick answer:** In a new [PHP7](https://wiki.php.net/rfc/easy_userland_csprng) there is a finally a support for a [cryptographically secure pseudo-random integers.](http://php.net/manual/en/function.random-int.php) ``` int random_int ( int $min , int $max ) ``` There is also a [polyfill for PHP5x](https://github.com/paragonie/random_compat). **Longer answer** --- There is no perfect random number generator, and computers use [pseudorandom number generator](https://en.wikipedia.org/wiki/Pseudorandom_number_generator) to create sequences that looks random. The sequences look random (and pass some [randomness tests](https://en.wikipedia.org/wiki/Randomness_tests)) but because there is some algorithm to generate it, you can repeat algorithm with absolutely the same states and get the same result. The same advice as with [cryptography](https://www.schneier.com/blog/archives/2011/04/schneiers_law.html) "do not invent your own cypher" can be translated to random number generators and mean that you can not just get a lot of random number generators combined together and get expect to get a better generator. --- One of the subsets of random number generators is [cryptographically secure random number generators](https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator): > The requirements of an ordinary PRNG are also satisfied by a > cryptographically secure PRNG, but the reverse is not true. CSPRNG > requirements fall into two groups: first, that they pass statistical > randomness tests; and secondly, that they hold up well under serious > attack, even when part of their initial or running state becomes > available to an attacker So this is pretty close to your definition of "*perfect*". One more time under no condition (except of learning how to do cryptography) you should try to implement one of that algorithms and use it in your system. --- But luckily [PHP7](http://php.net/manual/en/function.random-int.php) has it implemented, ``` int random_int ( int $min , int $max ) ``` > Generates cryptographic random integers that are suitable for use > where unbiased results are critical (i.e. shuffling a Poker deck). The sources of random are as follows: * On Windows CryptGenRandom() is used exclusively * arc4random\_buf() is used if it is available (generally BSD specific) * /dev/arandom is used where available * The `getrandom(2)` syscall (on newer Linux kernels) * /dev/urandom is used where none of the above is available This makes all the previous answers obsolete (and some deprecated).
Generate cryptographically secure random numbers in php
[ "", "php", "security", "random", "" ]
In Silverlight, How do I make a TextBox with `IsReadOnly="True"` not become grayed out. The gray effect looks horrible with my app and I would like to disable it, or change its appearance/color.
There are a couple of options in Silverlight 2, the simplest would be to use a TextBlock since that's only ever readonly. If you need a TextBox then what you need to do is give it a different style that doesn't do the grey affect. To do this open up blend. right click on your TextBox and select Edit Control Parts (Template) -> Edit a Copy... Call the new style whatever you want. You then want to edit this new style and delete the border called "ReadOnlyVisualElement" and delete the storyboard that alters the opacity property of that border. Hope this helps. Added Style XAML ``` <Style x:Key="ReadOnlyStyle" TargetType="TextBox"> <Setter Property="BorderThickness" Value="1"/> <Setter Property="Background" Value="#FFFFFFFF"/> <Setter Property="Foreground" Value="#FF000000"/> <Setter Property="Padding" Value="2"/> <Setter Property="BorderBrush"> <Setter.Value> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFA3AEB9" Offset="0"/> <GradientStop Color="#FF8399A9" Offset="0.375"/> <GradientStop Color="#FF718597" Offset="0.375"/> <GradientStop Color="#FF617584" Offset="1"/> </LinearGradientBrush> </Setter.Value> </Setter> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="TextBox"> <Grid x:Name="RootElement"> <vsm:VisualStateManager.VisualStateGroups> <vsm:VisualStateGroup x:Name="CommonStates"> <vsm:VisualState x:Name="Normal"/> <vsm:VisualState x:Name="MouseOver"> <Storyboard> <ColorAnimationUsingKeyFrames Storyboard.TargetName="MouseOverBorder" Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)"> <SplineColorKeyFrame KeyTime="0" Value="#FF99C1E2"/> </ColorAnimationUsingKeyFrames> </Storyboard> </vsm:VisualState> <vsm:VisualState x:Name="Disabled"> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="DisabledVisualElement" Storyboard.TargetProperty="Opacity"> <SplineDoubleKeyFrame KeyTime="0" Value="1"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </vsm:VisualState> <vsm:VisualState x:Name="ReadOnly"> <Storyboard> </Storyboard> </vsm:VisualState> </vsm:VisualStateGroup> <vsm:VisualStateGroup x:Name="FocusStates"> <vsm:VisualState x:Name="Focused"> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="Opacity"> <SplineDoubleKeyFrame KeyTime="0" Value="1"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </vsm:VisualState> <vsm:VisualState x:Name="Unfocused"> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="Opacity"> <SplineDoubleKeyFrame KeyTime="0" Value="0"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </vsm:VisualState> </vsm:VisualStateGroup> <vsm:VisualStateGroup x:Name="ValidationStates"> <vsm:VisualState x:Name="Valid"/> <vsm:VisualState x:Name="InvalidUnfocused"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ValidationErrorElement" Storyboard.TargetProperty="Visibility"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <Visibility>Visible</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </vsm:VisualState> <vsm:VisualState x:Name="InvalidFocused"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ValidationErrorElement" Storyboard.TargetProperty="Visibility"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <Visibility>Visible</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="validationTooltip" Storyboard.TargetProperty="IsOpen"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <System:Boolean>True</System:Boolean> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </vsm:VisualState> </vsm:VisualStateGroup> </vsm:VisualStateManager.VisualStateGroups> <Border x:Name="Border" Opacity="1" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="1"> <Grid> <Border x:Name="MouseOverBorder" BorderBrush="Transparent" BorderThickness="1"> <ScrollViewer x:Name="ContentElement" BorderThickness="0" IsTabStop="False" Padding="{TemplateBinding Padding}"/> </Border> </Grid> </Border> <Border x:Name="DisabledVisualElement" IsHitTestVisible="False" Opacity="0" Background="#A5F7F7F7" BorderBrush="#A5F7F7F7" BorderThickness="{TemplateBinding BorderThickness}"/> <Border x:Name="FocusVisualElement" Margin="1" IsHitTestVisible="False" Opacity="0" BorderBrush="#FF6DBDD1" BorderThickness="{TemplateBinding BorderThickness}"/> <Border x:Name="ValidationErrorElement" Visibility="Collapsed" BorderBrush="#FFDB000C" BorderThickness="1" CornerRadius="1"> <ToolTipService.ToolTip> <ToolTip x:Name="validationTooltip" DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}" Template="{StaticResource ValidationToolTipTemplate}" Placement="Right" PlacementTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}"> <ToolTip.Triggers> <EventTrigger RoutedEvent="Canvas.Loaded"> <BeginStoryboard> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="validationTooltip" Storyboard.TargetProperty="IsHitTestVisible"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <System:Boolean>true</System:Boolean> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </BeginStoryboard> </EventTrigger> </ToolTip.Triggers> </ToolTip> </ToolTipService.ToolTip> <Grid Height="12" HorizontalAlignment="Right" Margin="1,-4,-4,0" VerticalAlignment="Top" Width="12" Background="Transparent"> <Path Fill="#FFDC000C" Margin="1,3,0,0" Data="M 1,0 L6,0 A 2,2 90 0 1 8,2 L8,7 z"/> <Path Fill="#ffffff" Margin="1,3,0,0" Data="M 0,0 L2,0 L 8,6 L8,8"/> </Grid> </Border> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> ``` I would get the preview of Blend, coding the above by hand would be a large amount of unnecessary work.
Nothing seems to work in the xaml (as usual), so the best solution I've come up with is make a textbox readonly myself without the IsReadOnly property. ``` public class ReadOnlyTextBox : TextBox { protected override void OnKeyDown(KeyEventArgs e) { e.Handled = true; base.OnKeyDown(e); } } ```
Prevent a readonly textbox from being grayed out in Silverlight
[ "", "c#", ".net", "silverlight", "xaml", "" ]
Consider the following set of classes/Interfaces: ``` class IFish{ public: virtual void eat() = 0; } class IFriendly{ public: virtual void protect() = 0; } class IAggresive{ public: virtual void attack(Point inDest) = 0; } class CDolphin : public IFish, IFriendly{ eat... protect.... } class CShark : public IFish, IAggresive{ eat.... attack... } ``` Now I am having the following class ``` void CDiver { Void shouldRunAway(IFish* fish) { //??? } } ``` My question is , can "shouldRunAway" extract from the fish argument whether it is an IAggresive or IFreindly (if it is any of these at all...) is there some kind of casting that can help out?
Expanding on what Drakosha posted, you would dynamic\_cast the IFish pointer into an IAggressive pointer and check if it is NULL or not. Like this; ``` #include <iostream> class IFish { public: virtual void eat() = 0; }; class IFriendly { public: virtual void protect() = 0; }; class IAggressive { public: virtual void attack() = 0; }; class Dolphin : public IFish, public IFriendly { public: virtual void eat() { std::cout << "Dolphin::eat()\n"; } virtual void protect() { std::cout << "Dolphin::protect()\n"; } }; class Shark : public IFish, public IAggressive { public: virtual void eat() { std::cout << "Shark::eat()\n"; } virtual void attack() { std::cout << "Shark::attack()\n"; } }; class Diver { public: void shouldRunAway( IFish *fish ) { if ( dynamic_cast<IAggressive *>( fish ) != NULL ) { std::cout << "Run away!\n"; } else { std::cout << "Don't run away.\n"; } } }; int main( int argc, char *argv[] ) { Dolphin dolphin; Shark shark; Diver diver; diver.shouldRunAway( &dolphin ); diver.shouldRunAway( &shark ); return 0; } ```
Take a look at [dynamic\_cast](http://en.wikipedia.org/wiki/Dynamic_cast).
Multiple interfaces inhertience. Casting from one to another
[ "", "c++", "" ]
What is the fundamental difference between the `Set<E>` and `List<E>` interfaces?
`List` is an ordered sequence of elements whereas `Set` is a distinct list of elements which is unordered (thank you, [Quinn Taylor](https://stackoverflow.com/users/120292/quinn-taylor)). [**`List<E>:`**](http://docs.oracle.com/javase/8/docs/api/java/util/List.html) > An ordered collection (also known as a > sequence). The user of this interface > has precise control over where in the > list each element is inserted. The > user can access elements by their > integer index (position in the list), > and search for elements in the list. [**`Set<E>:`**](http://docs.oracle.com/javase/8/docs/api/java/util/Set.html) > A collection that contains no > duplicate elements. More formally, > sets contain no pair of elements e1 > and e2 such that e1.equals(e2), and at > most one null element. As implied by > its name, this interface models the > mathematical set abstraction.
| | List | Set | | --- | --- | --- | | Duplicates | Yes | No | | Order | Ordered | Depends on implementation | | Position Access | Yes | No |
What is the difference between Set and List?
[ "", "java", "list", "set", "" ]
I've been unable to find articles describing in any detailed manner the new features of WPF in .Net 4.0. Where could I find that? Thanks!
Jaime Rodriguez has a [good breakdown](http://blogs.msdn.com/jaimer/archive/2009/05/27/wpf-4-and-net-framework-4-beta-1-list-of-features-totrack.aspx) of the features to expect for WPF in .NET 4, as well as their current status / availability in the beta version of .NET 4.
Here is a video from MIX that highlights several features. <http://videos.visitmix.com/MIX09/T39F> There are several other available from Channel 9 <http://social.msdn.microsoft.com/Search/en-US/?query=%22WPF%204%22&ac=3>
New features of WPF 4?
[ "", "c#", "wpf", "wpf-4.0", "" ]
I have an winforms application that loads in excel files for analysis. Currently, in order to open the excel file the file must not be already open in excel otherwise a FileIOException is thrown when I try and load in the file. What I would like to do is allow my application to read in the file even if it is open in excel rather than forcing the user to close down the worksheet first. Note that the application in question only needs to read the file, not write to it. Is this possible?
You could try passing FileShare.ReadWrite when opening the file: ``` using (var stream = new FileStream( @"d:\myfile.xls", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { } ```
How are you trying to open the file? If you are trying to open it for read/write then you'll get the exception. If you are trying to open it for read only then you should be OK. ``` var file = File.Open("file.xls", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); ``` This will only work if Excel has opened the file with `FileShare.Read` set to allow other applications (i.e. your's) to have access to the file. If this isn't set then Excel will have opened the file with exclusive access. Note: I don't think this is the case as you can open an Excel file (in Excel) for read if someone else has it open for edit. **UPDATE** - OK I didn't test this properly until after darin's comments. You need the `FileShare.ReadWrite` flag despite the help indicating that it's for subsequent file openers. Not even `FileShare.Read` is good enough, which I find even odder.
How do I open a file that is opened in another application
[ "", "c#", "excel", "file-io", "" ]
As "load" is far too generic for searching: 1. What is the purpose of "load" and what does it do in this particular case? - in a template file, base\_weblog.html, `{% load weblog %}{% render_month_links %}` 2. Are some naming conventions used in order for "load" to do its job? E.g. names of folders and/or files and/or class names? 3. Where is the documentation for "load" and can you elaborate? --- Details: The example is from the source for <http://www.djangoproject.com/> - direct download URL is through <http://shrinkster.com/17g8>. Partial folder structure (items with no file extension are folders): ``` django_website apps accounts aggregator blog urls.py models.py class Entry(models.Model) templatetags weblog.py contact docs templates base_weblog.html aggregator blog entry_archive.html entry_archive_year.html month_links_snippet.html entry_archive_month.html entry_detail.html entry_snippet.html entry_archive_day.html comments contact docs feeds flatfiles flatpages registration ```
"weblog" after "load" (in template file `django_website/templates/base_weblog.html`) refers to file `weblog.py` in folder `django_website/apps/blog/templatetags`. Folder `templatetags` must be named exactly that and must contain a file named `__init__.py` (question 2). "load" makes the custom template tags (`render_latest_blog_entries` and `render_month_links` in this case) available for use in templates, `django_website\templates\base_weblog.html` in this case. "Load" is a security and performance function.
[`load`](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#load): Load a custom template tag set. See [Custom tag and filter libraries](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags) for more information.
What does "load" do in Django Templates?
[ "", "python", "django", "function", "django-templates", "templatetags", "" ]
How can I get the substring before the first space or dot? Like ``` $string = "test.test" //result = test $string = "test doe" //result = test ``` Sure I can use explode two times, but I am sure that's not the best solutions.
If you want to split on several different chars, take a look at [preg\_split](http://php.net/preg_split) ``` //split string on space or period: $split=preg_split('/[ \.]/', $string); ```
There's string token [strtok](https://www.php.net/manual/en/function.strtok.php).
Isolate leading string before one of two delimiting characters
[ "", "php", "substring", "" ]
I have been playing around with the MVP pattern using winforms for the last couple of days, there is only really one thing that I'm not sure how to do. How do you create a subform from another view. Would this be a valid option. ``` public class MyForm : IMainFormView { private MainFormPresenter pres; public MyForm() { pres = new MainFormPresenter(this); } //Event from interface. public event EventHandler<EventArgs> LoadSecondForm; public void SomeButtonClick() { LoadSecondForm(this, EventArgs.Empty); } } public class MainFormPresenter { private IMainFormView mView; public MainFormPresenter(IMainFormView view) { this.mView = view; this.Initialize(); } private void Initialize() { this.mView.LoadSecondForm += new EventHandler<EventArgs>(mView_LoadSecondForm); } private void mView_LoadSecondForm(object sender, EventArgs e) { SecondForm newform = new SecondForm(); //Second form has its own Presenter. newform.Load(); // Load the form and raise the events on its presenter. } } ``` I'm mainly concerned with how you would load a subform using this pattern, and how you would pass say an ID from the first page to the subform. Thanks.
<http://www.rickardnilsson.net/post/The-Humble-dialog-v2.aspx> The link above is the closest I've seen to answering this. Most attempts at solving this leave something to be desired.
Take a look at [this other SO question](https://stackoverflow.com/questions/1023995/mvvm-and-commands-that-show-more-gui). While it relates to WPF and not WinForms, the problem seems to be the same. Essentially, I consider the need to show a subsidiary window a Service (you might call it the WindowsService or DialogService or something like that). That helps you to put things into perspective, because as soon as you realize that, Dependency Injection becomes the answer. In your answer, you model this with events, but I prefer a more explicit model where you invoke a DialogService's ShowDialog method. However, the mechanics of each approach aren't that different.
Loading subviews with MVP
[ "", "c#", "winforms", "mvp", "" ]
I trying to complete a RPG game for a project, but have no idea on how to make the game map. It doesn't need to be graphical, but the code for the whole map and each tile must be correct. So far, I thought about making a non-matricial map (as request by the professor) by using an ArrayList which contain all the linked tiles. ``` public abstract class Casella { /** * @uml.property name="tabellone" * @uml.associationEnd multiplicity="(1 1)" inverse="casella:Tabellone" * @uml.association name="contains" */ private int id; private boolean free = true; private List adjacent; private List items; private Tabellone tabellone = null; public void in(){ free = false; } public void out(){ free = true; } } ``` This was the code for a single tile (which has 3 classes that extends it). I still have no idea on how to put together and generate a map. Thank you for your time.
I managed this by using adjacency lists. Each cell will have an ArrayList containing the indexes of the adjacent cells. Those indexes are the ones that the said cell have in the map ArrayList of cells. <http://en.wikipedia.org/wiki/Adjacency_list>
Don't start with the implementation, start with how you would like to use the map. That will give you some constraints how to implement it. For example: When drawing the map, how do you access it? By coordinate? Or by "go west from tile X"? [EDIT] I suggest to start with the main loop of the RPG game. You'll need to place the character/token somewhere (i.e. it needs some kind of relation to a tile). Then you need to move the character. A character must be able to examine the current tile (opponents, items, type). It needs a way to know how it can move (i.e. is there a wall to the right?) This gives you an interface for your map: Services which it renders for other objects in the game. When you have an idea of what the interface needs to provide, that should give you an idea how to implement the map (the data structure). As for generating a map, use a random number generator plus some "common sense". Have a look at the adjacent tiles: When they are all city, this tile is probably city, too. Same for plains. Hills are singular items, and they are least frequent. Run this code, print the map as ASCII ("C"ity, "P"lain, "H"ill) to see if it works.
How to Generate a Map in Java?
[ "", "java", "dictionary", "tile", "" ]
I often need to implement DAO's for some reference data that doesn't change very often. I sometimes cache this in collection field on the DAO - so that it is only loaded once and explicitly updated when required. However this brings in many concurrency issues - what if another thread attempts to access the data while it is loading or being updated. Obviously this can be handled by making both the getters and setters of the data synchronised - but for a large web application this is quite an overhead. I've included a trivial flawed example of what I need as a strawman. Please suggest alternative ways to implement this. ``` public class LocationDAOImpl implements LocationDAO { private List<Location> locations = null; public List<Location> getAllLocations() { if(locations == null) { loadAllLocations(); } return locations; } ``` For further information I'm using Hibernate and Spring but this requirement would apply across many technologies. Some further thoughts: Should this not be handled in code at all - instead let ehcache or similar handle it? Is there a common pattern for this that I'm missing? There are obviously many ways this can be achieved but I've never found a pattern that is simple and maintainable. Thanks in advance!
If you just want a quick roll-your own caching solution, have a look at [this](http://www.javaspecialists.eu/archive/Issue125.html) article on JavaSpecialist, which is a review of the book [Java Concurrency in Practice](http://www.amazon.co.uk/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601) by [Brian Goetz](http://www.briangoetz.com/). It talks about implementing a basic thread safe cache using a [FutureTask](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/FutureTask.html) and a [ConcurrentHashMap](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html). The way this is done ensures that only one concurrent thread triggers the long running computation (in your case, your database calls in your DAO). You'd have to modify this solution to add cache expiry if you need it. The other thought about caching it yourself is garbage collection. Without using a WeakHashMap for your cache, then the GC wouldn't be able to release the memory used by the cache if needed. If you are caching infrequently accessed data (but data that was still worth caching since it is hard to compute), then you might want to help out the garbage collector when running low on memory by using a WeakHashMap.
The most simple and safe way is to include the [ehcache library](http://ehcache.sourceforge.net/) in your project and use that to setup a cache. These people have solved all the issues you can encounter and they have made the library as fast as possible.
How to cache information in a DAO in a threadsafe manner
[ "", "java", "caching", "concurrency", "dao", "" ]
What is the best way to get a random entry from a Dictionary in c#? I need to get a number of random objects from the dictionary to display on a page, however I cannot use the following as dictionaries cannot be accessed by index: ``` Random rand = new Random(); Dictionary< string, object> dict = GetDictionary(); return dict[rand.Next()]; ``` Any suggestions?
*Updated to use generics, be even faster, and with an explanation of why this option is faster.* This answer is similar to the other responses, but since you said you need "a number of random elements" this will be more performant: ``` public IEnumerable<TValue> RandomValues<TKey, TValue>(IDictionary<TKey, TValue> dict) { Random rand = new Random(); List<TValue> values = Enumerable.ToList(dict.Values); int size = dict.Count; while(true) { yield return values[rand.Next(size)]; } } ``` You can use this method like so: ``` Dictionary<string, object> dict = GetDictionary(); foreach (object value in RandomValues(dict).Take(10)) { Console.WriteLine(value); } ``` This has performance improvements over the other responses (including yshuditelu's response). 1. It doesn't have to create a new collection of all of the dictionary's elements each time you want to fetch a new random value. This is a really big deal if your dictionary has a lot of elements in it. 2. It doesn't have to perform a lookup based on the Dictionary's key each time you fetch a random value. Not as big a deal as #1, but it's still over twice as fast this way. My tests show that with 1000 objects in the dictionary, this method goes about 70 times faster than the other suggested methods.
If you're using .net 3.5, Enumerable has an extension method [ElementAt](http://msdn.microsoft.com/en-us/library/bb299233.aspx) which would allow you to do: ``` return dict.ElementAt(rand.Next(0, dict.Count)).Value; ```
Random entry from dictionary
[ "", "c#", "dictionary", "" ]
I trying to parse a data in a `MySql` Format, I ran across `SimpleDateFormat`. I can get the proper day and month, but I got a strange result for the year : ``` date = 2009-06-22; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date d = sdf.parse(date); System.println(date); System.println(d.getDate()); System.println(d.getMonth()); System.println(d.getYear()); ``` Outputs : ``` 2009-06-22 22 OK 5 Hum... Ok, months go from 0 to 11 109 o_O WTF ? ``` I tried changing the format to `YYYY-MM-dd` (got an error) and `yy-MM-dd` (did nothing). I am programming on Android, don't know if it's important. For now, I bypass that using a split, but it's dirty and prevent me from using i18n features.
The year is relative to 1900. That's a "feature" of the `Date` class. Try to use `Calender`.
Thanks to Aaron, the right version : ``` Calendar c = Calendar.getInstance(); c.setTime(sdf.parse(date)); System.println(c.get(Calendar.YEAR)); ```
Why don't I get the year right using SimpleDateFormat in java?
[ "", "java", "android", "simpledateformat", "date-parsing", "" ]
I went through all the posts on [reflection](http://en.wikipedia.org/wiki/.NET_metadata#Reflection) but couldn't find the answer to my question. What were the problems in the programming world before .NET reflection came and how it solved those problems? Please explain with an example.
It should be stated that .NET reflection isn't revolutionary - the concepts have been around in other framework. Reflection in .NET has 2 facets: **Investigating type information** Without some kind of reflection / introspection API, it becomes very hard to perform things like serialization. Rather than having this provided at runtime (by inspecting the properties/fields/etc), you often need code-generation instead, i.e. code that explicitly knows how to serialize each of your types. Tedious, and painful if you want to serialize something that doesn't have a twin. Likewise, there is nowhere to store additional metadata about properties etc, so you end up having lots of additional code, or external configuration files. Something as simple as being able to associate a friendly name with a property (via an attribute) is a huge win for UI code. **Metaprogramming** .NET reflection also provides a mechanism to create types (etc) at runtime, which is hugely powerful for some specific scenarios; the alternatives are: * essentially running a parser/logic tree at runtime (rather than compiling the logic at runtime into executable code) - much slower * yet more code generation - yay!
I think to understand the need for reflection in .NET, we need to go back to before .NET. After all, modern languages like like Java and C# do not have a history BF (before reflection). C++ arguably has had the most influence on C# and Java. But C++ did not originally have reflection and we coded without it and we managed to get by. Occasionally we had void pointer and would use a cast to force it into whatever type we wanted. The problem here was that the cast could fail with terrible consequences: ``` double CalculateSize(void* rectangle) { return ((Rect*)rectangle)->getWidth() * ((Rect*)rectangle)->getHeight()); } ``` Now there are plenty of arguments why you shouldn't have coded yourself into this problem in the first place. But the problem is not much different from .NET 1.1 with C# when we didn't have generics: ``` Hashtable shapes = new Hashtable(); .... double CalculateSize(object shape) { return ((Rect)shape).Width * ((Rect)shape).Height; } ``` However, when the C# example fails it does so with a exception rather than a potential core dump. When reflection was added to C++ (known as Run Time Type Identification or RTTI), it was hotly debated. In Stroustrup's book The Design and Evolution of C++, he lists the following arguments against RTTI, in that some people: > ``` > Declared the support unnecessary > Declared the new style inherently evil ("against the spirit of C++") > Deemed it too expensive > Thought it too complicated and confusing > Saw it as the beginning of an avalanche of new features > ``` But it did allow us to query the type of objects, or features of objects. For example (using C#) ``` Hashtable shapes = new Hashtable(); .... double CalculateSize(object shape) { if(shape is Rect) { return ((Rect)shape).Width * ((Rect)shape).Height; } else if(shape is Circle) { return Math.Power(((Circle)shape).Radius, 2.0) * Math.PI; } } ``` Of course, with proper planning this example should never need to occur. So, real world situations where I've needed it include: * Accessing objects from shared memory, all I have is a pointer and I need to decide what to do with it. * Dynamically loading assemblies, think about NUnit where it loads every assembly and uses reflection to determine which classes are test fixtures. * Having a mixed bag of objects in a Hashtable and wanting to process them differently in an enumerator. * Many others... So, I would go as far as to argue that Reflection has not enabled the ability to do something that couldn't be done before. However, it does make some types of problems easier to code, clearer to reader, shorter to write, etc. Of course that's just my opinion, I could be wrong.
What problems does reflection solve?
[ "", "c#", "reflection", "" ]
What's the easiest way in python to concatenate string with binary values ? ``` sep = 0x1 data = ["abc","def","ghi","jkl"] ``` Looking for result data `"abc0x1def0x1ghi0x1jkl"` with the 0x1 being binary value not string "0x1".
I think ``` joined = '\x01'.join(data) ``` should do it. `\x01` is the escape sequence for a byte with value 0x01.
The chr() function will have the effect of translating a variable into a string with the binary value you are looking for. ``` >>> sep = 0x1 >>> sepc = chr(sep) >>> sepc '\x01' ``` The join() function can then be used to concat a series of strings with your binary value as a separator. ``` >>> data = ['abc']*3 >>> data ['abc', 'abc', 'abc'] >>> sepc.join(data) 'abc\x01abc\x01abc' ```
How to concatenate strings with binary values in python?
[ "", "python", "string", "binary", "concatenation", "" ]
Lets say I have hierarchy like this (This is just a test program. Please do not point anything related to memory leaks, destructor is not virtual etc): ``` class I { public: virtual void fun(int n, int n1) = 0; }; class A : public I { public: void fun(int n, int n1) { std::cout<<"A::fun():" <<n<<" and n1:" <<n1<<"\n"; } }; class B : public I { public: void fun(int n, int n1) { std::cout<<"B::fun():" <<n<<" and n1:" <<n1<<"\n"; } }; int main() { std::vector<I*> a; a.push_back(new A); a.push_back(new B); //I want to use std::for_each to call function fun with two arguments. } ``` How do I call fun() method which takes two arguments using the std::for\_each ? I think I have to use std::mem\_fun probably with std::bind2nd but am not able to figure out how to do this. Any clue how to achieve this? I am not using boost.
You could create your own functor like this: ``` class Apply { private: int arg1, arg2; public: Apply(int n, int n1) : arg1(n), arg2(n1) {} void operator() (I* pI) const { pI->fun(arg1, arg2); } }; int main () { // ... std::for_each(a.begin(), a.end(), Apply(n, n1)); } ``` or use boost::bind like this: ``` std::for_each( a.begin(), a.end(), boost::bind(&I::fun, _1, n, n1)); ```
You can't do this with the std binders. You can of course write your own functor. ``` struct TwoArguments { int one; int two; TwoArguments( int one, int two ) : one(one),two(two){ } void operator()( I* i ) const { i->fun( one, two ); } }; ```
How to pass two parameters when using std::mem_fun?
[ "", "c++", "stl", "" ]
If you wanted to change the value of the hidden field to something not in the value of the dropdown like so ``` <form> <select id="dropdown" name="dropdown" onchange="changeHiddenInput(this)"> <option value="foo">One - 42</option> <option value="bar">Two - 40</option> <option value="wig">Three - 38</option> </select> <input type="hidden" name="hiddenInput" id="hiddenInput" value="" /> </form> ``` And i want to pass (if two selected) dropdown="bar" and hiddenInput="40" The value has to be passed but needs to effect the hiddenfield. What do you think? Would you need to If then? or could you have it something like ``` <form> <select id="dropdown" name="dropdown" onchange="changeHiddenInput(this)"> <option value="foo" onchange="set hiddenInput - 42">One - 42</option> <option value="bar" onchange="set hiddenInput - 40">Two - 40</option> <option value="wig" onchange="set hiddenInput - 38">Three - 38</option> </select> <input type="hidden" name="hiddenInput" id="hiddenInput" value="" /> </form> ```
You have the right idea with the `onchange` attribute. Your function could look like: ``` function changeHiddenInput(mySelect) { var map = {foo: "42", bar: "40", wig: "38"}; var index = mySelect.selectedIndex; var value = mySelect.options[index].value; var hiddenInput = document.getElementById("hiddenInput"); hiddenInput.value = map[value]; } ``` The `map` variable there maps each option's value on to what the hidden attribute should be set to.
I'd keep the mapping on the server rather then trying to handle it client side. Forget the hidden input. Just look up the value based on the value of the dropdown after the data reaches the server.
Drop updating a hiddenfield with an unrelated value
[ "", "javascript", "forms", "webforms", "" ]
Let's say I have a table with two columns, where a user places a booking. ``` datefrom dateto ------------------------------------------- 2009-05-23 00:00:00 2009-05-27 00:00:00 ``` How would I use SQL to return how many days the user will be booking for? All I want is to return the number of days.
``` SELECT days = datediff(dd,datefrom,dateto) FROM table ```
In Oracle: ``` select dateto - datefrom from table; ```
Get distance between one date and another in SQL (ISO format)
[ "", "sql", "datetime", "" ]
Is there a performance difference between these two pieces of code? My gut feeling is that the second option is slower, as the Cell object has to be constructed each time, but I like the idea of returning a Cell. Option One: ``` //Call to method initiTextDefaultCell(borders); iTextTable.setDefaultCell(iTextDefaultCell); //Other code... private void initiTextDefaultCell(boolean borders) { if (!borders) iTextDefaultCell.setBorder(Rectangle.NO_BORDER); else iTextDefaultCell.setBorder(Rectangle.BOX); } ``` Option Two: ``` //Call to method iTextTable.setDefaultCell(initiTextDefaultCell(borders)); //Other code... private Cell initiTextDefaultCell(boolean borders) { Cell iTextDefaultCell = new Cell(); if (!borders) iTextDefaultCell.setBorder(Rectangle.NO_BORDER); else iTextDefaultCell.setBorder(Rectangle.BOX); return iTextDefaultCell; } ``` Thanks!
As you've said option two will be slower due to the allocation of a new object. This looks like a clarity-of-code vs. performance decision. I personally think option two is clearer and that the performance impact would be negligible. However without knowing what `iTextTable` is it's hard to say for certain which to use. If `initiTextDefaultCell` is called once when the table is instantiated then I'd go with option two, however if the number of times `initiTextDefaultCell` is called depends on the size of the table then option one would be better (assuming that the default cell was instantiated as part of the instantiation of `iTextTable`).
Write a test program and see for yourself.
Is there a performance difference between these two pieces of code?
[ "", "java", "performance", "" ]
Is it possible to detect the exact moment an element exists in the DOM on page load? Context: On page load i hide an element of my page using jQuery (i.e. If JavaScript is available i want to hide the div) but on poor internet connection you see the panel for a second or so before it disappears. I'd like to hide the element as soon as it's written to the DOM but i don't know how to do this or even if it's possible. I don't want to apply set display:hidden because i want to the panel to appear if JavaScript isn't available. TIA Matt Revision: I'm using jQuery - and my code in executed from within $(document).ready().
Put the javascript right after the element, that will minimise the time that the element may be visible: ``` <div id="CrouchingTiger">HiddenDragon</div> <script type="text/javascript"> document.getElementById('CrouchingTiger').style.display = 'none'; </script> ``` The script will run while the page is loading, as soon as the end tag of the script has been parsed.
That's what the `<noscript>` tag is there for. ``` <noscript>This site works better with Javascript enabled.</noscript> ``` It will only display the contents if scripting is disabled.If Javascript is enabled, the contents will not be displayed. That sounds like exactly the behavior you are looking for.
Detecting the exact moment an element appears in the DOM
[ "", "javascript", "jquery", "dom", "" ]
Since Java 1.4 doesn't have enums I'm am doing something like this: ``` public class SomeClass { public static int SOME_VALUE_1 = 0; public static int SOME_VALUE_2 = 1; public static int SOME_VALUE_3 = 2; public void receiveSomeValue(int someValue) { // do something } } ``` The caller of receiveSomeValue should pass one those 3 values but he can pass any other int. If it were an enum the caller could only pass one valid value. Should receiveSomeValue throw an InvalidValueException? What are good alternatives to Java 5 enums?
Best to use in pre 1.5 is the [Typesafe Enum Pattern](http://c2.com/cgi/wiki?EnumeratedTypesInJava) best described in the book [Effective Java by Josh Bloch](https://rads.stackoverflow.com/amzn/click/com/0321356683). However it has some limitations, especially when you are dealing with different classloaders, serialization and so on. You can also have a look at the Apache Commons Lang project and espacially the enum class, like John has written. It is an implementation of this pattern and supports building your own enums.
I'd typically create what I call a constant class, some thing like this: ``` public class MyConstant { public static final MyConstant SOME_VALUE = new MyConstant(1); public static final MyConstant SOME_OTHER_VALUE = new MyConstant(2); ... private final int id; private MyConstant(int id) { this.id = id; } public boolean equal(Object object) { ... } public int hashCode() { ... } } ``` where `equals` and `hashCode` are using the `id`.
Alternative to enum in Java 1.4
[ "", "java", "enums", "java1.4", "" ]
There are two things here i want to accomplish. * List I want to pass a datetime into my stored procedure in the following format ('2007-05-28 00:00:00'), but that doesn't seem to work unless i use {ts '2007-05-28 00:00:00'} * The next thing is I want to increase the @SEAL\_DATE by a second so it can be used to check the dates between the entered time and a second after. Thanks in advance ``` set ANSI_NULLS ON set QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[getSealRecordDate] (@SEAL_DATE DATETIME) AS -- Declare variables SELECT DISTINCT "FGFSTRANSFERS"."CONSIDERATION", "FGFSTRANSFERS"."AMOUNT_TRANSFER", "FGFSTRANSFERS"."DATE", "FGFSTransferDetails"."TRANSFER_ID", "FGFSTRANSFERS"."TRANSFER_ID", "FGFSTRANSFERS"."Curr", "FGFSTransferDetails"."CURR", "FGFSCUSTOMERS"."CMF_NAME_1", "FGFSCUSTOMERS"."CMF_NAME_2" FROM ("FGFSInvestment"."dbo"."FGFSTransferDetails" "FGFSTransferDetails" INNER JOIN "FGFSInvestment"."dbo"."FGFSTRANSFERS" "FGFSTRANSFERS" ON "FGFSTransferDetails"."TRANSFER_ID"="FGFSTRANSFERS"."TRANSFER_ID") INNER JOIN "FGFSInvestment"."dbo"."FGFSCUSTOMERS" "FGFSCUSTOMERS" ON "FGFSTRANSFERS"."CUSTODIAN"="FGFSCUSTOMERS"."CMF_ACCOUNT" WHERE ("FGFSTRANSFERS"."DATE">= @SEAL_DATE AND "FGFSTRANSFERS"."DATE"<{ts '2007-05-28 00:00:01'}) -- EXEC getSealRecordDate {ts '2007-05-28 00:00:00'} ``` **Pseudo-SQL** so it should be like: WHERE ("FGFSTRANSFERS"."DATE">= @SEAL\_DATE AND "FGFSTRANSFERS"."DATE"< @SEAL\_DATE+ 1 sec ) <-- Something like that
``` DATEADD(second, 1, @SEAL_DATE) ```
Take a look [How Does Between Work With Dates In SQL Server?](http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/how-does-between-work-with-dates-in-sql-) use dateadd to add a second ``` select dateadd(second,1,'20090625 00:00:00.000') ```
Passing datetime to a stored procedure & add a 1 sec to datetime
[ "", "sql", "sql-server", "t-sql", "datetime", "stored-procedures", "" ]
I am attempting to load an embedded Youtube video when my page loads, and then hide it right away once it has loaded. This is working fine, however when I want to make it visible it appears for just a second then it disappears. This is happening in both Firefox 3.0 and Safari 4, I haven't tried it in any other browsers. I have tried hiding it using .style.display = 'none' then .style.display = ''; and style.display='block'; to make it visible again, as well as tried using jQuery .hide() and .show() but both methods result in the youtube video vanishing after it is made visible. Is there a 'proper' way I should be making the <object>...<embed> tags hidden and visible using javascript so it doesn't disappear when I try to make it visible? The reason I'm not just loading the 2nd video dynamically when I need it is I want the video to start downloading so that it is immediately available to be played when I am ready to make it visible. Below is my html and javascript code snippets: mute(), play(), stop() are just wrappers for the youtube javascript api calls of the same name. switchVideoPlayers() is called from an html button passing 1 and 2 as oldid and newid respectively. I couldn't figure out what pieces I should include as snippets, so I've dumped the whole page below: ``` <html> <head> <title>YouTube test</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script> var player = new Array(); var currentplayer = 1; function onYouTubePlayerReady(playerid) { if (playerid.indexOf('obj') > -1) { playerid = playerid.substring(3); } debug("player " + playerid + " loaded"); player[playerid] = document.getElementById(playerid); if (playerid == 1) player[playerid].loadVideoById('5hSW67ySCio'); else { player[playerid].loadVideoById('VgMVHc5N3WM', 10); //videoid mute(playerid); setTimeout(function() { stop(playerid); $("#obj" + playerid).hide(); }, 1000); } } function play(id) { player[id].playVideo(); } function pause(id) { player[id].pauseVideo(); } function stop(id) { player[id].stopVideo(); } function mute(id) { player[id].mute(); } function unmute(id) { player[id].unMute(); } function seek(id,seconds) { player[id].seekTo(seconds, false); } function getCurrentTime(id) { return player[id].getCurrentTime(); } function loadNewVideo(id,videoid, startseconds) { player[id].loadVideoById(videoid, startseconds); mute(id); setTimeout(function() { stop(id); }, 1000); } function switchVideoPlayers(oldid, newid) { stop(oldid); $("#obj" + oldid).hide(); $("#obj" + newid).show(); setTimeout(function() { unmute(newid); play(newid); }, 10); } function debug(message) { $('#debug').html($('#debug').html() + message + "<br />"); } </script> </head> <body> <object id='obj1' width="425" height="344"> <param name="movie" value="http://www.youtube.com/v/5hSW67ySCio&hl=en&fs=1&"></param> <param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param> <embed id='1' src="http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed> </object> <object id='obj2' width="425" height="344"> <param name="movie" value="http://www.youtube.com/v/5hSW67ySCio&hl=en&fs=1&"></param> <param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param> <embed id='2' src="http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=2" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed> </object> <br /> <br /> <input type='button' value='Play' onclick='play(currentplayer);' /> <input type='button' value='Pause' onclick='pause(currentplayer);' /> <input type='button' value='Stop' onclick='stop(currentplayer);' /> <input type='button' value='Mute' onclick='mute(currentplayer);' /> <input type='button' value='UnMute' onclick='unmute(currentplayer);' /> <input type='button' value='Seek' onclick='seek(currentplayer,getCurrentTime(currentplayer) + 10);' /> <input type='button' value='Get Current Time' onclick='alert(getCurrentTime(currentplayer));' /> <input type='button' value='load strain video' onclick='loadNewVideo(currentplayer+1,"VgMVHc5N3WM", 10);' /> <input type='button' value='switch to next video' onclick='switchVideoPlayers(currentplayer,currentplayer + 1);' /> <br /> <br /> <a href='http://code.google.com/apis/youtube/js_api_reference.html'>api</a> <div id='debug'>DEBUG MESSAGES:<br /> </div> </body> </html> ```
Most browsers treat flash like this - when you hide + show it, it will re-initialize the swf. If you don't want it to get reinitialized, you can just move it out of the way (absolute position it) - something like -9999px or something, then just move it back into place when you want to show it.
Took another look at this, and it turns out the onYouTubePlayerReady() function gets called again when the video is made visible. Inside this function the code to hide the video player is called again which is why it was disappearing.
Hiding/UnHiding Flash Videos With Javascript
[ "", "javascript", "youtube", "" ]
I usually create a sequence from a single value using array syntax, like this: ``` IEnumerable<string> sequence = new string[] { "abc" }; ``` Or using a new List. I'd like to hear if anyone has a more expressive way to do the same thing.
Your example is not an empty sequence, it's a sequence with one element. To create an empty sequence of strings you can do ``` var sequence = Enumerable.Empty<string>(); ``` **EDIT** OP clarified they were looking to create a single value. In that case ``` var sequence = Enumerable.Repeat("abc",1); ```
I like what you suggest, but with the array type omitted: ``` var sequence = new[] { "abc" }; ```
Favorite way to create an new IEnumerable<T> sequence from a single value?
[ "", "c#", "linq", "c#-3.0", "" ]
I'm curious as to why it's so much faster to multiply than to take powers in python (though from what I've read this may well be true in many other languages too). For example it's much faster to do ``` x*x ``` than ``` x**2 ``` I suppose the \*\* operator is more general and can also deal with fractional powers. But if that's why it's so much slower, why doesn't it perform a check for an int exponent and then just do the multiplication? **Edit:** Here's some example code I tried... ``` def pow1(r, n): for i in range(r): p = i**n def pow2(r, n): for i in range(r): p = 1 for j in range(n): p *= i ``` Now, pow2 is just a quick example and is clearly not optimised! But even so I find that using n = 2 and r = 1,000,000, then pow1 takes ~ 2500ms and pow2 takes ~ 1700ms. I admit that for large values of n, then pow1 does get much quicker than pow2. But that's not too surprising.
Basically naive multiplication is O(n) with a very low constant factor. Taking the power is O(log n) with a higher constant factor (There are special cases that need to be tested... fractional exponents, negative exponents, etc) . Edit: just to be clear, that's O(n) where n is the exponent. Of course the naive approach will be faster for small n, you're only really implementing a small subset of exponential math so your constant factor is negligible.
Adding a check is an expense, too. Do you always want that check there? A compiled language could make the check for a constant exponent to see if it's a relatively small integer because there's no run-time cost, just a compile-time cost. An interpreted language might not make that check. It's up to the particular implementation unless that kind of detail is specified by the language. Python doesn't know what distribution of exponents you're going to feed it. If it's going to be 99% non-integer values, do you want the code to check for an integer every time, making runtime even slower?
Speed of calculating powers (in python)
[ "", "python", "algorithm", "performance", "" ]
We have a j2ee application running on Jboss and we want to monitor its memory usage. Currently we use the following code ``` System.gc(); Runtime rt = Runtime.getRuntime(); long usedMB = (rt.totalMemory() - rt.freeMemory()) / 1024 / 1024; logger.information(this, "memory usage" + usedMB); ``` This code works fine. That means it shows memory curve which corresponds to reality. When we create a big xml file from a DB a curve goes up, after the extraction is finished it goes down. ![alt text](https://i6.photobucket.com/albums/y231/oleg_pavliv/hc.jpg) A consultant told us that calling gc() explicitly is wrong, "let jvm decide when to run gc". Basically his arguments were the same as [disscussed here](https://stackoverflow.com/questions/66540/system-gc-in-java). But I still don't understand: * how can I have my memory usage curve? * what is wrong with the explicit gc()? I don't care about small performance issues which can happen with explicit gc() and which I would estimate in 1-3%. What I need is memory and thread monitor which helps me in analysis of our system on customer site.
If you want to really look at what is going on in the VM memory you should use a good tool like [VisualVM](https://visualvm.github.io/). This is Free Software and it's a great way to see what is going on. Nothing is really "wrong" with explicit `gc()` calls. However, remember that when you call `gc()` you are "suggesting" that the garbage collector run. There is no guarantee that it will run at the exact time you run that command.
There are tools that let you monitor the VM's memory usage. The [VM can expose memory statistics using JMX](https://docs.oracle.com/javase/6/docs/technotes/guides/management/jconsole.html). You can also [print GC statistics](http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html) to see how the memory is performing over time. Invoking System.gc() can harm the GC's performance because objects will be prematurely moved from the new to old generations, and weak references will be cleared prematurely. This can result in decreased memory efficiency, longer GC times, and decreased cache hits (for caches that use weak refs). I agree with your consultant: System.gc() is bad. I'd go as far as to [disable it](http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html#1.1.Other%20Considerations|outline) using the command line switch.
How to monitor Java memory usage?
[ "", "java", "garbage-collection", "monitoring", "memory-management", "" ]
Im building multi-server support for a file upload site Im running. When images are uploaded.... they are thumbnailed and stored on the main front-end server, until cron executes (every 10 mins) and moves them to storage servers, so for the first 10 mins, they will reside, and be served off the main front-end server. When a file is uploaded, users are given embed codes... which is a thumbnail url + link to the full size, which is a html page. So it might be something like <http://www.domain.com/temp_content/filename.jpg> which links to <http://www.domain.com/file-ID> Except in 10 mins, <http://www.domain.com/temp_content/filename.jpg> wont exist, it will be <http://server1.domain.com/thumbs/filename.jpg> if the user grabbed the original code... the thumb file will be broken. I COULD move the file to its destination, without cron, but that will take time, and will lag the script until the move is complete. I also dont like to have users running commands like that, I'd rather have the server do them at regular intervals. Anything else I can?
You could use a mod\_rewrite command in your .htaccess to check if the file in temp\_content exists, and if it doesn't, have it [redirect them to the new location](https://stackoverflow.com/questions/667284/htaccess-redirect-if-file-doesnt-exist).
Have you considered a database storing the image\_name/image\_location, and a generic PHP script to serve the images from the database-details?
How to make a static URL point to different servers?
[ "", "php", "file", "storage", "" ]
I have a hidden field and I add string to it, separated by semicolon. How I can I check the duplication when adding a new string? I am doing as ``` function AddToHiddenField(source, hdnFieldId) { var srcList = document.getElementById(source); var hdnFieldSubstring = document.getElementById(hdnFieldId); var len = srcList.length; hdnFieldSubstring.value = ''; for(var i = 0; i < len; i++) { if (srcList.options[i] != null) { if (hdnFieldSubstring.value == "") { hdnFieldSubstring.value = srcList.options[i].text; } else { hdnFieldSubstring.value = hdnFieldSubstring.value + ";" + srcList.options[i].text; } } } } ``` How can I check a string already exists in hdnFieldSubstring before added to it (in javascript)?
~~You can use JavaScript's `indexOf()` method. If the return value is greater than '-1', then it is in the string.~~ Several commenters made a good point about `indexOf()` returning false positives. I've updated my answer to correct that, and also include spelling fixes. I'm using the [`contains()` method from this question](https://stackoverflow.com/questions/237104/javascript-array-containsobj). Of course this will only work if your `srcList` doesn't contain semicolons. ``` function contains(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) { return true; } } return false; } function AddToHiddenField(source, hdnFieldId) { var srcList = document.getElementById(source); var hdnFieldSubstring = document.getElementById(hdnFieldId); var len = srcList.length; var value = ''; for(var i = 0; i < len; i++) { var currentOption = srcList.options[i].text; if (srcList.options[i] != null) { if (value == "") { value = currentOption; } else if(!contains(val.split(';'), currentOption)) { value += ";" + currentOption; } } } hdnFieldSubstring.value = value; } ``` If I were you, I'd fix the spelling errors in your variable names. You'll thank yourself later if you use the correct spelling for all variable names (unless you really mean to use "filed" instead of "field")
This would be simpler if you always put the semi colon in the value. I.e. ``` if (srcList.options[i] && hdnFieldSubstring.value.indexOf(srcList.options[i].text + ";") == -1) hdnFieldSubstring.value += srcList.options[i].text + ";"; ``` Now you can always search for the string with a semi-colon on the end. * Don't forget to make sure that the strings don't include semi-colons already. * If the last semi-colon will cause you problems then strip it off just before submitting the form by putting a handler on the submit button.
Check contents of a hidden field in javascript
[ "", "javascript", "asp.net-ajax", "" ]
Instead of executing: SELECT a FROM b WHERE a LIKE 'a%' OR a LIKE 'b%' OR a LIKE 'c%' is there a way to execute something functioning like this pseudocode? SELECT a FROM b ***WHERE a IN ('a%', 'b%', 'c%')***
Might be too specific to your example, but you could do LIKE '[a-c]%'. Other than that, I'm not aware of any LIKE-like IN syntax
You could dump your criteria values into a temp table (without the wildcard). Then do a join like: ``` SELECT b.a FROM b INNER JOIN #likevals on b.a LIKE #likevals.value + '%' ``` WHERE #likevals looks like: ``` value ------ a b c ```
Combining LIKE with IN in SQL
[ "", "sql", "sql-server-2008", "" ]
For example, I want to split ``` str = '"a,b,c",d,e,f' ``` into ``` ["a,b,c",'d','e','f'] ``` (i.e. don't split the quoted part) In this case, this can be done with ``` re.findall('".*?"|[^,]+',str) ``` However, if ``` str = '"a,,b,c",d,,f' ``` I want ``` ["a,,b,c",'d','','f'] ``` i.e. I want a behavior that is like python's split function. Is there any way I can do this in one (small) line, possibly using Python's re library? Actually, I just realized (on this site) that the csv module is perfect for what I want to do, but I am curious whether there is a regular expression that re can use to do it as well.
``` re.split(',(?=(?:[^"]*"[^"]*")*[^"]*$)', str) ``` After matching a comma, if there's an odd number of quotation marks up ahead ahead, the comma must be inside a pair of quotation marks, so it doesn't count as a delimiter. Obviously this doesn't take the possibility of escaped quotation marks into account, but that can handled if need be--it just makes the regex about twice as ugly as it already is. :D
Use the csv module as it is a real parser. Regular expressions are nonoptimal (or completely unsuited) for most things involving matching delimiters in which the rules change (I'm unsure as to whether this particular grammar is regular or not). You might be able to create a regex that would work in this case, but it would be rather complex (especially dealing with cases like "He said, \"How are you\"").
split a string by a delimiter in a context sensitive way
[ "", "python", "regex", "split", "" ]
I have a list of `Customer` objects that I need to have selectable from a JComboBox. From what I read I need to implement a custom renderer to have the fields I want displayed in the list. I want my JComboBox to have entries formatted as such: ``` +----------------------------------------------+ | Customer Name - Contact - City, State V | +==============================================+ | Customer #2 Name - Contact - City, State | | Customer #3 Name - Contact - City, State | | Customer #4 Name - Contact - City, State | | Customer #5 Name - Contact - City, State | +----------------------------------------------+ ``` I used this code: public class CustomerListCellRenderer extends DefaultListCellRenderer { ``` @Override public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof Customer) { Customer c = (Customer) value; StringBuffer sb = new StringBuffer(); if (c.getCompany() != null && c.getCompany().length() > 0) { sb.append(c.getCompany()); } sb.append(" - "); if (c.getCompany() != null && c.getCompany().length() > 0) { sb.append(c.getContact()); } sb.append(" - "); if (c.getCompany() != null && c.getCompany().length() > 0) { sb.append(c.getCity()); sb.append(", "); } if (c.getCompany() != null && c.getCompany().length() > 0) { sb.append(c.getState()); } setText(sb.toString()); } return this; } } ``` This doesn't work correctly under Solaris / Unix / Linux using the system GTKLookAndFeel. The background of the input area of the combobox is not drawn and no border is drawn around it. (See screenshot below). Is there another way to achieve this that will work correctly across the 3 major platforms (Win/Mac/GTK)? Can I do a converter to do this and only manipulate the data not the GUI? My current workaround is to override toString() on my Customer object to display each record in the format I want, but looking for other ideas. [![alt text](https://i.stack.imgur.com/u8BJa.png)](https://i.stack.imgur.com/u8BJa.png) Nick
Same issue, I did this in order to customize it for showing icons: ``` private static class CustomComboBoxRenderer extends DefaultListCellRenderer { private final ListCellRenderer backend; public CustomComboBoxRenderer(ListCellRenderer backend) { this.backend = backend; } @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component component = backend.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if(component instanceof JLabel == false) component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); JLabel label = (JLabel)component; label.setIcon(Icons.COMPONENT); return label; } } ``` Then assigned the renderer like this: ``` comboBox.setRenderer(new CustomComboBoxRenderer(comboBox.getRenderer())); ``` This has worked out fine for me, so far.
Try this: ``` public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value instanceof Customer) { Customer c = (Customer) value; StringBuffer sb = new StringBuffer(); if (c.getCompany() != null && c.getCompany().length() > 0) { sb.append(c.getCompany()); } sb.append(" - "); if (c.getCompany() != null && c.getCompany().length() > 0) { sb.append(c.getContact()); } sb.append(" - "); if (c.getCompany() != null && c.getCompany().length() > 0) { sb.append(c.getCity()); sb.append(", "); } if (c.getCompany() != null && c.getCompany().length() > 0) { sb.append(c.getState()); } value = sb.toString(); } return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); } } ``` Also use a StringBuilder not a StringBuffer (this is a single threaded situation). Also also it looks like you have cut and paste errors in the code for instance: ``` if (c.getCompany() != null && c.getCompany().length() > 0) { sb.append(c.getState()); } ``` Is checking the Company member and using the State member.
Java JComboBox Custom Renderer and GTK
[ "", "java", "linux", "swing", "gtk", "jcombobox", "" ]
I'm trying to write my first iterator class / container type. Basically, I want to be able to iterate though a file, have the file converted to HEX on the fly, and pass the result into the boost::xpressive library. I don't want to do a one shot conversion to a string in RAM, because some of the files I need to be able to process are larger than the expected system RAM (multiple GB). Here is what my code looks like. I'm using MSVC++ 2008. Header for Iterator: ``` class hexFile; class hexIterator : public std::iterator<std::bidirectional_iterator_tag, wchar_t> { hexFile *parent; __int64 cacheCurrentFor; wchar_t cacheCharacters[2]; void updateCache(); public: bool highCharacter; __int64 filePosition; hexIterator(); hexIterator(hexFile *file, bool begin); hexIterator operator++(); hexIterator operator++(int) { return ++(*this); } hexIterator operator--(); hexIterator operator--(int) { return --(*this); } bool operator==(const hexIterator& toCompare) const; bool operator!=(const hexIterator& toCompare) const; wchar_t& operator*(); wchar_t* operator->(); }; ``` Implementation for iterator: ``` #include <stdafx.h> class hexFile; hexIterator::hexIterator() { parent = NULL; highCharacter = false; filePosition = 0; } hexIterator::hexIterator(hexFile *file, bool begin) : parent(file) { if(begin) { filePosition = 0; highCharacter = false; } else { filePosition = parent->fileLength; highCharacter = true; } } hexIterator hexIterator::operator++() { if (highCharacter) { highCharacter = false; filePosition++; } else { highCharacter = true; } return (*this); } hexIterator hexIterator::operator--() { if (highCharacter) { highCharacter = false; } else { filePosition--; highCharacter = true; } return (*this); } bool hexIterator::operator==(const hexIterator& toCompare) const { if (toCompare.filePosition == filePosition && toCompare.highCharacter == highCharacter) return true; else return false; } bool hexIterator::operator!=(const hexIterator& toCompare) const { if (toCompare.filePosition == filePosition && toCompare.highCharacter == highCharacter) return false; else return true; } wchar_t& hexIterator::operator*() { updateCache(); if (highCharacter) return cacheCharacters[1]; return cacheCharacters[0]; } wchar_t* hexIterator::operator->() { updateCache(); if (highCharacter) return cacheCharacters + 1; return cacheCharacters; } void hexIterator::updateCache() { if (filePosition == cacheCurrentFor) return; BYTE rawData; DWORD numberRead; LONG lowValue = static_cast<LONG>(filePosition); LONG highValue = static_cast<LONG>(filePosition >> 32); SetFilePointer(parent->theFile, lowValue, &highValue, FILE_BEGIN); if (!ReadFile(parent->theFile, &rawData, 1, &numberRead, 0)) throw std::runtime_error(eAsciiMsg("Error reading from file.")); static const wchar_t hexCharacters[] = L"0123456789ABCDEF"; cacheCharacters[0] = hexCharacters[rawData & 0x0F]; cacheCharacters[1] = hexCharacters[rawData >> 4]; cacheCurrentFor = filePosition; } ``` Header for container ``` class hexFile { public: HANDLE theFile; unsigned __int64 fileLength; hexFile(const std::wstring& fileName) { theFile = CreateFile(fileName.c_str(),GENERIC_READ,FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,NULL,NULL); if (theFile == INVALID_HANDLE_VALUE) { throw std::runtime_error(eAsciiMsg("Could not open file!")); } BY_HANDLE_FILE_INFORMATION sizeFinder; GetFileInformationByHandle(theFile, &sizeFinder); fileLength = sizeFinder.nFileSizeHigh; fileLength <<= 32; fileLength += sizeFinder.nFileSizeLow; }; ~hexFile() { CloseHandle(theFile); }; hexIterator begin() { hexIterator theIterator(this, true); return theIterator; }; hexIterator end() { hexIterator theIterator(this, false); return theIterator; }; }; ``` However, no matter what test case I try, the regex never matches. I'm assuming it's some conceptual problem with my iterator.. it's supposed to be a constant bidirectional iterator in all cases. Anything I'm missing, or is there an easier way to do this? Billy3
This is quite a bit of code to read through; at first glance, I don't see anything. For implementation notes, this sounds like more of an iostream than an iterator, which with buffering could be significantly faster. Boost has a library to help implement [those](http://www.boost.org/doc/libs/1_39_0/libs/iostreams/doc/index.html). If you want to use an iterator, they also have a [library](http://www.boost.org/doc/libs/1_39_0/libs/iterator/doc/index.html) to help with that, it makes sure you get all the methods you need while simplifying the implementation a lot. For debugging, I'd try for unit tests; that should hopefully point out the problem; start with something small, like a file with two characters, walk through in a debugger to see what's going on, and iterate until you pass everything.
`operator++(int)` should be defined in terms of `operator++()`, not the other way around. Try switching them. Same for `operator--`.
Conceptual Problems with Iterator
[ "", "c++", "stl", "iterator", "" ]
I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses. I am the most comfortable coding this in python, but am open to other suggestions. Is this possible, and if so what python modules should I look at? Has this already been done? I'm on OSX but would also be interested in doing this on an Ubuntu box and Windows XP.
It looks like you need <http://patorjk.com/keyboard-layout-analyzer/> This handy program will analyze a block of text and tell you how far your fingers had to travel to type it, then recommend your optimal layout. To answer your original question, on Linux you can read from /dev/event\* for local keyboard, mouse and joystick events. I believe you could for example simply `cat /dev/event0 > keylogger`. The events are instances of `struct input_event`. See also <http://www.linuxjournal.com/article/6429>. Python's [struct](http://docs.python.org/library/struct.html) module is a convenient way to parse binary data. For OSX, take a look at the source code to logkext. <http://code.google.com/p/logkext/>
Unless you are planning on writing the interfaces yourself, you are going to require some library, since as other posters have pointed out, you need to access low-level key press events managed by the desktop environment. On Windows, the [PyHook](http://pypi.python.org/pypi/pyHook/1.4/) library would give you the functionality you need. On Linux, you can use the [Python X Library](http://python-xlib.sourceforge.net/) (assuming you are running a graphical desktop). Both of these are used to good effect by [pykeylogger](http://pykeylogger.wiki.sourceforge.net/). You'd be best off downloading the source (see e.g. pyxhook.py) to see specific examples of how key press events are captured. It should be trivial to modify this to sum the distribution of keys rather than recording the ordering.
How can you read keystrokes when the python program isn't in the foreground?
[ "", "python", "keyboard", "background", "keylogger", "" ]
I am wondering which is more efficient, to store temporary data (related to that session) in a session using the $\_SESSION variable in PHP or store and retrieve from an SQL database? Thank you for your time.
Keep in mind the session variable is backed by a storage mechanism, that is, when the request finishes the session gets written by the session handler, by default this is to a file. On the next request it is pulled back from that file (or whatever else the session handler uses). If you're reading and writing this data on every request, just stick with a the $\_SESSION variables, the overhead of connecting, querying and updating a database will not be faster than the default $\_SESSION. You'll probably only ever want to use a database backed session if you are running multiple load-balanced servers and need to share the session data between them. In this case, if you find the overhead of the database sessions to be slowing down your site to a noticeable degree you might consider sticking memcached between your web server and the database.
I don't know much about reading from a database or a file, but I don't think that "DB access is slower than others" is true. I've learned from my school lessons that Network latency is negligible compared to the I/O access. And if we use DB for sessions, we have some advantages: We don't have to worried about many servers because there is no file system different. I also think that storing/reading something to/from a database is more easier than a file system. Also, if we are using shared hosting, storing sessions in a database is a major advantage for the security. if i were wrong, please correct me. i still have many things to learn. Thanks.
Store in Session Data vs store in Sql Database for temporary data
[ "", "php", "mysql", "session", "storage", "temporary-objects", "" ]
I've got a very weird bug which I've yet to find a solution. **UPDATE** see solution below What I am trying to do is convert a full size picture into a 160x120 thumbnail. It works great with jpg and jpeg files of any size, but not with png. ImageMagick command: ``` /opt/local/bin/convert '/WEBSERVER/images/img_0003-192-10.png' -thumbnail x320 -resize '320x<' -resize 50% -gravity center -crop 160x120+0+0 +repage -quality 91 '/WEBSERVER/thumbs/small_img_0003-192-10.png' ``` PHP function (shortened) ``` ... $cmd = "/opt/local/bin/convert '/WEBSERVER/images/img_0003-192-10.png' -thumbnail x320 -resize '320x<' -resize 50% -gravity center -crop 160x120+0+0 +repage -quality 91 '/WEBSERVER/thumbs/small_img_0003-192-10.png'"; exec($cmd, $output, $retval); $errors += $retval; if ($errors > 0) { die(print_r($output)); } ``` When this function runs $retval equal 1 which means the convert command failed (thumbnail isn't created). This is where it gets interesting, if I run the exact same command in my shell, it works. ``` wedbook:~ wedix$ /opt/local/bin/convert '/WEBSERVER/images/img_0003-192-10.png' -thumbnail x320 -resize '320x<' -resize 50% -gravity center -crop 160x120+0+0 +repage -quality 91 '/WEBSERVER/thumbs/small_img_0003-192-10.png' wedbook:~ wedix$ ``` I've tried using different PHP function such as system, passthru but it didn't work. I thought maybe someone here knew the solution. I'm using 1. `MAMP 1.7.2` * `Apache/2.0.59` * `PHP/5.2.6` Thanks! **UPDATE** I updated the following dependencies 1. `libpng from 1.2.35 to 1.2.37` 2. `libiconv from 1.12_2 to 1.13_0` 3. `ImageMagick 6.5.2-4_1 to 6.5.2-9_0` However, it did not fix my problem. **2nd UPDATE** I finally found something that might help, when the function runs this is what gets printed in the Apache logs: ``` dyld: Library not loaded: /opt/local/lib/libiconv.2.dylib Referenced from: /opt/local/bin/convert Reason: Incompatible library version: convert requires version 8.0.0 or later, but libiconv.2.dylib provides version 7.0.0 ``` **3rd UPDATE** libiconv.2.dylib is version 8.0.0... ``` bash-3.2$ otool -L /opt/local/lib/libiconv.2.dylib /opt/local/lib/libiconv.2.dylib: /opt/local/lib/libiconv.2.dylib (compatibility version 8.0.0, current version 8.0.0) /usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 111.1.4) ``` **4th UPDATE** Problem was related to MAMP, see solution below
Solved it! It turns out the environement variable `DYLD_LIBRARY_PATH` wasn't set properly. Mac OS X Leopard comes with libiconv 7.0.0 but convert requires 8.0.0 (see 2nd UPDATE above) ``` bash-3.2$ otool -L /usr/lib/libiconv.2.dylib /usr/lib/libiconv.2.dylib: /usr/lib/libiconv.2.dylib (compatibility version 7.0.0, current version 7.0.0) /usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 111.1.1) ``` ImageMagick and all dependencies was installed with MacPorts under `/opt/local`. This requires to manually add the path /opt/local/lib to `DYLD_LIBRARY_PATH`. If I add the path `/opt/local/lib` to `DYLD_LIBRARY_PATH` in the Mac OS X Leopard `apachectl` envvars file `/usr/sbin/envvars` it doesn't work. Why? It's because I don't use apache from Mac OS X Leopard, I use MAMP. MAMP **has its own** apachectl script **and it's own** envvars file. I added the path `/opt/local/lib` to `DYLD_LIBRARY_PATH` in the MAMP `apachectl` envvars file `/Applications/MAMP/Library/bin/envvars` ``` DYLD_LIBRARY_PATH="/opt/local/lib:/Applications/MAMP/Library/lib:$DYLD_LIBRARY_PATH" ``` Now my PNG thumbnails are being generated and no errors are generated in the apache error log! I hope this will help someone and next time I'll remember to check every logs files before asking for help! Phil
My path was /opt/local/bin, but even adding that to DYLD\_LIBRARY\_PATH didn't work. Finally when I changed just plain ole PATH, it worked via PHP. ;Did not work... ;DYLD\_LIBRARY\_PATH="/opt/local/bin:/Applications/MAMP/Library/lib:$DYLD\_LIBRARY\_PATH" ;export DYLD\_LIBRARY\_PATH ; This works! export PATH="$PATH:/opt/local/bin"
ImageMagick: convert png fail via PHP and works via bash shell
[ "", "php", "apache2", "imagemagick", "mamp", "" ]
I may have a hole in my regex knowlege. If I am trying to look for items in a string which may be in the numeric range "item[355-502]" is there an easy way to do this. as far as I can tell I would have to do something like ``` (35[5-9]|3[6-9][0-9]|4[0-9][0-9]|50[0-2]) ``` *I know this also matches for 3550-5020 etc, that should be fine* [This,](http://www.regular-expressions.info/numericranges.html) indicates that this can't be done any other way, is this right. i'm in PHP is there a neater way to do this?
This is a numeric problem rather than a string problem, so I fear your solution does not lie completely in a regex! You will need to parse the digits and then perform numeric comparison, e.g.: ``` $input = whatever(); # gets something like "item[456]" ``` ...then match with the following pattern: ``` preg_match("/item\[(\d+)\]/", $input, $match); ``` ...to store the digits in memory, and then: ``` if($match[1] >= 355 and $match[1] <= 502){... ``` to check to see if the number is in range.
The only other way I can think of would be to keep the regex simple (item[0-9]{3}) and do the rest of the checking in code. Regular expressions can't solve all problems :)
number range in a regex
[ "", "php", "regex", "" ]
I'm working on building up an interface that I want to function as a "tabbed browsing" sort of function. Each of these tabs has already been written as an action and the tabbed interface works fine as links to the individual tabs. I decided to try writing the "index" page for this controller - putting the content of all the tabs into hidden divs and swapping between them with jQuery, but once I started to use the action view helper - I ran into a lot of people saying that its bad practice. ([see this article](http://tinyurl.com/actionstack)) Some of these actions build up forms - grab some data from the model, etc to display. I want each of the actions to continue to function on their own (some parse forms as well). Browsing to /item should give you the tabbed menu, plus all of the div's contents in a hidden tag - where /item/tab2 is a specific action (form submit for instance). Another complication/caveat - Some of the actions will throw Access Exceptions if the user doesn't have access to that "tab". I'd prefer not to build access checking into the system twice (thus showing a tab with empty content). I'm just trying to figure out what the best practice is to handle this sort of thing, and I thought that the action helper might be it. If I try to use View Helpers - I start wondering if that is the right place to assemble a Zend\_Form. Does anyone have any suggestions on the "proper" way to work around not using the `Zend_View_Helper_Action` ?
The Correct way to work around the action view helper, as I stated in the article you cited, is to create partials which access the model directly to fetch the data they need. This can be through a view helper (you make this yourself ;)) if this would involve a lot of logic in your view. The action view helper is plagued with more than just performance issues, but also creates horrendous debugging nightmares, and if you need it, then your application is probably not following MVC, and therefore, you are using the controller for reuse, instead of the model, which is the patterns intention. You can render partials from within your layout or current actions view with the render or partial methods of the view object. If you have multiple actions to deal with multiple possible posts from your tabs, then you should set all of these actions to render the same view script, which will then render all of the tabs with data direct from the model.
I'm not entirely sure what your exact problem is, however you can disable the layout: ``` $this->_helper->layout->disableLayout(); ``` Then the requested Action will just display it's view script, which you can load into the tab. Any authorisation code you have will function as normal and you can display the requested view script for the Action, or not depending on if they have access.
Action View Helper in Zend - Work around?
[ "", "php", "model-view-controller", "zend-framework", "zend-form", "" ]