Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
VS 2008 SP1. I have created a setup project for our client. The icons for the setup.exe and setup.msi are the standard icons. Our client doesn't want this these icons. They want to have icons that look like they logo. Is it possible to change the \*.exe and \*.msi icons to something different?
You can change the setup.exe icon, but I'm not sure about the \*.msi. I haven't tested this with it. 1. Build the setup project in Visual Studio 2. Open the setup.exe file you just built, File -> Open -> File 3. Right click the Icon node in the file explorer window and you can change and save. 4. Import the icon your want in the popup dialog, and make sure the ID of the icon is the smallest one. A quick Google search pulled up some other approaches, so if this won't work for your particular case, check some of [these](http://www.google.com/search?hl=en&rls=com.microsoft%3Aen-us&q=change+icon+on+setup+exe+msi+visual+studio) out.
It is not possible to change the icon of the msi. It does not have an icon set on it. It is just a document that is handled as install package if you have Windows Installer installed. If not, you will actually just see the windows default icon for unknown file types! For the setup.exe, you can do it by editing the icon(s) on the exe after it is build. Answer from mc2thaH (steps 2-4) is one approach. Another tool for icon editing is Greenfish Icon Editor Pro, which is a very good **free** icon editor with full support for 32bit image editing. [Download here](http://greenfish.extra.hu/downloads.php "Greenfish Download Page").
Is it possible to change the setup.exe and setup.msi icons to a different icon?
[ "", "c#", "installation", "" ]
I'm trying to compare an MD5 checksum generated by PHP to one generated by Oracle 10g. However it seems I'm comparing apples to oranges. Here's what I did to test the comparison: ``` //md5 tests //php md5 print md5('testingthemd5function'); print '<br/><br/>'; //oracle md5 $md5query = "select md5hash('testingthemd5function') from dual"; $stid = oci_parse($conn, $md5query); if (!$stid) { $e = oci_error($conn); print htmlentities($e['message']); exit; } $r = oci_execute($stid, OCI_DEFAULT); if (!$r) { $e = oci_error($stid); echo htmlentities($e['message']); exit; } $row = oci_fetch_row($stid); print $row[0]; ``` The md5 function (seen in the query above) in Oracle uses the 'dbms\_obfuscation\_toolkit.md5' package(?) and is defined like this: ``` CREATE OR REPLACE FUNCTION PORTAL.md5hash (v_input_string in varchar2) return varchar2 is v_checksum varchar2(20); begin v_checksum := dbms_obfuscation_toolkit.md5 (input_string => v_input_string); return v_checksum; end; ``` What comes out on my PHP page is: ``` 29dbb90ea99a397b946518c84f45e016 )Û¹©š9{”eÈOEà ``` Can anyone help me in getting the two to match?
It returns raw bytes, you need to convert that into hex. ``` $x = unpack("H*", $row[0]); echo $x[1]; ```
It appears that what's being printed from the Oracle query is the raw bytestream of the md5 checksum, mangled because most of those octets won't be ascii characters. Try converting it to hexadecimal first.
Getting Oracle's MD5 to match PHP's MD5
[ "", "php", "oracle", "md5", "" ]
I want to pass an object array to the setTimer function in Javascript. ``` setTimer("foo(object_array)",1000); ``` am getting error on this code. \*\*Note:\*\*Sorry ! some correction in my question : Is it possible in setInterval() function.
Use an anonymous function instead of a string on the first parameter of the [setTimeout](https://developer.mozilla.org/en/DOM/window.setTimeout) or [setInterval](https://developer.mozilla.org/en/DOM/window.setInterval) functions: ``` // assuming that object_array is available on this scope setInterval(function () { foo(object_array); }, 1000); ``` *Why it works:* When you define an inner function, it can refer to the variables present in their outer enclosing function even after their parent functions have already terminated. This language feature is called [closures](http://www.javascriptkit.com/javatutors/closures.shtml). If you pass a string as the first argument of these functions, the code will be executed internally using a call to the [eval](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/eval) function, and doing this is **not** considered as a [good practice](http://www.jslint.com/lint.html#evil). Eval provides direct access to the JavaScript compiler and executes the code it's passed with the privileges of the caller, also using eval *repeatedly/extensively* (i.e. your setInterval function is a good example) will lead to performance issues.
I'm going to expand on Luke's answer here because it addresses a use case that CMS's (and most answers to this kind of question) does not. If you need to bind your arguments to the function call *at the time you set the timeout*, a simple function enclosure will not work: ``` echo = function (txt) { console.log(txt); }; val = "immediate A"; echo(val); val = "delayed"; window.setTimeout(function () { echo(val); }, 1000); val = "immediate B"; echo(val); ``` Assuming you are using Firebug's console, the above will output "immediate A", "immediate B" and then "immediate B" 1 second later. To bind the value at the time of the setTimeout call use Luke's trap method. The following modifies it a little to accept arbitrary functions and argument lengths: ``` echo = function (txt) { console.log(txt); }; trap = function (fn, args) { return function() { return fn.apply(this, args); }; }; val = "immediate A"; echo(val); val = "delayed"; window.setTimeout( trap(echo, [val]), 1000); val = "immediate B"; echo(val); ``` Not sure if there is a way to pass the caller's context in implicitly, but it could be further expanded to accept a context argument if "this" doesn't get you there.
How to pass an Array object to the setInterval function
[ "", "javascript", "settimeout", "setinterval", "" ]
I was just wondering what do you think would be the best C# data structure for problem like this. So I will have an array of keys, and for each key array of arrays. Sounds complicated does it :) Anyway the simplest solution that comes to my mind, note that I never did any formal C# training. It was more I am C++ programmer and then for some stupid project did C# application. Therefore I might have missed out on a good structure I could use. So ``` Dictionary<string, List<Dictionary<string, double>> ``` is what I had in mind. But is there anything better? I will have set of data points for each key, but more than one set of data points. So I was just wondering if anyone has better design suggestion.
I assume that since you are using some sort of key to access the internal arrays, that you don't intend to just loop through the data object and pull out every value. If that is the case then you are right, a Dictionary is probably your best choice.
Sounds like you might want to create a custom object to encapsulate your datapoint, then store that in a dictionary keyed by whatever value makes sense. From what you've said, the object you store as the value in the dictionary, might itself be a collection of datapoints. So you might create an object which encapsulates your `List<Dictionary<string, double>>`
Which C# data structure to use?
[ "", "c#", "data-structures", "" ]
Hi i am using data table in asp.net. I am not able to get how can we filter unique data from data table . Problem is describe below ``` Data Table: Consumer No Date Value ABC001 1st Aug 09 1 ABC001 1st Aug 09 2 ABC001 2nd Aug 09 1 XYZ001 1st Aug 09 1 XYZ002 1st Aug 09 1 XYZ002 1st Aug 09 2 ``` I would like following output based upon filter applied over first and second column. In output we can see that there is unique combination of first and second column. ``` Consumer No Date ABC001 1st Aug 09 ABC001 2nd Aug 09 XYZ001 1st Aug 09 XYZ002 1st Aug 09 ``` How can i apply filter on data table?
``` yourdataset.Tables["TableName"].DefaultView.ToTable(true,"disticecolumn"); ``` > Creates and returns a new DataTable > based on rows in an existing > DataView. true in the .ToTable method specifies that returned DataTable contains rows that have distinct values for all its columns. From [msdn](http://msdn.microsoft.com/en-us/library/wec2b2e6.aspx) article ***Edit:*** It would be easier to do this from a database where you can use the '**distinct**' keyword.
There is apparently no way you can apply a DISTINCT filter on the Select() method of the DataTable. However, you can create a new DataTable using the following line of code: ``` DataTable filterTable = yourDataTable.DefaultView.ToTable("TargetTable", true, "Consumer", "No", "Date"); ``` This should return distinct rows, that meet your requirement! Credit to [DevPinoy.org](http://devpinoy.org/blogs/keithrull/archive/2008/02/07/how-to-get-the-distinct-rows-in-a-datatable-or-dataview.aspx) !
ASP.NET : Filter unique rows from Data table
[ "", "c#", "c#-2.0", "" ]
Well the title does the explaination. Which one is faster PHP/MySQL on Linux or on Windows. **Question 1** I know that MySQL is slower on Windows, because i tried to run a C++ program on Windows to access MySQL, it took a year every time it had to open a connection. When i ported the exact copy into the linux enviornment it was lightning fast. Im not sure why the difference is, Maybe cause when we talk about Linux every thing is million times faster, but it would be good to know why such a massive difference. **Question 2** I have set up PHP on IIS and mySQL on Windows ive just tested a very small application on this setup and it seems fine. What i really want to know is that is there any performance issues for PHP in Windows rather than Linux? **Edit Windows Vista Was the OS i tried on Originally, Havent Tested W7. Fedora 10 was the Linux :D**
They *should* be the same speed eventually. If you do an unscientific, unfair test, you might show a difference. Process startup speed might be different. In particular, process startup might be slower on Windows. This shouldn't matter too much in production unless you're using a model which creates new processes on a very frequent basis, which will be inefficient on either. Run a performance test of your actual application, with a large number of requests, over a significant length of time, on production-grade hardware. It's the only way to tell. Needless to say, I can safely say that almost nobody chooses Windows vs Linux based on performance. Usually it's what they are capable of managing in production and have hardware / software support for. If you're going to install 1000 boxes in production, Windows server licencing might get expensive (depending on your deal with MS). If you are only going to install a few, it probably doesn't matter (supporting the servers will be much more expensive).
Things are slowly getting better on Windows, with IIS 7 and PHP as a FastCGI ; see <http://php.iis.net/> But I have never heard anything good about PHP + IIS6... Never worked in this configuration myself, though ; so I can't speak of experience. One thing to consider is that Windows still (things are slowly getting better too) seems to be considered as a second-class citizen, when it comes to PHP... And it's harder to get exactly the version of PHP you want *(on Linux, you just recompile, and that's definitly not hard at all)* ; even more for PECL extensions, btw... As a sidenote : you can run PHP on windows with Apache ;-)
PHP, MySQL | Windows vs Linux
[ "", "php", "mysql", "performance", "operating-system", "" ]
If PHP session is created before login, there will be one session file created for each request to login page. The problem is if user makes multiple requests to server through a script then those many session files will be created. If user wants to attack server,he can send abnormally huge number of requests creating so many session files eating up all the temporary space and making the service unavailable. I am not sure if this kind of attack is really possible/feasible. Please share your comments on this and implications if PHP sessions is created before/after successful login.
I think you are misunderstanding session\_start() What happens with session\_start is, yes, it will create a file for the individual user. But the next time you call session\_start(), it is going to use that same file for that same user because the user has a cookie on their system that tells it what ID to use. In order to have the $\_SESSION array available, you must call session\_start() on every page. It is very possible that someone could whip up a scenario like you just described. In reality, yes, a hacker could always have a robot that clears its cookies after every attempt, make 10,000 requests, and possibly create a disk writing problem, but I really wouldn't worry about it too much, because the files are tiny, much smaller than the script you are writing. You'd have to write a lot more files (on the size of millions or billions) to actually create a problem. If you really want to see what the effects would be on your server. Write a script that creates files in a directory with the equivalent of 2 paragraphs of text. and put it in a loop for 10,000 files. If you are then worried about the affects it would have, I suggest implementing a tracker that can see an large amount of hits coming to the site from a single IP address and then either temporarily ban the IP address, or do what Google does and just provide them with a static captcha page that doesn't take many resources to serve. **So, going back to the actual 'question':** I set a session for every single user that ever visits my site, because I use sessions for not only User Authentication, but for tracking other variables on my site. So, I believe that you should set it even if they aren't logged in.
If you're worried about a session fixation attack, think about using [session\_regenerate\_id()](http://www.php.net/manual/en/function.session-regenerate-id.php) function.
Should PHP session be created before login or after successful login
[ "", "php", "session", "cookies", "" ]
tribool strikes me as one of the oddest corners of Boost. I see how it has some conveniences compared to using an enum but an enum can also be easily expanded represent more than 3 states. In what real world ways have you put tribool to use?
While I haven't used C++, and hence boost, I have used three-state variables quite extensively in a network application where I need to store state as true/false/pending.
An extra state in any value type can be extremely valuable. It avoids the use of "magic numbers" or extra flags to determine if the value of a variable is "maybe" or "unknown". Instead of `true` or `false`, the state of a `tribool` is `true`, `false`, or `indeterminate`. Let's say you have a database that contains a list of `customers` and their `dateOfBirth`. So you write a function along the lines of : ``` tribool IsCustomerAdult(customerName); ``` The function returns: > ``` > `true` if the customer is 18 or older; > `false` if the customer is less than 18; > `indeterminate` if the customer is not in the database > (or the dateOfBirth value is not present). > ``` Very useful.
Have you used boost::tribool in real work?
[ "", "c++", "boost", "" ]
I want to base64 encode data to put it in a URL and then decode it within my HttpHandler. I have found that [Base64 Encoding](http://en.wikipedia.org/wiki/Base64) allows for a '/' character which will mess up my UriTemplate matching. Then I found that there is a concept of a "modified Base64 for URL" from wikipedia: A modified Base64 for URL variant exists, where no padding '=' will be used, and the '+' and '/' characters of standard Base64 are respectively replaced by '-' and '\_', so that using URL encoders/decoders is no longer necessary and has no impact on the length of the encoded value, leaving the same encoded form intact for use in relational databases, web forms, and object identifiers in general. Using .NET I want to modify my current code from doing basic base64 encoding and decoding to using the "modified base64 for URL" method. Has anyone done this? To decode, I know it starts out with something like: ``` string base64EncodedText = base64UrlEncodedText.Replace('-', '+').Replace('_', '/'); // Append '=' char(s) if necessary - how best to do this? // My normal base64 decoding now uses encodedText ``` But, I need to potentially add one or two '=' chars to the end which looks a little more complex. My encoding logic should be a little simpler: ``` // Perform normal base64 encoding byte[] encodedBytes = Encoding.UTF8.GetBytes(unencodedText); string base64EncodedText = Convert.ToBase64String(encodedBytes); // Apply URL variant string base64UrlEncodedText = base64EncodedText.Replace("=", String.Empty).Replace('+', '-').Replace('/', '_'); ``` I have seen the [Guid to Base64 for URL](https://stackoverflow.com/questions/1032376/guid-to-base64-for-url) StackOverflow entry, but that has a known length and therefore they can hardcode the number of equal signs needed at the end.
This ought to pad it out correctly:- ``` base64 = base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '='); ```
Also check class **HttpServerUtility** with UrlTokenEncode and UrlTokenDecode methods that is handling URL safe Base64 encoding and decoding. **Note 1: The result is not a valid Base64 string. Some unsafe characters for URL are replaced.** **Note 2: The result differs from the base64url algorithm in RFC4648, it replaces the '=' padding with '0', '1' or '2' depending on how many equal signs it replaced to make the value safe for a query parameter.** ``` ///<summary> /// Base 64 Encoding with URL and Filename Safe Alphabet using UTF-8 character set. ///</summary> ///<param name="str">The origianl string</param> ///<returns>The Base64 encoded string</returns> public static string Base64ForUrlEncode(string str) { byte[] encbuff = Encoding.UTF8.GetBytes(str); return HttpServerUtility.UrlTokenEncode(encbuff); } ///<summary> /// Decode Base64 encoded string with URL and Filename Safe Alphabet using UTF-8. ///</summary> ///<param name="str">Base64 code</param> ///<returns>The decoded string.</returns> public static string Base64ForUrlDecode(string str) { byte[] decbuff = HttpServerUtility.UrlTokenDecode(str); return Encoding.UTF8.GetString(decbuff); } ```
Code for decoding/encoding a modified base64 URL (in ASP.NET Framework)
[ "", "c#", "url", "base64", "encode", "decode", "" ]
I'm trying to populate a dropdown list control. 'Inputs' is the DB. Table is 'ApplicationName', and it has a random value assigned to it. For some reason, when I click the Test Submit button, nothing is appearing in the control (DropDownList1). ``` protected void TestSubmit_ServerClick(object sender, EventArgs e) { // Initialize the database connector. SqlConnection connectSQL = new SqlConnection(); // Send the connection string. connectSQL.ConnectionString = @"Data Source = localhost\SQLEXPRESS;" + "Initial Catalog = Inputs; Integrated Security = SSPI"; try { // Setup our command. SqlCommand theCommand = new SqlCommand("SELECT * FROM Inputs", connectSQL); // Write the stored value in the text boxes. connectSQL.Open(); SqlDataReader theReader; theReader = theCommand.ExecuteReader(); theReader.Read(); DropDownList1.Items.Add(theReader["ApplicationName"].ToString()); theReader.Close(); connectSQL.Close(); } catch (Exception ee) { MessageBox("Oopsie: " + ee); } ```
Have you considered using a [SqlDataSource](http://msdn.microsoft.com/en-us/library/dz12d98w%28VS.80%29.aspx)? It'll be far less code for you to maintain and defend against defects for. ``` <asp:DropDownList id="DropDownList1" runat="server" DataTextField="ApplicationName" DataValueField="ApplicationName" DataSourceID="AppDataSource"> </asp:DropDownList> <asp:SqlDataSource id="AppDataSource" runat="server" DataSourceMode="DataReader" ConnectionString="<%$ ConnectionStrings:MyNorthwind%>" SelectCommand="SELECT ApplicationName FROM Inputs"> </asp:SqlDataSource> ```
I think you want to do a while(reader.read()) Then populate something like a dataset or a List, and then set the drop down lists data source to the dataset or list.
SQL value does not populate ASP DropDownList control
[ "", ".net", "asp.net", "sql", "ado.net", "" ]
When debugging C# with Visual Studio, is it possible to see WHICH object reference on a given line of code caused a NullReferenceException? I have what seems like an odd situation where, occassionally, when running a debug build of an application from Visual Studio, I will get a NullReferenceException at a certain line. Visual Studio will pop up the exception assistant box pointing at the line, but none of the 3 object references used on that line are null at that point. --- The line is: ``` myClassInstance.myMethod(myOtherClassInstance.IPAddressInstance.ToString()); ``` Both of my class instances are non-null, as is the IPAddress instance (which has its intended value).
If you're calling code marked with the `[DebuggerNonUserCode]` attribute, the problem might be in framework code, not on that line. In any case, do you have a specific example that you could post?
Be careful of functions that return null objects. This got me once and isn't very clear within the debugger. Check this out: ``` public class FooBar { public int ReturnInt() { return 0; } } public FooBar ReturnNullObject() { return null; } // Execution code: int exceptionalInt = ReturnNullObject().ReturnInt(); ``` Edit: according to your edit, make sure IPAddressInstance isn't returning null. Edit: you might want to break the single line into a couple of lines. This should help. ``` var ip = myOtherClassInstance.IPAddressInstance; var ipString = ip.ToString(); myClassInstance.myMethod(ipString); ```
Seeing WHICH object reference caused a NullReferenceException
[ "", "c#", ".net", "visual-studio", "debugging", "exception", "" ]
I would suspect this to work at first: ``` if ($('#element') == $('#element')) alert('hello'); ``` But it does not. How does one test if elements are the same?
As of jquery 1.6 you can now simply do: ``` $element1.is($element2) ```
This should work: ``` if ($(this)[0] === $(this)[0]) alert('hello'); ``` so should this ``` if (openActivity[0] == $(this)[0]) alert('hello'); ```
Test if two elements are the same
[ "", "javascript", "jquery", "" ]
Here is my current layout: (the question is the comment) ``` class A { int foo; } class B : A {} class C : B { void bar() { //I want to access foo base.foo; // Doesn't work base.base.foo // Doesn't work, of course } } ``` As you can see, I cannot access members of `A` by using `base` in C. How could I access it? Thanks :)
If you make foo protected, ``` class A { protected int foo; } ``` then a simple base will do: ``` void bar() { //I want to access foo base.foo; // will work now // base.base.foo // Doesn't work, of course } ``` But it would be better to build a (protected) property around foo: ``` class A { private int _foo; protected int Foo { get { return _foo; } set { _foo = value; } } } ```
The field in A is declared private. It should be protected for derived classes to access it.
Access member of second parent (inheritance)
[ "", "c#", "class", "inheritance", "double", "" ]
Been a few years since I've written C/C++, and now I'm facing a problem I just cannot seem to solve on my own. Given the following struct: ``` struct InputData { float diameter; float length; int vertIndex; struct InputData *parent; vector<InputData*> children; bool deadEnd; InputData(float dia, float lngth) { diameter = dia; length = lngth; vertIndex = NULL; parent = NULL; deadEnd = false; } }; ``` I start out by defining a number of nodes, and their parent/child relationship: ``` InputData i0 = InputData(3.0f, 3.0f); InputData i1 = InputData(2.0f, 2.0f); InputData i2 = InputData(1.0f, 1.0f); InputData i3 = InputData(1.0f, 1.0f); InputData i4 = InputData(1.0f, 1.0f); InputData i5 = InputData(1.01f, 0.5f); i0.children.push_back(&i1); i1.children.push_back(&i2); i2.children.push_back(&i3); i3.children.push_back(&i4); i4.children.push_back(&i5); i1.parent = &i0; i2.parent = &i1; i3.parent = &i2; i4.parent = &i3; i5.parent = &i4; ``` Note that i5 as the only node doesn't have any children. I then move on to do some work using this data (calling BuildMeshVertices(&i0, &vertices) from main()), and end up adding a child to i5: ``` void BuildMeshVertices(InputData* current, vector<SimpleVertex> *vertices) { //Do work if(current->children.size() == 1) { BuildMeshVertices(current->children[0], vertices); } else if(current->children.size() == 0 && current->deadEnd == false) { InputData iDeadEnd = InputData(1.01f, 0.5f); iDeadEnd.deadEnd = true; iDeadEnd.parent = current; current->children.push_back(&iDeadEnd); BuildMeshVertices(&iDeadEnd, vertices); } } ``` After which everything is fine. i0 has one child (i1), i1 has a one child (i2), so on and so forth and i5 now has a child as well. I call another function (BuildMeshIndices()), and suddenly a few lines into this function (line 63) the data for the newly added child to i5 is being overwritten. i5 still points to the right child, but the data for this child is suddenly garbled. Here's a screenshot [before and after](http://i27.tinypic.com/1q1gkh.png) (sorry about the link, but I weren't allowed to use IMG tags) I cannot figure out why this happens, but I've got a feeling it's got something to do with my poor memory management? **UPDATE** Also it doesn't have to be done this way. If for example changing the children vector to a vector of values is the preferred C++ way, I would much prefer that. I've tried to comment on the answers, but I'm not sure you guys are seeing the comments (According to the FAQ you need 50 reputation to leave comments)? Below is the full source code (with everything unnecessary stripped out, but enough to reproduce the error): ``` #include "stdafx.h" #include <vector> using std::vector; struct InputData { float diameter; float length; int vertIndex; struct InputData *parent; vector<InputData*> children; bool deadEnd; InputData(float dia, float lngth) { diameter = dia; length = lngth; vertIndex = NULL; parent = NULL; deadEnd = false; } }; //-------------------------------------------------------------------------------------- // Vertex types //-------------------------------------------------------------------------------------- struct SimpleVertex { float Pos; SimpleVertex(float Position) { Pos = Position; } }; void BuildMeshVertices(InputData* current, vector<SimpleVertex> *vertices) { current->vertIndex = vertices->size(); //Add vertices.. if(current->children.size() == 1) { BuildMeshVertices(current->children[0], vertices); } else if(current->children.size() == 0 && current->deadEnd == false) { InputData iDeadEnd = InputData(1.01f, 0.5f); iDeadEnd.deadEnd = true; iDeadEnd.parent = current; current->children.push_back(&iDeadEnd); BuildMeshVertices(&iDeadEnd, vertices); } } void BuildMeshIndices(InputData* current, vector<unsigned long> *indices) { indices->push_back(current->vertIndex+2); indices->push_back(current->vertIndex+0); indices->push_back(current->vertIndex+1); indices->push_back(current->vertIndex+3); indices->push_back(current->vertIndex+0); indices->push_back(current->vertIndex+2); InputData *parent = current->parent; unsigned long vOffset; if(parent != NULL && parent->children.size() == 1) { vOffset = (unsigned long)current->vertIndex; indices->push_back(vOffset+7); indices->push_back(vOffset+5); indices->push_back(vOffset+4); indices->push_back(vOffset+6); indices->push_back(vOffset+5); indices->push_back(vOffset+7); indices->push_back(vOffset+10); indices->push_back(vOffset+8); indices->push_back(vOffset+9); indices->push_back(vOffset+11); indices->push_back(vOffset+8); indices->push_back(vOffset+10); indices->push_back(vOffset+15); indices->push_back(vOffset+13); indices->push_back(vOffset+12); indices->push_back(vOffset+14); indices->push_back(vOffset+13); indices->push_back(vOffset+15); indices->push_back(vOffset+18); indices->push_back(vOffset+16); indices->push_back(vOffset+17); indices->push_back(vOffset+19); indices->push_back(vOffset+16); indices->push_back(vOffset+18); } if(current->children.size() == 1 && current->deadEnd == false) { BuildMeshIndices(current->children[0], indices); } } int _tmain(int argc, _TCHAR* argv[]) { InputData i0 = InputData(3.0f, 3.0f); InputData i1 = InputData(2.0f, 2.0f); InputData i2 = InputData(1.0f, 1.0f); InputData i3 = InputData(1.0f, 1.0f); InputData i4 = InputData(1.0f, 1.0f); InputData i5 = InputData(1.01f, 0.5f); i0.children.push_back(&i1); i1.children.push_back(&i2); i2.children.push_back(&i3); i3.children.push_back(&i4); i4.children.push_back(&i5); i1.parent = &i0; i2.parent = &i1; i3.parent = &i2; i4.parent = &i3; i5.parent = &i4; // Create vertex buffer vector<SimpleVertex> vertices; BuildMeshVertices(&i0, &vertices); // Create index buffer vector<unsigned long> indices; BuildMeshIndices(&i0, &indices); return 0; } ```
Change raw pointers to [smart pointers](http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/shared_ptr.htm) and you will get ride of memory management problems. You don't need to copy all boost to your project, just required headers. ``` #include <vector> #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> struct InputData { float diameter; float length; unsigned long vertIndex; boost::weak_ptr<InputData> parent; std::vector< boost::shared_ptr<InputData> > children; bool deadEnd; InputData(float dia, float lngth, boost::weak_ptr<InputData> p = boost::weak_ptr<InputData>(), bool de = false) : diameter(dia), length(lngth), vertIndex(0), parent(p), deadEnd(de) {} }; struct SimpleVertex { float Pos; SimpleVertex(float position) : Pos(position) {} }; void BuildMeshVertices(boost::shared_ptr<InputData> current, std::vector<SimpleVertex>& vertices) { current->vertIndex = vertices.size(); //Add vertices.. if(current->children.size() == 1) { BuildMeshVertices(current->children[0], vertices); } else if(current->children.size() == 0 && current->deadEnd == false) { // this was a stack variable, so the pointer became invalid when going out of ambit. boost::shared_ptr<InputData> iDeadEnd( new InputData(1.01f, 0.5f, current, true) ); current->children.push_back(iDeadEnd); BuildMeshVertices(iDeadEnd, vertices); } } void BuildMeshIndices(boost::shared_ptr<InputData> current, std::vector<unsigned long>& indices) { unsigned long vi = current->vertIndex; unsigned long ioffset[] = { vi+2, vi, vi+1, vi+3, vi, vi+2}; indices.insert(indices.end(), ioffset, ioffset+6); boost::shared_ptr<InputData> parent = current->parent.lock(); if (parent && parent->children.size() == 1) { unsigned long offs = current->vertIndex; unsigned long voffset[] = { offs+7, offs+5, offs+4, offs+6, offs+5, offs+7, offs+10, offs+8, offs+9, offs+11, offs+8, offs+10, offs+15, offs+13, offs+12, offs+14, offs+13, offs+15, offs+18, offs+16, offs+17, offs+19, offs+16, offs+18 }; indices.insert(indices.end(), voffset, voffset+24); } if(current->children.size() == 1 && current->deadEnd == false) { BuildMeshIndices(current->children[0], indices); } } int main() { boost::shared_ptr<InputData> i0( new InputData(3.0f, 3.0f) ); boost::shared_ptr<InputData> i1( new InputData(2.0f, 2.0f) ); boost::shared_ptr<InputData> i2( new InputData(1.0f, 1.0f) ); boost::shared_ptr<InputData> i3( new InputData(1.0f, 1.0f) ); boost::shared_ptr<InputData> i4( new InputData(1.0f, 1.0f) ); boost::shared_ptr<InputData> i5( new InputData(1.01f, 0.5f) ); i0->children.push_back(i1); i1->children.push_back(i2); i2->children.push_back(i3); i3->children.push_back(i4); i4->children.push_back(i5); i1->parent = i0; i2->parent = i1; i3->parent = i2; i4->parent = i3; i5->parent = i4; // Create vertex buffer std::vector<SimpleVertex> vertices; BuildMeshVertices(i0, vertices); // Create index buffer std::vector<unsigned long> indices; BuildMeshIndices(i0, indices); return 0; } ``` Think you still have a half C, half C++ dirty code... you should choose a language.
You are pushing the pointer to a stack object into your vector. Once execution leaves scope that stack object will get destroyed and the memory will be reused, resulting in a bogus value. Try ``` InputData *iDeadEnd = new InputData(1.01f, 0.5f); iDeadEnd->deadEnd = true; iDeadEnd->parent = current; current->children.push_back(iDeadEnd); ``` Then you'll have to free that memory at the appropriate time.
C++ variable data being overwritten
[ "", "c++", "vector", "pointers", "overwrite", "" ]
I have a slowness problem with Django and I can't find the source .. I'm not sure what I'm doing wrong, but at least twice while working on projects Django became really slow. Requests takes age to complete (~15 seconds) and Validating model when starting the development server is also very slow (12+ seconds on a quad core..) I've tried many solution found on the net for similar problem, but they don't seem related to me. The problem doesn't seem to come from Django's development server since the request are also very slow on the production server with apache and mod\_python. Then I thought it might be a DNS issue, but the site loads instantly when served with Apache2. I tried to strace the development server, but I didn't find anything interesting. Even commenting all the apps (except django apps) didn't change anything.. models still take age to validate. I really don't know where I should be looking now .. Anybody has an idea ?
I've posted [this question](https://serverfault.com/questions/47112/django-site-performance-problem) on serverfault maybe it will help you. If you are serving big static files - those will slow down response. This will be the case in any mode if your mod\_python or development server process big static files like images, client scripts, etc. You want to configure the production server to handle those files directly - i.e. bypassing the modules. btw, mod\_wsgi is nowadays the preferred way to run django in the production environment. If you have issues with system services or hardware then you might get some clues from [log messages](http://www.cyberciti.biz/faq/linux-log-files-location-and-how-do-i-view-logs-files/).
> Then I thought it might be a DNS > issue, but the site loads instantly > when served with Apache2. How are you serving your Django site? I presume you're running mod\_python on Apache2? You may want to start by running an Apache2 locally on you computer (use MAMP or WAMP and install mod\_python there) and seeing if it's still slow. Then you can tell whether it's a django/python issue or an Apache/mod\_python issue
django extreme slowness
[ "", "python", "django", "" ]
I have a project which I am building with Maven which uses Hibernate (and Spring) to retrieve data from a database, etc. My "tests" for the DAOs in my project extend Spring's `AbstractTransactionalDataSourceSpringContextTests` so that a DataSource can be wired into my class under test to be able to actually run the query/Hibernate logic, to fetch data, etc. On several other projects I've used these types of test in concert with a HSQL database (either in-memory or pointed at a file) to be able to efficiently test the actual database querying logic without relying on an external database. This works great, since it avoids any external dependencies and the "state" of the database prior to running the tests (each of which are wrapped in a transaction which is rolled back) is well defined. I'm curious though about the best way to organize these tests, which are really a loose flavor of integration tests, with Maven. It feels a bit dirty to keep these tests in `src/test/java`, but from what I've read there doesn't seem to be a consistent strategy or practice for organizing integration tests with Maven. From what I've read so far, seems like I can use the [Failsafe plugin](http://mojo.codehaus.org/failsafe-maven-plugin/usage.html) (or a second instance of Surefire) and bind it to the `integration-test` phase, and that I can also bind custom start-up or shutdown logic (such as for starting/stopping the HSQL instance) to `pre-integration-test` or `post-integration-test`. But, is this really the best method? So my question basically is - what is the generally accepted best practice on organizing this with Maven? I'm having trouble finding any sort of consistent answer in the documentation. What I'd like is to: * Seperate unit tests from integration tests, so only unit tests are run during the `test` phase * The ability to bind custom startup/shutdown logic to `pre-integration-test` and `post-integration-test` * Have the reports from the integration-tests merged/presented with the unit test Surefire reports
There is this [codehaus page](http://docs.codehaus.org/display/MAVENUSER/Maven+and+Integration+Testing) with some guidelines. I found the failsafe plugin a bit of a hack, and it makes running the unit tests in Eclipse fiendishly complicated. I do broadly what you're describing. Define integration tests in src/itest/java In the pre-integration-test phase: * Clear target/test-classes * Use the [build-helper-maven-plugin](http://mojo.codehaus.org/build-helper-maven-plugin/)'s add-test-source goal to add the itest source location * Use a custom Mojo to remove src/test/java from the configuration so the unit tests are not compiled again (I don't really like this, but it's needed to maintain the separation of unit and integration tests). * Use the compiler-plugin to compile the integration tests Then in the integration-test phase, use the surefire-plugin to run the tests. Finally, bind any tidy up goals to the post-integration-test phase (though normally they're not needed as you can use the test teardown() to tidy up). I've not yet found a way to merge the test results as the reporting phase has passed, but I tend to view the integration tests as an added bonus, so as long as they pass the report is not so important. Update: I think it's worth pointing out that you can run Jetty from within your integration tests rather than using a jetty goal. This gives you much finer control over the tests. You can get more details from [this answer](https://stackoverflow.com/questions/1186348/maven-ear-module-and-ejb-dependencies-tests/1186531#1186531) and the referenced blogs.
A very simple way of doing this is to use JUnit categories. You can then easily run some tests during the test phase and another during the integration-test phase. It takes minutes and requires only 3 steps. 1. Define a marker interface 2. Annotate the classes you wish to split 3. Configure Maven plugins. A full example is given here. <https://stackoverflow.com/a/10381662/1365383>
Best practices for integration tests with Maven?
[ "", "java", "testing", "maven-2", "integration-testing", "" ]
I recently added Struts 1.3 to my application on Tomcat. Here are my observations, 1. MVC. Servlet/JSP does this fine for me, where JSP is the view and servlet is the controller. I don't see any benefit to get the mapping from an XML file since our mapping is very static. 2. Action Form. I can see some benefits of action form but not huge. 3. Tags. I already uses JSTL and don't see any advantage using Struts tags. So I am thinking about removing Struts. Anyone can think of any other benefits I might have missed?
Personally I myself prefer jsp/servlet but theoretically Struts has some advantages. Here are some of the advantages i know of, you might have mentioned them already, but i thought it would be better if i list all of them here. 1. Centralized File-Based Configuration. Struts values/mapping are represented in XML or property files. This loose coupling means that many changes can be made without modifying or recompiling Java code, and that wholesale changes can be made by editing a single file. This approach also lets Java and Web developers focus on their specific tasks (implementing business logic, presenting certain values to clients, etc.) without needing to know about the overall system layout. 2. Form Beans. 3. Bean Tags. Struts provides a set of custom JSP tags that let you easily output the properties of JavaBeans components. 4. HTML Tags. Struts provides a set of custom JSP tags to create HTML forms that are associated with JavaBeans components. This bean/form association serves two useful purposes: * It lets you get initial form-field values from Java objects. * It lets you redisplay forms with some or all previously entered values intact. 5. Form Field Validation. Struts has a robust, extensible validator that can be used to uniformly validate your form fields. This validation can be performed on the server (in Java), or both on the server and on the client (in JavaScript). 6. "Plumbing code" contained within the Struts framework. Mapping HTTP request parameters to Java objects is handled by Struts, for example. You don't have to do it. This allows you to focus more on the domain problem instead of building infrastructure. 7. Good documentation & plenty of books. If you have to leave the project and/or someone else has to maintain it then using a well known and well documented framework will make that job much easier. A homebrewed framework just can't match that. 8. Broad user testing. Since Struts is used in plenty web-apps the framework will get looked at by many more eyes than anything you could write alone. Usually, but not always, that means any problems you have will have been seen by someone else (and hopefully resolved) first.
Large knowledge base. I agree that this perhaps isn't as valid as it used to be but Struts has been used in a lot of projects over the years. From a maintainability point of view using a well known framework makes it easier for other people to work on your application and also help build your own resumé for the future. Right now most development is either in the component based space (like [JSF](http://java.sun.com/javaee/javaserverfaces/), [wicket](http://wicket.apache.org/), [tapestry](http://tapestry.apache.org/)) or in the rails-like space (like [rails](http://rubyonrails.org/), [grails](http://grails.org/), [lift](http://liftweb.net/)) but the struts arcitechture is still in use and valid. You didn't say if you develop in a corporate environment or not, for a personal project perhaps the maintainability issue isn't that much of a problem. If you decide that struts suits you well you could also have a look at [stripes](http://www.stripesframework.org/), a struts-like framework that's based on the same concepts but is less verbose when it comes to configuration with more sensible defaults, less xml and support for annotations.
What Are the Benefits of Struts
[ "", "java", "model-view-controller", "tomcat", "servlets", "struts", "" ]
*Bounty Question* I am using c# 3.5 Window Forms Application. I am using the code mentioned in the accepted answer. and I am getting below error ## **The remote server returned an error: (401) Unauthorized.** **Sample code to verify the UserName and Password will be really appreciated** *Bounty Question Ends* --- I have an application with the following use-case: when the user first starts using the application, he inputs his username and password. Then, at a much later stage, the application may update his status. Currently I'm using Twitterizer, but I believe the question is beyond the scope of the specific library I'm using. Following are the two relevant lines of code: ``` Twitter twitter = new Twitter("username", "password", "source"); twitter.Status.Update("update"); ``` The construction of the Twitter object does not throw an exception if the username/password are incorrect. This is probably because nothing is sent at this point. On the other hand, the status update does throw an exception if the username/password are invalid. My problem is that I want to validate the username/password at the point of user input, not when trying to post the update. How can I validate the username/password without posting anything (in Twitterizer or otherwise)?
Taking a quick look at the verify\_credentials API as mentioned by peSHIr, I wrote a little routine which seems to do the trick. It's late, but I was able to test it a couple of times and seems to work. In my function, I am just returning true if I I get an HttpResponseCode.OK, and false if I get anything else or an exception is thrown. If twitter does not like the uid/password an exception will be thrown with a 401 error (not authorized.) ``` public bool CheckTwitterCredentials(string UserName, string Password) { // Assume failure bool Result = false; // A try except block to handle any exceptions try { // Encode the user name with password string UserPass = Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes(UserName + ":" + Password)); // Create our HTTP web request object HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("http://twitter.com/account/verify_credentials.xml"); // Set up our request flags and submit type Request.Method = "GET"; Request.ContentType = "application/x-www-form-urlencoded"; // Add the authorization header with the encoded user name and password Request.Headers.Add("Authorization", "Basic " + UserPass); // Use an HttpWebResponse object to handle the response from Twitter HttpWebResponse WebResponse = (HttpWebResponse)Request.GetResponse(); // Success if we get an OK response Result = WebResponse.StatusCode == HttpStatusCode.OK; } catch (Exception Ex) { System.Diagnostics.Debug.WriteLine("Error: " + Ex.Message); } // Return success/failure return Result; } ```
You could try to use the API call [account/verify\_credentials](https://dev.twitter.com/docs/api/1/get/account/verify_credentials). Hopefully the API library you use already supports this.. Twitter is notorious now for really hating third party programmers, so unless you have good reason to do something with Twitter, just stay away...
Twitter: verifying username and password in C#
[ "", "c#", "api", "c#-4.0", "twitter", "c#-3.0", "" ]
I have a winforms application.Winforms start with Program.cs where we have main() defined.I have put this code in try-catch block. ``` [STAThread] static void Main() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmSplash()); } catch (Exception ex) { MessageBox.Show(ex.Message); if (ex.InnerException != null) { MessageBox.Show(ex.InnerException.ToString()); } } } ``` Whenever there is a win32 exception,this mechanism fails and unhandled exception message is thrown and application crashes. I have 2 questions regarding this code: 1) Why win32 exceptions are not caught. 2) Is it a good practice to catch exceptions at the highest level.
**EDIT** : as [Pratik](https://stackoverflow.com/users/11711/pratik) pointed out, the following answer applies to .NET 1.0 and .NET 1.1 only. Starting with .NET 2.0, non-CLS exception should be caught as a [RuntimeWrappedException](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.runtimewrappedexception(VS.80).aspx). --- Because Win32 exceptions do not derive from the .NET Exception class. Try : ``` try { } catch (Exception ex) { // .NET exception } catch { // native exception } ``` See [Catch non-CLSCompliant exceptions in general handlers](http://msdn.microsoft.com/en-us/bb264489.aspx) for more information.
The execution of Application.Run is not throwing an error. That is happening on another thread (or at least asynchronously). Its good idea to inform the user in friendly way that the application has failed before it disapears completely, however its not a good idea to just catch then continue.
Why win32 exception are not caught by c# exception handling mechanism
[ "", "c#", "winforms", "exception", "" ]
I want to split ``` $path = getenv('PATH'); ``` into its components. How do I determine the separator char in an os-dependent fashion?
You can use the `PATH_SEPARATOR` constant, then the `DIRECTORY_SEPARATOR` constant to split the path if needed. See [`Directory Predefined Constants`](http://php.net/manual/en/dir.constants.php)
Use the `PATH_SEPARATOR` constant.
How do I properly split a PATH variable in PHP?
[ "", "php", "path", "operating-system", "variables", "environment", "" ]
``` <?php function date($x) { $contents = $_FILES['userfile']['tmp_name']; $contents = file("$contents"); $date = $contents[$x][6].$contents[$x][7] ."-".$contents[$x][8].$contents[$x][9] ."-"."20".$contents[$x][4].$contents[$x][5]; return $date; } ?> ``` Fatal error: Cannot redeclare date() in .../includes.php on line 20 I have created several functions with the same exact structure as the one above and they work fine. For some reason this function keeps returning this error. Any suggestions/solutions to this problem would be greatly appreciated! thx,
PHP already has a `date()` function and you cannot overwrite existing functions in this language. Rename your function and it will work. Or wrap it in a class and it will work as well.
date is an existing built-in function in PHP. You can not redeclare existing functions. <http://www.php.net/date>
PHP: Cannot redeclare function error?
[ "", "php", "" ]
``` id | photo title | created_date XEi43 | my family | 2009 08 04 dDls | friends group | 2009 08 05 32kJ | beautiful place | 2009 08 06 EOIk | working late | 2009 08 07 ``` Say I have the id `32kJ`. How would I get the next row or the previous one?
This is what I use for finding previous/next records. Any column in your table can be used as the sort column, and no joins or nasty hacks are required: Next record (date greater than current record): ``` SELECT id, title, MIN(created) AS created_date FROM photo WHERE created > (SELECT created FROM photo WHERE id = '32kJ') GROUP BY created ORDER BY created ASC LIMIT 1; ``` Previous record (date less than current record): ``` SELECT id, title, MAX(created) AS created_date FROM photo WHERE created < (SELECT created FROM photo WHERE id = '32kJ') GROUP BY created ORDER BY created DESC LIMIT 1; ``` Example: ``` CREATE TABLE `photo` ( `id` VARCHAR(5) NOT NULL, `title` VARCHAR(255) NOT NULL, `created` DATETIME NOT NULL, INDEX `created` (`created` ASC), PRIMARY KEY (`id`) ) ENGINE = InnoDB; INSERT INTO `photo` (`id`, `title`, `created`) VALUES ('XEi43', 'my family', '2009-08-04'); INSERT INTO `photo` (`id`, `title`, `created`) VALUES ('dDls', 'friends group', '2009-08-05'); INSERT INTO `photo` (`id`, `title`, `created`) VALUES ('32kJ', 'beautiful place', '2009-08-06'); INSERT INTO `photo` (`id`, `title`, `created`) VALUES ('EOIk', 'working late', '2009-08-07'); SELECT * FROM photo ORDER BY created; +-------+-----------------+---------------------+ | id | title | created | +-------+-----------------+---------------------+ | XEi43 | my family | 2009-08-04 00:00:00 | | dDls | friends group | 2009-08-05 00:00:00 | | 32kJ | beautiful place | 2009-08-06 00:00:00 | | EOIk | working late | 2009-08-07 00:00:00 | +-------+-----------------+---------------------+ SELECT id, title, MIN(created) AS next_date FROM photo WHERE created > (SELECT created FROM photo WHERE id = '32kJ') GROUP BY created ORDER BY created ASC LIMIT 1; +------+--------------+---------------------+ | id | title | next_date | +------+--------------+---------------------+ | EOIk | working late | 2009-08-07 00:00:00 | +------+--------------+---------------------+ SELECT id, title, MAX(created) AS prev_date FROM photo WHERE created < (SELECT created FROM photo WHERE id = '32kJ') GROUP BY created ORDER BY created DESC LIMIT 1; +------+---------------+---------------------+ | id | title | prev_date | +------+---------------+---------------------+ | dDls | friends group | 2009-08-05 00:00:00 | +------+---------------+---------------------+ ```
I realize that you are using MySQL, but just for reference, here is how you would do this using Oracle's analytic functions LEAD and LAG: ``` select empno, ename, job, lag(ename, 1) over (order by ename) as the_guy_above_me, lead(ename, 2) over (order by ename) as the_guy_two_rows_below_me from emp order by ename ``` I guess there's a reason why Oracle costs money and MySQL is free... :-) This page shows you [how to emulate analytic functions in MySQL](http://onlamp.com/pub/a/mysql/2007/04/12/emulating-analytic-aka-ranking-functions-with-mysql.html?page=2).
sql pulling a row for next or previous row of a current row
[ "", "sql", "mysql", "" ]
I received the following error when trying to retrieve data using [Google App Engine](http://en.wikipedia.org/wiki/Google_App_Engine) from a single entry to a single page e.g. foobar.com/page/1 would show all the data from id 1: ``` ValueError: invalid literal for int() with base 10 ``` Here are the files: **Views.py** ``` class One(webapp.RequestHandler): def get(self, id): id = models.Page.get_by_id(int(str(self.request.get("id")))) page_query = models.Page.get(db.Key.from_path('Page', id)) pages = page_query template_values = { 'pages': pages, } path = os.path.join(os.path.dirname(__file__), 'template/list.html') self.response.out.write(template.render(path, template_values)) ``` **Urls.py**: ``` (r'/browse/(\d+)/', One), ``` **Error:** ``` Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 501, in __call__ handler.get(*groups) File "/Volumes/foobar/views.py", line 72, in get id = models.Page.get_by_id(int(str(self.request.get("id")))) ValueError: invalid literal for int() with base 10: '' ```
I'm not quite sure what you're trying to achieve here. The first line: ``` id = models.Page.get_by_id(int(str(self.request.get("id")))) ``` returns a Page object with an ID fetched from the query string. To make it work with the passed in argument, change it to: ``` id = models.Page.get_by_id(int(id)) ``` Odder is the second line: ``` page_query = models.Page.get(db.Key.from_path('Page', id)) ``` This does not return a query - it returns a page object, and if you replace 'id' with 'int(id)' does precisely the same thing as the first line. What are you trying to achieve here?
Change `self.request.get("id")` to simply `id`, which is already being passed to your `get` handler. The code, as you have it, would only work for URLs like `/browse/1/?id=1`
ValueError: invalid literal for int() with base 10 trying to retrieve a query parameter from Google App engine
[ "", "python", "google-app-engine", "" ]
I have a problem with interface lag in C#. Since I'm still learning please be patient whilst I explain. I have narrowed the problem to my timer object. Basically my program queries a device through TCP/IP socket and outputs it to a textbox on screen. Now I am polling the device for data every second which requires some logic to be buried within timer object and the following is what happens between ticks: 1. Increment a value. 2. Construct the 2 strings that represents the command to be sent to the box (encapsulated in a function 3. Encode the command 4. Send command 5. Clear the byte array 6. Receive reply. Could this be too much processing being done in the event handler? Every time I try to move the window during the polling session i.e. when the timer is running I get a very bad input lag.
The timer you are using is executing on the windows message thread. Therefore, while the polling is running the windows message queue is blocked. This isn't a problem with doing too much processing, most of the time the thread will be waiting for the TCP/IP response. To fix this, you just have to do the do the work on a background thread and then update the UI on the UI thread. There are a heap of different timers in the .NET framework that work in different ways, the one you are using works processed the timer event on the same thread, others work on background threads. [Check this article out about the different timers](http://msdn.microsoft.com/en-us/magazine/cc164015.aspx). You could also just use your current timer to invoke a BackgroundWorker component to do the work on the background thread. The main benefit of this is the the BackgroundWorker will do the work on a background thread, but will raise the work complete event on the UI thread so that it is simple to update the UI without having to worry about which thread you are on.
I think this is because you're trying to do work in your UI thread. Have your timer run in a background work thread.
How do I reduce interface lag in C#?
[ "", "c#", ".net", "user-interface", "timer", "" ]
This may be a hairy question but. Say I have ``` Followers: -user_id -follower_id Activities: -id -user_id -activity_type -node_id ``` Pulling a users activity is fairly easy. But what is the best way to get a followers activity? A subselect? It seems like it is incredibly slow as users get more and more followers. Any ideas to speed this up? Also, on a more conceptual level. How does the grouping work. Is it all done with a single query? Or is all the activity data pulled in and then sorted and grouped on the PHP side? Users X, Y and Z did Activity A User J did 3 of Activity B
Subselects are often slower than JOINs, but it really depends on what exactly you're doing with them. To answer you main question, I would get follower data with a JOIN: ``` SELECT * FROM followers f LEFT JOIN activities a ON f.follower_id=a.user_id WHERE f.user_id=$followedPerson ``` That's assuming that the followers table represents a user with `user_id`, and someone who is following them with a `follower_id` that happens to be a `user_id` in the users table as well. It won't ever be *incredibly* slow as long as you have an index on `followers.user_id`. However, the amount of data such a query could return could become larger than you really want to deal with. You need to determine what kinds of activity your application is going to want to show, and try to filter it accordingly so that you aren't making huge queries all the time but only using a tiny fraction of the returned results. Pulling data out and grouping it PHP side is fine, but if you can avoid selecting it in the first place, you're better off. In this case, I would probably add an `ORDER BY f.follower_id,activity_date DESC`, assuming a date exists, and try to come up with some more filtering criteria for the activity table. Then I'd iterate through the rows in PHP, outputting data grouped by follower.
An activity log has the potential for a very large number of records since it usually has a mix of the current user's activity and all their friends. If you are joining various tables and a user has 100s of friends that's potentially a lot of data being pulled out. One approach is to denormalise the data and treat it as one big log where all entries that should appear on a user's activity log page to be stored in the activity log table against that user. For example if User A has two friends, User B and User C, when User A does something three activity log records are created: ``` record 1: "I did this" log for user A record 2: "My friend did this" log for user B record 3: "My friend did this" log for user C ``` You'll get duplicates, but it doesn't really matter. It's fast to select since it's from one table and indexed on just the user ID. And it's likely you'll housekeep an activity log table (i.e. delete entries over 1 month old). The activity log table could be something like: ``` -id -user_id (user who's activity log this is) -action_user_id (user who took the action, or null if same as user_id) -activity_type -date ``` To select all recent activity logs for a single user is then easy: ``` SELECT * from activity_log WHERE user_id = ? ORDER by date DESC LIMIT 0,50 ``` To make this approach really efficient you need to have enough information in the single activity log table to not need any further selects. For example you may store the raw log message, rather than build it on the fly.
PHP/MySQL Activity (ala facebook)
[ "", "php", "mysql", "social-networking", "" ]
I have a series of arrays that i draw data from and ultimately lead to a final array that holds the information i want. The final array is 2-dimensional, being comprised of a large number of single dimensional arrays, each holding up to 3 entries. ``` int[][] realOcc = new int[result.length][3]; ``` The way the array holds data is as follows: The first "cell" holds a name, the second a region ID and the third an occurence number - an int telling me how many times this name came up in this particular region ID. After sorting the array according to name using a Bubble Sort algorithm i naturally see many entries that i wouldn't want to be there. As an example, imagine a name coming up 3 times in a specific region ID. The way the array entries for this name would look like would be as follows: ``` Name1 regionID17 1 Name1 regionID17 2 Name1 regionID17 3 ... Name156 regionID1 1 Name168 regionID99 1 ... ``` What i want to do is get rid of all the excess entries as in, the entries that correspond to the same name and regID, and only keep the maximum occurence number for each name in a specific region. So, taking the above example, what i would like to see after manipulating the array would be: ``` Name1 regionID17 3 ... Name156 regionID1 1 Name168 regionID99 1 ... ``` Any ideas would be greatly appreciated since i'm pretty much stumped.. Keep in mind that since the data i'm pulling is pretty big in number, i also need to keep my code efficient.
I agree with Mario, you shouldn't be using an array structure here. The fact that you're using Bubble Sort suggests that you're in an intro programming course of some kind, so you may not know about `ArrayList`s, `HashSet`s, the `.equals()` method, or the like, but that's what you really want to do. Create a custom object with a custom `.equals()` method - something like: ``` public class Record{ String name; String region; public boolean equals(Object o){ Record r = (Record)o; return name.equals(r.name) && region.equals(r.region); } public int hashCode(){ return name.hashCode()+region.hashCode(); } } ``` Then you can use a `HashMap<Record, Integer>` to check if a record already exists in the set - if it does, increment count (the map's value) by 1, else add it. If you want everything sorted in a certain order, you can either define a custom `.compareTo()` method and use a `TreeMap` or, if you want everything in insertion order, use a `LinkedHashSet<Record>` to preserve that order.
What you really should look into is using an `ArrayList` class to hold these 'items.' You should also create a specific class to hold this data. Your custom class should look something like this: ``` class Entry implements Comparable<Entry> { private String name, region; private int occuranceCount; public Entry(String nameP, regionP, occurCountP){ name = nameP; region = regionP; occuranceCount = occurCountP; } // Getters public int compareTo(Entry other){ return name.compareTo(other.name); } // Equals and hashcode } ``` Then you can put these objects into an `ArrayList<Entry>` and use `Collections.sort()` which will be much faster than a bubble sort. After they are sorted, you can loop through and remove duplicate entries using `ArrayList.remove()`.
Multidimensional array manipulation - Java
[ "", "java", "arrays", "data-structures", "" ]
I recently had a class project where I had to make a program with G++. I used a makefile and for some reason it occasionally left a .h.gch file behind. Sometimes, this didn't affect the compilation, but every so often it would result in the compiler issuing an error for an issue which had been fixed or which did not make sense. I have two questions: 1) What is a .h.gch file and what is one used for? and 2) Why would it cause such problems when it wasn't cleaned up?
A `.gch` file is a precompiled header. If a `.gch` is not found then the normal header files will be used. However, if your project is set to generate pre-compiled headers it will make them if they don’t exist and use them in the next build. Sometimes the `*.h.gch` will get corrupted or contain outdated information, so deleting that file and compiling it again should fix it.
If you want to know about a file, simply type on terminal ``` file filename ``` `file a.h.gch` gives: ``` GCC precompiled header (version 013) for C ```
What is a .h.gch file?
[ "", "c++", "g++", "" ]
I have a basic xml file that looks like this. ``` <root> <item> <title><p>some title</p></title> </item> ... </root> ``` What I want, is to get the whole title string including the html tag of the xml using linq and displaying it in a repeater . I can get the title with no problem, but the `<p>` tag is being stripped out. If I use `title = item.Element("title").ToString()`, it works somehow but I get all the xml tag as well - meaning the title is not displayed in html. I already tried with encoding the `"<"` with `"&lt;"` but to do this makes the xml hard to read. What would be a possible solution besides using CDATA and encoding? Cheers Terry
Create a reader from the title element and read InnerXml: ``` static void Main(string[] args) { string xml = "<root><item><title><p>some title</p></title></item></root>"; XDocument xdoc = XDocument.Parse(xml); XElement te = xdoc.Descendants("title").First(); using (XmlReader reader = te.CreateReader()) { if (reader.Read()) title = reader.ReadInnerXml(); } } ```
See [Best way to get InnerXml of an XElement?](https://stackoverflow.com/questions/3793/best-way-to-get-innerxml-of-an-xelement) for some ideas on how to get the "InnerXml" of an XElement.
Get html tags embedded in xml using linq
[ "", "c#", "html", "xml", "linq", "" ]
I have a table with order information in an E-commerce store. Schema looks like this: [Orders] Id|SubTotal|TaxAmount|ShippingAmount|DateCreated **This table does only contain data for every Order. So if a day goes by without any orders, no sales data is there for that day.** I would like to select subtotal-per-day for the last 30 days, including those days with no sales. The resultset would look like this: Date | SalesSum 2009-08-01 | 15235 2009-08-02 | 0 2009-08-03 | 340 2009-08-04 | 0 ... Doing this, only gives me data for those days with orders: ``` select DateCreated as Date, sum(ordersubtotal) as SalesSum from Orders group by DateCreated ``` You could create a table called Dates, and select from that table and join the Orders table. But I really want to avoid that, because it doesn't work good enough when dealing with different time zones and things... Please don't laugh. SQL is not my kind of thing... :)
Create a function that can generate a date table as follows: (stolen from <http://www.codeproject.com/KB/database/GenerateDateTable.aspx>) ``` Create Function dbo.fnDateTable ( @StartDate datetime, @EndDate datetime, @DayPart char(5) -- support 'day','month','year','hour', default 'day' ) Returns @Result Table ( [Date] datetime ) As Begin Declare @CurrentDate datetime Set @CurrentDate=@StartDate While @CurrentDate<=@EndDate Begin Insert Into @Result Values (@CurrentDate) Select @CurrentDate= Case When @DayPart='year' Then DateAdd(yy,1,@CurrentDate) When @DayPart='month' Then DateAdd(mm,1,@CurrentDate) When @DayPart='hour' Then DateAdd(hh,1,@CurrentDate) Else DateAdd(dd,1,@CurrentDate) End End Return End ``` Then, join against that table ``` SELECT dates.Date as Date, sum(SubTotal+TaxAmount+ShippingAmount) FROM [fnDateTable] (dateadd("m",-1,CONVERT(VARCHAR(10),GETDATE(),111)),CONVERT(VARCHAR(10),GETDATE(),111),'day') dates LEFT JOIN Orders ON dates.Date = DateCreated GROUP BY dates.Date ```
``` declare @oldest_date datetime declare @daily_sum numeric(18,2) declare @temp table( sales_date datetime, sales_sum numeric(18,2) ) select @oldest_date = dateadd(day,-30,getdate()) while @oldest_date <= getdate() begin set @daily_sum = (select sum(SubTotal) from SalesTable where DateCreated = @oldest_date) insert into @temp(sales_date, sales_sum) values(@oldest_date, @daily_sum) set @oldest_date = dateadd(day,1,@oldest_date) end select * from @temp ``` OK - I missed that 'last 30 days' part. The bit above, while not as clean, IMHO, as the date table, should work. Another variant would be to use the while loop to fill a temp table just with the last 30 days and do a left outer join with the result of my original query.
Select data from SQL DB per day
[ "", "sql", "" ]
I would like to find the height/width of an image on disk without opening it, if possible (for performance reasons). The Windows properties pane for images contains information like width, height, bit depth, etc., which leads me to believe that it is storing metadata on the file somewhere. How can I access this information?
There are some stackoverflow questions on how to read the EXIF information from images, such as: [How to get the EXIF data from a file using C#](https://stackoverflow.com/questions/58649/how-to-get-the-exif-data-from-a-file-using-c)
Use System.Drawing.Image class. ``` Image img = Image.FromFile(fileName); ImageFormat format = img.RawFormat; Console.WriteLine("Image Type : "+format.ToString()); Console.WriteLine("Image width : "+img.Width); Console.WriteLine("Image height : "+img.Height); Console.WriteLine("Image resolution : "+(img.VerticalResolution*img.HorizontalResolution)); Console.WriteLine("Image Pixel depth : "+Image.GetPixelFormatSize(img.PixelFormat)); Console.WriteLine("Image Creation Date : "+creation.ToString("yyyy-MM-dd")); Console.WriteLine("Image Creation Time : "+creation.ToString("hh:mm:ss")); Console.WriteLine("Image Modification Date : "+modify.ToString("yyyy-MM-dd")); Console.WriteLine("Image Modification Time : "+modify.ToString("hh:mm:ss")); ```
Read extended image properties in c#
[ "", "c#", "windows", "file", "file-properties", "" ]
I have a table like this: ``` Date StudentName Score 01.01.09 Alex 100 01.01.09 Tom 90 01.01.09 Sam 70 01.02.09 Alex 100 01.02.09 Tom 50 01.02.09 Sam 100 ``` I need to rank the students in the result table by score within different dates, like this: ``` Date Student Rank 01.01.09 Alex 1 01.01.09 Tom 2 01.01.09 Sam 3 01.02.09 Alex 1 01.02.09 Sam 1 01.02.09 Tom 2 ``` How can I do this in SQL?
You want to use the `rank` function in T-SQL: ``` select date, student, rank() over (partition by date order by score desc) as rank from grades order by date, rank, student ``` The magic is in the `over` clause. See, it splits up those rankings by `date`, and then orders those subsets by `score`. Brilliant, eh?
You should use `ORDER BY`: ``` SELECT * FROM Students ORDER BY Date,Rank ``` That will order the data by date, then rank. You can add as many fields as you want, as long as they are comparable (you can't compare BLOBs or long text fields). Hope that helps.
Ranking Students by Grade in SQL
[ "", "sql", "sql-server", "t-sql", "" ]
Let's say that I have an article on a website, and I want to track the number of views to the article. In the Articles table, there's the PK ID - int, Name - nvarchar(50), and ViewCount - int. Every time the the page is viewed, I increment the ViewCount field. I'm worried about collisions when updating the field. I can run it in a sproc with a transaction like: ``` CREATE PROCEDURE IncrementView ( @ArticleID int ) as BEGIN TRANSACTION UPDATE Article set ViewCount = ViewCount + 1 where ID = @ArticleID IF @@ERROR <> 0 BEGIN -- Rollback the transaction ROLLBACK -- Raise an error and return RAISERROR ('Error Incrementing', 16, 1) RETURN END COMMIT ``` My fear is that I'm going to end up with PageViews not being counted in this model. The other possible solution is a log type of model where I actually log views to the articles and use a combination of a function and view to grab data about number of views to an article.
Probably a better model is to cache the number of views hourly in the app somewhere, and then update them in a batch-style process. -- Edit: To to elaborate more, a simple model for you may be: 1. Each page load, for the given page, increment a static hashmap. Also on each load, check if enough time has elapsed since 'Last Update', and if so, perform an update. 2. Be tricky, and put the base value in the asp.net cache (<http://msdn.microsoft.com/en-us/library/aa478965.aspx>) and, when it times out, [implement the cache removal handler as described in the link] do the update. Set the timeout for an hour. In both models, you'll have the static map of pages to counts; you'll update this each view, and you'll also use this - and the cached db amount - to get the current 'live' count.
The database should be able to handle a single digit increment atomically. Queries on the queue should be handled in order in the case where there might be a conflict. Your bigger issue, if there is enough volume will be handling all of the writes to the same row. Each write will block the reads and writes behind it. If you are worried, I would create a simple program that calls SQL updates in a row and run it with a few hundred concurrent threads (increase threads until your hardware is saturated). Make sure the attempts = the final result. Finding a mechanism to cache and/or perform batch updates as silky suggests sounds like a winner. Jacob
Incremented DB Field
[ "", "sql", "t-sql", "transactions", "" ]
The following code appears to demonstrate a bug in java.util.Date whereby an hour gets added on if the local clock is set to GMT with DST adjustment on and the time is before Nov 1 1971. My first assumption is always that I've got it wrong. Can anyone see what's wrong (or is this really a Java bug)? What's significant about Nov 1 1971? ``` import java.text.SimpleDateFormat; import java.util.Locale; import java.util.TimeZone; class JavaUtilDateBug { private static void demo() throws Exception { // UK developers usually have the clock on their development machines set // to "Europe/London" (i.e. GMT with daylight saving). Set it explicitly // here so readers in other countries can see the problem too. TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.ENGLISH); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy"); String strJan1st1970Expected = "Thu Jan 01 00:00:00 GMT 1970"; String strJan1st1970Actual = dateFormat.parse(strJan1st1970Expected).toString(); System.out.println("strJan1st1970Actual: " + strJan1st1970Actual); // -> "Thu Jan 01 01:00:00 GMT 1970" boolean jvmHasDateBug = !strJan1st1970Expected.equals(strJan1st1970Actual); System.out.println("jvmHasDateBug: " + jvmHasDateBug); // -> true // The anomaly only seems to affect times before 1 Nov 1971. final String strNov1st1971 = "Mon Nov 01 00:00:00 GMT 1971"; assert strNov1st1971.equals(dateFormat.parse(strNov1st1971).toString()); } public static void main(String[] args) { try { demo(); } catch (Exception e) { e.printStackTrace(); } } } ``` My Java environment: ``` java version "1.6.0_13" Java(TM) SE Runtime Environment (build 1.6.0_13-b03) Java HotSpot(TM) Client VM (build 11.3-b02, mixed mode, sharing) ```
I found a [matching bug](https://bugs.java.com/bugdatabase/view_bug?bug_id=4832236) in Sun's bug database. Seems that they consider it a "historical inaccuracy" (the formatting apparently should produce "BST" as time zone rather than GMT - the hour would then be correct) and won't fix it, because deep down, the TimeZone implementation cannot handle places switching the name of their time zone. As a workaround, you can explicitly set your time zone to GMT rather than "Europe/London". The problem then disappears.
There was a trial of British Standard Time between 27th Oct 1968 and 31st Oct 1971, which I suspect is what's causing this issue. There's some details of the trial here: <http://en.wikipedia.org/wiki/British_Summer_Time#Single.2FDouble_Summer_Time> The timezone for Europe/London in Jan 1st 1970 was British Standard Time (GMT+1) so when you use a `java.text.SimpleDateFormat` to parse Jan 01 00:00:00 GMT 1970 it generates the correct epoch value equal to Jan 01 01:00:00 1970 in BST. Then, due to the crappiness of `java.util.Date`, when you call `java.util.Date.toString()` it uses the default timezone for the current local as of *now*, which has changed to GMT and you get Jan 01 01:00:00 GMT 1970.
Why does an hour get added on to java.util.Date for dates before Nov 1 1971?
[ "", "java", "datetime", "" ]
What are the primary reasons for using the Java EE (EJBs) over just a simple Servlet implementation? I am working on developing a new project that will primarily be a web service that must be very fast and scalable. Sorry for any confusion, Although I am experienced in Java, I am very new to the Java Web world, and may not be asking this question well.
Servlets are HTTP request listeners; they can't respond to anything else. If you embed a great deal of logic in servlets it won't be available to any other clients. Write your app in POJOs. Get it thoroughly tested without an app server involved. Then worry about how you'd like to package and deploy it. Servlet? EJB? Web service? Something else? No problem - those are just packaging and deployment issues. Get the behavior that you want working properly in POJOs first. Spring can give you a lot of options here. I'd recommend it.
EJB's specification 1.x and 2.x added complexity that for most webapps was not needed. Due this complexities the new frameworks appeared to simplify the development and the runtime architecture ( Hibernate / Spring / other microcontainers / others ORM frameworks ) . EJB's 3.x matches this changes ( through JDO and JPA ) and now, using Servlets with these enhanced frameworks or Java EE with EJB 3 + would give you basically the same results. Using a Java EE Application Server would add you a number of administrative advantages ( GUI to manage pools, logs, monitoring, transactions etc. ) With out them you may have the same result but you would have to do it all by hand ( editing configuration files that is ) Which may not seem too problematic, but if you plan to have an administrator for your webapp It would be better to use the admin tools that come out of the box with this servers.
Advantages and Disadvantages of Java EE vs. Servlets
[ "", "java", "servlets", "jakarta-ee", "" ]
I want to have a generic thread safe collection and I saw that the Arraylist can easily be used thread safe by its static Synchronized method but what bugs me is that this ArrayList is not generic so when I want to use my objects I always have to cast them. Is there an easier way to do this? Also other list types would be possible.
A little knowledge is a dangerous thing ;-) Yes, you could use Meta-Knight's suggestion and use `SyncRoot`, but you need to be careful - it's not a panacea. See [this post](http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx) from the BCL Team Blog from Microsoft to see why it's not as simple as `SyncRoot`. Quotes from that post: > A few astute users of our generic > collections observed that we no longer > provide a public `SyncRoot` property on > `ICollection<T>` and > I think we're better off forcing > people to think more heavily about > synchronization, and frankly a > `SyncRoot` property on our generic > collections doesn't provide any value. Of course, that's not to say it can't be used under any circumstances - you just have to think the use cases through carefully and not be on auto-pilot.
If you read on MSDN regarding the synchronized method is still says this: "Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads."
Threadsafe and generic arraylist?
[ "", "c#", ".net", "collections", "multithreading", "thread-safety", "" ]
My code looks like this: ``` // Connect to SQLite DB DB('/path/to/sqlite.db'); DB('BEGIN TRANSACTION;'); // These loops are just examples. for ($i = 1; $i <= 10000; $i++) { for ($j = 1; $j <= 100; $j++) { DB('INSERT INTO "test" ("id", "name") VALUES (?, ?);', $i, 'Testing ' . $j); } } DB('END TRANSACTION;'); ``` And here is the DB() function: ``` function DB($query) { static $db = null; if (is_file($query) === true) { $db = new PDO('sqlite:' . $query, null, null, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING)); } else if (is_a($db, 'PDO') === true) { $result = $db->prepare($query); if (is_a($result, 'PDOStatement') === true) { if ($result->execute(array_slice(func_get_args(), 1)) === true) { if (stripos($query, 'INSERT') === 0) { return $db->lastInsertId(); } if (stripos($query, 'SELECT') === 0) { return $result->fetchAll(PDO::FETCH_ASSOC); } return $result->rowCount(); } } return false; } return true; } ``` The problem is that the DB() call inside the inner loop is taking to long to complete, I was thinking that doing something like this could speed up considerably the execution: ``` DB('BEGIN TRANSACTION;'); for ($i = 1; $i <= 10000; $i++) { $queries = array(); for ($j = 1; $j <= 100; $j++) { $queries[] = 'INSERT INTO "test" ("id", "name") VALUES (?, ?);' /*, $i, 'Testing ' . $j;*/ } DB(implode("\n", $queries)); } DB('END TRANSACTION;'); ``` The problem is I don't know how I could prepare (replace and escape) all the question marks with the respective variables, is there any way I can accomplish this?
If you are inserting lots of data into a table, try inserting the data in one query. ``` $query = 'INSERT INTO "test" ("id", "name") VALUES '; $data = array(); for ($i = 1; $i <= 10000; $i++) { for ($j = 1; $j <= 100; $j++) { $query .= '(?,?),'; $data[] = $i; $data[] = 'Testing '.$j; } } $query = substr($query, 0, -1); DB($query, $data); ``` This should eliminate the overhead with single insert queries. There's a limit on the query lenght though, if you have troubles with query lenght, try issueing DB() calls more often in for loop.
Why do you use prepared statements if you "prepare" them in the loop ? (in the DB function) Make a prepare befor the loop, and in the loop just give the values and execute. Of course this would require a rewrite of your DB method. Oh and btw. is your ID column the primary key ? if so you have another problem couse "i" would be for 100 "j" the same :) For example: ``` $sth = $dbh->prepare('INSERT INTO "test" ("id", "name") VALUES (:id, :name)'); $j=0; for ($i = 1; $i <= 10000; $i++){ $j = ($j==100) ? 0 : $j++; $sth->execute(array(':id' => $i, ':name' => 'Testing ' . $j)); } ```
Preparing SQL Statements with PDO
[ "", "php", "database", "sqlite", "pdo", "" ]
I am writing a back end program that telnets into a server, runs some commands and saves all the output from those commands. Something just like Expect. I would like to use an open source solution that is well supported and runs with JDK 6. I have found 3 options so far and would like some help deciding which one (or a better suggestion) to use. commons-net – This is very well supported but I having trouble getting a simple “Log in and do ‘ls’” command working. I would prefer to use this library, if anyone can provide a simple example (and not the example that comes with it that takes input from the user) I would like to go that route. If I’m unable to use commons-net the next two options are: JExpect – This is not that hard to use, does what I need but how well supported is it? Will it work with JDK 6, I think so. Java Telnet Application (jta26) – This was easy to use but I’m not sure how versatile it is. I didn’t see any place to set a timeout value in the TelnetWrapper. I also was not sure if this code is being maintained since the last update to the site was in 2005. (<http://www.javassh.org>) I know this is somewhat opinion oriented and hope SO is a good place to help me make a decision so I don’t start down one road and find out later it’s not what I’m looking for. Thanks.
Found what I was looking for here: <http://twit88.com/blog/2007/12/22/java-writing-an-automated-telnet-client/> **You will need to modify the prompt variable.** Copy of code: ``` import org.apache.commons.net.telnet.TelnetClient; import java.io.InputStream; import java.io.PrintStream; public class AutomatedTelnetClient { private TelnetClient telnet = new TelnetClient(); private InputStream in; private PrintStream out; private String prompt = "%"; public AutomatedTelnetClient(String server, String user, String password) { try { // Connect to the specified server telnet.connect(server, 23); // Get input and output stream references in = telnet.getInputStream(); out = new PrintStream(telnet.getOutputStream()); // Log the user on readUntil("login: "); write(user); readUntil("Password: "); write(password); // Advance to a prompt readUntil(prompt + " "); } catch (Exception e) { e.printStackTrace(); } } public void su(String password) { try { write("su"); readUntil("Password: "); write(password); prompt = "#"; readUntil(prompt + " "); } catch (Exception e) { e.printStackTrace(); } } public String readUntil(String pattern) { try { char lastChar = pattern.charAt(pattern.length() - 1); StringBuffer sb = new StringBuffer(); boolean found = false; char ch = (char) in.read(); while (true) { System.out.print(ch); sb.append(ch); if (ch == lastChar) { if (sb.toString().endsWith(pattern)) { return sb.toString(); } } ch = (char) in.read(); } } catch (Exception e) { e.printStackTrace(); } return null; } public void write(String value) { try { out.println(value); out.flush(); System.out.println(value); } catch (Exception e) { e.printStackTrace(); } } public String sendCommand(String command) { try { write(command); return readUntil(prompt + " "); } catch (Exception e) { e.printStackTrace(); } return null; } public void disconnect() { try { telnet.disconnect(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { try { AutomatedTelnetClient telnet = new AutomatedTelnetClient( "myserver", "userId", "Password"); System.out.println("Got Connection..."); telnet.sendCommand("ps -ef "); System.out.println("run command"); telnet.sendCommand("ls "); System.out.println("run command 2"); telnet.disconnect(); System.out.println("DONE"); } catch (Exception e) { e.printStackTrace(); } } } ```
Have you looked at [the Sadun utils library](http://sadun-util.sourceforge.net/telnet_library.html)? I used it once to open a telnet session to a server and send some commands, read a response, and close the connection, it worked fine and it's LGPL
Looking for Java Telnet emulator
[ "", "java", "telnet", "" ]
I'm struggling with a little internationalization issue in one of my apps. The story goes like this: I have a datatable which displays records, and a selectOneMenu in order to select a column of the dataTable to be filtered for. The selectOne is fed with SelectItems which are filled according to the actual locale in the backing bean on DataRefresh time. Now, when the user changes the locale the contents of the selectOne stay in the old locale until the page is rerendered. This is quite logical and expected. Of course I want that to change. So I tried writing an own selectOne which uses selectItems which contain references to languageFile entries in order to be able to change them without rerendering. Here's what I tried ``` <select id="j_id5:filterSelector" name="j_id5:filterSelector" size="1"> <c:forEach var="item" items="#{gridBean.filterFields}"> <option value="#{item.Value}">#{msg[item.Label]}</option> </c:forEach> </select> ``` Sadly JSF tells me the item does not have a Label or Value property, which I hardly believe. ;) Does anyone's got an idea how to access thise properties this way?
I solved the issue with storing the filterfields twice. Once for each language - runtime decission which is rendered. Not a nice one, but it works. Could'nt get the changeListener going...
It seems to me you should write: ``` #{item.value} ``` instead of `#{item.Value}`, as standard JavaBeans convention is to have `getXyz()` getter for `xyz` property. Also, why don't you provide a `valueChangeListener` to the UI component for locale selection, and then, inside it, populate the select item labels for that locale. That way you can use standard `f:selectItems` tag.
Accessing JSF SelectItem.Label and Value from XHTML without selectOneMenu
[ "", "java", "jsf", "foreach", "selectonemenu", "" ]
Is there a quick way to make Eclipse put curly brace on the next line (by itself) on a block of code?
For pre-written block of code, first do the settings as suggested by Don and then select that piece of code and right click Source Code->Format and the formatting would take place as per the settings done in the preferences.
Yes, edit your active profile (Java...Code Style...Formatter), and change the brace positions to the next line. Also, in Java..Editor..Typing, you can have it automatically insert your braces at the correct position.
Eclipse and curly braces
[ "", "java", "eclipse", "" ]
i am having trouble splitting a string in c# with a delimiter of "][". For example the string "abc][rfd][5][,][." Should yield an array containing; abc rfd 5 , . But I cannot seem to get it to work, even if I try RegEx I cannot get a split on the delimiter. EDIT: Essentially I wanted to resolve this issue without the need for a Regular Expression. The solution that I accept is; ``` string Delimiter = "]["; var Result[] = StringToSplit.Split(new[] { Delimiter }, StringSplitOptions.None); ``` I am glad to be able to resolve this split question.
To show both `string.Split` and `Regex` usage: ``` string input = "abc][rfd][5][,][."; string[] parts1 = input.Split(new string[] { "][" }, StringSplitOptions.None); string[] parts2 = Regex.Split(input, @"\]\["); ```
``` string tests = "abc][rfd][5][,][."; string[] reslts = tests.Split(new char[] { ']', '[' }, StringSplitOptions.RemoveEmptyEntries); ```
string.split - by multiple character delimiter
[ "", "c#", "split", "" ]
Is there a simple way to implement this, and if possible without instanciating an object : ``` interface I { static string GetClassName(); } public class Helper { static void PrintClassName<T>() where T : I { Console.WriteLine(T.GetClassName()); } } ```
Try an extension method instead: ``` public interface IMyInterface { string GetClassName(); } public static class IMyInterfaceExtensions { public static void PrintClassName<T>( this T input ) where T : IMyInterface { Console.WriteLine(input.GetClassName()); } } ``` This allows you to add static extension/utility method, but you still need an instance of your IMyInterface implementation. You can't have interfaces for static methods because it wouldn't make sense, they're utility methods without an instance and hence they don't really have a type.
You can not inherit static methods. Your code wouldn't compile in any way, because a interface can't have static methods because of this. As quoted from [littleguru](http://channel9.msdn.com/forums/TechOff/250972-Static-Inheritance/?CommentID=274217): > Inheritance in .NET works only on > instance base. Static methods are > defined on the type level not on the > instance level. That is why overriding > doesn't work with static > methods/properties/events... > > Static methods are only held once in > memory. There is no virtual table etc. > that is created for them. > > If you invoke an instance method in > .NET, you always give it the current > instance. This is hidden by the .NET > runtime, but it happens. Each instance > method has as first argument a pointer > (reference) to the object that the > method is run on. This doesn't happen > with static methods (as they are > defined on type level). **How should > the compiler decide to select the > method to invoke?**
C# interface static method call with generics
[ "", "c#", "generics", "inheritance", "interface", "static", "" ]
I'm wanting to convert the output from gethrtime to milliseconds. The obvious way to do this is to divide by 1000000. However, I'm doing this quite often and wonder if it could become a bottleneck. Is there an optimized divide operation when dealing with numbers like 1000000? Note: Any code must be portable. I'm using gcc and this is generally on Sparc hardware Some quick testing using the code below... hope that is right. ``` #include <sys/time.h> #include <iostream> using namespace std; const double NANOSECONDS_TO_MILLISECONDS = 1.0 / 1000000.0; int main() { hrtime_t start; hrtime_t tmp; hrtime_t fin; start = gethrtime(); tmp = (hrtime_t)(start * NANOSECONDS_TO_MILLISECONDS); fin = gethrtime(); cout << "Method 1" cout << "Original val: " << start << endl; cout << "Computed: " << tmp << endl; cout << "Time:" << fin - start << endl; start = gethrtime(); tmp = (start / 1000000); fin = gethrtime(); cout "Method 2" cout << "Original val: " << start << endl; cout << "Computed: " << tmp << endl; cout << "Time:" << fin - start << endl; return 0; } ``` Example outputs: ``` Original val: 3048161553965997 Computed: 3048161553 Time:82082 Original val: 3048161556359586 Computed: 3048161556 Time:31230 Original val: 3048239663018915 Computed: 3048239663 Time:79381 Original val: 3048239665393873 Computed: 3048239665 Time:31321 Original val: 3048249874282285 Computed: 3048249874 Time:81812 Original val: 3048249876664084 Computed: 3048249876 Time:34830 ``` If this is correct, then the multiple by reciprocal is actually slower in this case. It's probably due to using floating point math instead of fixed point math. I will just stick to integer division then which still takes hardly any time at all.
Division is *not* an expensive operation. I doubt very much if a divide-by-1000000 operation will be anywhere near the main bottleneck in your application. Floating-point processors will be way faster than any sort of "tricks" you can come up with than just doing the single operation.
Let your compiler figure it out! Seriously, if you're really concerned about optimizations at this level (and you shouldn't be unless it shows up in a profile), you should get used to looking at your compiler's assembly language output. You will be amazed what the compiler is doing on your behalf. All the people who are recommending math tricks either have bad compilers or they are underestimating their compilers. For example, try compiling this function: ``` unsigned long div1000000(unsigned long n) { return n / 1000000UL; } ``` Compiled with gcc 4.3.3 on x86 (-O3, -fomit-frame-pointer), I get: ``` $ objdump -d div.o -M intel test2.o: file format elf32-i386 Disassembly of section .text: 00000000 <div1000000>: 0: b8 83 de 1b 43 mov eax,0x431bde83 5: f7 64 24 04 mul DWORD PTR [esp+0x4] 9: c1 ea 12 shr edx,0x12 c: 89 d0 mov eax,edx e: c3 ret ``` In other words, the compiler took `n / 1000000UL` and turned it into `(unsigned long long)(n * 0x431bde83) >> (0x12 + 32)`. Why does that work? Off the top of my head, I have no idea! But the compiler decided that it would be faster than issuing a native divide. Moral of the story: * don't optimize this unless you're sure it's a bottleneck. * don't do fancy arithmetic (multiplying by the reciprocal, shifts, etc) unless you already know what your compiler is doing and you think you can beat it. * benchmark the result -- only leave in a wart like fancy bitmath if you have demonstrated that you've outdone your compiler.
nanoseconds to milliseconds - fast division by 1000000
[ "", "c++", "gcc", "solaris", "sparc", "" ]
What does the following line mean, particularly the operator `.=`? ``` $query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;"; ``` in [the code](https://www.php.net/manual/en/function.pg-query.php) ``` <?php $conn = pg_pconnect("dbname=publisher"); // these statements will be executed as one transaction $query = "UPDATE authors SET author=UPPER(author) WHERE id=1;"; $query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;"; pg_query($conn, $query); ?> ``` It seems to make some sort of array such that the last command processes first the first query and then the second.
This is the concatenate assignment operator. It will concatenate or add to the end of the string. So: ``` $a = "Hi!"; $a .= " I"; $a .= " love"; $a .= " StackOverflow"; $a .= " a"; $a .= " lot"; echo $a; // echos "Hi! I love StackOverflow a lot" ``` In your case ``` $query = "UPDATE authors SET author=UPPER(author) WHERE id=1;"; $query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;"; echo $query; /* echos "UPDATE authors SET author=UPPER(author) WHERE id=1; UPDATE authors SET author=LOWER(author) WHERE id=2; */ ```
It means `$query = $query . "UPDATE authors SET author=LOWER(author) WHERE id=2;";` So it appends the String to the Query Variable.
What is the .= (dot equals) operator in PHP?
[ "", "php", "" ]
I have a device that a user interacts with alongside of a C# WPF program. This program must beep when the user presses a button on the device, for either a specified amount of time or for as long as the user presses the button, whichever is shorter. The only speaker available to produce the beep/tone is the computer BIOS speaker; we cannot assume that other speakers are around (and it's actually safe to assume that there won't be any other speakers). How can I produce a continuous tone for the necessary duration? What I have so far produces lots of beeps, but not a continuous tone. First, a thread is started: ``` private void UserControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { if(this.Visibility == Visibility.Visible){ mBeepThread = new Thread(new ThreadStart(ProduceTone)); mBeepThread.Name = "Beep Thread"; mBeepThread.Start(); } } ``` The thread itself: ``` bool mMakeTone = false; private void ProduceTone(){ while(this.Visibility == Visibility.Visible){ if(mMakeTone ){ Console.Beep(); } else{ Thread.Sleep(10); } } } ``` And then the mMakeTone boolean is flipped to true during the duration of the button press, up to a time specified by the device itself. I suspect that it's just a quick change to the Console.Beep() line above, but I'm not sure what it would be.
There is an overload for Console.Beep that takes a frequency and duration, which is useful if you want to produce a sound for a specified duration. The ability to turn on a sound and then later turn it off using the BIOS speaker is not directly supported by the Console.Beep method, or any other API that I am aware of, without perhaps installing a fake sound card driver. A little experimentation has discovered the following: * Console.Beep() is synchronous and does not return until the sound is finished. * Calling Console.Beep() from a separate thread interrupts whatever is currently in progress. So... You should be able to accomplish your task by creating a new background thread to call Console.Beep() with the frequency of your choosing and a very long duration. To later terminate the sound, you may just call Console.Beep() on your main thread with any frequency and an extremely, non-zero duration (e.g. 1) to terminate the sound playing from the background thread. You should not make the sound playing on the background thread any longer that a reasonable duration because the thread will live until the sound would have ordinarily stopped playing and you don't want a lot of background threads piling up on you. ``` private void button1_Click(object sender, EventArgs e) { // Starts beep on background thread Thread beepThread = new Thread(new ThreadStart(PlayBeep)); beepThread.IsBackground = true; beepThread.Start(); } private void button2_Click(object sender, EventArgs e) { // Terminates beep from main thread Console.Beep(1000, 1); } private void PlayBeep() { // Play 1000 Hz for 5 seconds Console.Beep(1000, 5000); } ```
If you have a wave file of a continuous sound, you could use a SoundPlayer: ``` SoundPlayer player = new SoundPlayer(); player.SoundLocation = @"C:\Program Files\MyApp\sound.wav"; player.PlayLooping(); ... // Later, when you know it's time to stop the sound: player.Stop(); ``` I don't know if you would be able to hear the start and stop. If that won't work for you, you probably need to go down a level to Win32 calls. You might want to look at [Multimedia Audio](http://msdn.microsoft.com/en-us/library/ms712572(VS.85).aspx) or [DirectSound](http://msdn.microsoft.com/en-us/library/bb219818(VS.85).aspx).
C#: Produce a continuous tone until interrupted
[ "", "c#", "beep", "" ]
Per my other [question here about Disposable objects](https://stackoverflow.com/questions/1033334/is-there-a-list-of-common-object-that-implement-idisposable-for-the-using-stateme), should we call Close() before the end of a using block? ``` using (SqlConnection connection = new SqlConnection()) using (SqlCommand command = new SqlCommand()) { command.CommandText = "INSERT INTO YourMom (Amount) VALUES (1)"; command.CommandType = System.Data.CommandType.Text; connection.Open(); command.ExecuteNonQuery(); // Is this call necessary? connection.Close(); } ```
Since you have a using block, the Dispose method of the SQLCommand will be called and it will close the connection: ``` // System.Data.SqlClient.SqlConnection.Dispose disassemble protected override void Dispose(bool disposing) { if (disposing) { this._userConnectionOptions = null; this._poolGroup = null; this.Close(); } this.DisposeMe(disposing); base.Dispose(disposing); } ```
Disassembly of SqlConnection from using [.NET Reflector](http://www.red-gate.com/products/reflector/): ``` protected override void Dispose(bool disposing) { if (disposing) { this._userConnectionOptions = null; this._poolGroup = null; this.Close(); } this.DisposeMe(disposing); base.Dispose(disposing); } ``` It calls Close() inside of Dispose()
Do I have to Close() a SQLConnection before it gets disposed?
[ "", "c#", "asp.net", "using", "sqlconnection", "sqlcommand", "" ]
I have a product table with 100000 products and also I have a user table with 5000 records. and suppose a user can give us feedback about any combination of this products. So suppose he chooses to compare products 1,3,100,200,400,500 and so on. (he can send us another feedback about some other products) So here is my question, I just want to know what an expert database designer would think about this situation where the number of products and users are big. One way to store this ratings are in a single string like: 1#5 3#4 100#5 .... x#y means that he gave y stars to product with id of x. I can load this vote\_string in my php script for example and extract the details of it. So the rating table would likely have this structure: id, user\_id, vote\_string Another way is to store this feedback in this structure: **vote Table:** id, user\_id, date **vote\_details Table:** vote\_id, product\_id, vote ==> (vote\_id,products\_id) as primary key and vote\_id is foreign key. (or may these 2 tables can be compressed in a single table like id,user\_id,product\_id,vote [id,user\_id,product\_id] as primary key) So i guess it's very easier to query in the second design but it consumes more space and time for each query, also in case of product deletion it's quite better to use the second design. What would you do? Any kind of idea is appriciated.
you almost never want to go down the road of concatenating strings in database land. Just makes life really painful for doing queries - and also, not really the way that DB's are designed to process data. think that you want your second approach. You need to think about primary keys and the like {i.e can the same person vote for a product twice?}
By storing it as a string, like 1#5 3#4 100#5, you are making it harder later to create reports. You also have to do some string manipulation every time you need to use the data. For a simple structure like this I don't see the benefit. I would go for one table (id, userid, productid, vote), but I'm sure two is fine as well.
Storing an array in a string (Database experts question)
[ "", "sql", "mysql", "database", "database-design", "" ]
I found the source of the problem #2. It is the use of *session\_register(foo)*. I put the following to my *handle\_registration.php*. ``` session_register("foo"); session_register("foo2"); $foo2 = $_POST['email']; $foo['email'] = $_POST['email'] ``` The problem still persists, since no variables are stored to my session cookie. --- This is the logic of my [login script](https://stackoverflow.com/questions/415005/php-session-variables-not-carrying-over-to-my-logged-in-page-but-session-id-is/415017#415017). 1. **Solved by [Pascal Martin](https://stackoverflow.com/questions/1270005/to-set-up-a-login-system-by-sessions-in-php/1270063#1270063) and [The Disintegrator](https://stackoverflow.com/questions/1270005/to-set-up-a-login-system-by-sessions-in-php/1270021#1270021):** *Which is the right place to put the function `session_write_close` in generating sessions for login?* 2. How can you get a permanent session for user "session" such that a new session is not started each time index.php is loaded? I have the `session_start()` at the beginning of my `index.php`. **The very Beginning of my index.php** ``` session_start(); if($_SESSION['logged_in'] == false) { $random_number = rand(1,100000); session_id($random_number); session_id['email'] = ''; } ``` while the very end of my index.php ``` <?php session_write_close(); // Session code ends here! ?> ``` I have right after the very beginning of the session code the validation process of user's password by ``` $dbconn = pg_connect("host=localhost port=5432 dbname=masi user=masi password=123"); $result = pg_prepare($dbconn, "query22", "SELECT passhash_md5 FROM users WHERE email=$1;"); $passhash_md5 = pg_execute($dbconn, "query22", array($_REQUEST['email'])); // users from registration/login form if ($passhash_md5 == md5($_REQUEST['password'])) { $_SESSION['logged_in'] = true; $_SESSION['email'] = $_REQUEST['email']; $_SESSION['passhash_md5'] = md5($_REQUEST['password']); } // this may be unnecessary if the passhash_md5 cannot be changed by the user $passhash_md5_2 = pg_execute($dbconn, "query22", array($_SESSION['email'])); // users staying in the site if ($passhash_md5_2 == $_SESSION['passhash_md5'])) { $_SESSION['logged_in'] = true; } ``` The code generates me continuously random sessions such that no user's data is being saved for the user. I replaced each `$_REQUEST` after the login/registration handlers by `$_SESSION` in my code, since `$_REQUEST` does not include $\_SESSION - still the same problem and I cannot see the username in the homepage after registration/login.
Your code looks like this : ``` -- content cut -- </html> <?php session_regenerate_id(true); // Session code ends here! session_write_close(); ?> ``` You definitly have some output (the whole content of your page, actually) before `session_regenerate_id` is called ; hence the error. The problem is not with "empty lines" or spaces : it is with **output** ; and **HTML is output** ;-) Like the call to `session_start`, the call to `session_regenerate_id` should be done at the beginning of the script, before anything is sent to the browser. So, here, in the block at the "top" of your `index.php`. --- **EDIT : more thoughts.** BTW? I'm not sure you actually need to call [`session_write_close`](http://php.net/session_write_close) ; I've probably never used that function, I believe... And, quoting the doc : > Session data is usually stored after > your script terminated without the > need to call session\_write\_close() The only case you might need to call this function yourself is if you are doing long calculations : > session data is locked to prevent > concurrent writes only one script may > operate on a session at any time. When > using framesets together with sessions > you will experience the frames loading > one by one due to this locking. You > can reduce the time needed to load all > the frames by ending the session as > soon as all changes to session > variables are done. But this doesn't seem to be your case, as you are calling this at the end of your script. So, you could try removing the *(useless ?)* call to that function... And, about [`session_regenerate_id`](http://php.net/session_regenerate_id) : do you really need to call this function on each page ? I suppose never calling it would be enough for your site to work... Even if you might want to call it when the user logs in, for security precautions (If I remember correctly, it's nice to call this function whenever the privileges level of a user changes) Same about [session\_id](http://php.net/session_id), btw : do you really need to call this function on each page ?
You should use output buffering to prevent this ``` <?php ob_start(); everything here ob_end_flush(); ?> ``` You can't send headers once the normal output takes place.
To set up a login system by Sessions in PHP
[ "", "php", "session", "authentication", "" ]
We are planning to develop a client server application using C# and MySQL. We plan to sell the product on the shelf like any other software utility. We are worried about the decompilation of our product which does have some sort of edge over our competitors in terms of usability and bundled functionality. How can we prevent our software from decompilation, so the business logic of the product remains intact? We have heard about Reflector and other decompilers which makes our code very much vulnerable for copying. Our customer base is not Corporates but medical practitioners who themselves may not do it but our competitors may want to copy/disable licensing or even replicate the code/functionality so the value of our product goes down in the market. Any suggestion to prevent this is most welcome.
If you deploy .NET assemblies to your client machines, some kind of decompilation will always be possible using reflector and similar tools. However, this situation isn't materially different to what you'd encounter if you wrote the application in native C++. It is always possible to decompile things - if it were impossible, the processor couldn't understand it either. You're never going to defeat the expert cracker - they'll treat your security as an intellectual puzzle to be solved for the challenge alone. The question revolves around how hard it is to defeat your licensing practices and the *return on investment*. Sit down with a spreadsheet and look through the possible scenarios - the danger is probably less than you think. Factors like "ease of use" are visible in your software for any user to observe - so you'd think it easy to copy. But, good User experience is rare (and seldom copied well), because most developers (myself included) are nothing like typical users. I'd suggest you concentrate on making the job of a cracker harder, cause you can never make it impossible, just non-profitable. One possibility to try: It's possible to pre-compile assemblies into native code as a part of the installation process. Paint.NET does this for performance reasons. I believe that once you've done this, you can discard the original assemblies and use the optimised, native code editions.
If it were me, I wouldn't be attempt to obfuscate; I would: 1. Not worry about it and aim to continually improve and stay in front But secondly 2. Consider providing the 'secret' services over the Web. It's up to you to decide how critical and possible this is; but it does "prevent" decompilation, because the end user doesn't even have the code.
How to prevent decompilation of any C# application
[ "", "c#", "licensing", "obfuscation", "decompiling", "piracy-prevention", "" ]
Does anyone know is it possible to assign an object into cookies in javascript? If yes, how can we do it?
If you can serialize your object into its canonical string representation, and can unserialize it back into its object form from said string representation, then yes you can put it into a cookie. Judging from your [earlier question](https://stackoverflow.com/questions/1275888/any-way-that-i-can-assign-window-openurl-into-cookies-array-in-javascript) regarding storing the result of `window.open()` into a cookie, this is not the answer you are hoping for.
This is one way to do it, 1. Serialize your object into JSON. 2. Base64 encode the JSON. 3. Use the Base64 encoded string as the cookie value. Just reverse the process when reading the cookie. You have to use Version 1 cookies because Base64 character sets needs to be quoted. If you want use old Netscape style cookie, you need to use an URL-safe Base64 encoder. Of course, this is only good for small objects.
can we assign object into cookie in javascript?
[ "", "javascript", "" ]
I see code like this ``` class A implements Comparable<A> { } ``` What does this mean, what are the advantages and disadvantages of it?
It means that class is committed to respond to the methods defined by the "[interface](http://java.sun.com/docs/books/tutorial/java/concepts/interface.html)" [Comparable](http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html). The advantage you have with this ( and any other "implements" declaration ) it that you can "[abstract](http://en.wikipedia.org/wiki/Data_abstraction)" the type of the object and code to the interface instead. Consider this ``` class A implements Comparable { .... } class B implements Comparable { .... } class C implements Comparable { .... } ``` You then may code something that can use [Comparable](http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html) instead of a specific type: ``` public void doSomethingWith( Comparable c ) { c.compareTo( other ); // something else... } ``` And invoke it like: ``` doSomethingWith( new A() ); doSomethingWith( new B() ); doSomethingWith( new C() ); ``` Because you don't really care what the type of the class is, you just care it does implement the interface. This ( program to the interface rather to the implementation ) is one of the most powerful techniques in OO programming world, because it promotes [low-coupling](http://en.wikipedia.org/wiki/Coupling_%28computer_science%29).
It means that the class is one which can be operated on by functions which expect their arguments to be objects that can be compared with other objects of the same type (such as the pre-defined sorting functionality for lists). Implementing the Comparable interface means that the class supports certain functions which the interface requires (specifically, the `compareTo()` method), that the sorting (or other) operations being performed on the class will utilize to do their work without having to care about the rest of the class. For more details: <http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Comparable.html>
In java what does extending from a comparable mean
[ "", "java", "comparable", "" ]
Here is a problem that has had me completely baffled for the past few hours... I have an equation hard coded in my program: ``` double s2; s2 = -(0*13)/84+6/42-0/84+24/12+(6*13)/42; ``` Every time i run the program, the computer spits out 3 as the answer, however doing the math by hand, i get 4. Even further, after inputting the equation into Matlab, I also get the answer 4. Whats going on here? The only thing i can think of that is going wrong here would be round off error. However with a maximum of 5 rounding errors, coupled with using double precision math, my maximum error would be very very small so i doubt that is the problem. Anyone able to offer any solutions? Thanks in advance, -Faken
You're not actually doing floating point math there, you're doing integer math, which will floor the results of divisions. In C++, 5/4 = 1, *not* 1.25 - because 5 and 4 are both integers, so the result will be an integer, and thus the fractional part of the result is thrown away. On the other hand, 5.0/4.0 will equal approx. 1.25 because at least one of 5.0 and 4.0 is a floating-point number so the result will also be floating point.
You're confusing integer division with floating point division. 3 is the correct answer with integer division. You'll get 4 if you convert those values to floating point numbers.
Incorrect floating point math?
[ "", "c++", "floating-point", "" ]
I have two tables of ID's and dates and I want to order both tables by date and see those ids that are not in the same order e.g. table\_1 ``` id | date ------------ A 01/01/09 B 02/01/09 C 03/01/09 ``` table\_2 ``` id | date ------------ A 01/01/09 B 03/01/09 C 02/01/09 ``` and get the results ``` B C ``` Now admittedly I could just dump the results of an order by query and diff them, but I was wondering if there is an SQL-y way of getting the same results. Edit to clarify, the dates are not necessarily the same between tables, it's just there to determine an order Thanks
if the dates are different in `TABLE_1` and `TABLE_2`, you will have to join both tables on their rank. For exemple: ``` SQL> WITH table_1 AS ( 2 SELECT 'A' ID, DATE '2009-01-01' dt FROM dual UNION ALL 3 SELECT 'B', DATE '2009-01-02' FROM dual UNION ALL 4 SELECT 'C', DATE '2009-01-03' FROM dual 5 ), table_2 AS ( 6 SELECT 'A' ID, DATE '2009-01-01' dt FROM dual UNION ALL 7 SELECT 'C', DATE '2009-01-02' FROM dual UNION ALL 8 SELECT 'B', DATE '2009-01-03' FROM dual 9 ) 10 SELECT t1.ID 11 FROM (SELECT ID, row_number() over(ORDER BY dt) rn FROM table_1) t1 12 WHERE (ID, rn) NOT IN (SELECT ID, 13 row_number() over(ORDER BY dt) rn 14 FROM table_2); ID -- B C ```
Is it not just the case of joining on the date and comparing the IDs are the same. This assumes that table\_1 is the master sequence. ``` SELECT table_1.id FROM table_1 INNER JOIN table_2 on table_1.[date] = table_2.[date] WHERE table_1.id <> table_2.id ORDER BY table_1.id ```
SQL - Finding differences in row order of two tables
[ "", "sql", "oracle", "sql-order-by", "" ]
Is there a way to convert a string to a string that will display properly in a web document? For example, changing the string ``` "<Hello>" ``` To ``` "&lt;Hello&gt;" ```
`StringEscapeUtils` has functions designed exactly for this: <http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringEscapeUtils.html>
That's usually called "HTML escaping". I'm not aware of anything in the standard libraries for doing this (though you can approximate it by using XML escaping). There are lots of third-party libraries that can do this, however. [StringEscapeUtils](http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/StringEscapeUtils.html) from org.apache.commons.lang has a `escapeHtml` method that can do this.
How to escape HTML special characters in Java?
[ "", "java", "html", "" ]
Ok so here is my issue. I have to `HashSet`'s, I use the `removeAll` method to delete values that exist in one set from the other. Prior to calling the method, I obviously add the values to the `Set`s. I call `.toUpperCase()` on each `String` before adding because the values are of different cases in both lists. There is no rhyme or reason to the case. Once I call `removeAll`, I need to have the original cases back for the values that are left in the `Set`. Is there an efficient way of doing this without running through the original list and using `CompareToIgnoreCase`? Example: List1: ``` "BOB" "Joe" "john" "MARK" "dave" "Bill" ``` List2: ``` "JOE" "MARK" "DAVE" ``` After this, create a separate `HashSet` for each List using `toUpperCase()` on `String`s. Then call `removeAll`. ``` Set1.removeAll(set2); Set1: "BOB" "JOHN" "BILL" ``` I need to get the list to look like this again: ``` "BOB" "john" "Bill" ``` Any ideas would be much appreciated. I know it is poor, there should be a standard for the original list but that is not for me to decide.
In my original answer, I unthinkingly suggested using a `Comparator`, but this causes the `TreeSet` to violate the [`equals` contract](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#equals(java.lang.Object)) and is a bug waiting to happen: ``` // Don't do this: Set<String> setA = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); setA.add("hello"); setA.add("Hello"); System.out.println(setA); Set<String> setB = new HashSet<String>(); setB.add("HELLO"); // Bad code; violates symmetry requirement System.out.println(setB.equals(setA) == setA.equals(setB)); ``` --- It is better to use a dedicated type: ``` public final class CaselessString { private final String string; private final String normalized; private CaselessString(String string, Locale locale) { this.string = string; normalized = string.toUpperCase(locale); } @Override public String toString() { return string; } @Override public int hashCode() { return normalized.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof CaselessString) { return ((CaselessString) obj).normalized.equals(normalized); } return false; } public static CaselessString as(String s, Locale locale) { return new CaselessString(s, locale); } public static CaselessString as(String s) { return as(s, Locale.ENGLISH); } // TODO: probably best to implement CharSequence for convenience } ``` This code is less likely to cause bugs: ``` Set<CaselessString> set1 = new HashSet<CaselessString>(); set1.add(CaselessString.as("Hello")); set1.add(CaselessString.as("HELLO")); Set<CaselessString> set2 = new HashSet<CaselessString>(); set2.add(CaselessString.as("hello")); System.out.println("1: " + set1); System.out.println("2: " + set2); System.out.println("equals: " + set1.equals(set2)); ``` This is, unfortunately, more verbose.
It could be done by: 1. Moving the content of your lists into case-insensitive `TreeSet`s, 2. then removing all common `String`s case-insensitively thanks `TreeSet#removeAll(Collection<?> c)` 3. and finally relying on the fact that `ArrayList#retainAll(Collection<?> c)` will iterate over the elements of the list and for each element it will call `contains(Object o)` on the provided collection to know whether the value should be kept or not and here as the collection is case-insensitive, we will keep only the `String`s that match case-insensitively with what we have in the provided `TreeSet` instance. The corresponding code: ``` List<String> list1 = new ArrayList<>( Arrays.asList("BOB", "Joe", "john", "MARK", "dave", "Bill") ); List<String> list2 = Arrays.asList("JOE", "MARK", "DAVE"); // Add all values of list1 in a case insensitive collection Set<String> set1 = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); set1.addAll(list1); // Add all values of list2 in a case insensitive collection Set<String> set2 = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); set2.addAll(list2); // Remove all common Strings ignoring case set1.removeAll(set2); // Keep in list1 only the remaining Strings ignoring case list1.retainAll(set1); for (String s : list1) { System.out.println(s); } ``` **Output:** ``` BOB john Bill ``` **NB 1:** It is important to have the content of the second list into a `TreeSet` especially if we don't know the size of it because the behavior of `TreeSet#removeAll(Collection<?> c)` depends on the size of both collections, if the size of the current collection is strictly bigger than the size of the provided collection, then it will call directly `remove(Object o)` on the current collection to remove each element, in this case the provided collection could be a list. But if it is the opposite, it will call `contains(Object o)` on the provided collection to know whether a given element should be removed or not so if it is not an case-insensitive collection, we won't get the expected result. **NB 2:** The behavior of the method `ArrayList#retainAll(Collection<?> c)` described above is the same as the behavior of the default implementation of the method `retainAll(Collection<?> c)` that we can find in `AbstractCollection` such that this approach will actually work with any collections whose implementation of `retainAll(Collection<?> c)` has the same behavior.
Collection removeAll ignoring case?
[ "", "java", "collections", "case-insensitive", "hashset", "" ]
I've been using Zend Framework and just living with this problem for a while, but it's now just gotten too annoying so i'll send the question out to you. There are certain problems within the Zend framework that Zend can recognize (such as calling a nonexistent controller), and will send that problem to the ErrorController. I've got that working fine. There seem to be some problems that Zend Framework will fail and display the error through php, like if a certain function doesn't exist or something. Those I can see and fix. Sometimes though, Zend won't fail, but it will also just send out an empty response. I will get a blank page. They layout doesn't show up, there's no code, there's no nothing to give me an idea of what's gone wrong. Last time, there was a require() that failed. I had to manually figure this out with no feedback. Have any of you experienced this? Do you have any advice on how to get these errors to show? Any help would be appreciated!
The internal error handling of the framework's MVC components can only trap Exceptions, not PHP errors. To assist in debugging during development, you can use the standard: ``` error_reporting(E_ALL|E_STRICT); ini_set('display_errors', 'on'); ``` Also, if you're using the new Autoloader included with 1.8, use: ``` Zend_Loader_Autoloader::getInstance()->suppressNotFoundWarnings(false); ``` To allow failed include/require statements to be issued.
For others coming across this question: I changed the following line in configs/application.ini ``` resources.frontController.params.displayExceptions = 0 ``` To: ``` resources.frontController.params.displayExceptions = 1 ``` This allowed me to see the full Exception, including stacktrace.
Display php errors when using Zend framework
[ "", "php", "zend-framework", "" ]
> **Possible Duplicate:** > [Casting: (NewType) vs. Object as NewType](https://stackoverflow.com/questions/2483/casting-newtype-vs-object-as-newtype) Say for example I have a class called MyObjectType and I want to convert the sender parameter of an event to this type. I would usually go about it by simply doing this: ``` MyObjectType senderAsMyType = (MyObjectType) sender; ``` I've recently realised that it can also be done like this: ``` MyObjectType senderAsMyType = sender as MyObjectType; ``` Which way is most efficient? So that I can make my code consistent and use one of the ways throughout. Or do they both have pro's and cons? If so please could someone inform me of them. Thanks again,
If you wish to avoid any `InvalidCastExceptions` use ``` MyObjectType senderAsMyType = sender as MyObjectType; ``` otherwise use ``` MyObjectType senderAsMyType = (MyObjectType)sender; ``` if an `InvalidCastException` represents a true exceptional situation in your application. As for performance, I would contend that you would find no discernible difference between the two different kinds of casting. I *was* interested though so I used [Jon Skeet's BenchmarkHelper](http://msmvps.com/blogs/jon_skeet/archive/2009/01/26/benchmarking-made-easy.aspx) and achieved results that confirmed my suspicions: **Test:** ``` using System; using BenchmarkHelper; class Program { static void Main() { Object input = "test"; String output = "test"; var results = TestSuite.Create("Casting", input, output) .Add(cast) .Add(asCast) .RunTests() .ScaleByBest(ScalingMode.VaryDuration); results.Display(ResultColumns.NameAndDuration | ResultColumns.Score, results.FindBest()); } static String cast(Object o) { return (String)o; } static String asCast(Object o) { return o as String; } } ``` **Output:** ``` ============ Casting ============ cast 30.021 1.00 asCast 30.153 1.00 ```
I think this answer will help... [Casting: (NewType) vs. Object as NewType](https://stackoverflow.com/questions/2483/casting-newtype-vs-object-as-newtype)
Should I use (ObjectType) or 'as ObjectType' when casting in c#?
[ "", "c#", "casting", "" ]
I have the following json string and I want to retrieve just the email address from it. How do I do it in php? ``` {"communications":{"communication":[{"@array":"true","@id":"23101384","@uri":"xyz/v1/Communications/1111","household":{"@id":"111111","@uri":"xyz/v1/Households/5465465"},"person":{"@id":"","@uri":""},"communicationType":{"@id":"1","@uri":"xyz/v1/Communications/CommunicationTypes/1","name":"Home Phone"},"communicationGeneralType":"Telephone","communicationValue":"1111","searchCommunicationValue":"2693240758","listed":"true","communicationComment":null,"createdDate":"2008-11-10T12:31:26","lastUpdatedDate":"2009-08-11T23:40:02"},{"@array":"true","@id":"11111","@uri":"xyz/v1/Communications/111111111","household":{"@id":"14436295","@uri":"xyz/v1/Households/11111"},"person":{"@id":"2222222","@uri":"xyz/v1/People/22222222"},"communicationType":{"@id":"2","@uri":"xyz/v1/Communications/CommunicationTypes/2","name":"Work Phone"},"communicationGeneralType":"Telephone","communicationValue":"11111","searchCommunicationValue":"789787987","listed":"false","communicationComment":null,"createdDate":"2009-08-09T15:49:27","lastUpdatedDate":"2009-08-11T23:40:02"},{"@array":"true","@id":"11111","@uri":"xyz/v1/Communications/11111","household":{"@id":"1111","@uri":"xyz/v1/Households/1111"},"person":{"@id":"244404","@uri":"xyz/v1/People/1111"},"communicationType":{"@id":"3","@uri":"xyz/v1/Communications/CommunicationTypes/3","name":"Mobile"},"communicationGeneralType":"Telephone","communicationValue":"22222","searchCommunicationValue":"5475454","listed":"true","communicationComment":null,"createdDate":"2008-11-10T12:31:26","lastUpdatedDate":"2009-08-11T23:40:02"},{"@array":"true","@id":"15454","@uri":"xyz/v1/Communications/111111","household":{"@id":"14436295","@uri":"xyz/v1/Households/1111"},"person":{"@id":"244444474","@uri":"xyz/v1/People/111111"},"communicationType":{"@id":"4","@uri":"xyz/v1/Communications/CommunicationTypes/4","name":"Email"},"communicationGeneralType":"Email","communicationValue":"email@needthis.com","searchCommunicationValue":"email@needthis.com","listed":"true","communicationComment":null,"createdDate":"2008-11-10T12:31:26","lastUpdatedDate":"2009-08-11T23:39:06"}]}} ```
Another twist on how inerte did it would be to access it like: ``` $json_object = '{"communications": {"communication": [{"@array":"true","@id":"23101384","@uri":"xyz/v1/Communications/1111","household": {"@id":"111111","@uri":"xyz/v1/Households/5465465"}, "person": {"@id":"","@uri":""}, "communicationType":{"@id":"1","@uri":"xyz/v1/Communications/CommunicationTypes/1","name":"Home Phone"}, "communicationGeneralType":"Telephone","communicationValue":"1111","searchCommunicationValue":"2693240758", "listed":"true","communicationComment":null,"createdDate":"2008-11-10T12:31:26","lastUpdatedDate":"2009-08-11T23:40:02"}, {"@array":"true","@id":"11111","@uri":"xyz/v1/Communications/111111111","household": {"@id":"14436295","@uri":"xyz/v1/Households/11111"}, "person": {"@id":"2222222","@uri":"xyz/v1/People/22222222"}, "communicationType": {"@id":"2","@uri":"xyz/v1/Communications/CommunicationTypes/2","name":"Work Phone"}, "communicationGeneralType":"Telephone","communicationValue":"11111","searchCommunicationValue":"789787987","listed":"false", "communicationComment":null,"createdDate":"2009-08-09T15:49:27","lastUpdatedDate":"2009-08-11T23:40:02"}, {"@array":"true","@id":"11111","@uri":"xyz/v1/Communications/11111","household": {"@id":"1111","@uri":"xyz/v1/Households/1111"}, "person":{"@id":"244404","@uri":"xyz/v1/People/1111"}, "communicationType":{"@id":"3","@uri":"xyz/v1/Communications/CommunicationTypes/3","name":"Mobile"}, "communicationGeneralType":"Telephone","communicationValue":"22222","searchCommunicationValue":"5475454","listed":"true", "communicationComment":null,"createdDate":"2008-11-10T12:31:26","lastUpdatedDate":"2009-08-11T23:40:02"}, {"@array":"true","@id":"15454","@uri":"xyz/v1/Communications/111111","household":{"@id":"14436295","@uri":"xyz/v1/Households/1111"}, "person":{"@id":"244444474","@uri":"xyz/v1/People/111111"}, "communicationType":{"@id":"4","@uri":"xyz/v1/Communications/CommunicationTypes/4","name":"Email"}, "communicationGeneralType":"Email","communicationValue":"email@needthis.com","searchCommunicationValue":"email@needthis.com","listed":"true", "communicationComment":null,"createdDate":"2008-11-10T12:31:26","lastUpdatedDate":"2009-08-11T23:39:06"} ] } }'; $json_decoded = json_decode($json_object); echo "email: ".$json_decoded->communications->communication[3]->communicationValue."<br />"; ```
Considering you have [`json_decode`](http://www.php.net/json_decode)d you data this way : ``` $data = json_decode($json); ``` You can use [`var_dump`](http://www.php.net/var_dump) *(well, it's output looks way better if used with the [Xdebug](http://xdebug.org/) extension, which is nice to have on a development machine, btw)* to know what's in your data : ``` // Allows you to know what's in the data ;-) var_dump($data); ``` You'll get something like this : ``` object(stdClass)[1] public 'communications' => object(stdClass)[2] public 'communication' => array 0 => object(stdClass)[3] public '@array' => string 'true' (length=4) public '@id' => string '23101384' (length=8) public '@uri' => string 'xyz/v1/Communications/1111' (length=26) public 'household' => object(stdClass)[4] public '@id' => string '111111' (length=6) public '@uri' => string 'xyz/v1/Households/5465465' (length=25) public 'person' => object(stdClass)[5] public '@id' => string '' (length=0) public '@uri' => string '' (length=0) public 'communicationType' => object(stdClass)[6] public '@id' => string '1' (length=1) public '@uri' => string 'xyz/v1/Communications/CommunicationTypes/1' (length=42) public 'name' => string 'Home Phone' (length=10) public 'communicationGeneralType' => string 'Telephone' (length=9) public 'communicationValue' => string '1111' (length=4) public 'searchCommunicationValue' => string '2693240758' (length=10) public 'listed' => string 'true' (length=4) public 'communicationComment' => null public 'createdDate' => string '2008-11-10T12:31:26' (length=19) public 'lastUpdatedDate' => string '2009-08-11T23:40:02' (length=19) 1 => object(stdClass)[7] public '@array' => string 'true' (length=4) public '@id' => string '11111' (length=5) public '@uri' => string 'xyz/v1/Communications/111111111' (length=31) public 'household' => object(stdClass)[8] public '@id' => string '14436295' (length=8) public '@uri' => string 'xyz/v1/Households/11111' (length=23) public 'person' => object(stdClass)[9] public '@id' => string '2222222' (length=7) public '@uri' => string 'xyz/v1/People/22222222' (length=22) public 'communicationType' => object(stdClass)[10] public '@id' => string '2' (length=1) public '@uri' => string 'xyz/v1/Communications/CommunicationTypes/2' (length=42) public 'name' => string 'Work Phone' (length=10) public 'communicationGeneralType' => string 'Telephone' (length=9) public 'communicationValue' => string '11111' (length=5) public 'searchCommunicationValue' => string '789787987' (length=9) public 'listed' => string 'false' (length=5) public 'communicationComment' => null public 'createdDate' => string '2009-08-09T15:49:27' (length=19) public 'lastUpdatedDate' => string '2009-08-11T23:40:02' (length=19) 2 => object(stdClass)[11] public '@array' => string 'true' (length=4) public '@id' => string '11111' (length=5) public '@uri' => string 'xyz/v1/Communications/11111' (length=27) public 'household' => object(stdClass)[12] public '@id' => string '1111' (length=4) public '@uri' => string 'xyz/v1/Households/1111' (length=22) public 'person' => object(stdClass)[13] public '@id' => string '244404' (length=6) public '@uri' => string 'xyz/v1/People/1111' (length=18) public 'communicationType' => object(stdClass)[14] public '@id' => string '3' (length=1) public '@uri' => string 'xyz/v1/Communications/CommunicationTypes/3' (length=42) public 'name' => string 'Mobile' (length=6) public 'communicationGeneralType' => string 'Telephone' (length=9) public 'communicationValue' => string '22222' (length=5) public 'searchCommunicationValue' => string '5475454' (length=7) public 'listed' => string 'true' (length=4) public 'communicationComment' => null public 'createdDate' => string '2008-11-10T12:31:26' (length=19) public 'lastUpdatedDate' => string '2009-08-11T23:40:02' (length=19) 3 => object(stdClass)[15] public '@array' => string 'true' (length=4) public '@id' => string '15454' (length=5) public '@uri' => string 'xyz/v1/Communications/111111' (length=28) public 'household' => object(stdClass)[16] public '@id' => string '14436295' (length=8) public '@uri' => string 'xyz/v1/Households/1111' (length=22) public 'person' => object(stdClass)[17] public '@id' => string '244444474' (length=9) public '@uri' => string 'xyz/v1/People/111111' (length=20) public 'communicationType' => object(stdClass)[18] public '@id' => string '4' (length=1) public '@uri' => string 'xyz/v1/Communications/CommunicationTypes/4' (length=42) public 'name' => string 'Email' (length=5) public 'communicationGeneralType' => string 'Email' (length=5) public 'communicationValue' => string 'email@needthis.com' (length=18) public 'searchCommunicationValue' => string 'email@needthis.com' (length=18) public 'listed' => string 'true' (length=4) public 'communicationComment' => null public 'createdDate' => string '2008-11-10T12:31:26' (length=19) public 'lastUpdatedDate' => string '2009-08-11T23:39:06' (length=19) ``` Which means you should be able to access the data you're looking for with something like this : ``` foreach ($data->communications->communication as $communication) { if ($communication->communicationGeneralType == 'Email') { var_dump($communication->communicationValue); var_dump($communication->searchCommunicationValue); } } ``` Which will get you : ``` string 'email@needthis.com' (length=18) string 'email@needthis.com' (length=18) ``` "`communications`" is an object, that contains "`communication`", which is an array of objects, each one containing a `communicationGeneralType`, which allows you to determine whether the current communication is an EMail or not. WHen it is, you can use the `communicationValue` or `searchCommunicationValue` fields. And I don't really see a way of doing this without iterating over every `communication` element... Hope this helps!
json decode in php
[ "", "php", "json", "" ]
We have a "print engine" which basically picks pre defined tasks to run against a file and these "tasks" are .NET 2.0 - 3.5 (in C#) command-line applications. All it does is run one after the other and with the applications that we haven't developed internally, they run quite quickly, typically 10-30 ms. However, our .NET applications, typically take 1-3 seconds, and when you're dealing with several executables per file and several files, all executed synchronously, we end up with really long wait times. Typically these applications are doing a little bit of database work and some extremely basic file modification (plain text stuff). We have even stripped down some applications in order to see if it was just the overhead of the .NET Framework that was slowing everything down and everyone that has looked into it has just concluded that > ".NET is just slow and it's not made to > perform in this manner." I was wondering if this is true and what techniques I can use to either track the problem down or alleviate the lag. I've tried using profilers but so far I haven't seen one that will repeatedly execute a command-line .NET application, which is what we do. Most just want to run an executable once and attach to it to profile it. Ideally, we would like to opt out of using the print engine completely and develop our own more efficient engine, but that's just not going to happen.
> Typically these applications are doing a little bit of database work There you go. The packaged native applications likely aren't talking to a database. That alone could easily take 10-30 ms+ for even a single short query. Also, .NET does have some additional overhead required to establish an application domain. You might find that things work better if you can group some of your small applications into fewer larger ones, or perhaps use command-line parameters to configure them to run several tasks at once.
Most (all?) of .NET slowdowns are related to assembly loading and JIT compilation. If you can combine multiple tasks into the command-line, that will make it run MUCH faster. Remember when you execute a command line application over and over again for a single task that you are dynamically loading and compiling each assembly and all of its resources every time. Additionally, if you use NGEN to make a precompiled image of the assembly/assemblies, this will decrease the startup time dramatically.
Can .NET based applications be expected to perform in this manner?
[ "", "c#", ".net", "performance", "" ]
Is there any differences between doing ``` Field field = something.getSomethingElse().getField(); if (field == 0) { //do something } somelist.add(field); ``` versus ``` if (something.getSomethingElse().getField() == 0) { //do something } somelist.add(something.getSomethingElse().getField()); ``` **Do references to the field through getters incur a performance penalty or is it the same as referencing an assigned variable?** I understand that the variable is just a reference to the memory space, so the getter should just be another way to get at that memory space. Note that this is an academic question (school of just curious) rather then a practical one.
Assuming that `getSomethingElse()` is defined as ``` public SomethingElse getSomethingElse() { return this.somethingElse; } ``` performance difference will be minimal (or zero if it'll get inlined). However, in real life you can not always be sure that's the case - there may be some processing happening behind the scenes (not necessarily in the object itself but, say, via AOP proxy). So saving the result in the variable for repeat access may be a good idea.
It's a negligible detriment. Don't concern yourself with it too much or you'll fall prey to premature optimization. If your application is slow, this isn't the reason why.
In Java is there a performance difference between referencing a field through getter versus through a variable?
[ "", "java", "performance", "variables", "reference", "getter", "" ]
i want to develop an application where need to set reminder and send mail through database on particular time duration.
Please goto the following links for sending Email using SqlServer 2005 <http://www.sqlservercurry.com/2008/02/how-to-send-email-using-sql-server-2005.html>
Use SQL Server Database Mail. <http://technet.microsoft.com/en-us/library/ms175887(SQL.90).aspx> You can then create the process logic that calls the stored procedure [sp\_send\_dbmail](http://technet.microsoft.com/en-us/library/ms190307.aspx) in order to send mail. You can then schedule your process/stored procedure using a SQL Server Agent job.
How to send Mail through data base Using sql server 2005?
[ "", "c#", ".net", "sql-server", "" ]
I have the following function to get validation errors for a card. My question relates to dealing with GetErrors. Both methods have the same return type `IEnumerable<ErrorInfo>`. ``` private static IEnumerable<ErrorInfo> GetErrors(Card card) { var errors = GetMoreErrors(card); foreach (var e in errors) yield return e; // further yield returns for more validation errors } ``` Is it possible to return all the errors in `GetMoreErrors` without having to enumerate through them?
It is something that F# supports with `yield!` for a whole collection vs `yield` for a single item. (That can be very useful in terms of tail recursion...) Unfortunately it's not supported in C#. However, if you have several methods each returning an `IEnumerable<ErrorInfo>`, you can use `Enumerable.Concat` to make your code simpler: ``` private static IEnumerable<ErrorInfo> GetErrors(Card card) { return GetMoreErrors(card).Concat(GetOtherErrors()) .Concat(GetValidationErrors()) .Concat(AnyMoreErrors()) .Concat(ICantBelieveHowManyErrorsYouHave()); } ``` There's one very important difference between the two implementations though: this one will call all of the methods *immediately*, even though it will only use the returned iterators one at a time. Your existing code will wait until it's looped through everything in `GetMoreErrors()` before it even *asks* about the next errors. Usually this isn't important, but it's worth understanding what's going to happen when.
You could set up all the error sources like this (method names borrowed from Jon Skeet's answer). ``` private static IEnumerable<IEnumerable<ErrorInfo>> GetErrorSources(Card card) { yield return GetMoreErrors(card); yield return GetOtherErrors(); yield return GetValidationErrors(); yield return AnyMoreErrors(); yield return ICantBelieveHowManyErrorsYouHave(); } ``` You can then iterate over them at the same time. ``` private static IEnumerable<ErrorInfo> GetErrors(Card card) { foreach (var errorSource in GetErrorSources(card)) foreach (var error in errorSource) yield return error; } ``` Alternatively you could flatten the error sources with `SelectMany`. ``` private static IEnumerable<ErrorInfo> GetErrors(Card card) { return GetErrorSources(card).SelectMany(e => e); } ``` The execution of the methods in `GetErrorSources` will be delayed too.
Return all enumerables with yield return at once; without looping through
[ "", "c#", "ienumerable", "yield", "yield-return", "" ]
``` DateTime dt=Convert.ToDateTime(data); if ((dt.Year == DateTime.Now.Year) && (dt.Month == DateTime.Now.Month) && (dt.Day == DateTime.Now.Day)) lblDate.Text = "Today"; ``` This code too lazy 1. How to compare 2 date variables the easy way? 2. How to get the difference of 2 date variables in minutes?
For the first question: * In general: ``` if (first.Date == second.Date) ``` * To check whether a `DateTime` is "today" ``` if (dateTime.Date == DateTime.Today) ``` Note that this doesn't take any time zone issues into consideration... What do you want to happen if the other `DateTime` is in UTC, for example? I'm not sure what you mean by the second question. Could you elaborate? You can do: ``` TimeSpan difference = first - second; ``` if that's any help... look at the [`TimeSpan` documentation](http://msdn.microsoft.com/en-us/library/system.timespan.aspx) for more information about what's available. For instance, you may mean: ``` double minutes = (first - second).TotalMinutes; ``` but you may not...
``` 1. DateTime.Equals(DateTime dt1, DateTime dt2) ```
how to equal 2 date variable in c#
[ "", "c#", "" ]
Can you mix vb and c# files in the same project for a class library? Is there some setting that makes it possible? I tried and none of the intellisense works quite right, although the background compiler seems to handle it well enough (aside from the fact that I, then, had 2 classes in the same namespace with the same name and it didn't complain). We're trying to convert from VB to C# but **haven't** finished converting all the code. I have some new code I need to write, but didn't really want to make a new project just for it.
No, you can't. An assembly/project (each project compiles to 1 assembly usually) has to be one language. However, you can use multiple assemblies, and each can be coded in a different language because they are all compiled to CIL. It compiled fine and didn't complain because a VB.NET project will only actually compile the .vb files and a C# project will only actually compile the .cs files. It was ignoring the other ones, therefore you did not receive errors. **Edit:** If you add a .vb file to a C# project, select the file in the Solution Explorer panel and then look at the Properties panel, you'll notice that the Build Action is 'Content', not 'Compile'. It is treated as a simple text file and doesn't even get embedded in the compiled assembly as a binary resource. **Edit:** With asp.net websites you may add c# web user control to vb.net website
Well, actually I inherited a project some years ago from a colleague who had decided to mix VB and C# webforms within the same project. That worked but is far from fun to maintain. I decided that new code should be C# classes and to get them to work I had to add a subnode to the compilation part of web.config ``` <codeSubDirectories> <add directoryName="VB"/> <add directoryName="CS"/> </codeSubDirectories> ``` The all VB code goes into a subfolder in the App\_Code called VB and the C# code into the CS subfolder. This will produce two .dll files. It works, but code is compiled in the same order as listed in "codeSubDirectories" and therefore i.e Interfaces should be in the VB folder if used in both C# and VB. I have both a reference to a VB and a C# compiler in ``` <system.codedom> <compilers> ``` The project is currently updated to framework 3.5 and it still works (but still no fun to maintain..)
Mixing C# & VB In The Same Project
[ "", "c#", "vb.net", "" ]
Ive been looking at the move\_upload\_files function, but i dont think thats what i need. I need to upload a picture (max size 2mb png, jpg, gif only) then rename it, then create a thumbnail of it, and save both to the same directory. I figure ill upload/rename the main file first, then take that and create the thumbnail. But what functions should i be looking at to do this?
You will at least need to look at [PHP's GD functions](http://www.php.net/gd), or better yet [Imagick](http://www.php.net/imagick) for creating thumbs. There are zillions of tutorials on this, here are a couple: * <http://www.webcheatsheet.com/php/create_thumbnail_images.php> * <http://icant.co.uk/articles/phpthumbnails/> * <http://php.about.com/od/advancedphp/ss/php_thumbnail.htm> Or you could just use a ready-made solution, e.g.: * <http://phpthumb.sourceforge.net/>
``` if(isset($_FILES['p1']) && $_FILES['p1']['tmp_name'] != ''){ $sizes = array(); $sizes['50'] = 50; $sizes['150'] = 150; $sizes['500'] = 500; $prefix = time(); list(,,$type) = getimagesize($_FILES['p1']['tmp_name']); $type = image_type_to_extension($type); move_uploaded_file($_FILES['p1']['tmp_name'], 'uploads/'.$prefix.$type); $t = 'imagecreatefrom'.$type; $t = str_replace('.','',$t); $img = $t('uploads/'.$prefix.$type); foreach($sizes as $k=>$v){ $width = imagesx( $img ); $height = imagesy( $img ); $new_width = $v; $new_height = floor( $height * ( $v / $width ) ); $tmp_img = imagecreatetruecolor( $new_width, $new_height ); imagealphablending( $tmp_img, false ); imagesavealpha( $tmp_img, true ); imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height ); $c = 'image'.$type; $c = str_replace('.','',$c); $c( $tmp_img, 'uploads/'.$k.'_'.$prefix.$type ); }// }// ``` I use this to upload, rename and create 3 different thumbs, hope this helps someone out.
php upload image, rename, thumbnail, and save both
[ "", "php", "" ]
I've got a collection of ViewModels that are rendered as tabs using a style to pull out the relevant content to display on the tab: ``` public class TabViewModel : DependencyObject { public object Content { get { return (object)GetValue(ContentProperty); } set { SetValue(ContentProperty, value); } } } ``` Here's the TabControl: ``` <TabControl ItemsSource={Binding MyCollectionOfTabViewModels}" ItemContainerStyle="{StaticResource TabItemStyle}" /> ``` And here's the style ``` <Style TargetType="TabItem" x:Key="TabItemStyle"> <Setter Property="Content" Value="{Binding Content}"/> </Style> ``` We are creating an instance of a usercontrol and setting the "Content" property of the TabViewModel to that so that the usercontrol gets displayed in the TabItem's Content area. ``` MyCollectionOfViewModels.Add(new TabViewModel() { Content = new MyUserControl(); }); ``` My question is, **I would like to allow a MyUserControl (or any of its sub controls) added to the TabViewModel's Content property to be allowed to raise an event that the TabViewModel handles**. Anyone know how I would do that? We've experimented using RoutedEvents and RoutedCommands, but haven't been able to get anything to work 100% and have it be compatible with MVVM. I really think that this could be done with a RoutedEvent or RoutedCommand, but I don't seem to be able to get this to work. *Note: I've removed some of the relevant Prism-specific code, but if you are wondering why we do something so silly, it is because we are trying to stay control agnostic by using Prism's RegionManager.*
You could add a State property to your TabViewModel, and check the DependencyPropertyChanged events. So imagine the following enum: ``` public enum TabViewModelState { True, False, FileNotFound } ``` Then add a State property to your TabViewModel of this enum: ``` public static readonly DependencyProperty StateProperty = DependencyProperty.Register("State", typeof(TabViewModelState), typeof(TabViewModel), new PropertyMetadata(OnStateChanged)); private static void OnStateChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { TabViewModel viewModel= (TabViewModel)obj; //Do stuff with your viewModel } ``` Use a two-way binding to this property in your control: ``` <CheckBox Checked="{Binding Path=State, Converter={StaticResource StateToBooleanConverter}, Mode=TwoWay}" /> ``` And last but not least implement the converter that will convert to and from the original value needed for the control.. (in my example boolean <--> TabViewModelState): ``` public class StateToBooleanConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { TabViewModelState state = (TabViewModelState) value; return state == TabViewModelState.True; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { bool result = (bool) value; return result ? TabViewModelState.True : TabViewModelState.False; } } ``` So now you have a State property that is managed by the UI, and throws changed events when you need to respond.. Hope this helps!
If you put a command on your ViewModel and just bind to that from your UserControl it will fire anyway. You don't have to bubble it, the UserControl will just find the command and use it. If you had a delegate command 'GoCommand' on your ViewModel, your UserControls button binding would just look like this: ``` <Button Command="{Binding GoCommand}" >Go</Button> ``` I went through the same thought process thinking that the UserControl needs to bubble the command, but it dosn't - the binding will just hook itself up when it finds the command on the ViewModel. Hope this helps and I havn't missed the point! ;)
Bubbling RoutedEvent or RoutedCommand to a ViewModel
[ "", "c#", "wpf", "mvvm", "prism", "routed-events", "" ]
In python: ``` u'\u3053\n' ``` Is it utf-16? I'm not really aware of all the unicode/encoding stuff, but this type of thing is coming up in my dataset, like if I have `a=u'\u3053\n'`. `print` gives an exception and decoding gives an exception. ``` a.encode("utf-16") > '\xff\xfeS0\n\x00' a.encode("utf-8") > '\xe3\x81\x93\n' print a.encode("utf-8") > πüô print a.encode("utf-16") >  ■S0 ``` What's going on here?
It's a unicode character that doesn't seem to be displayable in your terminals encoding. `print` tries to encode the unicode object in the encoding of your terminal and if this can't be done you get an exception. On a terminal that can display utf-8 you get: ``` >>> print u'\u3053' こ ``` Your terminal doesn't seem to be able to display utf-8, else at least the `print a.encode("utf-8")` line should produce the correct character.
You ask: > u'\u3053\n' > > Is it utf-16? The answer is no: it's unicode, not any specific encoding. utf-16 is an encoding. To print a Unicode string effectively to your terminal, you need to find out what encoding that terminal is willing to accept and able to display. For example, the Terminal.app on my laptop is set to UTF-8 and with a rich font, so: [![screenshot](https://i.stack.imgur.com/EX4Ai.png)](https://i.stack.imgur.com/EX4Ai.png) (source: [aleax.it](http://www.aleax.it/Picture%203.png)) ...the Hiragana letter displays correctly. On a Linux workstation I have a terminal program that keeps resetting to Latin-1 so it would mangle things somewhat like yours -- I can set it to utf-8, but it doesn't have huge number of glyphs in the font, so it would display somewhat-useless placeholder glyphs instead.
Unicode utf-8/utf-16 encoding in Python
[ "", "python", "unicode", "encoding", "decoding", "" ]
I am running the code below in some if/else statements, I have a weird issue in the same file this exact code below works fine, however in another area if it is called I get this error; ``` Warning: include() [function.include]: URL file-access is disabled in the server configuration in C:\webserver\htdocs\processing\process.friends.php on line 168 Warning: include(http://localhost/index.php) [function.include]: failed to open stream: no suitable wrapper could be found in C:\webserver\htdocs\processing\process.friends.php on line 168 $_SESSION['sess_msg'] = 'Please Enter the Correct Security Code'; $_GET["friendid"] = $friendid; $_GET["p"] = 'mail.captcha'; $_GET["f"] = 'friend'; include ("index.php"); exit; ``` And just to clarify I am njot trying to run this code 2 times at the SAME time, it's more like this; Not just like this but you get the point that they are not run at the same time ``` if(something){ run the code above }else{ run the code above } ``` If it matters, I am currently running a LAMP setup on a windows PC
remove the "<http://localhost>" part of your code. As a rule of thumb, when you include your own files, you should include them from your file system. ``` include "./index.php"; ```
Just remove the **<http://localhost/>** part and you'll be okay.
Cannot include a file in php
[ "", "php", "" ]
Do check this code: ``` int result = 0; result = result++; System.out.println("Result 1 = " + result); result++; System.out.println("Result 2 = " + result); ``` The output i was expecting was : ``` Result 1 = 1 Result 2 = 2 ``` But i got the output: ``` Result 1 = 0 Result 2 = 1 ``` The problem lies at Line2. Can some one explain on Unary operator.??
In the statement `i = i++`: > This is guarenteed behaviour. The value of `i` is read for the purposes of evaluating the righthand side of the assignment. `i` is then incremented. statement end results in the evaluation result being assigned to `i`. > > There are two assignments in `i = i++;` and the last one to be executed will determine the result. The last to be executed will always be the statement level assignment and not the incrementer/decrementer. > > Terrible way to write code, but there you have it a deterministic result at least. <http://forums.sun.com/thread.jspa?threadID=318496>
When you do x++, the result is the value before the incrementation
Explain Java Unary operator
[ "", "java", "" ]
Is there any way to use raw strings in Java (without escape sequences)? (I'm writing a fair amount of regex code and raw strings would make my code immensely more readable) I understand that the language does not provide this directly, but is there any way to "simulate" them in any way whatsoever?
**Yes**. **Text Blocks** Come to Java [Java 13 delivers long-awaited multiline strings](https://blogs.oracle.com/javamagazine/text-blocks-come-to-java) Some history: [Raw String Literals](http://openjdk.java.net/jeps/326) were **withdrawn**. This was intended to be a preview language feature in JDK 12, but it was withdrawn and did not appear in JDK 12. [It was superseded by Text Blocks (JEP 355) in JDK 13.](https://openjdk.java.net/jeps/355) You can use text blocks to define multiline String literals with ease. You don’t need to add the visual clutter that comes with regular String literals: concatenation operators and escape sequences. You can also control how the String values are formatted. For example, let’s look at the following HTML snippet: ``` String html = """ <HTML> <BODY> <H1>"Java 13 is here!"</H1> </BODY> </HTML>"""; ``` Notice the **three quotation marks** that delimit the beginning and ending of the block.
This is a work-around if you are using eclipse. You can automatically have long blocks of text correctly multilined and special characters automatically escaped when you paste text into a string literal "-paste here-"; if you enable that option in **window→preferences→java→Editor→Typing→"Escape text when pasting into a string literal"**
Raw Strings in Java - for regex in particular. Multiline strings
[ "", "java", "regex", "string", "rawstring", "" ]
What's the common way to deal with concurrent updates in an SQL database ? Consider a simple SQL schema(constraints and defaults not shown..) like ``` create table credits ( int id, int creds, int user_id ); ``` The intent is to store some kind of credits for a user, e.g. something like stackoverflow's reputation. How to deal with concurrent updates to that table ? A few options: * `update credits set creds= 150 where userid = 1;` In this case the application retreived the current value, calculated the new value(150) and performed an update. Which spells disaster if someone else does the same at the same time. I'm guessing wrapping the retreival of the current value and update in a transaction would solve that , e.g. `Begin; select creds from credits where userid=1; do application logic to calculate new value, update credits set credits = 160 where userid = 1; end;` In this case you could check if the new credit would be < 0 and just truncate it to 0 if negative credits make no sense. * `update credits set creds = creds - 150 where userid=1;` This case wouldn't need to worry about concurrent updates as the DB takes care of the consistency problem, but has the flaw that creds would happily become negative, which might not make sense for some applications. So simply, what's the accepted method to deal with the (quite simple) problem outlined above, what if the db throws an error ?
Use transactions: ``` BEGIN WORK; SELECT creds FROM credits WHERE userid = 1; -- do your work UPDATE credits SET creds = 150 WHERE userid = 1; COMMIT; ``` Some important notes: * Not all database types support transactions. In particular, mysql's old default database engine (default before version 5.5.5), MyISAM, doesn't. Use InnoDB (the new default) if you're on mysql. * Transactions can abort due to reasons beyond your control. If this happens, your application must be prepared to start all over again, from the BEGIN WORK. * You'll need to set the isolation level to SERIALIZABLE, otherwise the first select can read data that other transactions have not committed yet(transactions arn't like mutexes in programming languages). Some databases will throw an error if there's concurrent ongoing SERIALIZABLE transactions, and you'll have to restart the transaction. * Some DBMS provide SELECT .. FOR UPDATE , which will lock the rows retreived by select until the transaction ends. Combining transactions with SQL stored procedures can make the latter part easier to deal with; the application would just call a single stored procedure in a transaction, and re-call it if the transaction aborts.
For MySQL InnoDB tables, this really depends on the isolation level you set. If you are using the default level 3 (REPEATABLE READ), then you would need to lock any row that affects subsequent writes, even if you are in a transaction. In your example you will need to : ``` SELECT FOR UPDATE creds FROM credits WHERE userid = 1; -- calculate -- UPDATE credits SET creds = 150 WHERE userid = 1; ``` If you are using level 4 (SERIALIZABLE), then a simple SELECT followed by update is sufficient. Level 4 in InnoDB is implemented by read-locking every row that you read. ``` SELECT creds FROM credits WHERE userid = 1; -- calculate -- UPDATE credits SET creds = 150 WHERE userid = 1; ``` However in this specific example, since the computation (adding credits) is simple enough to be done in SQL, a simple: ``` UPDATE credits set creds = creds - 150 where userid=1; ``` will be equivalent to a SELECT FOR UPDATE followed by UPDATE.
How to deal with concurrent updates in databases?
[ "", "sql", "concurrency", "" ]
I have the need to trigger the opening of the browser (IE, Firefox, Safari, etc) context-menu via javascript. The problem I am trying to solve, is when an overlaid element is right-clicked, the element below it shows its context menu. So if the top element is a label, when you right click, I need to show the context menu for the input element below. I know how to keep the label's context menu from showing, but I don't know how to open a context menu arbitrarily. Any help is appreciated!
Sorry to be the bearer of unfortunate news, but this is impossible to do with Javascript.
I don't want to frustrate you, quite the contrary, especially because you answered my own question :) I don't think that a browser's contect menu is accessible via an ordinary script on a web page. If what you are asking for was actually doable, then the browser makers would possibly consider this a bug and remove this behavior. Cross-browser, this behavior is very unlikely to be available today. Why don't you capture mouse events, and whenever the mouse is directly in the area of the element below that you want to show the context menu for, push the covering element below, otherwise back on top? That is one possiblity I could think of, basically revealing/exposing the hidden element depending on mouse position. Like cutting a hole into the overlay. Or why don't you make the text field transparent and put the overlay below the text field entirely? If this does not work out technically, then at least you have a point in filing bugs or enhancements against the targeted browsers. BTW it looks like the context menu actually works if the user right-clicks directly at the position of the caret, so this might be another loophole for you to consider.
How do I trigger the browser context menu on an element. (As if the user right-clicked)
[ "", "javascript", "contextmenu", "" ]
How can I quickly get a jQuery selector for the textboxes in the the first 5 rows of a table? I have a table with many rows and many textboxes; I'm just trying to select the textboxes in the first 5 rows of the table. Is there an easy way to do this?
Use [lt()](http://docs.jquery.com/Selectors/lt) ``` $('tr:lt(5) input[type=text]') ``` Note that it's lt(5), not lt(6), since the indexes are 0-based.
try: ``` $("#yourTable tr:lt(5) input[type=text]") ```
jQuery: select the first five rows of a table
[ "", "javascript", "jquery", "" ]
Which are the diferrences between the following two queries? Both returns different rows: ``` with ordered_table as ( select * from table order by column1 ) select first_value(column2 ignore nulls) over (partition by column3) from ordered_table; ``` and ``` select first_value(column2 ignore nulls) over (partition by column3 order by column1) from table; ``` Note: I'll try to provide a test-case but I think that for someone having the concepts clear is not needed.
``` WITH ordered_table AS ( SELECT * FROM table ORDER BY column1 ) SELECT FIRST_VALUE(column2 IGNORE NULLS) OVER (PARTITION BY column3) FROM ordered_table ``` This query will return the first per-partition value of `column2` in no particular order (i. e. the `CBO` is free to choose any order it considers the best). ``` SELECT FIRST_VALUE(column2 IGNORE NULLS) OVER (PARTITION BY column3 ORDER BY column1) FROM table; ``` This query will return the first per-partition value of `column2`, with partitions ordered by `column1`. Since `SQL` language operates on sets, and your `ORDER BY` clause does nothing with the set returned in the `CTE`, `Oracle` just ignores the `ORDER BY` part. `CBO` can choose to materialize, hash or in any other way mutilate the `CTE` before it's used by the outer query, so the `ORDER BY` used in the `CTE` will be lost for the outer query.
The ordering by column1 doesn't really do anything in the first query. It create a result set in order, but I don't think that carries into your partition statement. The ordering belongs in the actual partition clause.
Differences between two analytic queries
[ "", "sql", "oracle", "" ]
Suppose I have an array similar to this (actual values probably will not be so predictable): ``` $ar[0] = 5; $ar[1] = 10; $ar[2] = 15; $ar[3] = 20; ``` and I have `$n = 8`, what would be a good way to find that `$n` falls between `$ar[0]` and `$ar[1]`? Preferably, the solution would avoid looping through the entire array, as this will probably repeated many times over on an array of varying size. Edit: Yes, the array will always be sorted.
### For smaller arrays... If your array is always sorted with smaller values at the bottom, you can cycle through until you get to one that is greater than your comparable number. When you reach that point, record the key, or the number of iterations it took to get there.
If you don't want to loop through the entire array, and your array is sorted, you can start in the middle, compare the value you are looking for, and based on the result select the first half or the second half of the array to continue with.
Find which two values of an array a given value is between
[ "", "php", "arrays", "" ]
For Java programming, what are some benefits of using the @Deprecated notation on and interface method but not on the class that implements it? ``` public interface Joe { @Deprecated public void doSomething(); ... } public final class Joseph implements Joe { public void doSomething() { ... } ... } ```
I believe it's a shortcoming in the Java Language itself and it is nonsense to specify a method in an interface as deprecated via an annotation and not have the method considered deprecated in the implementing class. It would be better if the @deprecated-ness of the method were inherited. Unfortunately, it seems Java does not support this. Consider how tooling, such as an IDE, treats this situation: If the type of a variable is declared to be the interface, then @deprecated methods can be rendered with a strike through. But if the type of a variable is declared to be the implementing class and the class signature does not include @deprecated, then the method will be rendered without a strike through. The fundamental question is: what does it MEAN for a method to be deprecated in an interface but not in an implementing class (or in an extending interface)? The only reasonable intention is for the method to be deprecated for everything below the interface in the class hierarchy. But the language does not support that behavior.
@Deprecated is documentation. If people code to an interface you can mark certain aspects of that interface as deprecated. That way people know not to use it. The implementation class of the interface is a detail. A method in that class happens to satisfy the interface but may not be deprecated on its own. Deprecating that method may or may not be appropriate. Creating a new class that implements an interface means you need to implement the deprecated methods. They should probably work unless you know that the clients of the class don't use the deprecated methods. For example, if you are creating an HTTP servlet container you need to implement the `HttpServletResponse.encodeUrl()` method even though it's deprecated in favour of `encodeURL()`. That's because a user of your class may call that deprecated method.
What are benefits of using the @Deprecated notation on the interface only?
[ "", "java", "deprecated", "" ]
Ok, I'm still getting the hang of asp.net and the MVC framework and converting my knowledge over from classic ASP and VB - so please be gentle. I've got my first view (/home/details/X) functioning well [thanks to previous help pointing me in the right direction](https://stackoverflow.com/questions/1210413/asp-net-mvc-c-object-reference-errors-when-going-to-view-record-details), now I need to add data from multiple tables and queries/views to the MVC view (I hate that SQL and MVC both use the word view for different meanings). I'm not looking for someone to write the answer for me (unless they're feeling really energetic), more so for someone to point me in the right direction of what I should be looking at and reading up on to understand it and do this myself. **My problem** There are multiple datasets which I need to display in this view, and each different data set has a proper PK/FK 1-M relationship established, and the resultant records would need to be looped through. **How I would have done this previously** In my classic ASP days, I would have just defined the SQL query at the head of the page where the data was to be used, with a select statement along the lines of: ``` SELECT * FROM query_name WHERE query_uniquecolumnname = Request.QueryString("value") ``` Once that was done, you'd set the do while query\_name NOT BOF/EOF up, then drop in the field names you wanted from that query and it was all done. **How do I acheive this now?** So, fast forwarding from my classic ASP knowledge, how do I acheive the same outcome with MVC? The tables/views I wish to use are already defined within my data model (and the relationships are showing up in there which I would assume is a plus), I just need to work out how I could call these within the page and use the ID of the record being displayed in the Details view to ensure only related data is displayed. Thanks in advance
The concept you are looking for is called a [ViewModel](http://stephenwalther.com/blog/archive/2009/04/13/asp.net-mvc-tip-50-ndash-create-view-models.aspx). Essentially this is a custom class that you write that contains all the data that would be used in your view. So it is responsible for amalgamating all the data from the different tables and exposing it as properties. If you're using a data access layer, this is often as simple as bringing a few entities together. If you're using raw SQL to do it, then you would execute your queries when the properties were accessed. Then you would make your View inherit from the ViewModel, like so: ``` <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.MyViewModel>" %> ``` Now in your View, you can access all the different properties of your object simply by writing statements like: ``` <%= Html.TextBox("MyProperty", Model.MyProperty) %> ``` To construct your view from your controller, create a new instance of your class (MyViewModel), pass it the ID of the details record that you need, and the logic in your class will take care of getting the right data. Then return your view from your controller like normal. ``` var myDetailsModel = new MyViewModel(detailsID); return View(myDetailsModel); ```
I would recommend reading this primer on ASP.NET MVC <http://weblogs.asp.net/scottgu/archive/2009/04/28/free-asp-net-mvc-nerddinner-tutorial-now-in-html.aspx> It covers most basic scenarios you'll need to get up and running. If however you want to combine multiple resultsets into one, and then return it as a view, you should create a custom object, and map the resultset to it, then you can bind against your custom object in the view.
ASP.NET MVC C#: Bringing in data from multiple tables/queries into a view
[ "", "c#", "asp.net-mvc", "model-view-controller", "" ]
If `fruits` is the list `['apples', 'oranges', 'pears']`, is there a quick way using django template tags to produce "apples, oranges, and pears"? I know it's not difficult to do this using a loop and `{% if counter.last %}` statements, but because I'm going to use this repeatedly I think I'm going to have to learn how to write custom ~~tags~~ filters, and I don't want to reinvent the wheel if it's already been done. As an extension, my attempts to drop the [Oxford Comma](http://en.wikipedia.org/wiki/Serial_comma) (ie return "apples, oranges and pears") are even messier.
Here's the filter I wrote to solve my problem (it doesn't include the Oxford comma) ``` def join_with_commas(obj_list): """Takes a list of objects and returns their string representations, separated by commas and with 'and' between the penultimate and final items For example, for a list of fruit objects: [<Fruit: apples>, <Fruit: oranges>, <Fruit: pears>] -> 'apples, oranges and pears' """ if not obj_list: return "" l=len(obj_list) if l==1: return u"%s" % obj_list[0] else: return ", ".join(str(obj) for obj in obj_list[:l-1]) \ + " and " + str(obj_list[l-1]) ``` To use it in the template: `{{ fruits|join_with_commas }}`
First choice: use the existing join template tag. <http://docs.djangoproject.com/en/dev/ref/templates/builtins/#join> Here's their example ``` {{ value|join:" // " }} ``` Second choice: do it in the view. ``` fruits_text = ", ".join( fruits ) ``` Provide `fruits_text` to the template for rendering.
Comma separated lists in django templates
[ "", "python", "django", "list", "django-templates", "" ]
After frequently coming across recommendation not to use leading and double underscores in C/C++ identifiers I decided to fix all our sources once and for all. What I need to do now is convert `_Identifier` to `Identifier_`. Should I use a specialized tool for this task of regular expressions will do for this job? In latter case what is the pattern to match C/C++ identifier?
Although I am one of those that frequently points out that names with leading underscores may be reserved, I strongly recommend you don't do this unless you are experiencing problems caused by the names. Making this global change will make your version control system less useful than it might otherwise be by causing all sorts of spurious diffs. Also, there is a chance of creating duplicate names. Also, there are many underscore prefixed names that re perfectly valid. One thinks immediately of `__LINE__` and `__FILE__` etc, and of all the names of non-standard functions that may be provided by your specific implementation. Filtering out those names will be far from trivial (I would say next to impossible), certainly a simple Perl or sed script will not be enough. So instead, I would encourage you to change the names on a file by file basis as you make other changes to the code. Change your programming standards to avoid the leading underscore names and write new code in accordance with the standards.
If you use Visual Studio, there are refactoring plugins such as Visual Assist X to help you with this.
How to update all C/C++ identifier names in a project
[ "", "c++", "c", "regex", "refactoring", "" ]
While porting Windows code to Linux, I encountered the following error message with GCC 4.2.3. (Yes, I'm aware that it's a slight old version, but I can't easily upgrade.) ``` main.cpp:16: error: call of overloaded ‘list(MyClass&)’ is ambiguous /usr/include/c++/4.2/bits/stl_list.h:495: note: candidates are: std::list<_Tp, _Alloc>::list(const std::list<_Tp, _Alloc>&) [with _Tp = unsigned char, _Alloc = std::allocator<unsigned char>] /usr/include/c++/4.2/bits/stl_list.h:484: note: std::list<_Tp, _Alloc>::list(size_t, const _Tp&, const _Alloc&) [with _Tp = unsigned char, _Alloc = std::allocator<unsigned char>] ``` I'm using the following code to generate this error. ``` #include <list> class MyClass { public: MyClass(){} operator std::list<unsigned char>() const { std::list<unsigned char> a; return a; } operator unsigned char() const { unsigned char a; return a; } }; int main() { MyClass a; std::list<unsigned char> b = (std::list<unsigned char>)a; return 0; } ``` Has anyone experienced this error? More importantly, how to get around it? (It's possible to completely avoid the overload, sure, by using functions such as `GetChar()`, `GetList()` etc, but I'd like to avoid that.) (By the way, removing "`operator unsigned char()`" removes the error.)
It compiles properly if you remove the cast, and I've checked that the operator std::list is being executed. ``` int main() { MyClass a; std::list<unsigned char> b = a; return 0; } ``` Or if you cast it to a const reference. ``` int main() { MyClass a; std::list<unsigned char> b = (const std::list<unsigned char>&)a; return 0; } ```
The ambiguity comes from the interpretation of the *cast-expression*. When choosing the conversion, the compiler first considers a `static_cast` style cast and considers how to resolve an initialization which looks like this: ``` std::list<unsigned_char> tmp( a ); ``` This construction is ambiguous as `a` has a user-defined conversion to a `std::list<unsigned char>` and to an `unsigned char` and `std::list<unsigned char>` has both a constructor which takes a `const std::list<unsigned char>&` and a constructor which takes `size_t` (to which an `unsigned char` can be promoted). When casting to a `const std::list<unsigned_char>&`, this initialization is considered: ``` const std::list<unsigned_char>& tmp( a ); ``` In this case, when the user-defined conversion to `std::list<unsigned_char>` is chosen, the new reference can bind directly to the result of the conversion. If the user-defined conversion to `unsigned char` where chosen a temporary object of type `std::list<unsigned char>` would have to be created and this makes this option a worse conversion sequence than the former option.
C++ Operator overloading - casting from class
[ "", "c++", "gcc", "operators", "operator-overloading", "operator-keyword", "" ]
I am working on a project, in which I need to write xml to a file, this happens in a for loop, that is ``` for(int i = 0; i < screens.length; screens++) { XMLDocument allScreens = new XMLDocument(); allScreens.Load(allScreeensPath); XMLNode node = allScreens.Select("//Screen[@name='" + screens[i].name + "']"); allScreens.Remove(node); allScreens.Add(nweNode); allScreens.Save(allScreeensPath); } ``` basically the xml document is accessed, modified and saved in a for loop, this work some times. and some times I get the following error , I tries using text readers, text writers to do file operations (so that I can close, dispose the writers) but the error persists. How I can get through this?
This might be (not sure though) because you re-open the XML file for each iteration of your loop, which seems unnnecessary. Instead open the document before the loop, perform the loop, and then save it. ``` XMLDocument allScreens = new XMLDocument(); allScreens.Load(allScreeensPath); for(int i = 0; i < screens.length; screens++) { XMLNode node = allScreens.Select("//Screen[@name='" + screens[i].name + "']"); allScreens.Remove(node); allScreens.Add(nweNode); } allScreens.Save(allScreeensPath); ``` (I am not sure where `nweNode` comes into the picture in the code sample, but I leave it in since I only reworked the original code sample)
The simplest approach would be to load it once, do all the processing you need to and then save it once. I don't know why it's not working at the moment, admittedly - but I don't see any need to keep loading and saving. For example, here's an alternative version of your code: ``` XMLDocument allScreens = new XMLDocument(); allScreens.Load(allScreeensPath); foreach (Screen screen in screens) { XMLNode node = allScreens.Select("//Screen[@name='" + screen.Name + "']"); allScreens.Remove(node); allScreens.Add(newNode); } allScreens.Save(allScreeensPath); ```
Error :File cannot be accessed as File Being accessed by another process
[ "", "c#", "xml", "" ]
I'm trying to build a small code that works across multiple platforms and compilers. I use assertions, most of which can be turned off, but when compiling with PGI's `pgicpp` using `-mp` for OpenMP support, it automatically uses the `--no_exceptions` option: everywhere in my code with a "throw" statement generates a fatal compiler error. ("support for exception handling is disabled") Is there a `define`d macro I can test to hide the `throw` statements on PGI? I usually work with gcc, which has `GCC_VERSION` and the like. I can't find any documentation describing these macros in PGI.
Take a look at the [Pre-defined C/C++ Compiler Macros](http://predef.sourceforge.net/index.php) project on Sourceforge. PGI's compiler has a `__PGI` macro. Also, take a look at [libnuwen's](http://nuwen.net/libnuwen.html) compiler.hh header for a decent way to 'normalize' compiler versioning macros.
You could try this to see what macros are predefined by the compiler: ``` pgcc -dM ``` Maybe that will reveal a suitable macro you can use.
Detect compiler with #ifdef
[ "", "c++", "exception", "c-preprocessor", "pgi", "" ]
I am using SQL Server 2008 Enterprise. I want to export the query result into csv file from SQL Server Management Studio. The issue is, the default csv file is comma (',') separated for each result column in each exported row, and I want to make it '\t' separated since comma exists in some of the result column values. Any quick solutions? thanks in advance, George
If you really want the \t delimiter write a query like this ``` select Cast(PersonCode as varchar(50)) + '\t' + Cast(PersonReference as varchar(50)) from People ``` The casts are just incase you aren't working with varchar types, but you don't need them if you are. Run this query with results to text and just paste the result into notepad or similar.
When you click "Save as" and you are prompted to enter a filename, drop down the box below the filename and select "Text (Tab delimited)"
export query results into CSV file issue in SQL Server
[ "", "sql", "sql-server", "sql-server-2008", "csv", "" ]
I'm hoping someone can help with an exception I've inherited. Basically I'm writing the rows in a datagrid to a text file. Which works fine apart from when the row is hidden, when the row is hidden the exception "Index was outside the bounds of the array" is thrown at the line highlighted below. Thanks for any help. ``` DataRow dr; for (int i = 0; i < bindingManagerBase.Count; i++) {bindingManagerBase.Position = i; dr = ((DataRowView)bindingManagerBase.Current).Row; bindingManagerBase.SuspendBinding(); try { int rowIndex = dr.Table.Rows.IndexOf(dr); if (!rowsDisplayStatus[rowIndex]) //<---------Exception here "Index was outside the bounds of the array" //Picture below { m_Dgv.Rows[rowIndex].Visible = false; continue; } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } finally { bindingManagerBase.ResumeBinding(); } writeData(tw, dr); iIndex++; } ``` [![alt text](https://i.stack.imgur.com/hYD29.png)](https://i.stack.imgur.com/hYD29.png)
You're getting the row index and then trying to use it with `rowsDisplayStatus`. You can't use the database row index as an index into your collections. I would change: ``` if (!rowsDisplayStatus[rowIndex]) ``` to: ``` if (!rowsDisplayStatus[i]) ```
How is rowsDisplayStatus populated? If it only contains one element and something is expected to be at index 9, you should take a look at the code that populates it.
C# Index was outside the bounds of the array
[ "", "c#", "exception", "" ]
I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and realized I couldn't think of a single Python construct that multiline lambdas clash with. Given that I know the language pretty well, this surprised me. Now, I'm sure Guido had a reason for not including multiline lambdas in the language, but out of curiosity: what's a situation where including a multiline lambda would be ambiguous? Is what I've heard true, or is there some other reason that Python doesn't allow multiline lambdas?
Look at the following: ``` map(multilambda x: y=x+1 return y , [1,2,3]) ``` Is this a lambda returning `(y, [1,2,3])` (thus map only gets one parameter, resulting in an error)? Or does it return `y`? Or is it a syntax error, because the comma on the new line is misplaced? How would Python know what you want? Within the parens, indentation doesn't matter to python, so you can't unambiguously work with multilines. This is just a simple one, there's probably more examples.
Guido van Rossum (the inventor of Python) answers this exact question himself in [an old blog post](http://www.artima.com/weblogs/viewpost.jsp?thread=147358). Basically, he admits that it's theoretically possible, but that any proposed solution would be un-Pythonic: > "But the complexity of any proposed solution for this puzzle is immense, to me: it requires the parser (or more precisely, the lexer) to be able to switch back and forth between indent-sensitive and indent-insensitive modes, keeping a stack of previous modes and indentation level. Technically that can all be solved (there's already a stack of indentation levels that could be generalized). But none of that takes away my gut feeling that it is all an elaborate [Rube Goldberg contraption](http://en.wikipedia.org/wiki/Rube_Goldberg_Machine)."
No Multiline Lambda in Python: Why not?
[ "", "python", "syntax", "lambda", "" ]
I have two tables in MySQL ``` #messages table : messageid messagetitle . . #usersmessages table usersmessageid messageid userid . . ``` Now if I want to delete from messages table it's ok. But when I delete message by messageid the record still exists on usersmessage and I have to delete from this two tables at once. I used the following query : ``` DELETE FROM messages LEFT JOIN usersmessages USING(messageid) WHERE messageid='1' ; ``` Then I test ``` DELETE FROM messages , usersmessages WHERE messages.messageid = usersmessages.messageid and messageid='1' ; ``` But these two queries are not accomplishing this task .
Can't you just separate them by a semicolon? ``` Delete from messages where messageid = '1'; Delete from usersmessages where messageid = '1' ``` **OR** Just use `INNER JOIN` as below ``` DELETE messages , usersmessages FROM messages INNER JOIN usersmessages WHERE messages.messageid= usersmessages.messageid and messages.messageid = '1' ```
``` DELETE a.*, b.* FROM messages a LEFT JOIN usersmessages b ON b.messageid = a.messageid WHERE a.messageid = 1 ``` translation: delete from table **messages** where messageid =1, if table **uersmessages** has messageid = messageid of table **messages**, delete that row of **uersmessages** table.
Delete from two tables in one query
[ "", "sql", "mysql", "" ]
I want to put output information of my program to a folder. if given folder does not exist, then the program should create a new folder with folder name as given in the program. Is this possible? If yes, please let me know how. Suppose I have given folder path like `"C:\Program Files\alex"` and `alex` folder doesn't exist then program should create `alex` folder and should put output information in the `alex` folder.
You can create a folder with [os.makedirs()](http://docs.python.org/3/library/os.html?highlight=os.makedirs#os.makedirs) and use [os.path.exists()](http://docs.python.org/3/library/os.path.html?highlight=os.path.exists#os.path.exists) to see if it already exists: ``` newpath = r'C:\Program Files\arbitrary' if not os.path.exists(newpath): os.makedirs(newpath) ``` If you're trying to make an installer: [Windows Installer](http://www.advancedinstaller.com/) does a lot of work for you.
Have you tried os.mkdir? You might also try this little code snippet: ``` mypath = ... if not os.path.isdir(mypath): os.makedirs(mypath) ``` makedirs creates multiple levels of directories, if needed.
How to create new folder?
[ "", "python", "mkdir", "" ]
Are there any open source data streaming products for publishing and subscribing to objects? A commercial example is [SwissRisk Slingshot](http://slingshot.swissrisk.com/)
I will use [JGroups](http://www.jgroups.org/), a toolkit for reliable multicast communication.
The [Ajax Push Engine](http://www.ape-project.org/) looks like what you're after.
Open Source data streaming engine
[ "", "java", "open-source", "streaming", "" ]
I would like some information on the runtime libraries for Visual Studio 2008. Most specifically when should I consider the DLL versions and when should I consider the Static versions. The Visual Studio documentation delineates the technical differences in terms of DLL dependencies and linked libraries. But I'm left wondering why I should want to use one over the other. More important, why should I want to use the multi-threaded DLL runtime when this obviously forces my application into a DLL dependency, whereas the static runtime has no such requirement on my application user machine.
Larry Osterman feels that you should [always use the multi-threaded DLL](http://blogs.msdn.com/larryosterman/archive/2004/04/29/123090.aspx) for application programming. To summarize: * Your app will be smaller * Your app will load faster * Your app will support multiple threads without changing the library dependency * Your app can be split into multiple DLLs more easily (since there will only be one instance of the runtime library loaded) * Your app will automagically stay up to date with security fixes shipped by Microsoft Please read his [whole blog post](http://blogs.msdn.com/larryosterman/archive/2004/04/29/123090.aspx) for full details. On the downside, you need to [redistribute](http://www.microsoft.com/downloads/details.aspx?FamilyID=a5c84275-3b97-4ab7-a40d-3802b2af5fc2&displaylang=en) the runtime library, but that's commonly done and you can find [documentation](http://msdn.microsoft.com/en-us/library/ms235299.aspx) on how to include it in your installer.
Linking dynamically to the runtime libraries complicates deployment slightly due to the DLL dependency, but also allows your application to take advantage of updates (bug fixes or more likely performance improvements) to the MS runtime libraries without being recompiled. Statically linking simplifies deployment, but means that your application must be recompiled against newer versions of the runtime in order to use them.
Visual Studio 2008, Runtime Libraries usage advice
[ "", "c++", "visual-studio", "runtime", "" ]
I have the following code: ``` public void Test(IMyInterface iInterface) { iInterface.CallMethod ( ); } ``` Which works fine. However, if I change the code to be threaded: ``` private IMyInterface myInterface; public void Test(IMyInterface iInterface) { myInterface = iInterface; new Thread ( new ThreadStart ( CallInterfaceMethod) ).Start ( ); } public void CallInterfaceMethod ( ) { myInterface.CallMethod ( ) } ``` When i use the thread I receive the exception: Unable to cast COM object of type 'System.\_\_ComObject' to interface type 'IMyInterface'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{GUID}' failed due to the follow error: No such interface supported But the interface should be supported just fine? Anyone have any thoughts on what is going on here?
This nasty, nasty exception arises because of a concept known as COM marshalling. The essence of the problem lies in the fact that in order to consume COM objects from any thread, the thread must have access to the type information that describes the COM object. In your scenario described, the reason it fails on the second thread is because the second thread does not have type information for the interface. You could try adding the following to your code: ``` [ComImport] [Guid("23EB4AF8-BE9C-4b49-B3A4-24F4FF657B27")] public interface IMyInterface { void CallMethod(); } ``` Basically the declaration above instructs the .NET framework COM loader to load type information using traditional techniques from the registry and locate the associated type library and go from there. You should also restrict the creation of the COM object to a single thread (to prevent thread marshalling) to help solve this issue. To summarize, this error revolves around type information and thread marshalling. Make sure that each thread that wants to access the COM object has the relevant information to unmarshal the object from the source thread. PS: This problem is solved in .NET 4.0 using a technique called "Type Equivalence"
I got an advice and it helped me! Find in the main thread (Program.cs) the line [STAThread] and change it to [MTAThread].
Unable to cast COM object of type exception
[ "", "c#", "com", "interface", "" ]
I would like a c# regex to determine if a string contains 5+ characters within a defined sequence. Example: If the sequence was the alphabet then 'ghijk' would be true, while 'lmn' would be false. Edit: The sequence needs to be in order. from example above 'ghijz' would return false.
You don't necessarily need a regular expression to accomplish this: ``` bool IsInSequence(string str, string sequence) { return str != null && str.Length >= 5 && sequence.Contains(str); } ``` Unless I'm missing what you're trying to accomplish here.
``` [a-zA-Z]{5,} ```
RegEx Match Sequence of 5 characters
[ "", "c#", "regex", "" ]
I have just one method that I need several different classes to access and it just seems lame to make a utility class for just one method. The classes that need to use this method are already inheriting an abstract class so I can't use inheritance. What would you guys do in this situation?
> [I]t just seems lame to make a utility > class for just one method Just do it, it will grow. It always does. Common.Utilities or something of that nature is always necessary in any non-trivial solution.
Keep in mind that a class is just a small, focused machine. If the class only has one method then it's just a *very* small, focused machine. There's nothing wrong with it, and centralizing the code is valuable.
One method shared by several classes
[ "", "c#", ".net", "architecture", "" ]
Here's my situation: I want to SELECT all entries from a database WHERE id = $id. But I want the results to be listed in a certain priority. If, criteria = $criteria, then I want those results displayed first. Otherwise, I just want to keep displaying the rest of the rows. My question is this: will this solve my problem? ``` SELECT field1 WHERE (criteria=$criteria AND id = $id) OR id=$id LIMIT 5 ``` Will the query look at the () first? If not, is there another way to do this without splitting this into two separate queries? Thanks, Michael
``` SELECT field1 FROM mytable WHERE id = $id ORDER BY criteria = $criteria DESC, id LIMIT 5 ``` , or this: ``` SELECT * FROM ( SELECT field1 FROM mytable WHERE id = $id AND criteria = $criteria ORDER BY id LIMIT 5 ) q UNION FROM ( SELECT field1 FROM mytable WHERE id = $id ORDER BY id LIMIT 5 ) q2 ORDER BY criteria = $criteria DESC, id LIMIT 5 ``` The latter is more efficient if you have an index on `(id, criteria)` (in this order).
``` SELECT field1 FROM mytable WHERE id = $id ORDER BY CASE WHEN criteria = $criteria THEN 0 ELSE 1 END CASE LIMIT 5; ``` This will list rows matching the criteria before those not because zero comes before one. If this won't work directly - as written - then put the info into a sub-query: ``` SELECT field1 FROM (SELECT field1, CASE WHEN criteria = $criteria THEN 0 ELSE 1 END CASE AS ordering FROM mytable WHERE id = $id ) AS subqry ORDER BY ordering LIMIT 5; ``` Often, there will be other secondary criteria to determine the order of rows within the 0 vs 1 ordering.
Mysql "order of operations" Question
[ "", "sql", "mysql", "select", "" ]
am totally new to Javascript , but i need it for using googlemaps in my project , am trying to set values for the latitude , longitude and map zoom for every certain city , so am getting the city name from a hidden form input and using Switch to switch regarding the city name . ``` cityDiv = document.getElementById('id_city'); cityDiv.value = idCity ; switch (idCity) { case "city1": var map_long = 31.37667; var map_lat = 31.04306; var map_zoom = 3; break case "city2": var map_long = 31.33333; var map_lat = 29.85; var map_zoom = 7; break default: var map_long = 31.37667; var map_lat = 31.04306; var map_zoom = 3; } function onLoad() { map = new GMap(document.getElementById("map")); map.addControl(new GSmallMapControl()); map.addControl(new GMapTypeControl()); map.centerAndZoom(new GLatLng(map_lat,map_long) , map_zoom); GEvent.addListener(map, 'click', function(overlay, point) { if (prev_pin) { map.removeOverlay(prev_pin); prev_pin = null; } //var yPoint = new YGeoPoint({{ place.latitude }},{{ place.longitude }}); if (point) { pin = new GMarker(point); map.addOverlay(pin); prev_pin = pin; latDiv = document.getElementById('id_latitude'); lngDiv = document.getElementById('id_longitude'); lngDiv.value = point.x; latDiv.value = point.y; } }); } ``` Sorry for this newbie question . Best regards . EDIT from comment by geowa4: The question and the problem are The Variables never set :( , so whats wrong with my code ?! i change "cityDiv.value = idCity ; " to " var idCity = cityDiv.value ; " which didn't work as well but this time the map refuses to load
Your problem is scope, pure and simple. Using `var` scopes your variables to the current lexical scope, which in the case of `var map_long = 31.37667;` et al is the switch statement. Once you fall out of that scope, any variables declared in that scope vanish unless an external reference is maintained. You could remove the `var` statement, but that would make the variables global. I would recommend declaring your variables in a scope that makes sense to you, making them global only if absolutely necessary.
Have you tried dumping your values, stepping through and debugging? [Alert statements](https://developer.mozilla.org/en-US/docs/Web/API/Window/alert), or [`console.log()`](https://developer.mozilla.org/en-US/docs/Web/API/Console/log) statements, to see what the page thinks the value of that select is? You might also consider making an object, that you can then update: ``` // Untested, but you should get the gist var cityInfo = { map_long : 0.0, map_lat : 0.0, map_zoom : 0 }; switch (idCity) { case "city1": cityInfo.map_long = 31.37667; cityInfo.map_lat = 31.04306; cityInfo.map_zoom = 3; break case "city2": cityInfo.map_long = 31.33333; cityInfo.map_lat = 29.85; cityInfo.map_zoom = 7; break default: cityInfo.map_long = 31.37667; cityInfo.map_lat = 31.04306; cityInfo.map_zoom = 3; } ```
Javascript : Using Switch to set variables values for the function
[ "", "javascript", "" ]
I'm using static initialisation to ease the process of registering some classes with a factory in C++. Unfortunately, I think the compiler is optimising out the 'unused' objects which are meant to do the useful work in their constructors. Is there any way to tell the compiler not to optimise out a global variable? ``` class SomeClass { public: SomeClass() { /* do something useful */ } }; SomeClass instance; ``` My breakpoint in SomeClass's constructor doesn't get hit. In my actual code, SomeClass is in a header file and instance is in a source file, more or less alone. EDIT: As guessed by KJAWolf, this code is actually compiled into a static lib, not the executable. Its purpose is to register some types also provided by the static lib with a static list of types and their creators, for a factory to then read from on construction. Since these types are provided with the lib, adding this code to the executable is undesirable. Also I discovered that by moving the code to another source file that contains other existing code, it works fine. It seems that having a file purely consisting of these global objects is what's causing the problem. It's as if that translation unit was entirely ignored.
The compiler is not allowed to optimiza away global objects. Even if they are never used. Somthing else is happening in your code. Now if you built a static library with your global object and that global object is not referenced from the executable it will not be pulled into the executable by the linker.
The compiler should never optimize away such globals - if it does that, it is simply broken.
How do I prevent my 'unused' global variables being compiled out of my static library?
[ "", "c++", "global-variables", "" ]
This is the method for creating a variable on the heap in C++: ``` T *ptr = new T; ``` ptr refers to a pointer to the new T, obviously. My question is, can you do this: ``` T *ptr = new T*; ``` That seems like it could lead to some very, very dangerous code. Does anyone know if this is possible/how to use it properly?
``` int** ppint = new int*; *ppint = new int; delete *ppint; delete ppint; ```
`new T*` returns a pointer to a pointer to a T. So the declaration is not correct, it should be: ``` T** ptr = new T*; ``` And it will reside on the heap.
Can you declare a pointer on the heap?
[ "", "c++", "dynamic-memory-allocation", "heap-memory", "" ]
I have a method that queues some work to be executed asynchronously. I'd like to return some sort of handle to the caller that can be polled, waited on, or used to fetch the return value from the operation, but I can't find a class or interface that's suitable for the task. BackgroundWorker comes close, but it's geared to the case where the worker has its own dedicated thread, which isn't true in my case. IAsyncResult looks promising, but the provided AsyncResult implementation is also unusable for me. Should I implement IAsyncResult myself? **Clarification**: I have a class that conceptually looks like this: ``` class AsyncScheduler { private List<object> _workList = new List<object>(); private bool _finished = false; public SomeHandle QueueAsyncWork(object workObject) { // simplified for the sake of example _workList.Add(workObject); return SomeHandle; } private void WorkThread() { // simplified for the sake of example while (!_finished) { foreach (object workObject in _workList) { if (!workObject.IsFinished) { workObject.DoSomeWork(); } } Thread.Sleep(1000); } } } ``` The QueueAsyncWork function pushes a work item onto the polling list for a dedicated work thread, of which there will only over be one. My problem is not with writing the QueueAsyncWork function--that's fine. My question is, what do I return to the caller? What should `SomeHandle` be? The existing .Net classes for this are geared towards the situation where the asynchronous operation can be encapsulated in a single method call that returns. That's not the case here--all of the work objects do their work on the same thread, and a complete work operation might span multiple calls to `workObject.DoSomeWork()`. In this case, what's a reasonable approach for offering the caller some handle for progress notification, completion, and getting the final outcome of the operation?
Yes, implement IAsyncResult (or rather, an extended version of it, to provide for progress reporting). ``` public class WorkObjectHandle : IAsyncResult, IDisposable { private int _percentComplete; private ManualResetEvent _waitHandle; public int PercentComplete { get {return _percentComplete;} set { if (value < 0 || value > 100) throw new InvalidArgumentException("Percent complete should be between 0 and 100"); if (_percentComplete = 100) throw new InvalidOperationException("Already complete"); if (value == 100 && Complete != null) Complete(this, new CompleteArgs(WorkObject)); _percentComplete = value; } public IWorkObject WorkObject {get; private set;} public object AsyncState {get {return WorkObject;}} public bool IsCompleted {get {return _percentComplete == 100;}} public event EventHandler<CompleteArgs> Complete; // CompleteArgs in a usual pattern // you may also want to have Progress event public bool CompletedSynchronously {get {return false;}} public WaitHandle { get { // initialize it lazily if (_waitHandle == null) { ManualResetEvent newWaitHandle = new ManualResetEvent(false); if (Interlocked.CompareExchange(ref _waitHandle, newWaitHandle, null) != null) newWaitHandle.Dispose(); } return _waitHandle; } } public void Dispose() { if (_waitHandle != null) _waitHandle.Dispose(); // dispose _workObject too, if needed } public WorkObjectHandle(IWorkObject workObject) { WorkObject = workObject; _percentComplete = 0; } } public class AsyncScheduler { private Queue<WorkObjectHandle> _workQueue = new Queue<WorkObjectHandle>(); private bool _finished = false; public WorkObjectHandle QueueAsyncWork(IWorkObject workObject) { var handle = new WorkObjectHandle(workObject); lock(_workQueue) { _workQueue.Enqueue(handle); } return handle; } private void WorkThread() { // simplified for the sake of example while (!_finished) { WorkObjectHandle handle; lock(_workQueue) { if (_workQueue.Count == 0) break; handle = _workQueue.Dequeue(); } try { var workObject = handle.WorkObject; // do whatever you want with workObject, set handle.PercentCompleted, etc. } finally { handle.Dispose(); } } } } ```
The WorkObject class can contain the properties that need to be tracked. ``` public class WorkObject { public PercentComplete { get; private set; } public IsFinished { get; private set; } public void DoSomeWork() { // work done here this.PercentComplete = 50; // some more work done here this.PercentComplete = 100; this.IsFinished = true; } } ``` Then in your example: * Change the collection from a List to a Dictionary that can hold Guid values (or any other means of uniquely identifying the value). * Expose the correct WorkObject's properties by having the caller pass the Guid that it received from **QueueAsyncWork**. I'm assuming that you'll start **WorkThread** asynchronously (albeit, the only asynchronous thread); plus, you'll have to make retrieving the dictionary values and WorkObject properties thread-safe. ``` private Dictionary<Guid, WorkObject> _workList = new Dictionary<Guid, WorkObject>(); private bool _finished = false; public Guid QueueAsyncWork(WorkObject workObject) { Guid guid = Guid.NewGuid(); // simplified for the sake of example _workList.Add(guid, workObject); return guid; } private void WorkThread() { // simplified for the sake of example while (!_finished) { foreach (WorkObject workObject in _workList) { if (!workObject.IsFinished) { workObject.DoSomeWork(); } } Thread.Sleep(1000); } } // an example of getting the WorkObject's property public int GetPercentComplete(Guid guid) { WorkObject workObject = null; if (!_workList.TryGetValue(guid, out workObject) throw new Exception("Unable to find Guid"); return workObject.PercentComplete; } ```
Async result handle to return to callers
[ "", "c#", "asynchronous", "" ]
"User A" is logged on My application recognizes Environment.Username as "User A" Now in Windows, I click on Switch user ... "User B" logs on "User A's" processes are still running Application run by "User A" still says Environment.Username is "User A" I want the application to recognize that the currently logged on user (currently active user) is "User B" How do I do this?
``` ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT UserName FROM Win32_ComputerSystem"); foreach (ManagementObject queryObj in searcher.Get()) { loggedOnUserName = queryObj["UserName"].ToString(); loggedOnUserName = loggedOnUserName.Substring(loggedOnUserName.LastIndexOf('\\') + 1); } ``` When "User B" is logged on, the application running under "User A" reports "User B" in loggedOnUserName. That's what I was looking for. Thanks anyways.
There is no such thing as the currently active user since there can be more than one (Terminal server) You can use GetSystemMetrics(SM\_REMOTESESSION) to check if this a "local" session, and WTSGetActiveConsoleSessionId to get the session id of the console session (Currently logged on user as you call it) You can use WTSRegisterSessionNotification to get notified when this changes. ProcessIdToSessionId(GetCurrentProcess(),...) will get you the session id your process is in. Finally, WTSQuerySessionInformation() will get you info about a specific session.
Find out the current user's username - when multiple users are logged on
[ "", "c#", ".net", "windows", "authentication", "" ]
i've been looking around, but i'm not sure how to do it. i've found [this page](http://rkb.home.cern.ch/rkb/AN16pp/node208.html) which, in the last paragraph, says: *A simple generator for random numbers taken from a Poisson distribution is obtained using this simple recipe: if x1, x2, ... is a sequence of random numbers with uniform distribution between zero and one, k is the first integer for which the product x1 · x2 · ... · xk+1 < e-λ* i've found [another page](http://www.mathworks.com/access/helpdesk/help/toolbox/stats/bqttfc1.html) describing how to generate binomial numbers, but i think it is using an approximation of poisson generation, which doesn't help me. *For example, consider binomial random numbers. A binomial random number is the number of heads in N tosses of a coin with probability p of a heads on any single toss. If you generate N uniform random numbers on the interval (0,1) and count the number less than p, then the count is a binomial random number with parameters N and p.* i know there are libraries to do it, but i can't use them, only the standard uniform generators provided by the language (java, in this case).
## Poisson distribution Here's [how Wikipedia says Knuth says to do it](http://en.wikipedia.org/wiki/Poisson_distribution#Generating_Poisson-distributed_random_variables): ``` init: Let L ← e^(−λ), k ← 0 and p ← 1. do: k ← k + 1. Generate uniform random number u in [0,1] and let p ← p × u. while p > L. return k − 1. ``` In Java, that would be: ``` public static int getPoisson(double lambda) { double L = Math.exp(-lambda); double p = 1.0; int k = 0; do { k++; p *= Math.random(); } while (p > L); return k - 1; } ``` --- ## Binomial distribution Going by chapter 10 of [*Non-Uniform Random Variate Generation* (PDF)](http://luc.devroye.org/chapter_ten.pdf) by Luc Devroye (which I found linked from [the Wikipedia article](http://en.wikipedia.org/wiki/Binomial_distribution#Generating_binomial_random_variates)) gives this: ``` public static int getBinomial(int n, double p) { int x = 0; for(int i = 0; i < n; i++) { if(Math.random() < p) x++; } return x; } ``` --- ## Please note Neither of these algorithms is optimal. The first is O(λ), the second is O(n). Depending on how large these values typically are, and how frequently you need to call the generators, you might need a better algorithm. The paper I link to above has more complicated algorithms that run in constant time, but I'll leave those implementations as an exercise for the reader. :)
For this and other numerical problems the bible is the numerical recipes book. There's a free version for C here: <http://www.nrbook.com/a/bookcpdf.php> (plugin required) Or you can see it on google books: <http://books.google.co.uk/books?id=4t-sybVuoqoC&lpg=PP1&ots=5IhMINLhHo&dq=numerical%20recipes%20in%20c&pg=PP1#v=onepage&q=&f=false> The C code should be very easy to transfer to Java. This book is worth it's weight in gold for lots of numerical problems. On the above site you can also buy the latest version of the book.
Algorithm to generate Poisson and binomial random numbers?
[ "", "java", "math", "probability", "random", "poisson", "" ]
Or should I just explicitly reference the superclasses whose methods I want to call? It seems brittle to repeat the names of super classes when referencing their constructors, but this page <http://fuhm.net/super-harmful/> makes some good arguments against using super().
The book [Expert Python Programming](http://www.packtpub.com/expert-python-programming/) has discussed the topic of "super pitfalls" in chapter 3. It is worth reading. Below is the book's conclusion: > Super usage has to be consistent: In a class hierarchy, super should be used everywhere or nowhere. Mixing super and classic calls is a confusing practice. People tend to avoid super, for their code to be more explicit. **Edit:** Today I read this part of the book again. I'll copy some more sentences, since super usage is tricky: * Avoid multiple inheritance in your code. * Be consistent with its usage and don't mix new-style and old-style. * Check the class hierarchy before calling its methods in your subclass.
You can use super, but as the article says, there are drawbacks. As long as you know them, there is no problem with using the feature. It's like people saying "use composition, not inheritance" or "never use global variables". If the feature exists, there is a reason. Just be sure to understand the why and the what and use them wisely.
Is it a good idea to use super() in Python?
[ "", "python", "oop", "super", "" ]
I need to make a button that will display different things depending on the state if the app. So for example if nothing has been opened its title will be "Lesson Plans" and if project B is open it will be "project B Lesson Plan", I am using the java.awt.Button class for this. My question, is there a way to determine how big the button should be to fit the given text. For example can I somehow get the width of each character in the given font used by the button then multiply this by the characters in the title I want to use? How would I get this character width or is there some better way? Thanks!
Measuring widths of individual characters in particular fonts (not all characters are the same width) gets complicated, especially if you want to take into account the spaces between characters, and add some margin either side so they don't butt up against the edges of the button. (N.B. Others have provided a few ways of doing this more simply than I realized was possible!) Much better/more usual solution is to let Java do the work for you. If you're using using a `java.awt.Button` (or `javax.swing.JButton`), then it will usually automatically size to the text on it. If your particular button is behaving strangely, then you probably have a layout problem. Check the section of the Java tutorial on [Layout Managers](http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html) for more information. As an example (in Swing, rather than AWT - sorry!), these two buttons end up being the right size for the text on them: ``` import javax.swing.*; public class ButtonTest { public static void main(String[] args) { JButton button1 = new JButton("Some label"); JButton button2 = new JButton("Some much longer label"); JFrame frame = new JFrame(); JPanel panel = new JPanel(); panel.add(button1); panel.add(button2); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } } ``` If you really do want the size, rather than just letting Java do its best, then I would recommend calling `button1.getPreferredSize()` and `button2.getPreferredSize()` after the call to `frame.pack()`.
Just a quick glance at the API Docs shows: ``` public Rectangle2D getStringBounds(String str, FontRenderContext frc) ``` in java.awt.Font > Returns the logical bounds of the specified String in the specified FontRenderContext. The > logical bounds contains the origin, ascent, **advance**, and height, which includes the leading. So that should help you.
How to measure the needed size for a button in Java
[ "", "java", "button", "" ]