text
stringlengths
8
267k
meta
dict
Q: How can I clear event subscriptions in C#? Take the following C# class: c1 { event EventHandler someEvent; } If there are a lot of subscriptions to c1's someEvent event and I want to clear them all, what is the best way to achieve this? Also consider that subscriptions to this event could be/are lambdas/anonymous delegates. Currently my solution is to add a ResetSubscriptions() method to c1 that sets someEvent to null. I don't know if this has any unseen consequences. A: The best practice to clear all subscribers is to set the someEvent to null by adding another public method if you want to expose this functionality to outside. This has no unseen consequences. The precondition is to remember to declare SomeEvent with the keyword 'event'. Please see the book - C# 4.0 in the nutshell, page 125. Some one here proposed to use Delegate.RemoveAll method. If you use it, the sample code could follow the below form. But it is really stupid. Why not just SomeEvent=null inside the ClearSubscribers() function? public void ClearSubscribers () { SomeEvent = (EventHandler) Delegate.RemoveAll(SomeEvent, SomeEvent); // Then you will find SomeEvent is set to null. } A: Setting the event to null inside the class works. When you dispose a class you should always set the event to null, the GC has problems with events and may not clean up the disposed class if it has dangling events. A: You can achieve this by using the Delegate.Remove or Delegate.RemoveAll methods. A: Add a method to c1 that will set 'someEvent' to null. public class c1 { event EventHandler someEvent; public ResetSubscriptions() => someEvent = null; } A: Conceptual extended boring comment. I rather use the word "event handler" instead of "event" or "delegate". And used the word "event" for other stuff. In some programming languages (VB.NET, Object Pascal, Objective-C), "event" is called a "message" or "signal", and even have a "message" keyword, and specific sugar syntax. const WM_Paint = 998; // <-- "question" can be done by several talkers WM_Clear = 546; type MyWindowClass = class(Window) procedure NotEventHandlerMethod_1; procedure NotEventHandlerMethod_17; procedure DoPaintEventHandler; message WM_Paint; // <-- "answer" by this listener procedure DoClearEventHandler; message WM_Clear; end; And, in order to respond to that "message", a "event handler" respond, whether is a single delegate or multiple delegates. Summary: "Event" is the "question", "event handler (s)" are the answer (s). A: From within the class, you can set the (hidden) variable to null. A null reference is the canonical way of representing an empty invocation list, effectively. From outside the class, you can't do this - events basically expose "subscribe" and "unsubscribe" and that's it. It's worth being aware of what field-like events are actually doing - they're creating a variable and an event at the same time. Within the class, you end up referencing the variable. From outside, you reference the event. See my article on events and delegates for more information. A: class c1 { event EventHandler someEvent; ResetSubscriptions() => someEvent = delegate { }; } It is better to use delegate { } than null to avoid the null ref exception. A: Remove all events, assume the event is an "Action" type: Delegate[] dary = TermCheckScore.GetInvocationList(); if ( dary != null ) { foreach ( Delegate del in dary ) { TermCheckScore -= ( Action ) del; } } A: This is my solution: public class Foo : IDisposable { private event EventHandler _statusChanged; public event EventHandler StatusChanged { add { _statusChanged += value; } remove { _statusChanged -= value; } } public void Dispose() { _statusChanged = null; } } You need to call Dispose() or use using(new Foo()){/*...*/} pattern to unsubscribe all members of invocation list. A: Instead of adding and removing callbacks manually and having a bunch of delegate types declared everywhere: // The hard way public delegate void ObjectCallback(ObjectType broadcaster); public class Object { public event ObjectCallback m_ObjectCallback; void SetupListener() { ObjectCallback callback = null; callback = (ObjectType broadcaster) => { // one time logic here broadcaster.m_ObjectCallback -= callback; }; m_ObjectCallback += callback; } void BroadcastEvent() { m_ObjectCallback?.Invoke(this); } } You could try this generic approach: public class Object { public Broadcast<Object> m_EventToBroadcast = new Broadcast<Object>(); void SetupListener() { m_EventToBroadcast.SubscribeOnce((ObjectType broadcaster) => { // one time logic here }); } ~Object() { m_EventToBroadcast.Dispose(); m_EventToBroadcast = null; } void BroadcastEvent() { m_EventToBroadcast.Broadcast(this); } } public delegate void ObjectDelegate<T>(T broadcaster); public class Broadcast<T> : IDisposable { private event ObjectDelegate<T> m_Event; private List<ObjectDelegate<T>> m_SingleSubscribers = new List<ObjectDelegate<T>>(); ~Broadcast() { Dispose(); } public void Dispose() { Clear(); System.GC.SuppressFinalize(this); } public void Clear() { m_SingleSubscribers.Clear(); m_Event = delegate { }; } // add a one shot to this delegate that is removed after first broadcast public void SubscribeOnce(ObjectDelegate<T> del) { m_Event += del; m_SingleSubscribers.Add(del); } // add a recurring delegate that gets called each time public void Subscribe(ObjectDelegate<T> del) { m_Event += del; } public void Unsubscribe(ObjectDelegate<T> del) { m_Event -= del; } public void Broadcast(T broadcaster) { m_Event?.Invoke(broadcaster); for (int i = 0; i < m_SingleSubscribers.Count; ++i) { Unsubscribe(m_SingleSubscribers[i]); } m_SingleSubscribers.Clear(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/153573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "151" }
Q: Can I assign a global hotkey to an Adobe AIR app? Is it possible to assign a global hotkey to a specific feature in an Adobe AIR app, i.e. the app feature responds to the hotkey whether the app is active or not (it must be running of course, but only in the system tray). A: I don't this it's possible with Adobe AIR itself. The only method I can think of: * *Install 3rd party hotkey application (like AutoHotkey or HotKeyBind) *Configure hotkey application to make CTRL+ALT+Q to launch "c:\programs\thvo42\coolapp.exe --hotkey q" *In your AIR application, register for the NativeApplication.invoke event, and watch for arguments like '--hotkey q' to know that the Q hotkey was pressed, and then act accordingly. Of course, this is kind of a hassle, maybe with some hacking you can roll it all into a single install file. A: From the Reference Manual: To listen globally for key events, listen on the Stage for the capture and target or bubble phase. A: SWFKit creates a wrapper around your flash/flex movie, and allows access to system DLLs and other goodies, but unfortunately it would export as an .exe, so windows only and no AIR. ASFAIK, there is no support for it by using AIR alone.
{ "language": "en", "url": "https://stackoverflow.com/questions/153581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How to iterate over a timespan after days, hours, weeks and months? How do I iterate over a timespan after days, hours, weeks or months? Something like: for date in foo(from_date, to_date, delta=HOURS): print date Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates. A: I achieved this using pandas and datetime libraries as follows. It was much more convenient for me. import pandas as pd from datetime import datetime DATE_TIME_FORMAT = '%Y-%m-%d %H:%M:%S' start_datetime = datetime.strptime('2018-05-18 00:00:00', DATE_TIME_FORMAT) end_datetime = datetime.strptime('2018-05-23 13:00:00', DATE_TIME_FORMAT) timedelta_index = pd.date_range(start=start_datetime, end=end_datetime, freq='H').to_series() for index, value in timedelta_index.iteritems(): dt = index.to_pydatetime() print(dt) A: For iterating over months you need a different recipe, since timedeltas can't express "one month". from datetime import date def jump_by_month(start_date, end_date, month_step=1): current_date = start_date while current_date < end_date: yield current_date carry, new_month = divmod(current_date.month - 1 + month_step, 12) new_month += 1 current_date = current_date.replace(year=current_date.year + carry, month=new_month) (NB: you have to subtract 1 from the month for the modulus operation then add it back to new_month, since months in datetime.dates start at 1.) A: I don't think there is a method in Python library, but you can easily create one yourself using datetime module: from datetime import date, datetime, timedelta def datespan(startDate, endDate, delta=timedelta(days=1)): currentDate = startDate while currentDate < endDate: yield currentDate currentDate += delta Then you could use it like this: >>> for day in datespan(date(2007, 3, 30), date(2007, 4, 3), >>> delta=timedelta(days=1)): >>> print day 2007-03-30 2007-03-31 2007-04-01 2007-04-02 Or, if you wish to make your delta smaller: >>> for timestamp in datespan(datetime(2007, 3, 30, 15, 30), >>> datetime(2007, 3, 30, 18, 35), >>> delta=timedelta(hours=1)): >>> print timestamp 2007-03-30 15:30:00 2007-03-30 16:30:00 2007-03-30 17:30:00 2007-03-30 18:30:00 A: Use dateutil and its rrule implementation, like so: from dateutil import rrule from datetime import datetime, timedelta now = datetime.now() hundredDaysLater = now + timedelta(days=100) for dt in rrule.rrule(rrule.MONTHLY, dtstart=now, until=hundredDaysLater): print dt Output is 2008-09-30 23:29:54 2008-10-30 23:29:54 2008-11-30 23:29:54 2008-12-30 23:29:54 Replace MONTHLY with any of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, or SECONDLY. Replace dtstart and until with whatever datetime object you want. This recipe has the advantage for working in all cases, including MONTHLY. Only caveat I could find is that if you pass a day number that doesn't exist for all months, it skips those months. A: Month iteration approach: def months_between(date_start, date_end): months = [] # Make sure start_date is smaller than end_date if date_start > date_end: tmp = date_start date_start = date_end date_end = tmp tmp_date = date_start while tmp_date.month <= date_end.month or tmp_date.year < date_end.year: months.append(tmp_date) # Here you could do for example: months.append(datetime.datetime.strftime(tmp_date, "%b '%y")) if tmp_date.month == 12: # New year tmp_date = datetime.date(tmp_date.year + 1, 1, 1) else: tmp_date = datetime.date(tmp_date.year, tmp_date.month + 1, 1) return months More code but it will do fine dealing with long periods of time checking that the given dates are in order... A: Also can use the module arrow https://arrow.readthedocs.io/en/latest/guide.html#ranges-spans >>> start = datetime(2013, 5, 5, 12, 30) >>> end = datetime(2013, 5, 5, 17, 15) >>> for r in arrow.Arrow.range('hour', start, end): ... print(repr(r)) ... <Arrow [2013-05-05T12:30:00+00:00]> <Arrow [2013-05-05T13:30:00+00:00]> <Arrow [2013-05-05T14:30:00+00:00]> <Arrow [2013-05-05T15:30:00+00:00]> <Arrow [2013-05-05T16:30:00+00:00]> A: You should modify this line to make this work correctly: current_date = current_date.replace(year=current_date.year + carry,month=new_month,day=1) ;) A: This library provides a handy calendar tool: mxDateTime, that should be enough :)
{ "language": "en", "url": "https://stackoverflow.com/questions/153584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "76" }
Q: SQL sub-query problem with grouping, average In MS Transact SQL, let's say I have a table (Orders) like this: Order Date Order Total Customer # 09/30/2008 8.00 1 09/15/2008 6.00 1 09/01/2008 9.50 1 09/01/2008 1.45 2 09/16/2008 4.50 2 09/17/2008 8.75 3 09/18/2008 2.50 3 What I need out of this is: for each customer the average order amount for the most recent two orders. So for Customer #1, I should get 7.00 (and not 7.83). I've been staring at this for an hour now (inside a larger problem, which I've solved) and I think my brain has frozen. Help for a simple problem? A: This should make it select avg(total), customer from orders o1 where orderdate in ( select top 2 date from orders o2 where o2.customer = o1.customer order by date desc ) group by customer A: In SQL Server 2005 you have the RANK function, used with partition: USE AdventureWorks; GO SELECT i.ProductID, p.Name, i.LocationID, i.Quantity ,RANK() OVER (PARTITION BY i.LocationID ORDER BY i.Quantity DESC) AS 'RANK' FROM Production.ProductInventory i INNER JOIN Production.Product p ON i.ProductID = p.ProductID ORDER BY p.Name; GO Link A: One option would be for you to use a cursor to loop through all the customer Id's, then do the averages as several subqueries. Fair warning though, for large datasets, queries are not very efficient and can take a long time to process.
{ "language": "en", "url": "https://stackoverflow.com/questions/153585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I determine the intersection point of two lines in GDI+? I'm using .NET to make an application with a drawing surface, similar to Visio. The UI connects two objects on the screen with Graphics.DrawLine. This simple implementation works fine, but as the surface gets more complex, I need a more robust way to represent the objects. One of these robust requirements is determining the intersection point for two lines so I can indicate separation via some kind of graphic. So my question is, can anyone suggest a way to do this? Perhaps with a different technique (maybe GraphViz) or an algorithm? A: The representation of lines by y = mx + c is problematic for computer graphics, because vertical lines require m to be infinite. Furthermore, lines in computer graphics have a start and end point, unlike mathematical lines which are infinite in extent. One is usually only interested in a crossing of lines if the crossing point lies on both the line segments in question. If you have two line segments, one from vectors x1 to x1+v1, and one from vectors x2 to x2+v2, then define: a = (v2.v2 v1.(x2-x1) - v1.v2 v2.(x2-x1)) / ((v1.v1)(v2.v2) - (v1.v2)^2) b = (v1.v2 v1.(x2-x1) - v1.v1 v2.(x2-x1)) / ((v1.v1)(v2.v2) - (v1.v2)^2) where for the vectors p=(px,py), q=(qx,qy), p.q is the dot product (px * qx + py * qy). First check if (v1.v1)(v2.v2) = (v1.v2)^2 - if so, the lines are parallel and do not cross. If they are not parallel, then if 0<=a<=1 and 0<=b<=1, the intersection point lies on both of the line segments, and is given by the point x1 + a * v1 Edit The derivation of the equations for a and b is as follows. The intersection point satisfies the vector equation x1 + a*v1 = x2 + b*v2 By taking the dot product of this equation with v1, and with v2, we get two equations: v1.v1*a - v2.v1*b = v1.(x2-x1) v1.v2*a - v2.v2*b = v2.(x2-x1) which form two linear equations for a and b. Solving this system (by multiplying the first equation by v2.v2 and the second by v1.v1 and subtracting, or otherwise) gives the equations for a and b. A: You can ask Dr. Math, see this link. A: If you rotate your frame of reference to align with the first line segment (so the origin is now the start of the first line, and the vector for the first line extends along the X-axis) the question becomes, where does the second line hit the X-axis in the new coordinate system. This is a much easier question to answer. If the first line is called A and it is defined by A.O as the origin of the line and 'A.V' being the vector of the line so that A.O + A.V is the end point of the line. The frame of reference can be defined by the matrix: | A.V.X A.V.Y A.O.X | M = | A.V.Y -A.V.X A.O.Y | | 0 0 1 | In homogeneous coordinates this matrix provides a basis for the frame of reference that maps the line A to 0 to 1 on the X-axis. We can now define the transformed line B as: C.O = M*(B.O) C.V = M*(B.O + B.V) - C.O Where the * operator properly defined for homogeneous coordinates (a projection from 3 space onto 2 space in this case). Now all that remains is to check and see where C hits the X-axis which is the same as solving Y side of the parametric equation of C for t: C.O.Y + t * C.V.Y = 0 -C.O.Y t = -------- C.V.Y If t is in the range 0 to 1, then C hits the X-axis inside the line segment. The place it lands on the X-axis is given by the X side of the parametric equation for C: x = C.O.X + t * C.V.X If x is in the range 0 to 1 then the intersection is on the A line segment. We can then find the point in the original coordinate system with: p = A.O + A.V * x You would of course have to check first to see if either line segment is zero length. Also if C.V.Y = 0 you have parallel line segments. If C.V.X is also zero you have colinear line segments.
{ "language": "en", "url": "https://stackoverflow.com/questions/153592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Programmatically access a Microsoft Project (MPP) file from C# What are my options for programmatically accessing a Microsoft Project file? What are the pros and cons of each approach? I will basically need to import all data from the file into another data structure. Using the Office Interop assembies is low on the preference scale. A: You may use Aspose.Tasks for .NET. This component allows you to work with Microsoft Project files. It doesn't require MS Office to be installed on the server, unlike Office Interop. The API is very simple and easy to use. And it provides a rich set of features to read, edit, write, and convert MPP files. This component is a normal .NET assembly which can be used with your .NET applications. It works on any Windows OS and in 32/64-bit environments as well. Disclosure: I work as developer evangelist at Aspose. A: Here are the options: * *Interop (messy and horribly slow for large projects) *Save project in XML and work with it (messy) *Save project in the database (that's not publishing and it is available for project 2003 only - see ODBC option while saving). I've seen it being used a lot in the integration scenarios *Projette (commercial, $10 per license) *ILog Project Viewer (also commercial) A: The Microsoft Office API provides programmatic access to MS Project. I have only used it for Word and Excel so I don't know how rich the interface is - you will have to do some digging around on MSDN to find out what you can and can't do. One of the Java projects at my company uses a commerical product by Aspose which allows applications to manipulate Office documents including Project. It works well for their purposes, but again, they have only used it for Word and Excel so can't offer much advice on Project. EDIT (2019): I can confirm that it is a very capable product. A: The MPXJ (mpxj.sf.net) library comes in both Java and .Net flavours and will allow you to read and write multiple Microsoft Project file formats using a single consistent API. I am aware of commercial products which use both the Java and the .Net versions of MPXJ without any issues. Disclaimer: I'm the maintainer of MPXJ. A: Sourcefourge.net offers a component in Java which can be integrated with .net applications to read MPP files upto MPP 2007 the link is http://mpxj.sourceforge.net/getting-started.html
{ "language": "en", "url": "https://stackoverflow.com/questions/153593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Efficient way of logging to txt file from a console program What would be the most efficient way of recording to a log (.txt) from a console program on C# and .NET 2.2? My program loops multiple times always outputting different data based on what the user wants, so I'm searching for the most efficient way to achieve this. I know I can always reopen a stream and then close it, but everytime I do that it would be writing just one line, then next time around (seconds later) the program reloops and needs tor write again. In my opinion, that doesn't seem very resourse friendly. I'm using multiple threads that all have output data that I want to log (opening/closing the same file or accessing the same file on different threads might be bad). The "holds a reference to a stream writer that auto-flushes" sounds like a good idea, however I don't know how to do that. A: I accept the performance hit that comes with opening and closing every time I write a line. It is a reliability decision. If you are holding everything in memory and you have a hard crash, you have no log information at all to help troubleshoot. If this is not a concern for you, then holding it in memory will definitely provide better performance. A: You could hook into the tracing framework that forms part of the CLR. Using a simple class like: http://www.chaosink.co.uk/files/tracing.zip you can selectively log diagnostic information. To use it add the class to your application. Create an inistance of the tracer in your class like: private Tracing trace = new Tracing("My.Namespace.Class"); and call it using: MyClass() { trace.Verbose("Entered MyClass"); int x = 12; trace.Information("X is: {0}", x); trace.Verbose("Leaving MyClass"); } There are 4 levels of information in the inbuilt tracing framework: Verbose - To log program flow Information - To log specific information of interest to monitors Warning - To log an invalid state or recoverable exception Error - To log an unrecoverable exception or state To access the information from your application then add into the app.config (or web.config) the following: <system.diagnostics> <trace autoflush="false" indentsize="4"> <listeners> <add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="c:\mylogfile.log" /> </listeners> </trace> <switches> <add name="My.Namespace.Class" value="4"/> </switches> </system.diagnostics> You can also attach listeners for publishing to the eventlog or anywhere else that interests you. More information on the tracing framework can be found at: http://msdn.microsoft.com/en-us/library/ms733025.aspx A: I agree with using log4net. But if you really need something simple consider just having a singleton that holds a reference to a StreamWriter that auto-flushes on every WriteLine. So you keep the file open throughout the Session avoiding the close/open overhead while not risking to loose log data in case of a hard crash. A: Consider using log4net: a tool to help the programmer output log statements to a variety of output targets... We have kept the framework similar in spirit to the original log4j while taking advantage of new features in the .NET runtime. For more information on log4net see the features document... A: A simple approach would be to provide a TextWriterTraceListener and add it to the collection of TraceListeners on the Trace class. This will automatically write all your Trace.Write... calls to the corresponding file. A: The logging frameworks like log4net should handle multi-threading correctly. There might be also a useful hint: the logging significantly pollutes the code making it less readable. Did you consider using aspect for injecting logging functionality to the code at the compile time? See this article for an example.
{ "language": "en", "url": "https://stackoverflow.com/questions/153596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Unknown Column In Where Clause I have a simple query: SELECT u_name AS user_name FROM users WHERE user_name = "john"; I get Unknown Column 'user_name' in where clause. Can I not refer to 'user_name' in other parts of the statement even after select 'u_name as user_name'? A: Your defined alias are not welcomed by the WHERE clause you have to use the HAVING clause for this SELECT u_name AS user_name FROM users HAVING user_name = "john"; OR you can directly use the original column name with the WHERE SELECT u_name AS user_name FROM users WHERE u_name = "john"; Same as you have the result in user defined alias as a result of subquery or any calculation it will be accessed by the HAVING clause not by the WHERE SELECT u_name AS user_name , (SELECT last_name FROM users2 WHERE id=users.id) as user_last_name FROM users WHERE u_name = "john" HAVING user_last_name ='smith' A: Either: SELECT u_name AS user_name FROM users WHERE u_name = "john"; or: SELECT user_name from ( SELECT u_name AS user_name FROM users ) WHERE u_name = "john"; The latter ought to be the same as the former if the RDBMS supports predicate pushing into the in-line view. A: What about: SELECT u_name AS user_name FROM users HAVING user_name = "john"; A: corrected: SELECT u_name AS user_name FROM users WHERE u_name = 'john'; A: No you need to select it with correct name. If you gave the table you select from an alias you can use that though. A: See the following MySQL manual page: http://dev.mysql.com/doc/refman/5.0/en/select.html "A select_expr can be given an alias using AS alias_name. The alias is used as the expression's column name and can be used in GROUP BY, ORDER BY, or HAVING clauses." (...) It is not permissible to refer to a column alias in a WHERE clause, because the column value might not yet be determined when the WHERE clause is executed. See Section B.5.4.4, “Problems with Column Aliases”. A: SELECT user_name FROM ( SELECT name AS user_name FROM users ) AS test WHERE user_name = "john" A: No you cannot. user_name is doesn't exist until return time. A: select u_name as user_name from users where u_name = "john"; Think of it like this, your where clause evaluates first, to determine which rows (or joined rows) need to be returned. Once the where clause is executed, the select clause runs for it. To put it a better way, imagine this: select distinct(u_name) as user_name from users where u_name = "john"; You can't reference the first half without the second. Where always gets evaluated first, then the select clause. A: SQL is evaluated backwards, from right to left. So the where clause is parsed and evaluate prior to the select clause. Because of this the aliasing of u_name to user_name has not yet occurred. A: If you're trying to perform a query like the following (find all the nodes with at least one attachment) where you've used a SELECT statement to create a new field which doesn't actually exist in the database, and try to use the alias for that result you'll run into the same problem: SELECT nodes.*, (SELECT (COUNT(*) FROM attachments WHERE attachments.nodeid = nodes.id) AS attachmentcount FROM nodes WHERE attachmentcount > 0; You'll get an error "Unknown column 'attachmentcount' in WHERE clause". Solution is actually fairly simple - just replace the alias with the statement which produces the alias, eg: SELECT nodes.*, (SELECT (COUNT(*) FROM attachments WHERE attachments.nodeid = nodes.id) AS attachmentcount FROM nodes WHERE (SELECT (COUNT(*) FROM attachments WHERE attachments.nodeid = nodes.id) > 0; You'll still get the alias returned, but now SQL shouldn't bork at the unknown alias. A: Unknown column in WHERE clause caused by lines 1 and 2 and resolved by line 3: * *$sql = "SELECT * FROM users WHERE username =".$userName; *$sql = "SELECT * FROM users WHERE username =".$userName.""; *$sql = "SELECT * FROM users WHERE username ='".$userName."'"; A: May be it helps. You can SET @somevar := ''; SELECT @somevar AS user_name FROM users WHERE (@somevar := `u_name`) = "john"; It works. BUT MAKE SURE WHAT YOU DO! * *Indexes are NOT USED here *There will be scanned FULL TABLE - you hasn't specified the LIMIT 1 part *So, - THIS QUERY WILL BE SLLLOOOOOOW on huge tables. But, may be it helps in some cases A: While you can alias your tables within your query (i.e., "SELECT u.username FROM users u;"), you have to use the actual names of the columns you're referencing. AS only impacts how the fields are returned. A: Just had this problem. Make sure there is no space in the name of the entity in the database. e.g. ' user_name' instead of 'user_name' A: I had the same problem, I found this useful. mysql_query("SELECT * FROM `users` WHERE `user_name`='$user'"); remember to put $user in ' ' single quotes.
{ "language": "en", "url": "https://stackoverflow.com/questions/153598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "149" }
Q: Create MSBuild custom task to modify C# code *before* compile I want to create a custom MSBuild task that changes my .cs files before they are compiled by csc.exe (but, of course, that doesn't modify them in place - I don't want actual source files touched). I am aware of PostSharp and other AOP frameworks for .NET and they are not an option for this particular project, plus I'd like to learn how to do this. What precisely do I have to do to get this to work? Thanks Richard A: Given your restrictions I think you can do the following: * *Create custom task that accepts the list of cs files to adapt prior to compilation *The custom task adapts the list of files received and creates them on disk *The custom task sets the list of changed files on the output parameter *The output of the task would replace the original cs files list *The compilation is done against the changed files. The step 4 ensures that the files that are eventually compiled are the ones that were changed by your custom task. You will heavily rely on the ITaskItem interface for the job.
{ "language": "en", "url": "https://stackoverflow.com/questions/153602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: MPI or Sockets? I'm working on a loosely coupled cluster for some data processing. The network code and processing code is in place, but we are evaluating different methodologies in our approach. Right now, as we should be, we are I/O bound on performance issues, and we're trying to decrease that bottleneck. Obviously, faster switches like Infiniband would be awesome, but we can't afford the luxury of just throwing out what we have and getting new equipment. My question posed is this. All traditional and serious HPC applications done on clusters is typically implemented with message passing versus sending over sockets directly. What are the performance benefits to this? Should we see a speedup if we switched from sockets? A: Performance is not the only consideration in this case, even on high performance clusters. MPI offers a standard API, and is "portable." It is relatively trivial to switch an application between the different versions of MPI. Most MPI implementations use sockets for TCP based communication. Odds are good that any given MPI implementation will be better optimized and provide faster message passing, than a home grown application using sockets directly. In addition, should you ever get a chance to run your code on a cluster that has InfiniBand, the MPI layer will abstract any of those code changes. This is not a trivial advantage - coding an application to directly use OFED (or another IB Verbs) implementation is very difficult. Most MPI applications include small test apps that can be used to verify the correctness of the networking setup independently of your application. This is a major advantage when it comes time to debug your application. The MPI standard includes the "pMPI" interfaces, for profiling MPI calls. This interface also allows you to easily add checksums, or other data verification to all the message passing routines. A: Message Passing is a paradigm not a technology. In the most general installation, MPI will use sockets to communicate. You could see a speed up by switching to MPI, but only in so far as you haven't optimized your socket communication. How is your application I/O bound? Is it bound on transferring the data blocks to the work nodes, or is it bound because of communication during computation? If the answer is "because of communication" then the problem is you are writing a tightly-coupled application and trying to run it on a cluster designed for loosely coupled tasks. The only way to gain performance will be to get better hardware (faster switches, infiniband, etc. )... maybe you could borrow time on someone else's HPC? If the answer is "data block" transfers then consider assigning workers multiple data blocks (so they stay busy longer) & compress the data blocks before transfer. This is a strategy that can help in a loosely coupled application. A: MPI has the benefit that you can do collective communications. Doing broadcasts/reductions in O(log p) /* p is your number of processors*/ instead of O(p) is a big advantage. A: MPI MIGHT use sockets. But there are also MPI implementation to be used with SAN (System area network) that use direct distributed shared memory. That of course if you have the hardware for that. So MPI allows you to use such resources in the future. On that case you can gain massive performance improvements (on my experience with clusters back at university time, you can reach gains of a few orders of magnitude). So if you are writting code that can be ported to higher end clusters, using MPI is a very good idea. Even discarding performance issues, using MPI can save you a lot of time, that you can use to improve performance of other parts of your system or simply save your sanity. A: I'll have to agree with OldMan and freespace. Unless you know of a specific and improvement to some useful metric (performance, maintainability, etc.) over MPI, why reinvent the wheel. MPI represents a large amount of shared knowledge regarding the problem you are trying to solve. There are a huge number of issues you need to address which is beyond just sending data. Connection setup and maintenance will all become your responsibility. If MPI is the exact abstraction (it sounds like it is) you need, use it. At the very least, using MPI and later refactoring it out with your own system is a good approach costing the installation and dependency of MPI. I especially like OldMan's point that MPI gives you much more beyond simple socket communication. You get a slew of parallel and distributed computing implementation with a transparent abstraction. A: I would recommend using MPI instead of rolling your own, unless you are very good at that sort of thing. Having wrote some distributed computing-esque applications using my own protocols, I always find myself reproducing (and poorly reproducing) features found within MPI. Performance wise I would not expect MPI to give you any tangible network speedups - it uses sockets just like you. MPI will however provide you with much the functionality you would need for managing many nodes, i.e. synchronisation between nodes. A: I have not used MPI, but I have used sockets quite a bit. There are a few things to consider on high performance sockets. Are you doing many small packets, or large packets? If you are doing many small packets consider turning off the Nagle algorithm for faster response: setsockopt(m_socket, IPPROTO_TCP, TCP_NODELAY, ...); Also, using signals can actually be much slower when trying to get a high volume of data through. Long ago I made a test program where the reader would wait for a signal, and read a packet - it would get a bout 100 packets/sec. Then I just did blocking reads, and got 10000 reads/sec. The point is look at all these options, and actually test them out. Different conditions will make different techniques faster/slower. It's important to not just get opinions, but to put them to the test. Steve Maguire talks about this in "Writing Solid Code". He uses many examples that are counter-intuitive, and tests them to find out what makes better/faster code. A: MPI uses sockets underneath, so really the only difference should be the API that your code interfaces with. You could fine tune the protocol if you are using sockets directly, but thats about it. What exactly are you doing with the data? A: MPI Uses sockets, and if you know what you are doing you can probably get more bandwidth out of sockets because you need not send as much meta data. But you have to know what you are doing and it's likely to be more error prone. essentially you'd be replacing mpi with your own messaging protocol. A: For high volume, low overhead business messaging you might want to check out OAMQ with several products. The open source variant OpenAMQ supposedly runs the trading at JP Morgan, so it should be reliable, shouldn't it?
{ "language": "en", "url": "https://stackoverflow.com/questions/153616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How can I write a scheduler application in .NET? How can I write a scheduler application in C# .NET? A: You could also try Quartz.Net. A: It all depends on your requirements: * *If you have access to a database you use a table as a queue and a service to poll the queue at regular intervals. *If your application is client only (CLI) you can use the system scheduler ("Scheduled Tasks"). *Lastly, if your application is only in a database (using the CLR in SQL Server 2005 for example) then you can create a SQL Server job to schedule it. A: Assuming you're writing some system that needs to perform an action at a specific clock time, the following would cover the fundamental task of raising an event. Create a System.Timer for each event to be scheduled (wrap in an object that contains the parameters for the event). Set the timer by calculating the milliseconds until the event is supposed to happen. EG: // Set event to occur on October 1st, 2008 at 12:30pm. DateTime eventStarts = new DateTime(2008,10,1,12,30,00); Timer timer = new Timer((eventStarts - DateTime.Now).TotalMilliseconds); Since you didn't go into detail, the rest would be up to you; handle the timer.Elapsed event to do what you want, and write the application as a Windows Service or standalone or whatever. A: Write a windows service, there are excellent help topics on MSDN about what you need to do in order to make it installable etc. Next, add a timer to your project. Not a Winforms timer, those don't work in Windows Services. You'll notice this when the events don't fire. Figure out what your required timer resolution is - in other words, if you have something scheduled to start at midnight, is it Ok if it starts sometime between Midnight and 12:15AM? In production you'll set your timer to fire every X minutes, where X is whatever you can afford. Finally, when I do this I use a Switch statement and an enum to make a state machine, which has states like "Starting", "Fatal Error", "Timer Elapsed / scan for work to do", and "Working". (I divide the above X by two, since it takes two Xs to actually do work.) That may not be the best way of doing it, but I've done it that way a couple of times now and it has worked for me. A: You can try use Windows Task Scheduler API A: You can also use the timer control to have the program fire of whatever event you want every X ticks, or even just one. The best solution really depends on what you're tring to accomplish though.
{ "language": "en", "url": "https://stackoverflow.com/questions/153617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can you get the "real" HttpContext within an ASP.NET MVC application? Unfortunately, I need to do this. I'm using ELMAH for my error log. Before I route to my error.aspx view, I have to grab the default ELMAH error log so I can log the exception. You used to be able to use Elmah.ErrorLog.Default However, this is now marked as obsolete. The compiler directs me to use the method Elmah.ErrorLog.GetDefault(HttpContext context) MVC's context is of type HttpContextBase, which enables us to mock it (YAY!). How can we deal with MVC-unaware libraries that require the old style HttpContext? A: Try System.Web.HttpContext.Current. It should do the trick. Gets HTTP-specific information about an individual HTTP request. MSDN A: this.HttpContext.ApplicationInstance.Context
{ "language": "en", "url": "https://stackoverflow.com/questions/153630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "55" }
Q: Natural Sort in MySQL Is there an elegant way to have performant, natural sorting in a MySQL database? For example if I have this data set: * *Final Fantasy *Final Fantasy 4 *Final Fantasy 10 *Final Fantasy 12 *Final Fantasy 12: Chains of Promathia *Final Fantasy Adventure *Final Fantasy Origins *Final Fantasy Tactics Any other elegant solution than to split up the games' names into their components * *Title: "Final Fantasy" *Number: "12" *Subtitle: "Chains of Promathia" to make sure that they come out in the right order? (10 after 4, not before 2). Doing so is a pain in the a** because every now and then there's another game that breaks that mechanism of parsing the game title (e.g. "Warhammer 40,000", "James Bond 007") A: Here is a quick solution: SELECT alphanumeric, integer FROM sorting_test ORDER BY LENGTH(alphanumeric), alphanumeric A: Just found this: SELECT names FROM your_table ORDER BY games + 0 ASC Does a natural sort when the numbers are at the front, might work for middle as well. A: * *Add a Sort Key (Rank) in your table. ORDER BY rank *Utilise the "Release Date" column. ORDER BY release_date *When extracting the data from SQL, make your object do the sorting, e.g., if extracting into a Set, make it a TreeSet, and make your data model implement Comparable and enact the natural sort algorithm here (insertion sort will suffice if you are using a language without collections) as you'll be reading the rows from SQL one by one as you create your model and insert it into the collection) A: Same function as posted by @plalx, but rewritten to MySQL: DROP FUNCTION IF EXISTS `udf_FirstNumberPos`; DELIMITER ;; CREATE FUNCTION `udf_FirstNumberPos` (`instring` varchar(4000)) RETURNS int LANGUAGE SQL DETERMINISTIC NO SQL SQL SECURITY INVOKER BEGIN DECLARE position int; DECLARE tmp_position int; SET position = 5000; SET tmp_position = LOCATE('0', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF; SET tmp_position = LOCATE('1', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF; SET tmp_position = LOCATE('2', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF; SET tmp_position = LOCATE('3', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF; SET tmp_position = LOCATE('4', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF; SET tmp_position = LOCATE('5', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF; SET tmp_position = LOCATE('6', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF; SET tmp_position = LOCATE('7', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF; SET tmp_position = LOCATE('8', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF; SET tmp_position = LOCATE('9', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF; IF (position = 5000) THEN RETURN 0; END IF; RETURN position; END ;; DROP FUNCTION IF EXISTS `udf_NaturalSortFormat`; DELIMITER ;; CREATE FUNCTION `udf_NaturalSortFormat` (`instring` varchar(4000), `numberLength` int, `sameOrderChars` char(50)) RETURNS varchar(4000) LANGUAGE SQL DETERMINISTIC NO SQL SQL SECURITY INVOKER BEGIN DECLARE sortString varchar(4000); DECLARE numStartIndex int; DECLARE numEndIndex int; DECLARE padLength int; DECLARE totalPadLength int; DECLARE i int; DECLARE sameOrderCharsLen int; SET totalPadLength = 0; SET instring = TRIM(instring); SET sortString = instring; SET numStartIndex = udf_FirstNumberPos(instring); SET numEndIndex = 0; SET i = 1; SET sameOrderCharsLen = CHAR_LENGTH(sameOrderChars); WHILE (i <= sameOrderCharsLen) DO SET sortString = REPLACE(sortString, SUBSTRING(sameOrderChars, i, 1), ' '); SET i = i + 1; END WHILE; WHILE (numStartIndex <> 0) DO SET numStartIndex = numStartIndex + numEndIndex; SET numEndIndex = numStartIndex; WHILE (udf_FirstNumberPos(SUBSTRING(instring, numEndIndex, 1)) = 1) DO SET numEndIndex = numEndIndex + 1; END WHILE; SET numEndIndex = numEndIndex - 1; SET padLength = numberLength - (numEndIndex + 1 - numStartIndex); IF padLength < 0 THEN SET padLength = 0; END IF; SET sortString = INSERT(sortString, numStartIndex + totalPadLength, 0, REPEAT('0', padLength)); SET totalPadLength = totalPadLength + padLength; SET numStartIndex = udf_FirstNumberPos(RIGHT(instring, CHAR_LENGTH(instring) - numEndIndex)); END WHILE; RETURN sortString; END ;; Usage: SELECT name FROM products ORDER BY udf_NaturalSortFormat(name, 10, ".") A: Regarding the best response from Richard Toth https://stackoverflow.com/a/12257917/4052357 Watch out for UTF8 encoded strings that contain 2byte (or more) characters and numbers e.g. 12 南新宿 Using MySQL's LENGTH() in udf_NaturalSortFormat function will return the byte length of the string and be incorrect, instead use CHAR_LENGTH() which will return the correct character length. In my case using LENGTH() caused queries to never complete and result in 100% CPU usage for MySQL DROP FUNCTION IF EXISTS `udf_NaturalSortFormat`; DELIMITER ;; CREATE FUNCTION `udf_NaturalSortFormat` (`instring` varchar(4000), `numberLength` int, `sameOrderChars` char(50)) RETURNS varchar(4000) LANGUAGE SQL DETERMINISTIC NO SQL SQL SECURITY INVOKER BEGIN DECLARE sortString varchar(4000); DECLARE numStartIndex int; DECLARE numEndIndex int; DECLARE padLength int; DECLARE totalPadLength int; DECLARE i int; DECLARE sameOrderCharsLen int; SET totalPadLength = 0; SET instring = TRIM(instring); SET sortString = instring; SET numStartIndex = udf_FirstNumberPos(instring); SET numEndIndex = 0; SET i = 1; SET sameOrderCharsLen = CHAR_LENGTH(sameOrderChars); WHILE (i <= sameOrderCharsLen) DO SET sortString = REPLACE(sortString, SUBSTRING(sameOrderChars, i, 1), ' '); SET i = i + 1; END WHILE; WHILE (numStartIndex <> 0) DO SET numStartIndex = numStartIndex + numEndIndex; SET numEndIndex = numStartIndex; WHILE (udf_FirstNumberPos(SUBSTRING(instring, numEndIndex, 1)) = 1) DO SET numEndIndex = numEndIndex + 1; END WHILE; SET numEndIndex = numEndIndex - 1; SET padLength = numberLength - (numEndIndex + 1 - numStartIndex); IF padLength < 0 THEN SET padLength = 0; END IF; SET sortString = INSERT(sortString, numStartIndex + totalPadLength, 0, REPEAT('0', padLength)); SET totalPadLength = totalPadLength + padLength; SET numStartIndex = udf_FirstNumberPos(RIGHT(instring, CHAR_LENGTH(instring) - numEndIndex)); END WHILE; RETURN sortString; END ;; p.s. I would have added this as a comment to the original but I don't have enough reputation (yet) A: Another option is to do the sorting in memory after pulling the data from mysql. While it won't be the best option from a performance standpoint, if you are not sorting huge lists you should be fine. If you take a look at Jeff's post, you can find plenty of algorithms for what ever language you might be working with. Sorting for Humans : Natural Sort Order A: Add a field for "sort key" that has all strings of digits zero-padded to a fixed length and then sort on that field instead. If you might have long strings of digits, another method is to prepend the number of digits (fixed-width, zero-padded) to each string of digits. For example, if you won't have more than 99 digits in a row, then for "Super Blast 10 Ultra" the sort key would be "Super Blast 0210 Ultra". A: To order: 0 1 2 10 23 101 205 1000 a aac b casdsadsa css Use this query: SELECT column_name FROM table_name ORDER BY column_name REGEXP '^\d*[^\da-z&\.\' \-\"\!\@\#\$\%\^\*\(\)\;\:\\,\?\/\~\`\|\_\-]' DESC, column_name + 0, column_name; A: If you do not want to reinvent the wheel or have a headache with lot of code that does not work, just use Drupal Natural Sort ... Just run the SQL that comes zipped (MySQL or Postgre), and that's it. When making a query, simply order using: ... ORDER BY natsort_canon(column_name, 'natural') A: You can also create in a dynamic way the "sort column" : SELECT name, (name = '-') boolDash, (name = '0') boolZero, (name+0 > 0) boolNum FROM table ORDER BY boolDash DESC, boolZero DESC, boolNum DESC, (name+0), name That way, you can create groups to sort. In my query, I wanted the '-' in front of everything, then the numbers, then the text. Which could result in something like : - 0 1 2 3 4 5 10 13 19 99 102 Chair Dog Table Windows That way you don't have to maintain the sort column in the correct order as you add data. You can also change your sort order depending on what you need. A: A lot of other answers I see here (and in the duplicate questions) basically only work for very specifically formatted data, e.g. a string that's entirely a number, or for which there's a fixed-length alphabetic prefix. This isn't going to work in the general case. It's true that there's not really any way to implement a 100% general nat-sort in MySQL, because to do it what you really need is a modified comparison function, that switches between lexicographic sorting of the strings and numeric sort if/when it encounters a number. Such code could implement any algorithm you could desire for recognising and comparing the numeric portions within two strings. Unfortunately, though, the comparison function in MySQL is internal to its code, and cannot be changed by the user. This leaves a hack of some kind, where you try to create a sort key for your string in which the numeric parts are re-formatted so that the standard lexicographic sort actually sorts them the way you want. For plain integers up to some maximum number of digits, the obvious solution is to simply left-pad them with zeros so that they're all fixed width. This is the approach taken by the Drupal plugin, and the solutions of @plalx / @RichardToth. (@Christian has a different and much more complex solution, but it offers no advantages that I can see). As @tye points out, you can improve on this by prepending a fixed-digit length to each number, rather than simply left-padding it. There's much, much more you can improve on, though, even given the limitations of what is essentially an awkward hack. Yet, there doesn't seem to be any pre-built solutions out there! For example, what about: * *Plus and minus signs? +10 vs 10 vs -10 *Decimals? 8.2, 8.5, 1.006, .75 *Leading zeros? 020, 030, 00000922 *Thousand separators? "1,001 Dalmations" vs "1001 Dalmations" *Version numbers? MariaDB v10.3.18 vs MariaDB v10.3.3 *Very long numbers? 103,768,276,592,092,364,859,236,487,687,870,234,598.55 Extending on @tye's method, I've created a fairly compact NatSortKey() stored function that will convert an arbitrary string into a nat-sort key, and that handles all of the above cases, is reasonably efficient, and preserves a total sort-order (no two different strings have sort keys that compare equal). A second parameter can be used to limit the number of numbers processed in each string (e.g. to the first 10 numbers, say), which can be used to ensure the output fits within a given length. NOTE: Sort-key string generated with a given value of this 2nd parameter should only be sorted against other strings generated with the same value for the parameter, or else they might not sort correctly! You can use it directly in ordering, e.g. SELECT myString FROM myTable ORDER BY NatSortKey(myString,0); ### 0 means process all numbers - resulting sort key might be quite long for certain inputs But for efficient sorting of large tables, it's better to pre-store the sort key in another column (possibly with an index on it): INSERT INTO myTable (myString,myStringNSK) VALUES (@theStringValue,NatSortKey(@theStringValue,10)), ... ... SELECT myString FROM myTable ORDER BY myStringNSK; [Ideally, you'd make this happen automatically by creating the key column as a computed stored column, using something like: CREATE TABLE myTable ( ... myString varchar(100), myStringNSK varchar(150) AS (NatSortKey(myString,10)) STORED, ... KEY (myStringNSK), ...); But for now neither MySQL nor MariaDB allow stored functions in computed columns, so unfortunately you can't yet do this.] My function affects sorting of numbers only. If you want to do other sort-normalization things, such as removing all punctuation, or trimming whitespace off each end, or replacing multi-whitespace sequences with single spaces, you could either extend the function, or it could be done before or after NatSortKey() is applied to your data. (I'd recommend using REGEXP_REPLACE() for this purpose). It's also somewhat Anglo-centric in that I assume '.' for a decimal point and ',' for the thousands-separator, but it should be easy enough to modify if you want the reverse, or if you want that to be switchable as a parameter. It might be amenable to further improvement in other ways; for example it currently sorts negative numbers by absolute value, so -1 comes before -2, rather than the other way around. There's also no way to specify a DESC sort order for numbers while retaining ASC lexicographical sort for text. Both of these issues can be fixed with a little more work; I will updated the code if/when I get the time. There are lots of other details to be aware of - including some critical dependencies on the chaset and collation that you're using - but I've put them all into a comment block within the SQL code. Please read this carefully before using the function for yourself! So, here's the code. If you find a bug, or have an improvement I haven't mentioned, please let me know in the comments! delimiter $$ CREATE DEFINER=CURRENT_USER FUNCTION NatSortKey (s varchar(100), n int) RETURNS varchar(350) DETERMINISTIC BEGIN /**** Converts numbers in the input string s into a format such that sorting results in a nat-sort. Numbers of up to 359 digits (before the decimal point, if one is present) are supported. Sort results are undefined if the input string contains numbers longer than this. For n>0, only the first n numbers in the input string will be converted for nat-sort (so strings that differ only after the first n numbers will not nat-sort amongst themselves). Total sort-ordering is preserved, i.e. if s1!=s2, then NatSortKey(s1,n)!=NatSortKey(s2,n), for any given n. Numbers may contain ',' as a thousands separator, and '.' as a decimal point. To reverse these (as appropriate for some European locales), the code would require modification. Numbers preceded by '+' sort with numbers not preceded with either a '+' or '-' sign. Negative numbers (preceded with '-') sort before positive numbers, but are sorted in order of ascending absolute value (so -7 sorts BEFORE -1001). Numbers with leading zeros sort after the same number with no (or fewer) leading zeros. Decimal-part-only numbers (like .75) are recognised, provided the decimal point is not immediately preceded by either another '.', or by a letter-type character. Numbers with thousand separators sort after the same number without them. Thousand separators are only recognised in numbers with no leading zeros that don't immediately follow a ',', and when they format the number correctly. (When not recognised as a thousand separator, a ',' will instead be treated as separating two distinct numbers). Version-number-like sequences consisting of 3 or more numbers separated by '.' are treated as distinct entities, and each component number will be nat-sorted. The entire entity will sort after any number beginning with the first component (so e.g. 10.2.1 sorts after both 10 and 10.995, but before 11) Note that The first number component in an entity like this is also permitted to contain thousand separators. To achieve this, numbers within the input string are prefixed and suffixed according to the following format: - The number is prefixed by a 2-digit base-36 number representing its length, excluding leading zeros. If there is a decimal point, this length only includes the integer part of the number. - A 3-character suffix is appended after the number (after the decimals if present). - The first character is a space, or a '+' sign if the number was preceded by '+'. Any preceding '+' sign is also removed from the front of the number. - This is followed by a 2-digit base-36 number that encodes the number of leading zeros and whether the number was expressed in comma-separated form (e.g. 1,000,000.25 vs 1000000.25) - The value of this 2-digit number is: (number of leading zeros)*2 + (1 if comma-separated, 0 otherwise) - For version number sequences, each component number has the prefix in front of it, and the separating dots are removed. Then there is a single suffix that consists of a ' ' or '+' character, followed by a pair base-36 digits for each number component in the sequence. e.g. here is how some simple sample strings get converted: 'Foo055' --> 'Foo0255 02' 'Absolute zero is around -273 centigrade' --> 'Absolute zero is around -03273 00 centigrade' 'The $1,000,000 prize' --> 'The $071000000 01 prize' '+99.74 degrees' --> '0299.74+00 degrees' 'I have 0 apples' --> 'I have 00 02 apples' '.5 is the same value as 0000.5000' --> '00.5 00 is the same value as 00.5000 08' 'MariaDB v10.3.0018' --> 'MariaDB v02100130218 000004' The restriction to numbers of up to 359 digits comes from the fact that the first character of the base-36 prefix MUST be a decimal digit, and so the highest permitted prefix value is '9Z' or 359 decimal. The code could be modified to handle longer numbers by increasing the size of (both) the prefix and suffix. A higher base could also be used (by replacing CONV() with a custom function), provided that the collation you are using sorts the "digits" of the base in the correct order, starting with 0123456789. However, while the maximum number length may be increased this way, note that the technique this function uses is NOT applicable where strings may contain numbers of unlimited length. The function definition does not specify the charset or collation to be used for string-type parameters or variables: The default database charset & collation at the time the function is defined will be used. This is to make the function code more portable. However, there are some important restrictions: - Collation is important here only when comparing (or storing) the output value from this function, but it MUST order the characters " +0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" in that order for the natural sort to work. This is true for most collations, but not all of them, e.g. in Lithuanian 'Y' comes before 'J' (according to Wikipedia). To adapt the function to work with such collations, replace CONV() in the function code with a custom function that emits "digits" above 9 that are characters ordered according to the collation in use. - For efficiency, the function code uses LENGTH() rather than CHAR_LENGTH() to measure the length of strings that consist only of digits 0-9, '.', and ',' characters. This works for any single-byte charset, as well as any charset that maps standard ASCII characters to single bytes (such as utf8 or utf8mb4). If using a charset that maps these characters to multiple bytes (such as, e.g. utf16 or utf32), you MUST replace all instances of LENGTH() in the function definition with CHAR_LENGTH() Length of the output: Each number converted adds 5 characters (2 prefix + 3 suffix) to the length of the string. n is the maximum count of numbers to convert; This parameter is provided as a means to limit the maximum output length (to input length + 5*n). If you do not require the total-ordering property, you could edit the code to use suffixes of 1 character (space or plus) only; this would reduce the maximum output length for any given n. Since a string of length L has at most ((L+1) DIV 2) individual numbers in it (every 2nd character a digit), for n<=0 the maximum output length is (inputlength + 5*((inputlength+1) DIV 2)) So for the current input length of 100, the maximum output length is 350. If changing the input length, the output length must be modified according to the above formula. The DECLARE statements for x,y,r, and suf must also be modified, as the code comments indicate. ****/ DECLARE x,y varchar(100); # need to be same length as input s DECLARE r varchar(350) DEFAULT ''; # return value: needs to be same length as return type DECLARE suf varchar(101); # suffix for a number or version string. Must be (((inputlength+1) DIV 2)*2 + 1) chars to support version strings (e.g. '1.2.33.5'), though it's usually just 3 chars. (Max version string e.g. 1.2. ... .5 has ((length of input + 1) DIV 2) numeric components) DECLARE i,j,k int UNSIGNED; IF n<=0 THEN SET n := -1; END IF; # n<=0 means "process all numbers" LOOP SET i := REGEXP_INSTR(s,'\\d'); # find position of next digit IF i=0 OR n=0 THEN RETURN CONCAT(r,s); END IF; # no more numbers to process -> we're done SET n := n-1, suf := ' '; IF i>1 THEN IF SUBSTRING(s,i-1,1)='.' AND (i=2 OR SUBSTRING(s,i-2,1) RLIKE '[^.\\p{L}\\p{N}\\p{M}\\x{608}\\x{200C}\\x{200D}\\x{2100}-\\x{214F}\\x{24B6}-\\x{24E9}\\x{1F130}-\\x{1F149}\\x{1F150}-\\x{1F169}\\x{1F170}-\\x{1F189}]') AND (SUBSTRING(s,i) NOT RLIKE '^\\d++\\.\\d') THEN SET i:=i-1; END IF; # Allow decimal number (but not version string) to begin with a '.', provided preceding char is neither another '.', nor a member of the unicode character classes: "Alphabetic", "Letter", "Block=Letterlike Symbols" "Number", "Mark", "Join_Control" IF i>1 AND SUBSTRING(s,i-1,1)='+' THEN SET suf := '+', j := i-1; ELSE SET j := i; END IF; # move any preceding '+' into the suffix, so equal numbers with and without preceding "+" signs sort together SET r := CONCAT(r,SUBSTRING(s,1,j-1)); SET s = SUBSTRING(s,i); # add everything before the number to r and strip it from the start of s; preceding '+' is dropped (not included in either r or s) END IF; SET x := REGEXP_SUBSTR(s,IF(SUBSTRING(s,1,1) IN ('0','.') OR (SUBSTRING(r,-1)=',' AND suf=' '),'^\\d*+(?:\\.\\d++)*','^(?:[1-9]\\d{0,2}(?:,\\d{3}(?!\\d))++|\\d++)(?:\\.\\d++)*+')); # capture the number + following decimals (including multiple consecutive '.<digits>' sequences) SET s := SUBSTRING(s,LENGTH(x)+1); # NOTE: LENGTH() can be safely used instead of CHAR_LENGTH() here & below PROVIDED we're using a charset that represents digits, ',' and '.' characters using single bytes (e.g. latin1, utf8) SET i := INSTR(x,'.'); IF i=0 THEN SET y := ''; ELSE SET y := SUBSTRING(x,i); SET x := SUBSTRING(x,1,i-1); END IF; # move any following decimals into y SET i := LENGTH(x); SET x := REPLACE(x,',',''); SET j := LENGTH(x); SET x := TRIM(LEADING '0' FROM x); # strip leading zeros SET k := LENGTH(x); SET suf := CONCAT(suf,LPAD(CONV(LEAST((j-k)*2,1294) + IF(i=j,0,1),10,36),2,'0')); # (j-k)*2 + IF(i=j,0,1) = (count of leading zeros)*2 + (1 if there are thousands-separators, 0 otherwise) Note the first term is bounded to <= base-36 'ZY' as it must fit within 2 characters SET i := LOCATE('.',y,2); IF i=0 THEN SET r := CONCAT(r,LPAD(CONV(LEAST(k,359),10,36),2,'0'),x,y,suf); # k = count of digits in number, bounded to be <= '9Z' base-36 ELSE # encode a version number (like 3.12.707, etc) SET r := CONCAT(r,LPAD(CONV(LEAST(k,359),10,36),2,'0'),x); # k = count of digits in number, bounded to be <= '9Z' base-36 WHILE LENGTH(y)>0 AND n!=0 DO IF i=0 THEN SET x := SUBSTRING(y,2); SET y := ''; ELSE SET x := SUBSTRING(y,2,i-2); SET y := SUBSTRING(y,i); SET i := LOCATE('.',y,2); END IF; SET j := LENGTH(x); SET x := TRIM(LEADING '0' FROM x); # strip leading zeros SET k := LENGTH(x); SET r := CONCAT(r,LPAD(CONV(LEAST(k,359),10,36),2,'0'),x); # k = count of digits in number, bounded to be <= '9Z' base-36 SET suf := CONCAT(suf,LPAD(CONV(LEAST((j-k)*2,1294),10,36),2,'0')); # (j-k)*2 = (count of leading zeros)*2, bounded to fit within 2 base-36 digits SET n := n-1; END WHILE; SET r := CONCAT(r,y,suf); END IF; END LOOP; END $$ delimiter ; A: I think this is why a lot of things are sorted by release date. A solution could be to create another column in your table for the "SortKey". This could be a sanitized version of the title which conforms to a pattern you create for easy sorting or a counter. A: Other answers are correct, but you may want to know that MariaDB 10.11 LTS has a natural_sort_key() function. The function is documented here. A: I've written this function for MSSQL 2000 a while ago: /** * Returns a string formatted for natural sorting. This function is very useful when having to sort alpha-numeric strings. * * @author Alexandre Potvin Latreille (plalx) * @param {nvarchar(4000)} string The formatted string. * @param {int} numberLength The length each number should have (including padding). This should be the length of the longest number. Defaults to 10. * @param {char(50)} sameOrderChars A list of characters that should have the same order. Ex: '.-/'. Defaults to empty string. * * @return {nvarchar(4000)} A string for natural sorting. * Example of use: * * SELECT Name FROM TableA ORDER BY Name * TableA (unordered) TableA (ordered) * ------------ ------------ * ID Name ID Name * 1. A1. 1. A1-1. * 2. A1-1. 2. A1. * 3. R1 --> 3. R1 * 4. R11 4. R11 * 5. R2 5. R2 * * * As we can see, humans would expect A1., A1-1., R1, R2, R11 but that's not how SQL is sorting it. * We can use this function to fix this. * * SELECT Name FROM TableA ORDER BY dbo.udf_NaturalSortFormat(Name, default, '.-') * TableA (unordered) TableA (ordered) * ------------ ------------ * ID Name ID Name * 1. A1. 1. A1. * 2. A1-1. 2. A1-1. * 3. R1 --> 3. R1 * 4. R11 4. R2 * 5. R2 5. R11 */ CREATE FUNCTION dbo.udf_NaturalSortFormat( @string nvarchar(4000), @numberLength int = 10, @sameOrderChars char(50) = '' ) RETURNS varchar(4000) AS BEGIN DECLARE @sortString varchar(4000), @numStartIndex int, @numEndIndex int, @padLength int, @totalPadLength int, @i int, @sameOrderCharsLen int; SELECT @totalPadLength = 0, @string = RTRIM(LTRIM(@string)), @sortString = @string, @numStartIndex = PATINDEX('%[0-9]%', @string), @numEndIndex = 0, @i = 1, @sameOrderCharsLen = LEN(@sameOrderChars); -- Replace all char that has to have the same order by a space. WHILE (@i <= @sameOrderCharsLen) BEGIN SET @sortString = REPLACE(@sortString, SUBSTRING(@sameOrderChars, @i, 1), ' '); SET @i = @i + 1; END -- Pad numbers with zeros. WHILE (@numStartIndex <> 0) BEGIN SET @numStartIndex = @numStartIndex + @numEndIndex; SET @numEndIndex = @numStartIndex; WHILE(PATINDEX('[0-9]', SUBSTRING(@string, @numEndIndex, 1)) = 1) BEGIN SET @numEndIndex = @numEndIndex + 1; END SET @numEndIndex = @numEndIndex - 1; SET @padLength = @numberLength - (@numEndIndex + 1 - @numStartIndex); IF @padLength < 0 BEGIN SET @padLength = 0; END SET @sortString = STUFF( @sortString, @numStartIndex + @totalPadLength, 0, REPLICATE('0', @padLength) ); SET @totalPadLength = @totalPadLength + @padLength; SET @numStartIndex = PATINDEX('%[0-9]%', RIGHT(@string, LEN(@string) - @numEndIndex)); END RETURN @sortString; END GO A: MySQL doesn't allow this sort of "natural sorting", so it looks like the best way to get what you're after is to split your data set up as you've described above (separate id field, etc), or failing that, perform a sort based on a non-title element, indexed element in your db (date, inserted id in the db, etc). Having the db do the sorting for you is almost always going to be quicker than reading large data sets into your programming language of choice and sorting it there, so if you've any control at all over the db schema here, then look at adding easily-sorted fields as described above, it'll save you a lot of hassle and maintenance in the long run. Requests to add a "natural sort" come up from time to time on the MySQL bugs and discussion forums, and many solutions revolve around stripping out specific parts of your data and casting them for the ORDER BY part of the query, e.g. SELECT * FROM table ORDER BY CAST(mid(name, 6, LENGTH(c) -5) AS unsigned) This sort of solution could just about be made to work on your Final Fantasy example above, but isn't particularly flexible and unlikely to extend cleanly to a dataset including, say, "Warhammer 40,000" and "James Bond 007" I'm afraid. A: So, while I know that you have found a satisfactory answer, I was struggling with this problem for awhile, and we'd previously determined that it could not be done reasonably well in SQL and we were going to have to use javascript on a JSON array. Here's how I solved it just using SQL. Hopefully this is helpful for others: I had data such as: Scene 1 Scene 1A Scene 1B Scene 2A Scene 3 ... Scene 101 Scene XXA1 Scene XXA2 I actually didn't "cast" things though I suppose that may also have worked. I first replaced the parts that were unchanging in the data, in this case "Scene ", and then did a LPAD to line things up. This seems to allow pretty well for the alpha strings to sort properly as well as the numbered ones. My ORDER BY clause looks like: ORDER BY LPAD(REPLACE(`table`.`column`,'Scene ',''),10,'0') Obviously this doesn't help with the original problem which was not so uniform - but I imagine this would probably work for many other related problems, so putting it out there. A: If you're using PHP you can do the the natural sort in php. $keys = array(); $values = array(); foreach ($results as $index => $row) { $key = $row['name'].'__'.$index; // Add the index to create an unique key. $keys[] = $key; $values[$key] = $row; } natsort($keys); $sortedValues = array(); foreach($keys as $index) { $sortedValues[] = $values[$index]; } I hope MySQL will implement natural sorting in a future version, but the feature request (#1588) is open since 2003, So I wouldn't hold my breath. A: A simplified non-udf version of the best response of @plaix/Richard Toth/Luke Hoggett, which works only for the first integer in the field, is SELECT name, LEAST( IFNULL(NULLIF(LOCATE('0', name), 0), ~0), IFNULL(NULLIF(LOCATE('1', name), 0), ~0), IFNULL(NULLIF(LOCATE('2', name), 0), ~0), IFNULL(NULLIF(LOCATE('3', name), 0), ~0), IFNULL(NULLIF(LOCATE('4', name), 0), ~0), IFNULL(NULLIF(LOCATE('5', name), 0), ~0), IFNULL(NULLIF(LOCATE('6', name), 0), ~0), IFNULL(NULLIF(LOCATE('7', name), 0), ~0), IFNULL(NULLIF(LOCATE('8', name), 0), ~0), IFNULL(NULLIF(LOCATE('9', name), 0), ~0) ) AS first_int FROM table ORDER BY IF(first_int = ~0, name, CONCAT( SUBSTR(name, 1, first_int - 1), LPAD(CAST(SUBSTR(name, first_int) AS UNSIGNED), LENGTH(~0), '0'), SUBSTR(name, first_int + LENGTH(CAST(SUBSTR(name, first_int) AS UNSIGNED))) )) ASC A: I have tried several solutions but the actually it is very simple: SELECT test_column FROM test_table ORDER BY LENGTH(test_column) DESC, test_column DESC /* Result -------- value_1 value_2 value_3 value_4 value_5 value_6 value_7 value_8 value_9 value_10 value_11 value_12 value_13 value_14 value_15 ... */ A: Also there is natsort. It is intended to be a part of a drupal plugin, but it works fine stand-alone. A: Here is a simple one if titles only have the version as a number: ORDER BY CAST(REGEXP_REPLACE(title, "[a-zA-Z]+", "") AS INT)'; Otherwise you can use simple SQL if you use a pattern (this pattern uses a # before the version): create table titles(title); insert into titles (title) values ('Final Fantasy'), ('Final Fantasy #03'), ('Final Fantasy #11'), ('Final Fantasy #10'), ('Final Fantasy #2'), ('Bond 007 ##2'), ('Final Fantasy #01'), ('Bond 007'), ('Final Fantasy #11}'); select REGEXP_REPLACE(title, "#([0-9]+)", "\\1") as title from titles ORDER BY REGEXP_REPLACE(title, "#[0-9]+", ""), CAST(REGEXP_REPLACE(title, ".*#([0-9]+).*", "\\1") AS INT); +-------------------+ | title | +-------------------+ | Bond 007 | | Bond 007 #2 | | Final Fantasy | | Final Fantasy 01 | | Final Fantasy 2 | | Final Fantasy 03 | | Final Fantasy 10 | | Final Fantasy 11 | | Final Fantasy 11} | +-------------------+ 8 rows in set, 2 warnings (0.001 sec) You can use other patterns if needed. For example if you have a movie "I'm #1" and "I'm #1 part 2" then maybe wrap the version e.g. "Final Fantasy {11}" A: I know this topic is ancient but I think I've found a way to do this: SELECT * FROM `table` ORDER BY CONCAT( GREATEST( LOCATE('1', name), LOCATE('2', name), LOCATE('3', name), LOCATE('4', name), LOCATE('5', name), LOCATE('6', name), LOCATE('7', name), LOCATE('8', name), LOCATE('9', name) ), name ) ASC Scrap that, it sorted the following set incorrectly (It's useless lol): Final Fantasy 1 Final Fantasy 2 Final Fantasy 5 Final Fantasy 7 Final Fantasy 7: Advent Children Final Fantasy 12 Final Fantasy 112 FF1 FF2
{ "language": "en", "url": "https://stackoverflow.com/questions/153633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "97" }
Q: Updating UI After Asynchronous WebMethod Calls Greetings! I have a WebService that contains a WebMethod that does some work and returns a boolean value. The work that it does may or may not take some time, so I'd like to call it asynchronously. [WebService(Namespace = "http://tempuri.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] public class MyWebSvc : System.Web.Services.WebService { [WebMethod] public bool DoWork() { bool succ = false; try { // do some work, which might take a while } catch (Exception ex) { // handle succ = false; } return succ; } } This WebService exists on each server in a web farm. So to call the DoWork() method on each server, I have a class library to do so, based on a list of server URLs: static public class WebSvcsMgr { static public void DoAllWork(ICollection<string> servers) { MyWebSvc myWebSvc = new MyWebSvc(); foreach (string svr_url in servers) { myWebSvc.Url = svr_url; myWebSvc.DoWork(); } } } Finally, this is called from the Web interface in an asp:Button click event like so: WebSvcsMgr.DoAllWork(server_list); For the static DoAllWork() method called by the Web Form, I plan to make this an asynchronous call via IAsyncResult. However, I'd like to report a success/fail of the DoWork() WebMethod for each server in the farm as the results are returned. What would be the best approach to this in conjuction with an UpdatePanel? A GridView? Labels? And how could this be returned by the static helper class to the Web Form? A: Asynchronous pages are helpful in scenarios when you need to asynchronously call web service methods. A: A Literal in a conditional Update Panel would be fine. <asp:UpdatePanel ID="up" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:Literal ID="litUpdateMe" runat="server" /> </ContentTemplate> </asp:UpdatePanel>
{ "language": "en", "url": "https://stackoverflow.com/questions/153639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Why do you need $ when accessing array and hash elements in Perl? Since arrays and hashes can only contain scalars in Perl, why do you have to use the $ to tell the interpreter that the value is a scalar when accessing array or hash elements? In other words, assuming you have an array @myarray and a hash %myhash, why do you need to do: $x = $myarray[1]; $y = $myhash{'foo'}; instead of just doing : $x = myarray[1]; $y = myhash{'foo'}; Why are the above ambiguous? Wouldn't it be illegal Perl code if it was anything but a $ in that place? For example, aren't all of the following illegal in Perl? @var[0]; @var{'key'}; %var[0]; %var{'key'}; A: This is valid Perl: @var[0]. It is an array slice of length one. @var[0,1] would be an array slice of length two. @var['key'] is not valid Perl because arrays can only be indexed by numbers, and the other two (%var[0] and %var['key']) are not valid Perl because hash slices use the {} to index the hash. @var{'key'} and @var{0} are both valid hash slices, though. Obviously it isn't normal to take slices of length one, but it is certainly valid. See the slice section of perldata perldocfor more information about slicing in Perl. A: People have already pointed out that you can have slices and contexts, but sigils are there to separate the things that are variables from everything else. You don't have to know all of the keywords or subroutine names to choose a sensible variable name. It's one of the big things I miss about Perl in other languages. A: I can think of one way that $x = myarray[1]; is ambiguous - what if you wanted a array called m? $x = m[1]; How can you tell that apart from a regex match? In other words, the syntax is there to help the Perl interpreter, well, interpret! A: In Perl 5 (to be changed in Perl 6) a sigil indicates the context of your expression. * *You want a particular scalar out of a hash so it's $hash{key}. *You want the value of a particular slot out of an array, so it's $array[0]. However, as pointed out by zigdon, slices are legal. They interpret the those expressions in a list context. * *You want a lists of 1 value in a hash @hash{key} works *But also larger lists work as well, like @hash{qw<key1 key2 ... key_n>}. *You want a couple of slots out of an array @array[0,3,5..7,$n..$n+5] works *@array[0] is a list of size 1. There is no "hash context", so neither %hash{@keys} nor %hash{key} has meaning. So you have "@" + "array[0]" <=> < sigil = context > + < indexing expression > as the complete expression. A: The sigil provides the context for the access: * *$ means scalar context (a scalar variable or a single element of a hash or an array) *@ means list context (a whole array or a slice of a hash or an array) *% is an entire hash A: In Perl 5 you need the sigils ($ and @) because the default interpretation of bareword identifier is that of a subroutine call (thus eliminating the need to use & in most cases ). A: I've just used my $x = myarray[1]; in a program and, to my surprise, here's what happened when I ran it: $ perl foo.pl Flying Butt Monkeys! That's because the whole program looks like this: $ cat foo.pl #!/usr/bin/env perl use strict; use warnings; sub myarray { print "Flying Butt Monkeys!\n"; } my $x = myarray[1]; So myarray calls a subroutine passing it a reference to an anonymous array containing a single element, 1. That's another reason you need the sigil on an array access. A: Slices aren't illegal: @slice = @myarray[1, 2, 5]; @slice = @myhash{qw/foo bar baz/}; And I suspect that's part of the reason why you need to specify if you want to get a single value out of the hash/array or not. A: The sigil give you the return type of the container. So if something starts with @, you know that it returns a list. If it starts with $, it returns a scalar. Now if there is only an identifier after the sigil (like $foo or @foo, then it's a simple variable access. If it's followed by a [, it is an access on an array, if it's followed by a {, it's an access on a hash. # variables $foo @foo # accesses $stuff{blubb} # accesses %stuff, returns a scalar @stuff{@list} # accesses %stuff, returns an array $stuff[blubb] # accesses @stuff, returns a scalar # (and calls the blubb() function) @stuff[blubb] # accesses @stuff, returns an array Some human languages have very similar concepts. However many programmers found that confusing, so Perl 6 uses an invariant sigil. In general the Perl 5 compiler wants to know at compile time if something is in list or in scalar context, so without the leading sigil some terms would become ambiguous.
{ "language": "en", "url": "https://stackoverflow.com/questions/153644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Automating Word Mailmerge not working as expected I'm having a problem with some mail merge code that is supposed to produce letters within our application. I'm aware that this code is a bit rough at the moment, but we're in the "Get something working" phase before we tidy it up. Now the way this is supposed to work, and the way it works when we do it manually, is we have a file (the fileOut variable + ".template") which is a template for the letter. We open that template, merge it, and then save it as the filename in the fileOut variable. However, what it is doing is saving a copy of the template file to the fileout filename, instead of the output of the merge. I've searched, and I seem to be banging my head against a brick wall. datafile is the datafile that contains the merge data. Using the same files, it all works if you do it manually. Public Function processFile(ByVal datafile As String, ByVal fileOut As String) As String Dim ans As String = String.Empty errorLog = "C:\Temp\Template_error.log" If (File.Exists(datafile)) Then Try ' Create an instance of Word and make it invisible.' wrdApp = CreateObject("Word.Application") wrdApp.Visible = False ' Add a new document.' wrdDoc = wrdApp.Documents.Add(fileOut & ".template") wrdDoc.Select() Dim wrdSelection As Word.Selection Dim wrdMailMerge As Word.MailMerge wrdDoc.MailMerge.OpenDataSource(datafile) wrdSelection = wrdApp.Selection() wrdMailMerge = wrdDoc.MailMerge() With wrdMailMerge .Execute() End With wrdDoc.SaveAs(fileOut) wrdApp.Quit(False) ' Release References.' wrdSelection = Nothing wrdMailMerge = Nothing wrdDoc = Nothing wrdApp = Nothing ans = "Merged OK" Call writeToLogFile(errorLog, "This worked, written to " & fileOut) Catch ex As Exception ans = "error : exception thrown " & ex.ToString Call writeToLogFile(errorLog, ans) End Try Else ans = "error ; unable to open Date File : " & datafile If (logErrors) Then Call writeToLogFile(errorLog, "The specified source csv file does not exist. Unable " & _ "to process it. Filename provided: " & datafile) End If End If Return ans End Function A: I've found the solution. When you merge a document, it creates a new document with the merge results in it. Code fragment below explains. wrdDoc = wrdApp.Documents.Add(TemplateFileName) wrdDoc.Select() Dim wrdSelection As Word.Selection Dim wrdMailMerge As Word.MailMerge wrdDoc.MailMerge.OpenDataSource(DataFileName) wrdSelection = wrdApp.Selection() wrdMailMerge = wrdDoc.MailMerge() With wrdMailMerge .Execute() End With ' This is the wrong thing to do. It just re-saves the template file you opened. ' 'wrdDoc.SaveAs(OutputFileName) ' ' The resulting merged document is actually stored ' ' in the MailMerge object, so you have to save that ' wrdMailMerge.Application.ActiveDocument.SaveAs(OutputFileName) wrdApp.Quit(False) A: I think the problem is this line: wrdDoc.MailMerge.OpenDataSource(templateName) So templateName is something like 'C:\My Template.doc', right? It looks like you are supplying the file path of a the Word document itself instead of a data source (the Excel or CSV file, Access Table, etc.) linked to the ".template" document. Try: data = "C:\My Data.xls" wrdDoc.MailMerge.OpenDataSource(data) A: One way to cheat is to record a macro while manually doing all the steps you mention. Once you're done, adjust the macro to be more flexible. That's what I did last time I couldn't figure it out while writing my own macro's :)
{ "language": "en", "url": "https://stackoverflow.com/questions/153666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: GUIDs in a C++ Linux GCC app I've got a bunch of servers running this Linux app. I'd like for them to be able to generate a GUID with a low probability of collision. I'm sure I could just pull 128 bytes out of /dev/urandom and that would probably be fine, but is there a simple & easy way to generate a GUID that is more equivalent to the Win32 one? Specifically, one that takes into account space (well, MAC address), time, and randomness? I don't want to call off the box for it, I just want something like CreateGuid() A: There is libuuid. A: If you are going to use something then an Internet standard would be a good idea: Check out RFC (Request For Comment). The one I know that is specific to GUID is: RFC 4122 A: This Internet Draft describes one type of UUID in great details and I have used a similar approach with great success when I needed a UUID implementation and could not link to an existing library for architectural reasons. This article provides a good overview. A: There is a Boost version available. http://www.boostpro.com/vault/index.php?action=downloadfile&filename=uuid_v11.zip&directory=&PHPSESSID=69e18b945f686398b963710fd52f143a
{ "language": "en", "url": "https://stackoverflow.com/questions/153676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: 7-Zip (7za.dll) .NET wrapper Is there some code or a library that lets me control the 7-Zip unpacking functionality from C# code? A: There is a project on CodePlex, SevenZipSharp. I haven't tried it yet, but it looks promising.
{ "language": "en", "url": "https://stackoverflow.com/questions/153678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Managing Window Z-Order Like Photoshop CS So I've got an application whose window behavior I would like to behave more like Photoshop CS. In Photoshop CS, the document windows always stay behind the tool windows, but are still top level windows. For MDI child windows, since the document window is actually a child, you can't move it outside of the main window. In CS, though, you can move your image to a different monitor fine, which is a big advantage over docked applications like Visual Studio, and over regular MDI applications. Anyway, here's my research so far. I've tried to intercept the WM_MOUSEACTIVATE message, and use the DeferWindowPos commands to do my own ordering of the window, and then return MA_NOACTIVATEANDEAT, but that causes the window to not be activated properly, and I believe there are other commands that "activate" a window without calling WM_MOUSEACTIVATE (like SetFocus() I think), so that method probably won't work anyway. I believe Windows' procedure for "activating" a window is 1. notify the unactivated window with the WM_NCACTIVATE and WM_ACTIVATE messages 2. move the window to the top of the z-order (sending WM_POSCHANGING, WM_POSCHANGED and repaint messages) 3. notify the newly activated window with WM_NCACTIVATE and WM_ACTIVATE messages. It seems the cleanest way to do it would be to intercept the first WM_ACTIVATE message, and somehow notify Windows that you're going to override their way of doing the z-ordering, and then use the DeferWindowPos commands, but I can't figure out how to do it that way. It seems once Windows sends the WM_ACTIVATE message, it's already going to do the reordering its own way, so any DeferWindowPos commands I use are overridden. Right now I've got a basic implementation quasy-working that makes the tool windows topmost when the app is activated, but then makes them non-topmost when it's not, but it's very quirky (it sometimes gets on top of other windows like the task manager, whereas Photoshop CS doesn't do that, so I think Photoshop somehow does it differently) and it just seems like there would be a more intuitive way of doing it. Anyway, does anyone know how Photoshop CS does it, or a better way than using topmost? A: I havn't seen anything remarkable about Photoshop CS that requries anything close to this level of hacking that can't instead be done simply by specifying the correct owner window relationships when creating windows. i.e. any window that must be shown above some other window specifies that window as its owner when being created - if you have multiple document windows, each one gets its own set of owned child windows that you can dynamically show and hide as the document window gains and looses activation. A: You can try handle WM_WINDOWPOSCHANGING event to prevent overlaping another windows (with pseudo-topmost flag). So you are avoiding all problems with setting/clearing TopMost flag. public class BaseForm : Form { public virtual int TopMostLevel { get { return 0; } } [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool EnumThreadWindows(uint dwThreadId, Win32Callback lpEnumFunc, IntPtr lParam); /// <summary> /// Get process window handles sorted by z order from top to bottom. /// </summary> public static IEnumerable<IntPtr> GetWindowsSortedByZOrder() { List<IntPtr> handles = new List<IntPtr>(); EnumThreadWindows(GetCurrentThreadId(), (hWnd, lparam) => { handles.Add(hWnd); return true; }, IntPtr.Zero); return handles; } protected override void WndProc(ref Message m) { if (m.Msg == (int)WindowsMessages.WM_WINDOWPOSCHANGING) { //Looking for Window at the bottom of Z-order, but with TopMostLevel > this.TopMostLevel foreach (IntPtr handle in GetWindowsSortedByZOrder().Reverse()) { var window = FromHandle(handle) as BaseForm; if (window != null && this.TopMostLevel < window.TopMostLevel) { //changing hwndInsertAfter field in WindowPos structure if (IntPtr.Size == 4) { Marshal.WriteInt32(m.LParam, IntPtr.Size, window.Handle.ToInt32()); } else if (IntPtr.Size == 8) { Marshal.WriteInt64(m.LParam, IntPtr.Size, window.Handle.ToInt64()); } break; } } } base.WndProc(ref m); } } public class FormWithLevel1 : BaseForm { public override int TopMostLevel { get { return 1; } } } So, FormWithLevel1 will be always over any BaseForm. You can add any number of Z-order Levels. Windows on the same level behave as usual, but will be always under Windows with level Current+1 and over Windows with level Current-1. A: Not being familiar to Photoshop CS it is bit hard to know exactly what look and feel you are trying to achieve. But I would have thought if you created a modeless dialog window as you tool window and you made sure it had the WS_POPUP style then the resulting tool window would not be clipped to the main parent window and Windows would automatically manage the z-Order making sure that the tool window stayed on top of the parent window. And as the tool window dialog is modeless it would not interfere with the main window. A: Managing Window Z-Order Like Photoshop CS You should create the toolwindow with the image as the parent so that windows manage the zorder. There is no need to set WS_POPUP or WS_EX_TOOLWINDOW. Those flags only control the rendering of the window. Call CreateWindowEx with the hwnd of the image window as the parent. A: In reply to Chris and Emmanuel, the problem with using the owner window feature is that a window can only be owned by one other window, and you can't change who owns a window. So if tool windows A and B always need to be on top of document windows C and D, then when doc window C is active, I want it to own windows A and B so that A and B will always be on top of it. But when I activate doc window D, I would have to change ownership of tool windows A and B to D, or else they will go behind window D (since they're owned by window C). However, Windows doesn't allow you to change ownership of a window, so that option isn't available. For now I've got it working with the topmost feature, but it is a hack at best. I do get some consolation in the fact that GIMP has tried themselves to emulate Photoshop with their version 2.6, but even their implementation occasionally acts quirky, which leads me to believe that their implementation was a hack as well. A: Have you tried to make the tool windows topmost when the main window receives focus, and non-topmost when it loses focus? It sounds like you've already started to look at this sort of solution... but much more elaborate. As a note, it seems to be quite well documented that tool windows exhibit unexpected behavior when it comes to z-ordering. I haven't found anything on MSDN to confirm it, but it could be that Windows manages them specially. A: I would imagine they've, since they're not using .NET, rolled their own windowing code over the many years of its existence and it is now, like Amazon's original OBIDOS, so custom to their product that off-the-shelf (aka .NET's MDI support) just aren't going to come close. I don't like answering without a real answer, but likely you'd have to spend a lot of time and effort to get something similar if Photoshop-like is truly your goal. Is it worth your time? Just remember many programmers over many years and versions have come together to get Photoshop's simple-seeming windowing behavior to work just right and to feel natural to you. It looks like you're already having to delve pretty deep into Win32 API functions and values to even glimpse at a "solution" and that should be your first red flag. Is it eventually possible? Probably. But depending on your needs and your time and a lot of other factors only you could decide, it may not be practical.
{ "language": "en", "url": "https://stackoverflow.com/questions/153685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Modelling Related Objects I'm designing an application which deals with two sets of data - Users and Areas. The data is read from files produced by a third party. I have a User class and an Area class, and the data is read into a Users array and an Areas array (or other appropriate memory structure, depending on the technology we go with). Both classes have a unique ID member which is read from the file, and the User class contains an array of Area IDs, giving a relationship where one user is associated with many Areas. The requirements are quite straightforward: * *List of Users *List of Areas *List of Users for Specified Area *List of Areas for Specified Users My first thought was to leave the data in the two arrays, then for each of the requirements, have a seperate method which would interrogate one or both arrays as required. This would be easy to implement, but I'm not convinced it's necessarily the best way. Then I thought about having a 'Get Areas' method on the User class and a 'Get Users' member on the Area class which would be more useful if for example I'm at a stage where I have an Area object, I could find it's users by a property, but then how would a 'Get Users' method on the Area class be aware of/have access to the Users array. I've had this problem a number of times before, but never really came up with a definitive solution. Maybe I'm just making it more complicated than it actually is. Can anyone provide any tips, URLs or books that would help me with this sort of design? UPDATE: Thank you all for taking your time to leave some tips. Your comments are very much appreciated. I agree that the root of this problem is a many-to-many relationship. I understand how that would be modelled in a relational database, that's pretty simple. The data I receive is in the form of binary files from a third party, so I have no control over the structure of these, but I can store it whichever way is best when I read it in. It is a bit square pegs in round holes, but I thought reading it in then storing it in a database, the program would then have to query the database to get to the results. It's not a massive amount of data, so I thought it would be possible to get out what I need by storing it in memory structures. A: this is really a many-to-many relationship, User <<--->> Area break it up into 3 objects, User, Area, and UserArea: User: Id, name, etc. Area: Id, name, etc. UserArea: UserId, AreaId A: Very basic, but the idea is: struct/class Membership { int MemberID; int userID; int areaID; } This class implements the "user belongs to area" membership concept. Stick one of these for each membership in a collection, and query that collection for subsets that meet your requirements. EDIT: Another option You could store in each Member a list of Areas, and in each Area, a list of Members. in Area: public bool addMember(Member m) { if (/*eligibility Requirements*/) { memberList.add(m); m.addArea(this); return true; } return false; } and a similar implementation in Member (without the callback) The advantage of this is that it's pretty easy to return an iterator to walk through an Area and find Members (and vice versa) The disadvantage is that it's very tightly coupled, which could cause future problems. I think the first implementation is more LINQ friendly. A: Does an area belong to multiple users? If yes, it's a technically a many-to-many relationship. If you were to transform the data into a relational database, you'd create a table with all the relationships. I guess if you want to work with arrays, you could create a third array. Or if you actually want to do this in an OO way, both classes should have arrays of pointers to the associated areas/users. A: I'm sorry, but this is not an object-oriented problem. It is a relational problem. Hence all the references to cardinality (many-to-many). This is relational database modeling 101. I don't mean to criticize Gavin, just to point out a new perspective. So what good is my rant. The answer should be to integrate with a relational data store, not to pound it into a object oriented paradigm. This is the classic square peg, round hole issue. A: Why not use DataTables with relations, if .NET is involved? You may want to look into Generics as well, again, if .NET is involved. A: One option is to use a dictionary for each of the last 2 requirements. That is, a Dictionary<Area, List<User>> and a Dictionary<User, List<Area>>. You could build these up as you read in the data. You might even wrap a class around these 2 dictionaries, and just have a method on that class for each of the requirements. That would allow you to make sure the dictionaries stay in sync. A: Agree with dacracot Also look at DevExpress XPO
{ "language": "en", "url": "https://stackoverflow.com/questions/153689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: change default collation in phpmyadmin It seems to me that phpMyAdmin imports tables by default with collation latin1_swedish_ci, how i change this? A: know this is an old post. But the way i changed the default charset through phpMyAdmin was: phpMyadmin main page > Variables tab (Server variables and settings) > searched for "character" and changed all variables from "latin1" to "utf8". (on a MAMP installation with phpMyAdmin v. 3.5.7) And as the others said, this is the variables for MySQL and not some phpMyAdmin specific ones. A: MySQL DB « change Collation Name of a Database|Table to utf8_general_ci inorder to support Unicode. Change Configuration settings file also XAMPP: uncomment UTF 8 Settings from the Configuration settings file « D:\xampp\mysql\bin\my.ini ## UTF 8 Settings #init-connect=\'SET NAMES utf8\' collation_server=utf8_unicode_ci character_set_server=utf8 skip-character-set-client-handshake character_sets-dir="D:/xampp/mysql/share/charsets" For MySQL server to support UTF8 and the below line of code in file my.cnf ## UTF 8 Settings collation_server=utf8_unicode_ci character_set_server=utf8 @see * *XAMPP - Apache Virtual Host Setting *XAMPP security concept - Error 403,404 A: * *Insert this strings into my.ini (or my.cnf) [mysqld] collation_server = utf8_unicode_ci character_set_server=utf8 *Add into config.inc.php $cfg['DefaultConnectionCollation'] = 'utf8_general_ci'; *You need to restart MySQL server and remove cookies,data for domain where is located PhpMyAdmin *Reload page with PhpMyAmdin and at look the result A: In your Mysql configuration change the default-character-set operative under the [mysqld] tab. For example: [mysqld] default-character-set=utf8 Don't forget to restart your Mysql server afterwards for the changes to take effect. A: For Linux: * *You need to have access to the MySQL config file. The location can vary from /etc/mysql/my.cnf to ~/my.cnf (user directory). *Add the following lines in the section [mysqld]: collation_server = utf8_unicode_ci character_set_server=utf8 *Restart the server: service mysqld restart A: This is not a phpMyAdmin question. Collations are part of recent MySQL releases, you must set the default collation of the server (or at least of the database) to change that behaviour. To convert already imported tables to UTF-8 you can do (in PHP): $dbname = 'my_databaseName'; mysql_connect('127.0.0.1', 'root', ''); mysql_query("ALTER DATABASE `$dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci"); $res = mysql_query("SHOW TABLES FROM `$dbname`"); while($row = mysql_fetch_row($res)) { $query = "ALTER TABLE {$dbname}.`{$row[0]}` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci"; mysql_query($query); $query = "ALTER TABLE {$dbname}.`{$row[0]}` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci"; mysql_query($query); } echo 'all tables converted'; Code snippet taken from here. A: For utf8mb4, add/change the following in the [mysqld] section: collation_server = utf8mb4_unicode_ci character_set_server = utf8mb4 Then restart the mysql service (for Ubuntu the command is sudo service mysql restart) A: I wanted to use utf8mb4 instead, and the configuration had to be the following: collation_server = utf8mb4_general_ci character_set_server=utf8mb4 the server would not start if the character_set was set to utf8 A: The original question was for the default setting in phpMyAdmin. I think the question relates to creating a NEW database in phpMyAdmin - when the page shows utf8mb4... This IS a phpMyAdmin setting! If you want the default for creating new databases to show utf8_general_ci. Add the following 2 line to your config.inc.php file: $cfg['DefaultCharset'] = 'utf8'; $cfg['DefaultConnectionCollation'] = 'utf8_general_ci'; See phpMyAdmin docs https://docs.phpmyadmin.net/en/latest/config.html and https://docs.phpmyadmin.net/en/latest/config.html#cfg_DefaultConnectionCollation
{ "language": "en", "url": "https://stackoverflow.com/questions/153706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: Inheriting from protected classes in C+++ Suppose I have the following declaration: class Over1 { protected: class Under1 { }; }; I know that I could do the following: class Over2 : public Over1 { protected: class Under2 : public Under1 { }; }; But is there a way to declare Under2 without Over2? Since you would have to extend Over1 to use any derivative of Under1 this may seem silly, but in this situation there might be 30 different flavors of Under. I can either: * *Put them all inside Over1 : Not attractive since Over2 may only use 1 or 2 of them *Put them each in their own version of Over : Not attractive since then you will have to multiply inherit from almost the same class. *Find a way to create children of Under1 without creating children of Over1 So is this possible? Thanks. A: Better than creating nested classes, you might want to look at embedding those closses into a namespace. That way, you don't need the outer class in order to get the inner class. There are some great arguments for and against in the Google C++ Style Guide. A: Using templates and explicit specializations you can do this with just one additional class declaration in Over1. class Over1 { protected: class Under1 { }; template <typename T> class UnderImplementor; }; struct Under2Tag; struct Under3Tag; struct Under4Tag; template <> class Over1::UnderImplementor<Under2Tag> : public Over1::Under1 { }; template <> class Over1::UnderImplementor<Under3Tag> : public Over1::Under1 { }; template <> class Over1::UnderImplementor<Under4Tag> : public Over1::Under1 { }; Hope this helps. A: If you want to keep Under1 protected, then by definition, you need to inherit from Over1 to access it. I would suggest making Under1 public, or using namespaces as Douglas suggested. I don't have the compiler to test these out right now, so I'm not at all sure that these would work, but you could try this: class Over1 { protected: class Under1 { }; public: class Under1Interface : public Under1 { }; }; class Under2 : public Over1::Under1Interface { }; Or perhaps something like this: class Over1 { protected: class Under1 { }; }; class Under2 : private Over1, public Over1::Under1 { }; Or even: class Under2; class Over1 { friend class Under2; protected: class Under1 { }; }; class Under2 : public Over1::Under1 { }; Although that would expose all of Over1s privates to Under2 - not likely something you'd want. A: Sounds like a bit of a funky design to me. Why not try structuring your code differently. I think this could possibly be a good candidate for the decorator pattern, where you could wrap your base class in various decorators to achieve the desired functionality, the various flavors of 'under' could be decorators. Just a thought, hard to tell without knowing more about the intentions of your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/153707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Creating music visualizer So how does someone create a music visualizer? I've looked on Google but I haven't really found anything that talks about the actual programming; mostly just links to plug-ins or visualizing applications. I use iTunes but I realize that I need Xcode to program for that (I'm currently deployed in Iraq and can't download that large of a file). So right now I'm just interested in learning "the theory" behind it, like processing the frequencies and whatever else is required. A: There are a variety of ways of processing the audio data, the simplest of which is just to display it as a rapidly changing waveform, and then apply some graphical effect to that. Similarly, things like the volume can be calculated (and passed as a parameter to some graphics routine) without doing a Fast Fourier Transform to get frequencies: just calculate the average amplitude of the signal. Converting the data to the frequency domain using an FFT or otherwise allows more sophisticated effects, including things like spectrograms. It's deceptively tricky though to detect even quite 'obvious' things like the timing of drum beats or the pitch of notes directly from the FFT output Reliable beat-detection and tone-detection are hard problems, especially in real time. I'm no expert, but this page runs through some simple example algorithms and their results. A: As a visualizer plays a song file, it reads the audio data in very short time slices (usually less than 20 milliseconds). The visualizer does a Fourier transform on each slice, extracting the frequency components, and updates the visual display using the frequency information. How the visual display is updated in response to the frequency info is up to the programmer. Generally, the graphics methods have to be extremely fast and lightweight in order to update the visuals in time with the music (and not bog down the PC). In the early days (and still), visualizers often modified the color palette in Windows directly to achieve some pretty cool effects. One characteristic of frequency-component-based visualizers is that they don't often seem to respond to the "beats" of music (like percussion hits, for example) very well. More interesting and responsive visualizers can be written that combine the frequency-domain information with an awareness of "spikes" in the audio that often correspond to percussion hits. A: For creating BeatHarness ( http://www.beatharness.com ) I've 'simply' used an FFT to get the audiospectrum, then use some filtering and edge / onset-detectors. About the Fast Fourier Transform : http://en.wikipedia.org/wiki/Fast_Fourier_transform If you're accustomed to math you might want to read Paul Bourke's page : http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/dft/ (Paul Bourke is a name you want to google anyway, he has a lot of information about topics you either want to know right now or probably in the next 2 years ;)) If you want to read about beat/tempo-detection google for Masataka Goto, he's written some interesting papers about it. Edit: His homepage : http://staff.aist.go.jp/m.goto/ Interesting read : http://staff.aist.go.jp/m.goto/PROJ/bts.html Once you have some values for for example bass, midtones, treble and volume(left and right), it's all up to your imagination what to do with them. Display a picture, multiply the size by the bass for example - you'll get a picture that'll zoom in on the beat, etc. A: * *Devise an algorithm to draw something interesting on the screen given a set of variables *Devise a way to convert an audio stream into a set of variables analysing things such as beats/minute frequency different frequency ranges, tone etc. *Plug the variables into your algorithm and watch it draw. A simple visualization would be one that changed the colour of the screen every time the music went over a certain freq threshhold. or to just write the bpm onto the screen. or just displaying an ociliscope. check out this wikipedia article A: Like suggested by @Pragmaticyankee processing is indeed an interesting way to visualize your music. You could load your music in Ableton Live, and use an EQ to filter out the high, middle and low frequencies from your music. You could then use a VST follwoing plugin to convert audio enveloppes into MIDI CC messages, such as Gatefish by Mokafix Audio (works on windows) or PizMidi’s midiAudioToCC plugin (works on mac). You can then send these MIDI CC messages to a light-emitting hardware tool that supports MIDI, for instance percussa audiocubes. You could use a cube for every frequency you want to display, and assign a color to the cube. Have a look at this post: http://www.percussa.com/2012/08/18/how-do-i-generate-rgb-light-effects-using-audio-signals-featured-question/ A: We have lately added DirectSound-based audio data input routines in LightningChart data visualization library. LightningChart SDK is set of components for Visual Studio .NET (WPF and WinForms), you may find it useful. With AudioInput component, you can get real-time waveform data samples from sound device. You can play the sound from any source, like Spotify, WinAmp, CD/DVD player, or use mic-in connector. With SpectrumCalculator component, you can get power spectrum (FFT conversion) that is handy in many visualizations. With LightningChartUltimate component you can visualize data in many different forms, like waveform graphs, bar graphs, heatmaps, spectrograms, 3D spectrograms, 3D lines etc. and they can be combined. All rendering takes place through Direct3D acceleration. Our own examples in the SDK have a scientific approach, not really having much entertainment aspect, but it definitely can be used for awesome entertainment visualizations too. We have also configurable SignalGenerator (sweeps, multi-channel configurations, sines, squares, triangles, and noise waveforms, WAV real-time streaming, and DirectX audio output components for sending wave data out from speakers or line-output. [I'm CTO of LightningChart components, doing this stuff just because I like it :-) ] A: Typically, you take a certain amount of the audio data, run a frequency analysis over it, and use that data to modify some graphic that's being displayed over and over. The obvious way to do the frequency analysis is with an FFT, but simple tone detection can work just as well, with a lower lower computational overhead. So, for example, you write a routine that continually draws a series of shapes arranged in a circle. You then use the dominant frequencies to determine the color of the circles, and use the volume to set the size.
{ "language": "en", "url": "https://stackoverflow.com/questions/153712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "59" }
Q: Verify email in Java Is there any way to verify in Java code that an e-mail address is valid. By valid, I don't just mean that it's in the correct format (someone@domain.subdomain), but that's it's a real active e-mail address. I'm almost certain that there's no 100% reliable way to do this, because such a technique would be the stuff of spammer's dreams. But perhaps there's some technique that gives some useful indication about whether an address is 'real' or not. A: Here is what I have around. To check that the address is a valid format, here is a regex that verifies that it's nearly rfc2822 (it doesn't catch some weird corner cases). I found it on the 'net last year. private static final Pattern rfc2822 = Pattern.compile( "^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$" ); if (!rfc2822.matcher(email).matches()) { throw new Exception("Invalid address"); } That will take care of simple syntax (for the most part). The other check I know of will let you check if the domain has an MX record. It looks like this: Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); DirContext ictx = new InitialDirContext(env); Attributes attrs = ictx.getAttributes(domainName, new String[] {"MX"}); Attribute attr = attrs.get("MX"); if (attr == null) // No MX record else // If attr.size() > 0, there is an MX record This, I also found on the 'net. It came from this link. If these both pass, you have a good chance at having a valid address. As for if the address it's self (not just the domain), it's not full, etc... you really can't check that. Note that the second check is time intensive. It can take anywhere from milliseconds to >30 seconds (if the DNS does not respond and times out). It's not something to try and run real-time for large numbers of people. Hope this helps. EDIT I'd like to point out that, at least instead of the regex, there are better ways to check basic validity. Don and Michael point out that Apache Commons has something, and I recently found out you can use .validate() on InternetAddress to have Java check that the address is really RFC-8222, which is certainly more accurate than my regex. A: You cannot really verify that an email exists, see my answer to a very similar question here: Email SMTP validator A: Without sending an email, it could be hard to get 100%, but if you do a DNS lookup on the host that should at least tell you that it is a viable destination system. A: Apache commons provides an email validator class too, which you can use. Simply pass your email address as an argument to isValid method. A: Do a DNS lookup on the hostname to see if that exists. You could theoretically also initiate a connection to the mailserver and see if it tells you whether the recipient exists, but I think many servers pretend they know an address, then reject the email anyway. A: The only way you can be certain is by actually sending a mail and have it read. Let your registration process have a step that requires responding to information found only in the email. This is what others do. A: I'm not 100% sure, but isn't it possible to send an RCPT SMTP command to a mail server to determine if the recipient is valid? It would be even more expensive than the suggestion above to check for a valid MX host, but it would also be the most accurate. A: public static boolean isValidEmail(String emailAddress) { return emailAddress.contains(" ") == false && emailAddress.matches(".+@.+\\.[a-z]+"); } A: If you're using GWT, you can't use InternetAddress, and the pattern supplied by MBCook is pretty scary. Here is a less scary regex (might not be as accurate): public static boolean isValidEmail(String emailAddress) { return emailAddress.contains(" ") == false && emailAddress.matches(".+@.+\\.[a-z]+"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/153716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: What alternatives are there to Google App Engine? What alternatives are there to GAE, given that I already have a good bit of code working that I would like to keep. In other words, I'm digging python. However, my use case is more of a low number of requests, higher CPU usage type use case, and I'm worried that I may not be able to stay with App Engine forever. I have heard a lot of people talking about Amazon Web Services and other sorts of cloud providers, but I am having a hard time seeing where most of these other offerings provide the range of services (data querying, user authentication, automatic scaling) that App Engine provides. What are my options here? A: As of 2016, if you're willing to lump PaaS (platform as a service) and FaaS (function as a service) in the same serverless computing category, then you have a few FaaS options. Proprietary AWS Lambda AWS Lambda lets you run code without provisioning or managing servers. You pay only for the compute time you consume - there is no charge when your code is not running. With Lambda, you can run code for virtually any type of application or backend service - all with zero administration. Just upload your code and Lambda takes care of everything required to run and scale your code with high availability. You can set up your code to automatically trigger from other AWS services or call it directly from any web or mobile app. AWS Step Functions complements AWS Lambda. AWS Step Functions makes it easy to coordinate the components of distributed applications and microservices using visual workflows. Building applications from individual components that each perform a discrete function lets you scale and change applications quickly. Step Functions is a reliable way to coordinate components and step through the functions of your application. Step Functions provides a graphical console to arrange and visualize the components of your application as a series of steps. This makes it simple to build and run multi-step applications. Step Functions automatically triggers and tracks each step, and retries when there are errors, so your application executes in order and as expected. Step Functions logs the state of each step, so when things do go wrong, you can diagnose and debug problems quickly. You can change and add steps without even writing code Google Cloud Functions As of 2016 it is in alpha. Google Cloud Functions is a lightweight, event-based, asynchronous compute solution that allows you to create small, single-purpose functions that respond to cloud events without the need to manage a server or a runtime environment. Events from Google Cloud Storage and Google Cloud Pub/Sub can trigger Cloud Functions asynchronously, or you can use HTTP invocation for synchronous execution. Azure Functions An event-based serverless compute experience to accelerate your development. It can scale based on demand and you pay only for the resources you consume. Open Serverless The Serverless Framework allows you to deploy auto-scaling, pay-per-execution, event-driven functions to any cloud. We currently support Amazon Web Service's Lambda, and are expanding to support other cloud providers. IronFunctions IronFunctions is an open source serverless computing platform for any cloud - private, public, or hybrid. It remains to seen how well FaaS competes with CaaS (container as a service). The former seems more lightweight. Both seem suited to microservices architectures. I anticipate that functions (as in FaaS) are not the end of the line, and that many years forward we'll see further service abstractions, e.g. test-only development, followed by plain-language scenarios. A: Alternatives: 1. AppScale 2. Heroku. Ref: Alternative for Google AppEngine? A: AppScale AppScale is a platform that allows users to deploy and host their own Google App Engine applications. It executes automatically over Amazon EC2 and Eucalyptus as well as Xen and KVM. It has been developed and is maintained by AppScale Systems. It supports the Python, Go, PHP, and Java Google App Engine platforms. http://github.com/AppScale/appscale In the mean time... ...it is amost 2015 and it seems that containers are the way to go forward. Alternatives to GAE are emerging: Google has released Kubernetes, container scheduling software developed by them to manage GCE containers, but can be used on other clusters as well. There are some upcoming PaaS on Docker such as * *http://deis.io/ *http://www.tsuru.io/ *even Appscale themselves are supporting Docker Interesting stuff to keep an eye on. A: Amazon's Elastic Compute Cloud or EC2 is a good option. You basically run Linux VMs on their servers that you can control via a web interface (for powering up and down) and of course access via SSH or whatever you normally set up... And as it's a linux install that you control, you can of course run python if you wish. A: Microsoft Windows Azure might be worth consideration. I'm afraid I haven't used it so can't say if it's any good and you should bear in mind that it's a CTP at the moment. Check it out here. A: You may also want to take a look at AWS Elastic Beanstalk - it has a closer equivalence to GAE functionality, in that it is designed to be PaaS, rather than an IaaS (i.e. EC2) A: A bit late, but I would give Heroku a go: Heroku is a polyglot cloud application platform. With Heroku, you don’t need to think about servers at all. You can write apps using modern development practices in the programming language of your choice, back it with add-on resources such as SQL and NoSQL databases, Memcached, and many others. You manage your app using the Heroku command-line tool and you deploy code using the Git revision control system, all running on the Heroku infrastructure. https://www.heroku.com/about A: I don't think there is another alternative (with regards to code portability) to GAE right now since GAE is in a class of its own. Sure GAE is cloud computing, but I see GAE as a subset of cloud computing. Amazon's EC2 is also cloud computing (as well as Joyent Accelerators, Slicehost Slices), but obviously they are two different beasts as well. So right now you're in a situation that requires rethinking your architecture depending on your needs. The immediate benefits of GAE is that its essentially maintenance free as it relates to infrastructure (scalable web server and database administration). GAE is more tailored to those developers that only want to focus on their applications and not the underlying system.In a way you can consider that developer friendly. Now it should also be said that these other cloud computing solutions also try to allow you to only worry about your application as much as you like by providing VM images/templates. Ultimately your needs will dictate the approach you should take. Now with all this in mind we can also construct hybrid solutions and workarounds that might fulfill our needs as well. For example, GAE doesn't seem directly suited to this specific app needs you describe. In other words, GAE offers relatively high number of requests, low number of cpu cycles (not sure if paid version will be any different). However, one way to tackle this challenge is by building a customized solution involving GAE as the front end and Amazon AWS (EC2, S3, and SQS) as the backend. Some will say you might as well build your entire stack on AWS, but that may involve rewriting lots of existing code as well. Furthermore, as a workaround a previous stackoverflow post describes a method of simulating background tasks in GAE. Furthermore, you can look into HTTP Map/Reduce to distribute workload as well. A: If you're interested in the cloud, and maybe want to create your own for production and/or testing you have to look at Eucalyptus. It's allegedly code compatible with EC2 but open source. A: I'd be more interested in seeing how App Engine can be easily coupled with another server used for CPU intensive requests. A: TyphoonAE is trying to do this. I haven't tested it, but while it is still in beta, it looks like it's atleast in active development. A: The shift to cloud computing is happening so rapidly that you have no time to waste for testing different platforms. I suggest you trying out Jelastic if you are interested in Java as well. One of the greatest things about Jelastic is that you do not need to make any changes in the code of your application, except the changes for your application functionality, but not for the reason the chosen platform demands this. With reference to this you do not actually waste your time.The deployment process is just flawless, and you can deploy your .war file anywhere further.Using GAE requires you to modify the app around their system needs. In case if you happen to get working with Java and start looking for a more flexible platform, Jelastic is a compatible alternative. A: You can also use Red Hat's Cape Dwarf project, to run GAE apps on top of the Wildfly appserver (previously JBoss) without modification. You can check it out here: http://capedwarf.org/
{ "language": "en", "url": "https://stackoverflow.com/questions/153721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "48" }
Q: How to round a number to n decimal places in Java What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations. I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes. I know one method of doing this is to use the String.format method: String.format("%.5g%n", 0.912385); returns: 0.91239 which is great, however it always displays numbers with 5 decimal places even if they are not significant: String.format("%.5g%n", 0.912300); returns: 0.91230 Another method is to use the DecimalFormatter: DecimalFormat df = new DecimalFormat("#.#####"); df.format(0.912385); returns: 0.91238 However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this: 0.912385 -> 0.91239 0.912300 -> 0.9123 What is the best way to achieve this in Java? A: As some others have noted, the correct answer is to use either DecimalFormat or BigDecimal. Floating-point doesn't have decimal places so you cannot possibly round/truncate to a specific number of them in the first place. You have to work in a decimal radix, and that is what those two classes do. I am posting the following code as a counter-example to all the answers in this thread and indeed all over StackOverflow (and elsewhere) that recommend multiplication followed by truncation followed by division. It is incumbent on advocates of this technique to explain why the following code produces the wrong output in over 92% of cases. public class RoundingCounterExample { static float roundOff(float x, int position) { float a = x; double temp = Math.pow(10.0, position); a *= temp; a = Math.round(a); return (a / (float)temp); } public static void main(String[] args) { float a = roundOff(0.0009434f,3); System.out.println("a="+a+" (a % .001)="+(a % 0.001)); int count = 0, errors = 0; for (double x = 0.0; x < 1; x += 0.0001) { count++; double d = x; int scale = 2; double factor = Math.pow(10, scale); d = Math.round(d * factor) / factor; if ((d % 0.01) != 0.0) { System.out.println(d + " " + (d % 0.01)); errors++; } } System.out.println(count + " trials " + errors + " errors"); } } Output of this program: 10001 trials 9251 errors EDIT: To address some comments below I redid the modulus part of the test loop using BigDecimal and new MathContext(16) for the modulus operation as follows: public static void main(String[] args) { int count = 0, errors = 0; int scale = 2; double factor = Math.pow(10, scale); MathContext mc = new MathContext(16, RoundingMode.DOWN); for (double x = 0.0; x < 1; x += 0.0001) { count++; double d = x; d = Math.round(d * factor) / factor; BigDecimal bd = new BigDecimal(d, mc); bd = bd.remainder(new BigDecimal("0.01"), mc); if (bd.multiply(BigDecimal.valueOf(100)).remainder(BigDecimal.ONE, mc).compareTo(BigDecimal.ZERO) != 0) { System.out.println(d + " " + bd); errors++; } } System.out.println(count + " trials " + errors + " errors"); } Result: 10001 trials 4401 errors A: Suppose you have double d = 9232.129394d; you can use BigDecimal BigDecimal bd = new BigDecimal(d).setScale(2, RoundingMode.HALF_EVEN); d = bd.doubleValue(); or without BigDecimal d = Math.round(d*100)/100.0d; with both solutions d == 9232.13 A: You can use BigDecimal BigDecimal value = new BigDecimal("2.3"); value = value.setScale(0, RoundingMode.UP); BigDecimal value1 = new BigDecimal("-2.3"); value1 = value1.setScale(0, RoundingMode.UP); System.out.println(value + "n" + value1); Refer: http://www.javabeat.net/precise-rounding-of-decimals-using-rounding-mode-enumeration/ A: To achieve this we can use this formatter: DecimalFormat df = new DecimalFormat("#.00"); String resultado = df.format(valor) or: DecimalFormat df = new DecimalFormat("0.00"); : Use this method to get always two decimals: private static String getTwoDecimals(double value){ DecimalFormat df = new DecimalFormat("0.00"); return df.format(value); } Defining this values: 91.32 5.22 11.5 1.2 2.6 Using the method we can get this results: 91.32 5.22 11.50 1.20 2.60 demo online. A: Use setRoundingMode, set the RoundingMode explicitly to handle your issue with the half-even round, then use the format pattern for your required output. Example: DecimalFormat df = new DecimalFormat("#.####"); df.setRoundingMode(RoundingMode.CEILING); for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) { Double d = n.doubleValue(); System.out.println(df.format(d)); } gives the output: 12 123.1235 0.23 0.1 2341234.2125 EDIT: The original answer does not address the accuracy of the double values. That is fine if you don't care much whether it rounds up or down. But if you want accurate rounding, then you need to take the expected accuracy of the values into account. Floating point values have a binary representation internally. That means that a value like 2.7735 does not actually have that exact value internally. It can be slightly larger or slightly smaller. If the internal value is slightly smaller, then it will not round up to 2.7740. To remedy that situation, you need to be aware of the accuracy of the values that you are working with, and add or subtract that value before rounding. For example, when you know that your values are accurate up to 6 digits, then to round half-way values up, add that accuracy to the value: Double d = n.doubleValue() + 1e-6; To round down, subtract the accuracy. A: If you really want decimal numbers for calculation (and not only for output), do not use a binary-based floating point format like double. Use BigDecimal or any other decimal-based format. I do use BigDecimal for calculations, but bear in mind it is dependent on the size of numbers you're dealing with. In most of my implementations, I find parsing from double or integer to Long is sufficient enough for very large number calculations. In fact, I've recently used parsed-to-Long to get accurate representations (as opposed to hex results) in a GUI for numbers as big as ################################# characters (as an example). A: Try this: org.apache.commons.math3.util.Precision.round(double x, int scale) See: http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html Apache Commons Mathematics Library homepage is: http://commons.apache.org/proper/commons-math/index.html The internal implemetation of this method is: public static double round(double x, int scale) { return round(x, scale, BigDecimal.ROUND_HALF_UP); } public static double round(double x, int scale, int roundingMethod) { try { return (new BigDecimal (Double.toString(x)) .setScale(scale, roundingMethod)) .doubleValue(); } catch (NumberFormatException ex) { if (Double.isInfinite(x)) { return x; } else { return Double.NaN; } } } A: Since I found no complete answer on this theme I've put together a class that should handle this properly, with support for: * *Formatting: Easily format a double to string with a certain number of decimal places *Parsing: Parse the formatted value back to double *Locale: Format and parse using the default locale *Exponential notation: Start using exponential notation after a certain threshold Usage is pretty simple: (For the sake of this example I am using a custom locale) public static final int DECIMAL_PLACES = 2; NumberFormatter formatter = new NumberFormatter(DECIMAL_PLACES); String value = formatter.format(9.319); // "9,32" String value2 = formatter.format(0.0000005); // "5,00E-7" String value3 = formatter.format(1324134123); // "1,32E9" double parsedValue1 = formatter.parse("0,4E-2", 0); // 0.004 double parsedValue2 = formatter.parse("0,002", 0); // 0.002 double parsedValue3 = formatter.parse("3423,12345", 0); // 3423.12345 Here is the class: import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.ParseException; import java.util.Locale; public class NumberFormatter { private static final String SYMBOL_INFINITE = "\u221e"; private static final char SYMBOL_MINUS = '-'; private static final char SYMBOL_ZERO = '0'; private static final int DECIMAL_LEADING_GROUPS = 10; private static final int EXPONENTIAL_INT_THRESHOLD = 1000000000; // After this value switch to exponential notation private static final double EXPONENTIAL_DEC_THRESHOLD = 0.0001; // Below this value switch to exponential notation private DecimalFormat decimalFormat; private DecimalFormat decimalFormatLong; private DecimalFormat exponentialFormat; private char groupSeparator; public NumberFormatter(int decimalPlaces) { configureDecimalPlaces(decimalPlaces); } public void configureDecimalPlaces(int decimalPlaces) { if (decimalPlaces <= 0) { throw new IllegalArgumentException("Invalid decimal places"); } DecimalFormatSymbols separators = new DecimalFormatSymbols(Locale.getDefault()); separators.setMinusSign(SYMBOL_MINUS); separators.setZeroDigit(SYMBOL_ZERO); groupSeparator = separators.getGroupingSeparator(); StringBuilder decimal = new StringBuilder(); StringBuilder exponential = new StringBuilder("0."); for (int i = 0; i < DECIMAL_LEADING_GROUPS; i++) { decimal.append("###").append(i == DECIMAL_LEADING_GROUPS - 1 ? "." : ","); } for (int i = 0; i < decimalPlaces; i++) { decimal.append("#"); exponential.append("0"); } exponential.append("E0"); decimalFormat = new DecimalFormat(decimal.toString(), separators); decimalFormatLong = new DecimalFormat(decimal.append("####").toString(), separators); exponentialFormat = new DecimalFormat(exponential.toString(), separators); decimalFormat.setRoundingMode(RoundingMode.HALF_UP); decimalFormatLong.setRoundingMode(RoundingMode.HALF_UP); exponentialFormat.setRoundingMode(RoundingMode.HALF_UP); } public String format(double value) { String result; if (Double.isNaN(value)) { result = ""; } else if (Double.isInfinite(value)) { result = String.valueOf(SYMBOL_INFINITE); } else { double absValue = Math.abs(value); if (absValue >= 1) { if (absValue >= EXPONENTIAL_INT_THRESHOLD) { value = Math.floor(value); result = exponentialFormat.format(value); } else { result = decimalFormat.format(value); } } else if (absValue < 1 && absValue > 0) { if (absValue >= EXPONENTIAL_DEC_THRESHOLD) { result = decimalFormat.format(value); if (result.equalsIgnoreCase("0")) { result = decimalFormatLong.format(value); } } else { result = exponentialFormat.format(value); } } else { result = "0"; } } return result; } public String formatWithoutGroupSeparators(double value) { return removeGroupSeparators(format(value)); } public double parse(String value, double defValue) { try { return decimalFormat.parse(value).doubleValue(); } catch (ParseException e) { e.printStackTrace(); } return defValue; } private String removeGroupSeparators(String number) { return number.replace(String.valueOf(groupSeparator), ""); } } A: You can use the DecimalFormat class. double d = 3.76628729; DecimalFormat newFormat = new DecimalFormat("#.##"); double twoDecimal = Double.valueOf(newFormat.format(d)); A: I agree with the chosen answer to use DecimalFormat --- or alternatively BigDecimal. Please read Update below first! However if you do want to round the double value and get a double value result, you can use org.apache.commons.math3.util.Precision.round(..) as mentioned above. The implementation uses BigDecimal, is slow and creates garbage. A similar but fast and garbage-free method is provided by the DoubleRounder utility in the decimal4j library: double a = DoubleRounder.round(2.0/3.0, 3); double b = DoubleRounder.round(2.0/3.0, 3, RoundingMode.DOWN); double c = DoubleRounder.round(1000.0d, 17); double d = DoubleRounder.round(90080070060.1d, 9); System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); Will output 0.667 0.666 1000.0 9.00800700601E10 See https://github.com/tools4j/decimal4j/wiki/DoubleRounder-Utility Disclosure: I am involved in the decimal4j project. Update: As @iaforek pointed out DoubleRounder sometimes returns counterintuitive results. The reason is that it performs mathematically correct rounding. For instance DoubleRounder.round(256.025d, 2) will be rounded down to 256.02 because the double value represented as 256.025d is somewhat smaller than the rational value 256.025 and hence will be rounded down. Notes: * *This behaviour is very similar to that of the BigDecimal(double) constructor (but not to valueOf(double) which uses the string constructor). *The problem can be circumvented with a double rounding step to a higher precision first, but it is complicated and I am not going into the details here For those reasons and everything mentioned above in this post I cannot recommend to use DoubleRounder. A: Just in case someone still needs help with this. This solution works perfectly for me. private String withNoTrailingZeros(final double value, final int nrOfDecimals) { return new BigDecimal(String.valueOf(value)).setScale(nrOfDecimals, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString(); } returns a String with the desired output. A: Assuming value is a double, you can do: (double)Math.round(value * 100000d) / 100000d That's for 5 digits precision. The number of zeros indicate the number of decimals. A: So after reading most of the answers, I realized most of them won't be precise, in fact using BigDecimal seems like the best choice, but if you don't understand how the RoundingMode works, you will inevitable lose precision. I figured this out when working with big numbers in a project and thought it could help others having trouble rounding numbers. For example. BigDecimal bd = new BigDecimal("1363.2749"); bd = bd.setScale(2, RoundingMode.HALF_UP); System.out.println(bd.doubleValue()); You would expect to get 1363.28 as an output, but you will end up with 1363.27, which is not expected, if you don't know what the RoundingMode is doing. So looking into the Oracle Docs, you will find the following description for RoundingMode.HALF_UP. Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. So knowing this, we realized that we won't be getting an exact rounding, unless we want to round towards nearest neighbor. So, to accomplish an adequate round, we would need to loop from the n-1 decimal towards the desired decimals digits. For example. private double round(double value, int places) throws IllegalArgumentException { if (places < 0) throw new IllegalArgumentException(); // Cast the number to a String and then separate the decimals. String stringValue = Double.toString(value); String decimals = stringValue.split("\\.")[1]; // Round all the way to the desired number. BigDecimal bd = new BigDecimal(stringValue); for (int i = decimals.length()-1; i >= places; i--) { bd = bd.setScale(i, RoundingMode.HALF_UP); } return bd.doubleValue(); } This will end up giving us the expected output, which would be 1363.28. A: Real's Java How-to posts this solution, which is also compatible for versions before Java 1.6. BigDecimal bd = new BigDecimal(Double.toString(d)); bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP); return bd.doubleValue(); UPDATE: BigDecimal.ROUND_HALF_UP is deprecated - Use RoundingMode BigDecimal bd = new BigDecimal(Double.toString(number)); bd = bd.setScale(decimalPlaces, RoundingMode.HALF_UP); return bd.doubleValue(); A: I came here just wanting a simple answer on how to round a number. This is a supplemental answer to provide that. How to round a number in Java The most common case is to use Math.round(). Math.round(3.7) // 4 Numbers are rounded to the nearest whole number. A .5 value is rounded up. If you need different rounding behavior than that, you can use one of the other Math functions. See the comparison below. round As stated above, this rounds to the nearest whole number. .5 decimals round up. This method returns an int. Math.round(3.0); // 3 Math.round(3.1); // 3 Math.round(3.5); // 4 Math.round(3.9); // 4 Math.round(-3.0); // -3 Math.round(-3.1); // -3 Math.round(-3.5); // -3 *** careful here *** Math.round(-3.9); // -4 ceil Any decimal value is rounded up to the next integer. It goes to the ceiling. This method returns a double. Math.ceil(3.0); // 3.0 Math.ceil(3.1); // 4.0 Math.ceil(3.5); // 4.0 Math.ceil(3.9); // 4.0 Math.ceil(-3.0); // -3.0 Math.ceil(-3.1); // -3.0 Math.ceil(-3.5); // -3.0 Math.ceil(-3.9); // -3.0 floor Any decimal value is rounded down to the next integer. This method returns a double. Math.floor(3.0); // 3.0 Math.floor(3.1); // 3.0 Math.floor(3.5); // 3.0 Math.floor(3.9); // 3.0 Math.floor(-3.0); // -3.0 Math.floor(-3.1); // -4.0 Math.floor(-3.5); // -4.0 Math.floor(-3.9); // -4.0 rint This is similar to round in that decimal values round to the closest integer. However, unlike round, .5 values round to the even integer. This method returns a double. Math.rint(3.0); // 3.0 Math.rint(3.1); // 3.0 Math.rint(3.5); // 4.0 *** Math.rint(3.9); // 4.0 Math.rint(4.5); // 4.0 *** Math.rint(5.5); // 6.0 *** Math.rint(-3.0); // -3.0 Math.rint(-3.1); // -3.0 Math.rint(-3.5); // -4.0 *** Math.rint(-3.9); // -4.0 Math.rint(-4.5); // -4.0 *** Math.rint(-5.5); // -6.0 *** A: If you're using a technology that has a minimal JDK. Here's a way without any Java libs: double scale = 100000; double myVal = 0.912385; double rounded = (int)((myVal * scale) + 0.5d) / scale; A: Here is a better function that rounds edge cases like 1.005 correctly. Simply, we add the smallest possible float value (= 1 ulp; unit in the last place) to the number before rounding. This moves to the next representable value after the number, away from zero. This is a little program to test it: ideone.com /** * Round half away from zero ('commercial' rounding) * Uses correction to offset floating-point inaccuracies. * Works symmetrically for positive and negative numbers. */ public static double round(double num, int digits) { // epsilon correction double n = Double.longBitsToDouble(Double.doubleToLongBits(num) + 1); double p = Math.pow(10, digits); return Math.round(n * p) / p; } // test rounding of half System.out.println(round(0.5, 0)); // 1 System.out.println(round(-0.5, 0)); // -1 // testing edge cases System.out.println(round(1.005, 2)); // 1.01 System.out.println(round(2.175, 2)); // 2.18 System.out.println(round(5.015, 2)); // 5.02 System.out.println(round(-1.005, 2)); // -1.01 System.out.println(round(-2.175, 2)); // -2.18 System.out.println(round(-5.015, 2)); // -5.02 A: here is my answer: double num = 4.898979485566356; DecimalFormat df = new DecimalFormat("#.##"); time = Double.valueOf(df.format(num)); System.out.println(num); // 4.89 A: double myNum = .912385; int precision = 10000; //keep 4 digits myNum= Math.floor(myNum * precision +.5)/precision; A: @Milhous: the decimal format for rounding is excellent: You can also use the DecimalFormat df = new DecimalFormat("#.00000"); df.format(0.912385); to make sure you have the trailing 0's. I would add that this method is very good at providing an actual numeric, rounding mechanism - not only visually, but also when processing. Hypothetical: you have to implement a rounding mechanism into a GUI program. To alter the accuracy / precision of a result output simply change the caret format (i.e. within the brackets). So that: DecimalFormat df = new DecimalFormat("#0.######"); df.format(0.912385); would return as output: 0.912385 DecimalFormat df = new DecimalFormat("#0.#####"); df.format(0.912385); would return as output: 0.91239 DecimalFormat df = new DecimalFormat("#0.####"); df.format(0.912385); would return as output: 0.9124 [EDIT: also if the caret format is like so ("#0.############") and you enter a decimal, e.g. 3.1415926, for argument's sake, DecimalFormat does not produce any garbage (e.g. trailing zeroes) and will return: 3.1415926 .. if you're that way inclined. Granted, it's a little verbose for the liking of some dev's - but hey, it's got a low memory footprint during processing and is very easy to implement.] So essentially, the beauty of DecimalFormat is that it simultaneously handles the string appearance - as well as the level of rounding precision set. Ergo: you get two benefits for the price of one code implementation. ;) A: The code snippet below shows how to display n digits. The trick is to set variable pp to 1 followed by n zeros. In the example below, variable pp value has 5 zeros, so 5 digits will be displayed. double pp = 10000; double myVal = 22.268699999999967; String needVal = "22.2687"; double i = (5.0/pp); String format = "%10.4f"; String getVal = String.format(format,(Math.round((myVal +i)*pp)/pp)-i).trim(); A: If you're using DecimalFormat to convert double to String, it's very straightforward: DecimalFormat formatter = new DecimalFormat("0.0##"); formatter.setRoundingMode(RoundingMode.HALF_UP); double num = 1.234567; return formatter.format(num); There are several RoundingMode enum values to select from, depending upon the behaviour you require. A: DecimalFormat is the best ways to output, but I don't prefer it. I always do this all the time, because it return the double value. So I can use it more than just output. Math.round(selfEvaluate*100000d.0)/100000d.0; OR Math.round(selfEvaluate*100000d.0)*0.00000d1; If you need large decimal places value, you can use BigDecimal instead. Anyways .0 is important. Without it the rounding of 0.33333d5 return 0.33333 and only 9 digits are allows. The second function without .0 has problems with 0.30000 return 0.30000000000000004. A: I have used bellow like in java 8. it is working for me double amount = 1000.431; NumberFormat formatter = new DecimalFormat("##.00"); String output = formatter.format(amount); System.out.println("output = " + output); Output: output = 1000.43 A: Here is a summary of what you can use if you want the result as String: * *DecimalFormat#setRoundingMode(): DecimalFormat df = new DecimalFormat("#.#####"); df.setRoundingMode(RoundingMode.HALF_UP); String str1 = df.format(0.912385)); // 0.91239 *BigDecimal#setScale() String str2 = new BigDecimal(0.912385) .setScale(5, BigDecimal.ROUND_HALF_UP) .toString(); Here is a suggestion of what libraries you can use if you want double as a result. I wouldn't recommend it for string conversion, though, as double may not be able to represent what you want exactly (see e.g. here): * *Precision from Apache Commons Math double rounded = Precision.round(0.912385, 5, BigDecimal.ROUND_HALF_UP); *Functions from Colt double rounded = Functions.round(0.00001).apply(0.912385) *Utils from Weka double rounded = Utils.roundDouble(0.912385, 5) A: new BigDecimal(String.valueOf(double)).setScale(yourScale, BigDecimal.ROUND_HALF_UP); will get you a BigDecimal. To get the string out of it, just call that BigDecimal's toString method, or the toPlainString method for Java 5+ for a plain format string. Sample program: package trials; import java.math.BigDecimal; public class Trials { public static void main(String[] args) { int yourScale = 10; System.out.println(BigDecimal.valueOf(0.42344534534553453453-0.42324534524553453453).setScale(yourScale, BigDecimal.ROUND_HALF_UP)); } A: You could use the following utility method- public static double round(double valueToRound, int numberOfDecimalPlaces) { double multipicationFactor = Math.pow(10, numberOfDecimalPlaces); double interestedInZeroDPs = valueToRound * multipicationFactor; return Math.round(interestedInZeroDPs) / multipicationFactor; } A: A succinct solution: public static double round(double value, int precision) { int scale = (int) Math.pow(10, precision); return (double) (Math.round(value * scale) / scale); } See also, https://stackoverflow.com/a/22186845/212950 Thanks to jpdymond for offering this. Edit: Added round brackets. Casts the whole result to double, not the first argument only! A: You can also use the DecimalFormat df = new DecimalFormat("#.00000"); df.format(0.912385); to make sure you have the trailing 0's. A: the following method could be used if need double double getRandom(int decimalPoints) { double a = Math.random(); int multiplier = (int) Math.pow(10, decimalPoints); int b = (int) (a * multiplier); return b / (double) multiplier; } for example getRandom(2) A: * *In order to have trailing 0s up to 5th position DecimalFormat decimalFormatter = new DecimalFormat("#.00000"); decimalFormatter.format(0.350500); // result 0.350500 *In order to avoid trailing 0s up to 5th position DecimalFormat decimalFormatter= new DecimalFormat("#.#####"); decimalFormatter.format(0.350500); // result o.3505 A: public static double formatDecimal(double amount) { BigDecimal amt = new BigDecimal(amount); amt = amt.divide(new BigDecimal(1), 2, BigDecimal.ROUND_HALF_EVEN); return amt.doubleValue(); } Test using Junit @RunWith(Parameterized.class) public class DecimalValueParameterizedTest { @Parameterized.Parameter public double amount; @Parameterized.Parameter(1) public double expectedValue; @Parameterized.Parameters public static List<Object[]> dataSets() { return Arrays.asList(new Object[][]{ {1000.0, 1000.0}, {1000, 1000.0}, {1000.00000, 1000.0}, {1000.01, 1000.01}, {1000.1, 1000.10}, {1000.001, 1000.0}, {1000.005, 1000.0}, {1000.007, 1000.01}, {1000.999, 1001.0}, {1000.111, 1000.11} }); } @Test public void testDecimalFormat() { Assert.assertEquals(expectedValue, formatDecimal(amount), 0.00); } A: Where dp = decimal place you want, and value is a double. double p = Math.pow(10d, dp); double result = Math.round(value * p)/p; A: Keep in mind that String.format() and DecimalFormat produce string using default Locale. So they may write formatted number with dot or comma as a separator between integer and decimal parts. To make sure that rounded String is in the format you want use java.text.NumberFormat as so: Locale locale = Locale.ENGLISH; NumberFormat nf = NumberFormat.getNumberInstance(locale); // for trailing zeros: nf.setMinimumFractionDigits(2); // round to 2 digits: nf.setMaximumFractionDigits(2); System.out.println(nf.format(.99)); System.out.println(nf.format(123.567)); System.out.println(nf.format(123.0)); Will print in English locale (no matter what your locale is): 0.99 123.57 123.00 The example is taken from Farenda - how to convert double to String correctly. A: A simple way to compare if it is limited number of decimal places. Instead of DecimalFormat, Math or BigDecimal, we can use Casting! Here is the sample, public static boolean threeDecimalPlaces(double value1, double value2){ boolean isEqual = false; // value1 = 3.1756 // value2 = 3.17 //(int) (value1 * 1000) = 3175 //(int) (value2 * 1000) = 3170 if ((int) (value1 * 1000) == (int) (value2 * 1000)){ areEqual = true; } return isEqual; } A: Very simple method public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); DecimalFormat deciFormat = new DecimalFormat(); deciFormat.setMaximumFractionDigits(places); String newValue = deciFormat.format(value); return Double.parseDouble(newValue); } double a = round(12.36545, 2); A: There is a problem with the Math.round solution when trying to round to a negative number of decimal places. Consider the code long l = 10; for(int dp = -1; dp > -10; --dp) { double mul = Math.pow(10,dp); double res = Math.round(l * mul) / mul; System.out.println(""+l+" rounded to "+dp+" dp = "+res); l *=10; } this has the results 10 rounded to -1 dp = 10.0 100 rounded to -2 dp = 100.0 1000 rounded to -3 dp = 1000.0 10000 rounded to -4 dp = 10000.0 100000 rounded to -5 dp = 99999.99999999999 1000000 rounded to -6 dp = 1000000.0 10000000 rounded to -7 dp = 1.0E7 100000000 rounded to -8 dp = 1.0E8 1000000000 rounded to -9 dp = 9.999999999999999E8 The problem with -5 decimal places occur when dividing 1 by 1.0E-5 which is inexact. This can be fixed using double mul = Math.pow(10,dp); double res; if(dp < 0 ) { double div = Math.pow(10,-dp); res = Math.round(l * mul) *div; } else { res = Math.round(l * mul) / mul; } But this is another reason to use the BigDecimal methods. A: This was the simplest way I found to display only two decimal places. double x = 123.123; System.out.printf( "%.2f", x ); A: If you Consider 5 or n number of decimal. May be this answer solve your prob. double a = 123.00449; double roundOff1 = Math.round(a*10000)/10000.00; double roundOff2 = Math.round(roundOff1*1000)/1000.00; double roundOff = Math.round(roundOff2*100)/100.00; System.out.println("result:"+roundOff); Output will be: 123.01 this can be solve with loop and recursive function.
{ "language": "en", "url": "https://stackoverflow.com/questions/153724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1438" }
Q: Validation Block vs Nhibernate.Validator I am looking for validation framework and while I am already using NHibernate I am thinking of using NHibernate.validator from contrib project however I also look at MS Validation Block which seem to be robust but i am not yet get into detail of each one yet so I wonder has anyone had step into these two frameworks and how is the experience like? A: NHibernate Validator does not require you to use NHibernate for persistence. Usage can be as simple as: var engine = new ValidatorEngine(); InvalidValue[] errors = engine.Validate(someModelObjectWithAttributes); foreach(var error in errors) { Console.WriteLine(error.Message); } Of course it can hook into NHibernate and prevent persistence of invalid objects, but you may use it to validate non-persistent objects as well. A: For the most part I would say that Spring.NET is pretty independent. Meaning it should not force you to re-architect. You can use as much or as little as you want. It should be pretty easy to write an object that you can inject into classes needing validation using spring. You would then wire this object up in castle to take the name of the "Validation Group" or "Validators" you needed and then have spring inject the validators into that object where your form/business object/service would then use the validators. Here is a link to the doc,Validation is section 12: http://www.springframework.net/docs/1.2.0-M1/reference/html/index.html Are you just using Castle or are you using Monorail? A: Of course you can try to write your own validation framework. For eg. Karl Seguin will help you: http://codebetter.com/blogs/karlseguin/archive/2009/04/26/validation-part-1-getting-started.aspx http://codebetter.com/blogs/karlseguin/archive/2009/04/27/validation-part-2-client-side.aspx http://codebetter.com/blogs/karlseguin/archive/2009/04/28/validation-part-3-server-side.aspx It's really nice solution :) A: How about D) None of the above. I remember evaluating this last year and decided on going with Spring.NET's validation framework. If your using NHibernate your probably want to use Spring.NET's facilities for using NHibernate as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/153731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How do I break up high-cpu requests on Google App Engine? To give an example of the kind of request that I can't figure out what else to do for: The application is a bowling score/stat tracker. When someone enters their scores in advanced mode, a number of stats are calculated, as well as their score. The data is modeled as: Game - members like name, user, reference to the bowling alley, score Frame - pinfalls for each ball, boolean lists for which pins were knocked down on each ball, information about the path of the ball (stance, target, where it actually went), the score as of that frame, etc GameStats - stores calculated statistics for the entire game, to be merged with other game stats as needed for statistics display across groups of games. An example of this information in practice can be found here. When a game is complete, and a frame is updated, I have to update the game, the frame, every frame after it and possibly some before it (to make sure their scores are correct), and the stats. This operation always flags the CPU monitor. Even if the game isn't complete, and statistics don't need to be calculated, the scores and such need to be updated to show the real-time progress to the user, and so these also get flagged. The average CPU time for this handler is over 7000 mcycles, and it doesn't even display a view. Most people bowl 3 to 4 games per series - if they are entering their scores realtime, at the lanes, that's about 1 request every 2 to 4 minutes, but if they write it all down and enter it later, there are 30-40 of these requests being made in a row. As requested, the data model for the important classes: class Stats(db.Model): version = db.IntegerProperty(default=1) first_balls=db.IntegerProperty(default=0) pocket_tracked=db.IntegerProperty(default=0) pocket=db.IntegerProperty(default=0) strike=db.IntegerProperty(default=0) carry=db.IntegerProperty(default=0) double=db.IntegerProperty(default=0) double_tries=db.IntegerProperty(default=0) target_hit=db.IntegerProperty(default=0) target_missed_left=db.IntegerProperty(default=0) target_missed_right=db.IntegerProperty(default=0) target_missed=db.FloatProperty(default=0.0) first_count=db.IntegerProperty(default=0) first_count_miss=db.IntegerProperty(default=0) second_balls=db.IntegerProperty(default=0) spare=db.IntegerProperty(default=0) single=db.IntegerProperty(default=0) single_made=db.IntegerProperty(default=0) multi=db.IntegerProperty(default=0) multi_made=db.IntegerProperty(default=0) split=db.IntegerProperty(default=0) split_made=db.IntegerProperty(default=0) class Game(db.Model): version = db.IntegerProperty(default=3) user = db.UserProperty(required=True) series = db.ReferenceProperty(Series) score = db.IntegerProperty() game_number = db.IntegerProperty() pair = db.StringProperty() notes = db.TextProperty() simple_entry_mode = db.BooleanProperty(default=False) stats = db.ReferenceProperty(Stats) complete = db.BooleanProperty(default=False) class Frame(db.Model): version = db.IntegerProperty(default=1) user = db.UserProperty() game = db.ReferenceProperty(Game, required=True) frame_number = db.IntegerProperty(required=True) first_count = db.IntegerProperty(required=True) second_count = db.IntegerProperty() total_count = db.IntegerProperty() score = db.IntegerProperty() ball = db.ReferenceProperty(Ball) stance = db.FloatProperty() target = db.FloatProperty() actual = db.FloatProperty() slide = db.FloatProperty() breakpoint = db.FloatProperty() pocket = db.BooleanProperty() pocket_type = db.StringProperty() notes = db.TextProperty() first_pinfall = db.ListProperty(bool) second_pinfall = db.ListProperty(bool) split = db.BooleanProperty(default=False) A: A few suggestions: * *You could store the stats for frames as part of the same entity as the game, rather than having a separate entity for each, by storing it as a list of bitfields (stored in integers) for the pins standing at the end of each half-frame, for example. Let me know if you want more details on how this would be implemented. *Failing that, you can calculate some of the more interrelated stats on fetch. For example, calculating the score-so-far ought to be simple if you have the whole game loaded at once, which means you can avoid having to update multiple frames on every request. *We can be of more help if you show us your data model. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/153732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What are RFC's? I think there are a lot of people out there unaware of RFC's (Request for Comments). I know what they are at a logical level, but can anybody give a good description for a new developer? Also, sharing some resources on how to use and read them would be nice. A: From http://linux.about.com/cs/linux101/g/rfclparrequestf.htm The name of the result and the process for creating a standard on the Internet. New standards are proposed and published on the Internet, as a Request For Comments. The proposal is reviewed by the Internet Engineering Task Force (http://www.ietf.org/), a consensus-building body that facilitates discussion, and eventually a new standard is established, but the reference number/name for the standard retains the acronym RFC, e.g. the official standard for e-mail message formats is RFC 822. See also: RFC Wikipedia Article A: This could also mean "Request for Change" in an Agile environment. Just throwing that out there as everyone is so certain is just means "Request for Comments". A: The term comes from the days of ARPANET, the predecessor to the internet, where the researchers would basically just throw ideas out there to, well, make a request for comments from the other researchers on the project. They could be about pretty much anything and were not very formal at the time. If you go read them, it’s pretty comical how informal they were. Now, there are more standards about what goes in RFC's and you can't get an RFC published until you have met strict guidelines and have done extensive research. They are pretty much reserved for well researched network standards that have been approved by the IETF. A: Wikipedia gives a good description of what [RFC] is about but in a nutshell it is a set of recommendation from the Internet Engineering Task Force applicable to the working of the Internet and Internet-connected systems. They are used as the standards. So if you're looking for a definitive source of the information about the implementation of FTP, LDAP, IMAP, POP etc you don't have to look further than the appropriate RFC documents. A: It's a Request For Comments. That title is a little misleading though, as it's often used as a name for standards, mostly those by the IETF. See Wikipedia
{ "language": "en", "url": "https://stackoverflow.com/questions/153735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: Vector and Layer Data Structure I'm working with some code that is confusing me and I'm wondering if I'm just not grokking the data structures. The data I'm working with utilizes vectors and layers. I believe a vector is just a row of data but I'm not sure. Any information you could provide or point me to about the use of these would be very helpful. A: The simplest view of a vector is a fixed-size list, such as a one-dimensional array. I've never heard of a "Layer", and googling turned up nothing relevant either. What are you trying to do?
{ "language": "en", "url": "https://stackoverflow.com/questions/153742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to inject Javascript in WebBrowser control? I've tried this: string newScript = textBox1.Text; HtmlElement head = browserCtrl.Document.GetElementsByTagName("head")[0]; HtmlElement scriptEl = browserCtrl.Document.CreateElement("script"); lblStatus.Text = scriptEl.GetType().ToString(); scriptEl.SetAttribute("type", "text/javascript"); head.AppendChild(scriptEl); scriptEl.InnerHtml = "function sayHello() { alert('hello') }"; scriptEl.InnerHtml and scriptEl.InnerText both give errors: System.NotSupportedException: Property is not supported on this type of HtmlElement. at System.Windows.Forms.HtmlElement.set_InnerHtml(String value) at SForceApp.Form1.button1_Click(Object sender, EventArgs e) in d:\jsight\installs\SForceApp\SForceApp\Form1.cs:line 31 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) Is there an easy way to inject a script into the dom? A: I believe the most simple method to inject Javascript in a WebBrowser Control HTML Document from c# is to invoke the "execScript" method with the code to be injected as argument. In this example the javascript code is injected and executed at global scope: var jsCode="alert('hello world from injected code');"; WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" }); If you want to delay execution, inject functions and call them after: var jsCode="function greet(msg){alert(msg);};"; WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" }); ............... WebBrowser.Document.InvokeScript("greet",new object[] {"hello world"}); This is valid for Windows Forms and WPF WebBrowser controls. This solution is not cross browser because "execScript" is defined only in IE and Chrome. But the question is about Microsoft WebBrowser controls and IE is the only one supported. For a valid cross browser method to inject javascript code, create a Function object with the new Keyword. This example creates an anonymous function with injected code and executes it (javascript implements closures and the function has access to global space without local variable pollution). var jsCode="alert('hello world');"; (new Function(code))(); Of course, you can delay execution: var jsCode="alert('hello world');"; var inserted=new Function(code); ................. inserted(); Hope it helps A: As a follow-up to the accepted answer, this is a minimal definition of the IHTMLScriptElement interface which does not require to include additional type libraries: [ComImport, ComVisible(true), Guid(@"3050f28b-98b5-11cf-bb82-00aa00bdce0b")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] [TypeLibType(TypeLibTypeFlags.FDispatchable)] public interface IHTMLScriptElement { [DispId(1006)] string text { set; [return: MarshalAs(UnmanagedType.BStr)] get; } } So a full code inside a WebBrowser control derived class would look like: protected override void OnDocumentCompleted( WebBrowserDocumentCompletedEventArgs e) { base.OnDocumentCompleted(e); // Disable text selection. var doc = Document; if (doc != null) { var heads = doc.GetElementsByTagName(@"head"); if (heads.Count > 0) { var scriptEl = doc.CreateElement(@"script"); if (scriptEl != null) { var element = (IHTMLScriptElement)scriptEl.DomElement; element.text = @"function disableSelection() { document.body.onselectstart=function(){ return false; }; document.body.ondragstart=function() { return false; }; }"; heads[0].AppendChild(scriptEl); doc.InvokeScript(@"disableSelection"); } } } } A: this is a solution using mshtml IHTMLDocument2 doc = new HTMLDocumentClass(); doc.write(new object[] { File.ReadAllText(filePath) }); doc.close(); IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)doc.all.tags("head")).item(null, 0); IHTMLScriptElement scriptObject = (IHTMLScriptElement)doc.createElement("script"); scriptObject.type = @"text/javascript"; scriptObject.text = @"function btn1_OnClick(str){ alert('you clicked' + str); }"; ((HTMLHeadElementClass)head).appendChild((IHTMLDOMNode)scriptObject); A: HtmlDocument doc = browser.Document; HtmlElement head = doc.GetElementsByTagName("head")[0]; HtmlElement s = doc.CreateElement("script"); s.SetAttribute("text","function sayHello() { alert('hello'); }"); head.AppendChild(s); browser.Document.InvokeScript("sayHello"); (tested in .NET 4 / Windows Forms App) Edit: Fixed case issue in function set. A: Here is the easiest way that I found after working on this: string javascript = "alert('Hello');"; // or any combination of your JavaScript commands // (including function calls, variables... etc) // WebBrowser webBrowser1 is what you are using for your web browser webBrowser1.Document.InvokeScript("eval", new object[] { javascript }); What global JavaScript function eval(str) does is parses and executes whatever is written in str. Check w3schools ref here. A: Also, in .NET 4 this is even easier if you use the dynamic keyword: dynamic document = this.browser.Document; dynamic head = document.GetElementsByTagName("head")[0]; dynamic scriptEl = document.CreateElement("script"); scriptEl.text = ...; head.AppendChild(scriptEl); A: Here is a VB.Net example if you are trying to retrieve the value of a variable from within a page loaded in a WebBrowser control. Step 1) Add a COM reference in your project to Microsoft HTML Object Library Step 2) Next, add this VB.Net code to your Form1 to import the mshtml library: Imports mshtml Step 3) Add this VB.Net code above your "Public Class Form1" line: <System.Runtime.InteropServices.ComVisibleAttribute(True)> Step 4) Add a WebBrowser control to your project Step 5) Add this VB.Net code to your Form1_Load function: WebBrowser1.ObjectForScripting = Me Step 6) Add this VB.Net sub which will inject a function "CallbackGetVar" into the web page's Javascript: Public Sub InjectCallbackGetVar(ByRef wb As WebBrowser) Dim head As HtmlElement Dim script As HtmlElement Dim domElement As IHTMLScriptElement head = wb.Document.GetElementsByTagName("head")(0) script = wb.Document.CreateElement("script") domElement = script.DomElement domElement.type = "text/javascript" domElement.text = "function CallbackGetVar(myVar) { window.external.Callback_GetVar(eval(myVar)); }" head.AppendChild(script) End Sub Step 7) Add the following VB.Net sub which the Javascript will then look for when invoked: Public Sub Callback_GetVar(ByVal vVar As String) Debug.Print(vVar) End Sub Step 8) Finally, to invoke the Javascript callback, add this VB.Net code when a button is pressed, or wherever you like: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click WebBrowser1.Document.InvokeScript("CallbackGetVar", New Object() {"NameOfVarToRetrieve"}) End Sub Step 9) If it surprises you that this works, you may want to read up on the Javascript "eval" function, used in Step 6, which is what makes this possible. It will take a string and determine whether a variable exists with that name and, if so, returns the value of that variable. A: I used this :D HtmlElement script = this.WebNavegador.Document.CreateElement("SCRIPT"); script.SetAttribute("TEXT", "function GetNameFromBrowser() {" + "return 'My name is David';" + "}"); this.WebNavegador.Document.Body.AppendChild(script); Then you can execute and get the result with: string myNameIs = (string)this.WebNavegador.Document.InvokeScript("GetNameFromBrowser"); I hope to be helpful A: If all you really want is to run javascript, this would be easiest (VB .Net): MyWebBrowser.Navigate("javascript:function foo(){alert('hello');}foo();") I guess that this wouldn't "inject" it but it'll run your function, if that's what you're after. (Just in case you've over-complicated the problem.) And if you can figure out how to inject in javascript, put that into the body of the function "foo" and let the javascript do the injection for you. A: For some reason Richard's solution didn't work on my end (insertAdjacentText failed with an exception). This however seems to work: HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0]; HtmlElement scriptEl = webBrowser1.Document.CreateElement("script"); IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement; element.text = "function sayHello() { alert('hello') }"; head.AppendChild(scriptEl); webBrowser1.Document.InvokeScript("sayHello"); This answer explains how to get the IHTMLScriptElement interface into your project. A: The managed wrapper for the HTML document doesn't completely implement the functionality you need, so you need to dip into the MSHTML API to accomplish what you want: 1) Add a reference to MSHTML, which will probalby be called "Microsoft HTML Object Library" under COM references. 2) Add 'using mshtml;' to your namespaces. 3) Get a reference to your script element's IHTMLElement: IHTMLElement iScriptEl = (IHTMLElement)scriptEl.DomElement; 4) Call the insertAdjacentText method, with the first parameter value of "afterBegin". All the possible values are listed here: iScriptEl.insertAdjacentText("afterBegin", "function sayHello() { alert('hello') }"); 5) Now you'll be able to see the code in the scriptEl.InnerText property. Hth, Richard A: You can always use a "DocumentStream" or "DocumentText" property. For working with HTML documents I recommend a HTML Agility Pack. A: i use this: webBrowser.Document.InvokeScript("execScript", new object[] { "alert(123)", "JavaScript" }) A: What you want to do is use Page.RegisterStartupScript(key, script) : See here for more details: http://msdn.microsoft.com/en-us/library/aa478975.aspx What you basically do is build your javascript string, pass it to that method and give it a unique id( in case you try to register it twice on a page.) EDIT: This is what you call trigger happy. Feel free to down it. :) A: If you need to inject a whole file then you can use this: With Browser.Document Dim Head As HtmlElement = .GetElementsByTagName("head")(0) Dim Script As HtmlElement = .CreateElement("script") Dim Streamer As New StreamReader(<Here goes path to file as String>) Using Streamer Script.SetAttribute("text", Streamer.ReadToEnd()) End Using Head.AppendChild(Script) .InvokeScript(<Here goes a method name as String and without parentheses>) End With Remember to import System.IO in order to use the StreamReader. I hope this helps. A: bibki.js webBrowser1.DocumentText = "<html><head><script>" + "function test(message) { alert(message); }" + "</script></head><body><button " + "onclick=\"window.external.Test('called from script code')\">" + "call client code from script code</button>" + "</body></html>";
{ "language": "en", "url": "https://stackoverflow.com/questions/153748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "82" }
Q: jQuery Datepicker with text input that doesn't allow user input How do I use the jQuery Datepicker with a textbox input: $("#my_txtbox").datepicker({ // options }); that doesn't allow the user to input random text in the textbox. I want the Datepicker to pop up when the textbox gains focus or the user clicks on it, but I want the textbox to ignore any user input using the keyboard (copy & paste, or any other). I want to fill the textbox exclusively from the Datepicker calendar. Is this possible? jQuery 1.2.6 Datepicker 1.5.2 A: Based on my experience I would recommend the solution suggested by Adhip Gupta: $("#my_txtbox").attr( 'readOnly' , 'true' ); The following code won't let the user type new characters, but will allow them to delete characters: $("#my_txtbox").keypress(function(event) {event.preventDefault();}); Additionally, this will render the form useless to those who have JavaScript disabled: <input type="text" readonly="true" /> A: <input type="text" readonly="true" /> causes the textbox to lose its value after postback. You rather should use Brad8118's suggestion which is working perfectly. $("#my_txtbox").keypress(function(event) {event.preventDefault();}); EDIT: to get it working for IE use 'keydown' instead of 'keypress' A: After initialising the date picker: $(".project-date").datepicker({ dateFormat: 'd M yy' }); $(".project-date").keydown(false); A: You have two options to get this done. (As far as i know) * *Option A: Make your text field read only. It can be done as follows. *Option B: Change the curser onfocus. Set ti to blur. it can be done by setting up the attribute onfocus="this.blur()" to your date picker text field. Ex: <input type="text" name="currentDate" id="currentDate" onfocus="this.blur()" readonly/> A: $("#txtfromdate").datepicker({ numberOfMonths: 2, maxDate: 0, dateFormat: 'dd-M-yy' }).attr('readonly', 'readonly'); add the readonly attribute in the jquery. A: To datepicker to popup on gain focus: $(".selector").datepicker({ showOn: 'both' }) If you don't want user input, add this to the input field <input type="text" name="date" readonly="readonly" /> A: I just came across this so I am sharing here. Here is the option https://eonasdan.github.io/bootstrap-datetimepicker/Options/#ignorereadonly Here is the code. HTML <br/> <!-- padding for jsfiddle --> <div class="input-group date" id="arrival_date_div"> <input type="text" class="form-control" id="arrival_date" name="arrival_date" required readonly="readonly" /> <span class="input-group-addon"> <span class="glyphicon-calendar glyphicon"></span> </span> </div> JS $('#arrival_date_div').datetimepicker({ format: "YYYY-MM-DD", ignoreReadonly: true }); Here is the fiddle: http://jsfiddle.net/matbaric/wh1cb6cy/ My version of bootstrap-datetimepicker.js is 4.17.45 A: You should be able to use the readonly attribute on the text input, and jQuery will still be able to edit its contents. <input type='text' id='foo' readonly='true'> A: I know this thread is old, but for others who encounter the same problem, that implement @Brad8118 solution (which i prefer, because if you choose to make the input readonly then the user will not be able to delete the date value inserted from datepicker if he chooses) and also need to prevent the user from pasting a value (as @ErikPhilips suggested to be needed), I let this addition here, which worked for me: $("#my_txtbox").bind('paste',function(e) { e.preventDefault(); //disable paste }); from here https://www.dotnettricks.com/learn/jquery/disable-cut-copy-and-paste-in-textbox-using-jquery-javascript and the whole specific script used by me (using fengyuanchen/datepicker plugin instead): $('[data-toggle="datepicker"]').datepicker({ autoHide: true, pick: function (e) { e.preventDefault(); $(this).val($(this).datepicker('getDate', true)); } }).keypress(function(event) { event.preventDefault(); // prevent keyboard writing but allowing value deletion }).bind('paste',function(e) { e.preventDefault() }); //disable paste; A: Instead of adding readonly you can also use onkeypress="return false;" A: try $("#my_txtbox").keypress(function(event) {event.preventDefault();}); A: If you are reusing the date-picker at multiple places then it would be apt to modify the textbox also via JavaScript by using something like: $("#my_txtbox").attr( 'readOnly' , 'true' ); right after/before the place where you initialize your datepicker. A: This demo sort of does that by putting the calendar over the text field so you can't type in it. You can also set the input field to read only in the HTML to be sure. <input type="text" readonly="true" /> A: HTML <input class="date-input" type="text" readonly="readonly" /> CSS .date-input { background-color: white; cursor: pointer; } A: I've found that the jQuery Calendar plugin, for me at least, in general just works better for selecting dates. A: $('.date').each(function (e) { if ($(this).attr('disabled') != 'disabled') { $(this).attr('readOnly', 'true'); $(this).css('cursor', 'pointer'); $(this).css('color', '#5f5f5f'); } }); A: Here is your answer which is way to solve.You do not want to use jquery when you restricted the user input in textbox control. <input type="text" id="my_txtbox" readonly /> <!--HTML5--> <input type="text" id="my_txtbox" readonly="true"/> A: $("#my_txtbox").prop('readonly', true) worked like a charm.. A: Instead of using textbox you can use button also. Works best for me, where I don't want users to write date manually. A: I know this question is already answered, and most suggested to use readonly attribure. I just want to share my scenario and answer. After adding readonly attribute to my HTML Element, I faced issue that I am not able to make this attribute as required dynamically. Even tried setting as both readonly and required at HTML creation time. So I will suggest do not use readonly if you want to set it as required also. Instead use $("#my_txtbox").datepicker({ // options }); $("#my_txtbox").keypress(function(event) { return ( ( event.keyCode || event.which ) === 9 ? true : false ); }); This allow to press tab key only. You can add more keycodes which you want to bypass. I below code since I have added both readonly and required it still submits the form. After removing readonly it works properly. https://jsfiddle.net/shantaram/hd9o7eor/ $(function() { $('#id-checkbox').change( function(){ $('#id-input3').prop('required', $(this).is(':checked')); }); $('#id-input3').datepicker(); $("#id-input3").keypress(function(event) { return ( ( event.keyCode || event.which ) === 9 ? true : false ); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet"/> <form action='https://jsfiddle.net/'> Name: <input type="text" name='xyz' id='id-input3' readonly='true' required='true'> <input type='checkbox' id='id-checkbox'> Required <br> <br> <input type='submit' value='Submit'> </form> A: replace the ID of time picker: IDofDatetimePicker to your id. This will prevent the user from entering any further keyboard inputs but still, the user will be able to access the time popup. $("#my_txtbox").keypress(function(event) {event.preventDefault();}); Try this source: https://github.com/jonthornton/jquery-timepicker/issues/109 A: This question has a lot of older answers and readonly seems to be the generally accepted solution. I believe the better approach in modern browsers is to use the inputmode="none" in the HTML input tag: <input type="text" ... inputmode="none" /> or, if you prefer to do it in script: $(selector).attr('inputmode', 'none'); I haven't tested it extensively, but it is working well on the Android setups I have used it with. A: In my case i have use disableTextInput property $( ".datepicker" ).datepicker({'dateFormat' : 'd-m-y', 'disableTextInput':true }); A: Or you could, for example, use a hidden field to store the value... <asp:HiddenField ID="hfDay" runat="server" /> and in the $("#my_txtbox").datepicker({ options: onSelect: function (dateText, inst) { $("#<% =hfDay.ClientID %>").val(dateText); } A: If you want the user to select a date from the datepicker but you dont want the user to type inside the textbox then use the following code : <script type="text/javascript"> $(function () { $("#datepicker").datepicker({ maxDate: "-1D" }).attr('readonly', 'readonly'); $("#datepicker").readonlyDatepicker(true); });
{ "language": "en", "url": "https://stackoverflow.com/questions/153759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "146" }
Q: How do I convert an Illustrator file to a path for WPF Our graphics person uses Adobe Illustrator and we'd like to use her images inside our WPF application as paths. Is there a way to do this? A: You can go from AI to SVG to XAML. * *From Adobe Illustrator: File -> Save As -> *.SVG. * *SVG "Profile 1.1" seems to be sufficient. *Note that to preserve path/group names in XAML you should enable "Preserve Illustrator Editing Capabilities" (or at least as it's called in CS4). *SharpVectors can convert SVG data to XAML data. This will produce a fragment of XAML with root <DrawingGroup>. *Do what you need to do to copy-paste and otherwise use the XAML, such as placing it into an Image like below. Named objects or groups in the AI file should still have their names in the XAML i.e. via x:Name="...". <Image> <Image.Source> <DrawingImage> <DrawingImage.Drawing> <DrawingGroup ... the output from step #2 ...>...</DrawingGroup> </DrawingImage.Drawing> </DrawingImage> </Image.Source> </Image> *Coordinate systems can be a pain if you want to be animating things. There are some other posts such as this which may have insights. A: Get her to export the illustrations as some other format (recent versions of Illustrator support SVG) that you can use or convert to something that will work. A: The detour suggested by @ConcernedOfTunbridgeWells is starting to make sense now. Other solutions are not being maintained and do not work anymore. Hence, you can use this option as workaround: * *Save files as svg. *Convert them to XAML using Inkscape. This solution even has the advantage of text will stay text and is not converted to a path. How to convert many files? Inkscape also supports a batch mode to convert many files at once. I took a great script (by Johannes Deml) for batch conversions on Windows that takes vectors files and converts them to various other formats using Inkscapes batch mode. I adapted it to convert to XAML, too. You can find the script that includes XAML on Github. Some instructions on how to use the script are provided by the original author.
{ "language": "en", "url": "https://stackoverflow.com/questions/153762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How to see the schema of a db2 table (file) As in subject... is there a way of looking at an empty table schema without inserting any rows and issuing a SELECT? A: SELECT * FROM SYSIBM.SYSCOLUMNS WHERE TBNAME = 'tablename'; A: Are you looking for DESCRIBE? db2 describe table user1.department Table: USER1.DEPARTMENT Column Type Type name schema name Length Scale Nulls ------------------ ----------- ------------------ -------- -------- -------- AREA SYSIBM SMALLINT 2 0 No DEPT SYSIBM CHARACTER 3 0 No DEPTNAME SYSIBM CHARACTER 20 0 Yes A: For DB2 AS/400 (V5R4 here) I used the following queries to examine for database / table / column metadata: SELECT * FROM SYSIBM.TABLES -- Provides all tables SELECT * FROM SYSIBM.VIEWS -- Provides all views and their source (!!) definition SELECT * FROM SYSIBM.COLUMNS -- Provides all columns, their data types & sizes, default values, etc. SELECT * FROM SYSIBM.SQLPRIMARYKEYS -- Provides a list of primary keys and their order A: Looking at your other question, DESCRIBE may not work. I believe there is a system table that stores all of the field information. Perhaps this will help you out. A bit more coding but far more accurate.
{ "language": "en", "url": "https://stackoverflow.com/questions/153769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What is the preferred way to redirect a request in Pylons without losing form data? I'm trying to redirect/forward a Pylons request. The problem with using redirect_to is that form data gets dropped. I need to keep the POST form data intact as well as all request headers. Is there a simple way to do this? A: Receiving data from a POST depends on the web browser sending data along. When the web browser receives a redirect, it does not resend that data along. One solution would be to URL encode the data you want to keep and use that with a GET. In the worst case, you could always add the data you want to keep to the session and pass it that way.
{ "language": "en", "url": "https://stackoverflow.com/questions/153773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Wcf and Interfaces as Parameters i have a library with some entities that share the same interface. clients and service share this assembly. now i wonder if there is a way to have this Interface-type as Parameter in my service contracts so that i can use the same method for all classes implementing the interface. the entities themselve are all decorated with datacontract-attribute and its members with datamember attributes. is it possible at all? probably with the NetDataContractSerializer? i know that i can do it with a base class (some abstract class e.g.) and the knowntype-attribute but i´d definitely prefer the Interface as identificator of the objects cause it is used widely in the client app and would ease development. thanks A: I solved the problem using the ServiceKnownType attribute at the implementations of the OperationContracts. When telling your classes that implement the interface as ServiceKnownType's, you can use the interface as parameter and therefore are able to use all classes implementing your interface as long as they are serializable. (look at "Programming WCF Services" from Juval Löwy, page 100) A: It certainly isn't possible under regular "mex". It might be possible with assembly sharing, but I really wouldn't recommend it - you are fighting WCF: it will be brittle, etc. Of course, you can always mask this in your object model - i.e. rather than calling the [OperationContract] method directly, abstract this away into a wrapper method that hides the WCF details (perhaps using different objects for the data transfer than it actually returns). A: [I just read your answer and realized that you were asking specifically about parameters to service methods. I'll leave my comments here in case they're still helpful.] What I've done on projects where I know I have WCF on both sides of the wire, is something like: A library of only the shared interfaces, eg: namespace SharedInterfaces { public interface ICompositeType { bool BoolValue { get; set; } string StringValue { get; set; } } } The WCF service library, where the [DataContract]s (POCOs) implement the shared interfaces. [DataContract] public class CompositeType : ICompositeType { bool boolValue = true; string stringValue = "Hello "; [DataMember] public bool BoolValue { get { return boolValue; } set { boolValue = value; } } [DataMember] public string StringValue { get { return stringValue; } set { stringValue = value; } } } In the service client, each proxy POCO can be "compelled" to implement the shared, deployed, interface using a partial class (it will anyway if svcutil did it's job correctly), and you'll be able to program to the interface in the rest of your client code: namespace ServiceClient.ServiceReference1 { public partial class CompositeType : ICompositeType { } } This partial is also useful if you want to add some additional properties or methods that the client can make use of (eg. Presenter or ViewModel concepts in MVP or MVVM patterns).
{ "language": "en", "url": "https://stackoverflow.com/questions/153775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How can I call a javascript function from inside a method? I am inside of... public class bgchange : IMapServerDropDownBoxAction { void IServerAction.ServerAction(ToolbarItemInfo info) { Some code... and after "some code" I want to trigger [WebMethod] public static void DoSome() { } Which triggers some javascript. Is this possible? Ok, switch methods here. I was able to call dosome(); which fired but did not trigger the javascript. I have tried to use the registerstartupscript method but don't fully understand how to implement it. Here's what I tried: public class bgchange : IMapServerDropDownBoxAction { void IServerAction.ServerAction(ToolbarItemInfo info) { ...my C# code to perform on dropdown selection... //now I want to trigger some javascript... // Define the name and type of the client scripts on the page. String csname1 = "PopupScript"; Type cstype = this.GetType(); // Get a ClientScriptManager reference from the Page class. ClientScriptManager cs = Page.ClientScript; // Check to see if the startup script is already registered. if (!cs.IsStartupScriptRegistered(cstype, csname1)) { String cstext1 = "alert('Hello World');"; cs.RegisterStartupScript(cstype, csname1, cstext1, true); } } } I got the registerstartupscript code from an msdn example. Clearly I am not implementing it correctly. Currently vs says "An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.ClientScript.get' refering to the piece of code "Page.Clientscript;" Thanks. A: I'm not sure I fully understand the sequence of what you are trying to do, what's client-side and what's not.... However, you could add a Start-up javascript method to the page which would then call the WebMethod. When calling a WebMethod via javascript, you can add a call-back function, which would then be called when the WebMethod returns. If you add a ScriptManager tag on your page, you can call WebMethods defined in the page via Javascript. <asp:ScriptManager ID="scriptManager1" runat="server" EnablePageMethods="true" /> From the Page_Load function you can add a call to your WebMethod.. Page.ClientScript.RegisterStartupScript( this.GetType(), "callDoSome", "PageMethods.DoSome(Callback_Function, null)", true); Callback_Function represents a javascript function that will be executed after the WebMethod is called... <script language="javascript" type="text/javascript"> function Callback_Function(result, context) { alert('WebMethod was called'); } </script> EDIT: Found this link for Web ADF controls. Is this what you are using?? From that page, it looks like something like this will do a javascript callback. public void ServerAction(ToolbarItemInfo info) { string jsfunction = "alert('Hello');"; Map mapctrl = (Map)info.BuddyControls[0]; CallbackResult cr = new CallbackResult(null, null, "javascript", jsfunction); mapctrl.CallbackResults.Add(cr); } A: If the above is how you are calling RegisterStartupScript, it won't work because you don't have a reference to the "Page" object. bgchange in your example extends Object (assuming IMapServerDropDownBoxAction is an interface), which means that there is no Page instance for you to reference. This you did the exact same thing from a Asp.Net Page or UserControl, it would work, because Page would be a valid reference. public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Page.ClientScript.RegisterStartupScript( this.GetType(), "helloworldpopup", "alert('hello world');", true); } } A: You cannot call methods within a browser directly from the server. You can, however, add javascript functions to the response that will execute methods within the browser. Within the ServerAction method, do the following string script = "<script language='javascript'>\n"; script += "javascriptFunctionHere();\n"; script += "</script>"; Page.RegisterStartupScript("ForceClientToCallServerMethod", script); More info here A: hmmm... the question changed dramatically since my original answer. Now I think the answer is no. But I might be wrong.
{ "language": "en", "url": "https://stackoverflow.com/questions/153776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: File Sharing API or Framework in OS X 10.5.* Is there any programming interface or CLI for changing network or file sharing settings in OS X Leopard? A: It is called dscl (Directory Service command line utility).
{ "language": "en", "url": "https://stackoverflow.com/questions/153781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Dropdown controls in ASP.NET 2.0 I am using a codebehind page in ASP.NET to perform a SQL query. The query is loaded into a string, the connection is established (To Oracle), and we get it started by having the connection perform .ExecuteReader into a OleDBDataReader (We'll call it DataRead). I'll try to hammer out an example below. (Consider Drop as an ASP DropDownList control) Dim LookFor as String = "Fuzzy Bunnies" While DataRead.Read If LookFor = DataRead.Item("Kinds of Bunnies") Then 'Meets special critera, do secondary function' Drop.Items.Add(DataRead.Item("Subgroup of Bunnies")) ... End if ... End While This is the only way I know of doing a dynamic add to a DropDownList. However, each item in a DropDownList has a .text property and a .value property. How can we define the .value as being different from the .text in code? A: The Add function can take a ListItem, so you can do Dim li as new ListItem(DataRead.Item("Subgroup of Bunnies"), "myValue") Drop.Items.Add(li) A: Add should have an overload that accepts a ListItem object. Using that, you can usually do something like this: Drop.Items.Add(New ListItem("Text", "Value")) A: If I understand the question, Items.Add has an overload that takes a ListItem, so you could create a new ListItem object in that line: Drop.Items.Add(new ListItem("text", "value")) A: Pardon my possibly faulty VB Dim item as New ListItem() item.Value = "foo" item.Text = "bar" Drop.Items.Add(item) You can also use the ListItem constructor (e.g. new ListItem("text", "value")) A: you'd select a second column into your datareader (such as an IDENTITY field) and then assign do your Item generation like this: Dim item as new listitem item.text = DataRead.Item("SubGroup Of Bunnies") item.value = DataRead.Item("ID") Drop.Items.Add(item) You may also want to look into the DATABIND functionality, and filtering out "FUZZY BUNNIES" in the SQL statement itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/153782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Printing images on multi-page SSRS RDLC report does not work I am working on an application that loads a generic list of objects into an RDLC report, which is then rendered on the client machine using the WebForms ReportViewer Control. It renders fine and exports fine, but if I try to print it, it spools maybe 500k to the printer and then stops responding. A: Ok, it seems to be a hardware problem! Since you add a image control to your RDLC report it should work very well. I have created many RDLC forms, with images on header, and everything is fine. You should always check if printer has some kind of issue and test it against another ones.
{ "language": "en", "url": "https://stackoverflow.com/questions/153791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: From objects to tables using activerecord I'm getting some objects from an external library and I need to store those objects in a database. Is there a way to create the tables and relationships starting from the objects, or I have to dig into them and create migrations and models by hand? Thanks! Roberto A: Even if you could dynamically create tables on the fly like that (not saying that you can). I wouldn't want to do that. There is so much potential for error there. I would create the migrations by hand and have the tables and fields pre-created and fill them in with rows as needed. A: Note: This is a TERRIBLE hack and you'll be ironing out the bugs for years to come, but it is however pretty easy: This relies on rails ActiveSupport, and ActiveRecord already being loaded Say you get a random object from a third party library which has 2 instance variables - it's class might look like this: class Animal attr_accessor :name, :number_of_legs end a = SomeThirdPartyLibrary.get_animal You can use reflection to figure out it's name, and columns: table_name = a.class.to_s.tableize column_names = a.instance_variables.map{ |n| n[1..-1] } # remove the @ column_types = a.instance_variables.map{ |n| a.instance_variable_get(n).class }.map{ |c| sql_type_for_class(c) } # go write sql_type_for_class please Then you can use ActiveRecord migrations to create your table, like this: ActiveRecord::Migration.class_eval do create_table table_name do |t| column_names.zip(column_types).each do |colname, coltype| t.column colname, coltype end end end Then you can finally declare an activerecord class which will then interface with the just-created table. # Note we declare a module so the new classes don't conflict with the existing ones module GeneratedClasses; end eval "class GeneratedClasses::#{a.class} < ActiveRecord::Base; end" Presto! Now you can do this: a = GeneratedClasses::Animal.new a.update_attributes whatever a.save PS: Don't do this! Apart from being awful, if your rails app restarts it will lose all concept of the Generated Classes, so you'll need to devise some mechanism of persisting those too. A: I have this exact situation. I have to read data external to the application and the performance hit is so big, that I store locally. I have gone with a solution where I have, over time, developed a schema and migrations by hand, that work with the data, and allow me to persist the data to the tables. I have developed a caching scheme that works for my data and the performance has increased significantly. All that to say, I did everything by hand and I don't regret it. I can have confidence that my database is stable and that I am not re-creating db tables on the fly. Because of that, I have no concern about the stability of my application. A: Depending on what you're trying to do with the objects, you can store objects directly into the database by serializing them. A: Try looking at some ORM solutions. Or store as XML.
{ "language": "en", "url": "https://stackoverflow.com/questions/153795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Find controls on sharepoint master page I'm trying to loop through all the controls on a sharepoint page, for the purposes of testing i just want to output the control ID this is the code i'm using Public Shared Sub SubstituteValues3(ByVal CurrentPage As Page, ByRef s As StringBuilder) 'Page() '- MasterPage '- HtmlForm '- ContentPlaceHolder '- The TextBoxes, etc. For Each ctlMaster As Control In CurrentPage.Controls If TypeOf ctlMaster Is MasterPage Then HttpContext.Current.Response.Output.Write("Master Page <br/>") For Each ctlForm As Control In ctlMaster.Controls If TypeOf ctlForm Is HtmlForm Then HttpContext.Current.Response.Output.Write("HTML Form <br/>") For Each ctlContent As Control In ctlForm.Controls If TypeOf ctlContent Is ContentPlaceHolder Then HttpContext.Current.Response.Output.Write("Content Placeholder <br/>") For Each ctlChild As Control In ctlContent.Controls HttpContext.Current.Response.Output.Write(ctlChild.ID.ToString & "<br />") Next End If Next End If Next End If Next HttpContext.Current.Response.Output.Write("--------------") HttpContext.Current.Response.End() however it's not getting past the 'MasterPage' output. I would expect to see the names of all the controls i have inside my content placeholder but i find it all a bit confusing. A: Start with Page.Master.Controls From there what you have should basically work For Each ctlForm As Control In Page.Master.Controls If TypeOf ctlForm Is HtmlForm Then HttpContext.Current.Response.Output.Write("HTML Form <br/>") For Each ctlContent As Control In ctlForm.Controls If TypeOf ctlContent Is ContentPlaceHolder Then HttpContext.Current.Response.Output.Write("Content Placeholder <br/>") For Each ctlChild As Control In ctlContent.Controls HttpContext.Current.Response.Output.Write(ctlChild.ID.ToString & "<br />") Next End If Next End If Next A: A MasterPage isn't a control of the current page, it's a property of it, in Page.MasterPage A: i found this piece of code which seems list the controls I need, i think it's more of a hack though. For i = 0 To CurrentPage.Request.Form.AllKeys.Length - 1 If CurrentPage.Request.Form.GetKey(i).Contains("ctl00$PlaceHolderMain$") Then Dim key As String = CurrentPage.Request.Form.GetKey(i).Substring(22) Dim keyText As String = String.Format("[{0}]", key) HttpContext.Current.Response.Output.Write(keyText & "<br/>") 'Text.Replace(keyText, CurrentPage.Request.Form("ctl00$PlaceHolderMain$" & key)) End If Next A: you can do this simply with recursion, not efficent, but it is simple... try this method: public void getControls(Control input) { foreach (Control c in input.Controls) { Response.Write(c.GetType().ToString() + " - " + c.ID + "<br />"); getControls(c); } } And call it like this: getControls(Page); That will cycle trough all controls on your page and output the type - ID of them and print it out to the top of the page... you could also use the code to construct a list or whatever you want to do.
{ "language": "en", "url": "https://stackoverflow.com/questions/153796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Concatenate RTF files in PHP (REGEX) I've got a script that takes a user uploaded RTF document and merges in some person data into the letter (name, address, etc), and does this for multiple people. I merge the letter contents, then combine that with the next merge letter contents, for all people records. Affectively I'm combining a single RTF document into itself for as many people records to which I need to merge the letter. However, I need to first remove the closing RTF markup and opening of the RTF markup of each merge or else the RTF won't render correctly. This sounds like a job for regular expressions. Essentially I need a regex that will remove the entire string: }\n\page ANYTHING \par Example, this regex would match this: crap } \page{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0 Arial;}} {\*\generator Msftedit 5.41.15.1515;}\viewkind4\uc1\pard\f0\fs20 September 30, 2008\par more crap So I could make it just: crap \page more crap Is RegEx the best approach here? UPDATE: Why do I have to use RTF? I want to enable the user to upload a form letter that the system will then use to create the merged letters. Since RTF is plain text, I can do this pretty easily in code. I know, RTF is a disaster of a spec, but I don't know any other good alternative. A: I would question the use of RTF in this case. It's not entirely clear to me what you're trying to do overall, so I can't necessarily suggest anything better, but if you can try to explain your project more broadly, maybe I can help. If this is really the way you want to go though, this regex gave me the correct output given your input: $output = preg_replace("/}\s?\n\\\\page.*?\\\\par\s?\n/ms", "\\page\n", $input); A: To this I can say ick ick ick. Nevertheless, rcar's cludge probably will work, barring some weird edge-case where RTF doesn't actually end in that form, or the document-wide styles include important information that utterly messes up the formatting, or any other of the many failure modes.
{ "language": "en", "url": "https://stackoverflow.com/questions/153801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Last Modified of Folders How does Windows determine the last modified date of a folder? A: According to MSDN, the last modification timestamp is stored per directory: * *If you create two new folders on an NTFS partition called D:\NTFS1 and D:\NTFS2, both the created and modified date and time are the same. *If you move the D:\NTFS2 folder into the D:\NTFS1 folder, creating D:\NTFS1\NTFS2, then: * *D:\NTFS1 - The created folder is the same and the modified stamp changes. *D:\NTFS1\NTFS2 - Both the created folder changes and the modified folder stay the same. This behavior occurs because, even though you moved the folder, a new folder is seen as being created within the D:\NTFS1 folder by the Master File Table (MFT). *If you copy the D:\NTFS2 folder into the D:\NTFS1 folder, creating the D:\NTFS1\NTFS2 folder, and the D:\NTFS2 folder still exists (after having copied it): * *D:\NTFS1 - The created folder is the same and the modified folder time and date stamp changes. *D:\NTFS2 - No changes occur because it is the original folder. *D:\NTFS1\NTFS2 - Both the created folder and the modified folder changes to the same stamp, which is that of the time of the move. This behavior occurs because even though you copied the folder, the new folder is seen as being created by the MFT and is given a new created and modified time stamp. Note: The design and behavior of the FAT file system is different with regards to the modified time stamp. On a FAT file system, the modified date of a folder does not change if the contents of the folder change. For example, if you have D:\FAT1 and D:\FAT2, and you copy or move D:\FAT2 into D:\FAT1, the created date and modified date of D:\FAT1 remains the same. A: uses the date of last file activity inside the folder. A: When a directory entry is updated, the last modified date of the directory itself is also updated.
{ "language": "en", "url": "https://stackoverflow.com/questions/153803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Subversion - is trunk really the best place for the main development? In SVN, trunk is the recommended place for the main development and I use this convention for all of my projects. However, this means that trunk is sometimes unstable, or even broken. This happens for instance when * *I commit something by mistake *When the trunk simply has to be broken because of the way SVN works. Canonical example is file renames - you must commit any file renames first and do any further modifications later; however, file rename may require code refactoring to reflect namespace or class name change so you basically need to commit a single logic operation in two steps. And the build is broken between steps 1 and 2. I can imagine there would be tools to prevent commiting something by mistake (TeamCity and delayed commits, for instance) but can you really overcome the second problem? If not, wouldn't it be better to do the "wild development" on some branch like /branch/dev and only merge to trunk when the build is reasonably solid? A: The trunk is where the ongoing development is supposed to happen. You really shouldn't have a problem with "broken" code, if everyone is testing their changes before committing them. A good rule of thumb is to do an update (get all the latest code from the repos) after you have coded your changes. Then build and do some unit testing. If everything builds and works, you should be good to check it in. When you get ready for a release, make a branch. Test can do their release verification against the branch. If problems are found, the fix(s) are made to the branch and trunk, and new cut of the branch is given to test. Meanwhile, the developers are busily adding new changes to the trunk. So... the issues identified by test and the brilliant solutions to these trivial problems are current in both the branch and trunk, test folk have a stable cut to work with, and development has continued moving forward whilest test verified the current release. Like Hanibal always said on "The A-Team", "I love it when a plan comes together." A: Teams that use Subversion often have a pathological aversion to merging, because prior to 1.5 it was a long complex process prone to failure. If you have enough developers so that having an always working trunk is absolutely necessary since many people are working on many different modules that work together, branchy development will certainly help. By the way, even when you rename a file you are still permitted to edit it. I do that all the time. A: Your trunk should ALWAYS compile, if you need to make breaking changes you should use a branch and merge the changes back later. Read this chapter of the SVN book: http://svnbook.red-bean.com/nightly/en/svn.branchmerge.html A: I've created a couple of shell-scripts to simplify creating short-lived development branches: # Create new branch and switch to it function svn_bswitch() { branch=$1; shift msg="$1"; shift URL=$(svn info . | sed -ne 's@URL: \(.*\)@\1@p') REPO=$(svn info . | sed -ne 's@Repository Root: \(.*\)@\1@p') BRANCH_URL=$REPO/branch/$branch svn copy $URL $BRANCH_URL -m "$msg" } # Switch to a branch or tag function svn_switch() { d=$1; shift REPO=$(svn info . | sed -ne 's@Repository Root: \(.*\)@\1@p') URL=$REPO/$d svn switch $URL } A: I would recommend reading this article on SCM best practices. Extracted from the article: Have a mainline. A "mainline," or "trunk," is the branch of a codeline that evolves forever. A mainline provides an ultimate destination for almost all changes - both maintenance fixes and new features - and represents the primary, linear evolution of a software product. Release codelines and development codelines are branched from the mainline, and work that occurs in branches is propagated back to the mainline. Edit: I would also recommend reading SCM Patterns. A: It really depends on your environment. In some cases, having the trunk broken temporarily isn't a big deal. But if you're working with more than 2-3 people, that probably wouldn't be a good idea. In that case, I'd think using branches more freely is a good idea. They're easy enough to set up, and to remerge (if you don't let things get too far out of sync). Of course, if all your developers are using the same branch, you won't really gain anything - you'll just have your trunk called /branch/dev, but having it broken would still be a major issue! Break down the branches so that only a few developers work on each one, and you should be good. A: In our company, we have a nightly build of the trunk. It is expected that everybody test their code so that it at the very least compiles before they check it in. If the nightly build fails, the offending code is removed until fixed. I think the most important part is for everybody to understand the role of subversion and why it is important that they check in only code that compiles. A: Nope trunk isn't the best place. At our organization we always follow this approach: Trunk contains release code, so it always compiles. With new each release/milestone we open a new branch. Whenever a developer owns up an item, he/she creates a new branch to this release branch and merges it into a release branch only after testing it. Release branch is merged into trunk after system testing. The attached image is a crude representation. A: Another example of when the good old "stable trunk, dev in branch" process becomes an issue: You're developing a web application that depends on a lot of live, possibly user-contributed, data. You can for some reason not just generate another instance of the database backend(-s) or external filesystems that you depend on. (For example, your environment might be lacking data model migrations) Team A has been developing a new feature F in /branches/F. Team B just started another branch to fix some performance issues that occur on the live site in /branches/P, and the first thing Team B needs to do is refactor a bunch of the database tables and/or how files are laid out on the external filesystem. This causes Team A to have to refactor a lot of their new stuff before they can continue development. Then Team C comes in and does another thing... And suddenly everyone's got an issue. Then comes the merge phase - and after that nobody ever want's to use TortoiseSVN anymore. A: Nope, trunk is not the best place for committing development level code. In our environment, we regard our trunk as the mirror to whatever has been deployed to production. The workflow maybe different for web development and application development but the trunk should contain the latest production changes. We do work on development branches i.e. branches/feature1 and create a qa tag by copying branches/feature1 --> tags/feature1-qa1 and fix any bugs in branches/feature1 to create tags/feature1-qa1 and so on. When were ready to deploy, all changes that happened in branches/feature1 since last merge to trunk is merged back trunk before creating the final release tag i.e. tags/5.1.0. Work flow may vary depending on how your team is setup or what type of project/environment you're in.
{ "language": "en", "url": "https://stackoverflow.com/questions/153812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: How should I store a GUID in Oracle? I am coming from the SQL server world where we had uniqueidentifier. Is there an equivalent in oracle? This column will be frequently queried so performance is the key. I am generating the GUID in .Net and will be passing it to Oracle. For a couple reasons it cannot be generated by oracle so I cannot use sequence. A: As others have stated, there is a performance hit using GUIDs compared to numeric sequences. That said, there is a function named "SYS_GUID()" available since Oracle 8i that provides the raw equivalent: SQL> SELECT SYS_GUID() FROM DUAL; SYS_GUID() -------------------------------- 248AACE7F7DE424E8B9E1F31A9F101D5 A function could be created to return a formatted GUID: CREATE OR REPLACE FUNCTION GET_FORMATTED_GUID RETURN VARCHAR2 IS guid VARCHAR2(38) ; BEGIN SELECT SYS_GUID() INTO guid FROM DUAL ; guid := '{' || SUBSTR(guid, 1, 8) || '-' || SUBSTR(guid, 9, 4) || '-' || SUBSTR(guid, 13, 4) || '-' || SUBSTR(guid, 17, 4) || '-' || SUBSTR(guid, 21) || '}' ; RETURN guid ; END GET_FORMATTED_GUID ; / Thus returning an interchangeable string: SQL> SELECT GET_FORMATTED_GUID() FROM DUAL ; GET_FORMATTED_GUID() -------------------------------------- {15417950-9197-4ADD-BD49-BA043F262180} A note of caution should be made that some Oracle platforms return similar but still unique values of GUIDs as noted by Steven Feuerstein. Update 11/3/2020: With 10g, Oracle added support for regular expression functions which means the concatenation can be simplified using the REGEXP_REPLACE() function. REGEXP_REPLACE( SYS_GUID(), '([0-9A-F]{8})([0-9A-F]{4})([0-9A-F]{4})([0-9A-F]{4})([0-9A-F]{12})', '{\1-\2-\3-\4-\5}' ) The expression breaks out the string value returned by SYS_GUID() into 5 groups of hexadecimal values and rebuilds it, inserting a "-" between each group. A: CREATE table test (testguid RAW(16) default SYS_GUID() ) This blog studied the relative performance. A: If I understand the question properly, you want to generate a unique id when you insert a row in the db. You could use a sequence to do this. link here Once you have created your sequence you can use it like this: INSERT INTO mytable (col1, col2) VALUES (myseq.NEXTVAL, 'some other data'); A: RAW(16) is apparently the preferred equivalent for the uniqueidentifier MS SQL type. A: GUIDs are not as used in Oracle as in MSSQL, we tend to have a NUMBER field (not null & primary key) , a sequence, and a trigger on insert to populate it (for every table). A: There is no uniqueidentifier in Oracle. You can implement one yourself by using RAW (kind of a pain) or CHAR. Performance on queries that JOIN on a CHAR field will suffer (maybe as much as 40%) in comparison with using an integer. If you're doing distributed/replicated databases, the performance hit is worth it. Otherwise, just use an integer. A: The general practice using Oracle is to create an artificial key. This is a column defined as a number. It is populated via a sequence. It is indexed/constrained via a primary key definition.
{ "language": "en", "url": "https://stackoverflow.com/questions/153815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "59" }
Q: How can I apply mathematical function to MySQL query? I've got the following query to determine how many votes a story has received: SELECT s_id, s_title, s_time, (s_time-now()) AS s_timediff, ( (SELECT COUNT(*) FROM s_ups WHERE stories.q_id=s_ups.s_id) - (SELECT COUNT(*) FROM s_downs WHERE stories.s_id=s_downs.s_id) ) AS votes FROM stories I'd like to apply the following mathematical function to it for upcoming stories (I think it's what reddit uses) - http://redflavor.com/reddit.cf.algorithm.png I can perform the function on the application side (which I'm doing now), but I can't sort it by the ranking which the function provides. Any advise? A: Try this: SELECT s_id, s_title, log10(Z) + (Y * s_timediff)/45000 AS redditfunction FROM ( SELECT stories.s_id, stories.s_title, stories.s_time, stories.s_time - now() AS s_timediff, count(s_ups.s_id) - count(s_downs.s_id) as X, if(X>0,1,if(x<0,-1,0)) as Y, if(abs(x)>=1,abs(x),1) as Z FROM stories LEFT JOIN s_ups ON stories.q_id=s_ups.s_id LEFT JOIN s_downs ON stories.s_id=s_downs.s_id GROUP BY stories.s_id ) as derived_table1 You might need to check this statement if it works with your datasets. A: y and z are the tricky ones. You want a specific return based on x's value. That sounds like a good reason to make a function. http://dev.mysql.com/doc/refman/5.0/en/if-statement.html You should make 1 function for y and one for z. pass in x, and expect a number back out. DELIMINATOR // CREATE FUNCTION y_element(x INT) RETURNS INT BEGIN DECLARE y INT; IF x > 0 SET y = 1; ELSEIF x = 0 SET y = 0; ELSEIF x < 0 SET y = -1; END IF; RETURN y; END //; DELIMINATOR; There is y. I did it by hand without checking so you may have to fix a few typo's. Do z the same way, and then you have all of the values for your final function.
{ "language": "en", "url": "https://stackoverflow.com/questions/153825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: What do you use for validation against XML schema? When I want to validate my XML docuemnts against a schema in my server-side Java, I use the built-in JRE Xerces implementation and javax.xml.validation.Schema. It works fine, but when validation fails, Xerces gives error messages that are very close to useless, for example: cvc-minLength-valid: Value '' with length = '0' is not facet-valid with respect to minLength '1' for type 'PopulatedStringType' These can take an age to diagnose and track down to the particular part of the XML document that fails validation, and all because of a poor error message. So my question is, do you use an alternative means of validating XML against Schema, that gives a more useful output on validation failure? Please not that this is server-side Java, so please don't say "use XML Spy" or similar. A: In your handler for the validation, you should receive a SAXParseException with that message, as well as the column number and the line number in the XML file. Isnt't it the case? A: We use Oracle's XDK (XML Development Kit) which includes xmlparserv2.jar with a validating parser and XSLT 2.0. It uses the JAXB API so you should only have to add it to your classpath and change your imports. It throws errors that aren't perfect, but I would say more easily understood than your example. A: xmlstarlet(xmlstar.sourceforge.net/) is a command line toolkit. you could run it using Runtime.exec() for a given xml (as long as the xml is in a file). A: We use Castor. Castor is an Open Source data binding framework for Java[tm]. It's the shortest path between Java objects, XML documents and relational tables. Castor provides Java-to-XML binding, Java-to-SQL persistence, and more. A: If you are having trouble interpreting the Xerces errors and would like something that helps to highlight where in your document you have violated the rules, check out some of the XML authoring tools such as oXygen. (source: oxygenxml.com) Once you associate the schema with your instance XML document the editor will highlight the offending area of the document and provide you with a description of the violation. Plus, you can use different engines to perform the validation: oXygen has built-in support for: Xerces, LIBXML, XSV, Saxon SA, MSXML4.0, MSXML .NET and SQC.
{ "language": "en", "url": "https://stackoverflow.com/questions/153835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Saving MFC Model as SQLite database I am playing with a CAD application using MFC. I was thinking it would be nice to save the document (model) as an SQLite database. Advantages: * *I avoid file format changes (SQLite takes care of that) *Free query engine *Undo stack is simplified (table name, column name, new value and so on...) Opinions? A: This is a fine idea. Sqlite is very pleasant to work with! But remember the old truism (I can't get an authoritative answer from Google about where it originally is from) that storing your data in a relational database is like parking your car by driving it into the garage, disassembling it, and putting each piece into a labeled cabinet. Geometric data, consisting of points and lines and segments that refer to each other by name, is a good candidate for storing in database tables. But when you start having composite objects, with a heirarchy of subcomponents, it might require a lot less code just to use serialization and store/load the model with a single call. So that would be a fine idea too. But serialization in MFC is not nearly as much of a win as it is in, say, C#, so on balance I would go ahead and use SQL. A: This is a great idea but before you start I have a few recommendations: * *Be careful that each database is uniquely identifiable in some way besides file name such as having a table that describes the file within the database. *Take a look at some of the MFC based examples and wrappers already available before creating your own. The ones I have seen had borrowed on each to create a better result. Google: MFC SQLite Wrapper. *Using SQLite database is also useful for maintaining state. Think ahead about how you would manage keeping in mind what features are included and are missing in SQLite. *You can also think now about how you may extend your application to the web by making sure your database table structure is easily exportable to other SQL database systems- as well as easy enough to extend to a backup system.
{ "language": "en", "url": "https://stackoverflow.com/questions/153838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WCF is not binding to the correct IP address We have a WCF service deployed on a Windows 2003 server that is exhibiting some problems. The configuration is using wsHttpBinding and we are specifying the IP address. The services is being hosted by a Windows Service. When we start the service up, most of the time it grabs the wrong IP address. A few times it bound to the correct address only to drop that binding and go to the other address (there are 2) bound to the NIC after processing for a short while. It is currently using port 80 (we've configured IIS to bind to only 1 address via httpcfg) although we have tried it using different ports with the same results. When the Windows Service starts hosting the WCF service, the properties show that it is being bound to the correct address; however, tcpview shows that it is indeed listening on the incorrect address. Here is the portion of the config that sets up tehe baseAddress. The one that gets bound to ends up being .4 instead of .9 <services> <service name="Service.MyService" behaviorConfiguration="serviceBehavior"> <host> <baseAddresses> <add baseAddress="http://xx.xx.xx.9:80/" /> </baseAddresses> </host> <endpoint address="MyService" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IMyService" contract="Service.IMyService" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> * *Is there some other configuration that needs to be set? *Is there a tool that can help track down where this is getting bound to the wrong address? A: Your WCF configuration looks OK to me. This might be an issue with the binding order of your NIC cards. Make sure that the NIC with correct address is first. Here is an article that discuss how to set and view nic binding orders: http://theregime.wordpress.com/2008/03/04/how-to-setview-the-nic-bind-order-in-windows/ A: The issue seems to be ISS related. Here is the description about the error your getting from http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/ddf72ae0-aa1e-48c9-88d1-10bae1e87e4f.mspx?mfr=true This error is logged to the event log when HTTP.sys parses the IP inclusion list and finds that all of the entries in the list are invalid. If this happens, as the description in Table 11.15 notes, HTTP.sys listens to all IP addresses. You can also check the following thread which talks about a similiar issue http://www.webhostingtalk.com/showthread.php?t=534174 Hope this helps. A: We had the same issue and this feature helped us to solve our problem : http://msdn.microsoft.com/en-us/library/system.servicemodel.hostnamecomparisonmode.aspx Hope this help. A: More information: I removed the xx.xx.xx.4 IP address from the NIC altogether and turned off IIS. Now when I try to start the service it fails and I find this in the System event log. Description: Unable to bind to the underlying transport for xx.xx.xx.4:80. The IP Listen-Only list may contain a reference to an interface which may not exist on this machine. The data field contains the error number. My configuration file still has the xx.xx.xx.9 baseAddress setting. A: One more piece of informatoin. If we change the binding to use NetTcp instead of WsHttp it binds to the correct address on port 80. Changing it back to WsHttp it goes back to the incorrect IP address. A: BaseAddress is ignored. You need to set a host header under IIS.
{ "language": "en", "url": "https://stackoverflow.com/questions/153846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: [] brackets in sql statements What do the brackets do in a sql statement? For example, in the statement: insert into table1 ([columnname1], columnname2) values (val1, val2) Also, what does it do if the table name is in brackets? A: They are meant to escape reserved keywords or invalid column identifiers. CREATE TABLE test ( [select] varchar(15) ) INSERT INTO test VALUES('abc') SELECT [select] FROM test A: The [] marks the delimitation of a identifier, so if you have a column whose name contains spaces like Order Qty you need to enclose it with [] like: select [Order qty] from [Client sales] They are also to escape reserved keywords used as identifiers A: They allow you to use keywords (such as date) in the name of the column, table, etc... Since this is a bad practice to begin with, they are generally not included. The only place you should see them being used is by people starting out with sql queries that don't know any better. Other than that they just clutter up your query. A: Anything inside the brackets is considered a single identifier (e.g. [test machine]. This can be used to enclose names with spaces or to escape reserve words (e.g. [order], [select], [group]). A: This is Microsoft SQL Server nonstandard syntax for "delimited identifiers." SQL supports delimiters for identifiers to allow table names, column names, or other metadata objects to contain the following: * *SQL reserved words: "Order" *Words containing spaces: "Order qty" *Words containing punctuation: "Order-qty" *Words containing international characters *Column names that are case-sensitive: "Order" vs. "order" Microsoft SQL Server uses the square brackets, but this is not the syntax standard SQL uses for delimited identifiers. Standardly, double-quotes should be used for delimiters. In Microsoft SQL Server, you can enable a mode to use standard double-quotes for delimiters as follows: SET QUOTED_IDENTIFIER ON; A: if you use any column name which is same as any reserved keyword in sql, in that case you can put the column name in square bracket to distinguish between your custom column name and existing reserved keyword. A: When having table names or filenames with spaces or dashes (-) etc... you can receive "Systax error in FROM clause". Use [] brackets to solve this. See: https://msdn.microsoft.com/en-us/library/ms175874.aspx A: They are simply delimiters that allow you to put special characters (like spaces) in the column or table name e.g. insert into [Table One] ([Column Name 1], columnname2) values (val1, val2)
{ "language": "en", "url": "https://stackoverflow.com/questions/153861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: How should I split large and bloated classes into smaller ones? I have a large 'Manager' class which I think is doing too much but I am unsure on how to divide it into more logical units. Generally speaking the class basically consists of the following methods: class FooBarManager { GetFooEntities(); AddFooEntity(..); UpdateFooEntity(..); SubmitFooEntity(..); GetFooTypes(); GetBarEntities(); } The Manager class is part of my business logic and constains an instance of another "Manager" class on the data access level which contains all CRUD operations for all entities. I have different entities coming from the data access layer and therefore have a converter in place outside of the Manager class to convert data entities to business entities. The reason for the manager classes was that I wanted to be able to mock out each of the "Manager" classes when I do unittesting. Each of the manager classes is now over 1000 loc and contain 40-50 methods each. I consider them to be quite bloated and find it awkward to put all of the data access logic into a single class. What should I be doing differently? How would I go about splitting them and is there any specific design-pattern should I be using? A: You really shouldn't put all data access into one class unless it's generic. I would start by splitting out your data access classes into one manager per object or related groups of objects, i.e. CompanyManager, CustomerManager, etc. If your need to access the manager through one "god class" you could have an instance of each manager available in your one true Manager class. A: Your FooBarManager looks a lot like a God Object anti pattern. In a situation like yours, consider delving into Patterns of Enterprise Application Architecture, by Martin Fowler. At first sight, it looks like you want to create a Data Mapper. But consider alternatives like Active Records, that might be enough for your needs. Also consider using an ORM library/software for your platform. Building your own without a good reason will only confront you to the many problems that have already been more or less solved by these tools. A: / FooManager Manager (derive from Manager) \ BarManager Should be self-explaining A: I'd suggest using composition. Think about the functions the manager is doing. Split them along the lines of single responsibility. It appears most of FooBarManager is a collection of Foo and bar entities. So, at a minimum, break out the collection logic from FooBarManager public class EntityCollection<T> : IList<T> where T : BaseEntity { /* all management logic here */} public class FooCollection : EntityCollection<foo> {} public class BarCollection : EntityCollection<bar> {} public class FooBarManager { public FooCollection { /*...*/ } public BarCollection { /*...*/ } public FooBarManager() : this(new FooCollection(), new BarCollection()){} public FooBarManager(FooCollection fc, BarCollection bc) { /*...*/ } }
{ "language": "en", "url": "https://stackoverflow.com/questions/153863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is a Pointer? See: Understanding Pointers In many C flavoured languages, and some older languages like Fortran, one can use Pointers. As someone who has only really programmed in basic, javascript, and actionscript, can you explain to me what a Pointer is, and what it is most useful for? Thanks! A: This wikipedia article will give you detailed information on what a pointer is: In computer science, a pointer is a programming language data type whose value refers directly to (or "points to") another value stored elsewhere in the computer memory using its address. Obtaining or requesting the value to which a pointer refers is called dereferencing the pointer. A pointer is a simple implementation of the general reference data type (although it is quite different from the facility referred to as a reference in C++). Pointers to data improve performance for repetitive operations such as traversing string and tree structures, and pointers to functions are used for binding methods in Object-oriented programming and run-time linking to dynamic link libraries (DLLs). A: A pointer is a variable that contains the address of another variable. This allows you to reference another variable indirectly. For example, in C: // x is an integer variable int x = 5; // xpointer is a variable that references (points to) integer variables int *xpointer; // We store the address (& operator) of x into xpointer. xpointer = &x; // We use the dereferencing operator (*) to say that we want to work with // the variable that xpointer references *xpointer = 7; if (5 == x) { // Not true } else if (7 == x) { // True since we used xpointer to modify x } A: Pointers are not as hard as they sound. As others have said already, they are variables that hold the address of some other variable. Suppose I wanted to give you directions to my house. I wouldn't give you a picture of my house, or a scale model of my house; I'd just give you the address. You could infer whatever you needed from that. In the same way, a lot of languages make the distinction between passing by value and passing by reference. Essentially it means will i pass an entire object around every time I need to refer to it? Or, will I just give out it's address so that others can infer what they need? Most modern languages hide this complexity by figuring out when pointers are useful and optimizing that for you. However, if you know what you're doing, manual pointer management can still be useful in some situations. A: There have been several discussions in SO about this topic. You can find information about the topic with the links below. There are several other relevant SO discussions on the subject, but I think that these were the most relevant. Search for 'pointers [C++]' in the search window (or 'pointers [c]') and you will get more information as well. In C++ I Cannot Grasp Pointers and Classes What is the difference between modern ‘References’ and traditional ‘Pointers’? A: As someone already mention, a pointer is a variable that contains the address of another variable. It's mostly used when creating new objects (in run-time).
{ "language": "en", "url": "https://stackoverflow.com/questions/153874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: What is the difference between ManualResetEvent and AutoResetEvent in .NET? I have read the documentation on this and I think I understand. An AutoResetEvent resets when the code passes through event.WaitOne(), but a ManualResetEvent does not. Is this correct? A: Yes. It's like the difference between a tollbooth and a door. The ManualResetEvent is the door, which needs to be closed (reset) manually. The AutoResetEvent is a tollbooth, allowing one car to go by and automatically closing before the next one can get through. A: AutoResetEvent maintains a boolean variable in memory. If the boolean variable is false then it blocks the thread and if the boolean variable is true it unblocks the thread. When we instantiate an AutoResetEvent object, we pass the default value of boolean value in the constructor. Below is the syntax of instantiate an AutoResetEvent object. AutoResetEvent autoResetEvent = new AutoResetEvent(false); WaitOne method This method blocks the current thread and wait for the signal by other thread. WaitOne method puts the current thread into a Sleep thread state. WaitOne method returns true if it receives the signal else returns false. autoResetEvent.WaitOne(); Second overload of WaitOne method wait for the specified number of seconds. If it does not get any signal thread continues its work. static void ThreadMethod() { while(!autoResetEvent.WaitOne(TimeSpan.FromSeconds(2))) { Console.WriteLine("Continue"); Thread.Sleep(TimeSpan.FromSeconds(1)); } Console.WriteLine("Thread got signal"); } We called WaitOne method by passing the 2 seconds as arguments. In the while loop, it wait for the signal for 2 seconds then it continues its work. When the thread got the signal WaitOne returns true and exits the loop and print the "Thread got signal". Set method AutoResetEvent Set method sent the signal to the waiting thread to proceed its work. Below is the syntax of calling Set method. autoResetEvent.Set(); ManualResetEvent maintains a boolean variable in memory. When the boolean variable is false then it blocks all threads and when the boolean variable is true it unblocks all threads. When we instantiate a ManualResetEvent, we initialize it with default boolean value. ManualResetEvent manualResetEvent = new ManualResetEvent(false); In the above code, we initialize the ManualResetEvent with false value, that means all the threads which calls the WaitOne method will block until some thread calls the Set() method. If we initialize ManualResetEvent with true value, all the threads which calls the WaitOne method will not block and free to proceed further. WaitOne Method This method blocks the current thread and wait for the signal by other thread. It returns true if its receives a signal else returns false. Below is the syntax of calling WaitOne method. manualResetEvent.WaitOne(); In the second overload of WaitOne method, we can specify the time interval till the current thread wait for the signal. If within time internal, it does not receives a signal it returns false and goes into the next line of method. Below is the syntax of calling WaitOne method with time interval. bool isSignalled = manualResetEvent.WaitOne(TimeSpan.FromSeconds(5)); We have specify 5 seconds into the WaitOne method. If the manualResetEvent object does not receives a signal between 5 seconds, it set the isSignalled variable to false. Set Method This method is used for sending the signal to all waiting threads. Set() Method set the ManualResetEvent object boolean variable to true. All the waiting threads are unblocked and proceed further. Below is the syntax of calling Set() method. manualResetEvent.Set(); Reset Method Once we call the Set() method on the ManualResetEvent object, its boolean remains true. To reset the value we can use Reset() method. Reset method change the boolean value to false. Below is the syntax of calling Reset method. manualResetEvent.Reset(); We must immediately call Reset method after calling Set method if we want to send signal to threads multiple times. A: Yes. This is absolutely correct. You could see ManualResetEvent as a way to indicate state. Something is on (Set) or off (Reset). An occurrence with some duration. Any thread waiting for that state to happen can proceed. An AutoResetEvent is more comparable to a signal. A one shot indication that something has happened. An occurrence without any duration. Typically but not necessarily the "something" that has happened is small and needs to be handled by a single thread - hence the automatic reset after a single thread have consumed the event. A: Yes, thats right. You can get an idea by the usage of these two. If you need to tell that you are finished with some work and other (threads) waiting for this can now proceed, you should use ManualResetEvent. If you need to have mutual exclusive access to any resource, you should use AutoResetEvent. A: The short answer is yes. The most important difference is that an AutoResetEvent will only allow one single waiting thread to continue. A ManualResetEvent on the other hand will keep allowing threads, several at the same time even, to continue until you tell it to stop (Reset it). A: Taken from C# 3.0 Nutshell book, by Joseph Albahari Threading in C# - Free E-Book A ManualResetEvent is a variation on AutoResetEvent. It differs in that it doesn't automatically reset after a thread is let through on a WaitOne call, and so functions like a gate: calling Set opens the gate, allowing any number of threads that WaitOne at the gate through; calling Reset closes the gate, causing, potentially, a queue of waiters to accumulate until its next opened. One could simulate this functionality with a boolean "gateOpen" field (declared with the volatile keyword) in combination with "spin-sleeping" – repeatedly checking the flag, and then sleeping for a short period of time. ManualResetEvents are sometimes used to signal that a particular operation is complete, or that a thread's completed initialization and is ready to perform work. A: I created simple examples to clarify understanding of ManualResetEvent vs AutoResetEvent. AutoResetEvent: lets assume you have 3 workers thread. If any of those threads will call WaitOne() all other 2 threads will stop execution and wait for signal. I am assuming they are using WaitOne(). It is like; if I do not work, nobody works. In first example you can see that autoReset.Set(); Thread.Sleep(1000); autoReset.Set(); When you call Set() all threads will work and wait for signal. After 1 second I am sending second signal and they execute and wait (WaitOne()). Think about these guys are soccer team players and if one player says I will wait until manager calls me, and others will wait until manager tells them to continue (Set()) public class AutoResetEventSample { private AutoResetEvent autoReset = new AutoResetEvent(false); public void RunAll() { new Thread(Worker1).Start(); new Thread(Worker2).Start(); new Thread(Worker3).Start(); autoReset.Set(); Thread.Sleep(1000); autoReset.Set(); Console.WriteLine("Main thread reached to end."); } public void Worker1() { Console.WriteLine("Entered in worker 1"); for (int i = 0; i < 5; i++) { Console.WriteLine("Worker1 is running {0}", i); Thread.Sleep(2000); autoReset.WaitOne(); } } public void Worker2() { Console.WriteLine("Entered in worker 2"); for (int i = 0; i < 5; i++) { Console.WriteLine("Worker2 is running {0}", i); Thread.Sleep(2000); autoReset.WaitOne(); } } public void Worker3() { Console.WriteLine("Entered in worker 3"); for (int i = 0; i < 5; i++) { Console.WriteLine("Worker3 is running {0}", i); Thread.Sleep(2000); autoReset.WaitOne(); } } } In this example you can clearly see that when you first hit Set() it will let all threads go, then after 1 second it signals all threads to wait! As soon as you set them again regardless they are calling WaitOne() inside, they will keep running because you have to manually call Reset() to stop them all. manualReset.Set(); Thread.Sleep(1000); manualReset.Reset(); Console.WriteLine("Press to release all threads."); Console.ReadLine(); manualReset.Set(); It is more about Referee/Players relationship there regardless of any of the player is injured and wait for playing others will continue to work. If Referee says wait (Reset()) then all players will wait until next signal. public class ManualResetEventSample { private ManualResetEvent manualReset = new ManualResetEvent(false); public void RunAll() { new Thread(Worker1).Start(); new Thread(Worker2).Start(); new Thread(Worker3).Start(); manualReset.Set(); Thread.Sleep(1000); manualReset.Reset(); Console.WriteLine("Press to release all threads."); Console.ReadLine(); manualReset.Set(); Console.WriteLine("Main thread reached to end."); } public void Worker1() { Console.WriteLine("Entered in worker 1"); for (int i = 0; i < 5; i++) { Console.WriteLine("Worker1 is running {0}", i); Thread.Sleep(2000); manualReset.WaitOne(); } } public void Worker2() { Console.WriteLine("Entered in worker 2"); for (int i = 0; i < 5; i++) { Console.WriteLine("Worker2 is running {0}", i); Thread.Sleep(2000); manualReset.WaitOne(); } } public void Worker3() { Console.WriteLine("Entered in worker 3"); for (int i = 0; i < 5; i++) { Console.WriteLine("Worker3 is running {0}", i); Thread.Sleep(2000); manualReset.WaitOne(); } } } A: If you want to understand AutoResetEvent and ManualResetEvent you need to understand not threading but interrupts! .NET wants to conjure up low-level programming the most distant possible. An interrupts is something used in low-level programming which equals to a signal that from low became high (or viceversa). When this happens the program interrupt its normal execution and move the execution pointer to the function that handles this event. The first thing to do when an interrupt happend is to reset its state, becosa the hardware works in this way: * *a pin is connected to a signal and the hardware listen for it to change (the signal could have only two states). *if the signal changes means that something happened and the hardware put a memory variable to the state happened (and it remain like this even if the signal change again). *the program notice that variable change states and move the execution to a handling function. *here the first thing to do, to be able to listen again this interrupt, is to reset this memory variable to the state not-happened. This is the difference between ManualResetEvent and AutoResetEvent. If a ManualResetEvent happen and I do not reset it, the next time it happens I will not be able to listen it. A: autoResetEvent.WaitOne() is similar to try { manualResetEvent.WaitOne(); } finally { manualResetEvent.Reset(); } as an atomic operation A: Just imagine that the AutoResetEvent executes WaitOne() and Reset() as a single atomic operation. The AutoResetEvent also guarantees to only release one waiting thread. A: OK, normally it does not a good practice to add 2 answers in same thread, but I did not want to edit/delete my previous answer, since it can help on another manner. Now, I created, much more comprehensive, and easy to understand, run-to-learn console app snippet below. Just run the examples on two different consoles, and observe behaviour. You will get much more clear idea there what is happening behind the scenes. Manual Reset Event using System; using System.Threading; namespace ConsoleApplicationDotNetBasics.ThreadingExamples { public class ManualResetEventSample { private readonly ManualResetEvent _manualReset = new ManualResetEvent(false); public void RunAll() { new Thread(Worker1).Start(); new Thread(Worker2).Start(); new Thread(Worker3).Start(); Console.WriteLine("All Threads Scheduled to RUN!. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId); Console.WriteLine("Main Thread is waiting for 15 seconds, observe 3 thread behaviour. All threads run once and stopped. Why? Because they call WaitOne() internally. They will wait until signals arrive, down below."); Thread.Sleep(15000); Console.WriteLine("1- Main will call ManualResetEvent.Set() in 5 seconds, watch out!"); Thread.Sleep(5000); _manualReset.Set(); Thread.Sleep(2000); Console.WriteLine("2- Main will call ManualResetEvent.Set() in 5 seconds, watch out!"); Thread.Sleep(5000); _manualReset.Set(); Thread.Sleep(2000); Console.WriteLine("3- Main will call ManualResetEvent.Set() in 5 seconds, watch out!"); Thread.Sleep(5000); _manualReset.Set(); Thread.Sleep(2000); Console.WriteLine("4- Main will call ManualResetEvent.Reset() in 5 seconds, watch out!"); Thread.Sleep(5000); _manualReset.Reset(); Thread.Sleep(2000); Console.WriteLine("It ran one more time. Why? Even Reset Sets the state of the event to nonsignaled (false), causing threads to block, this will initial the state, and threads will run again until they WaitOne()."); Thread.Sleep(10000); Console.WriteLine(); Console.WriteLine("This will go so on. Everytime you call Set(), ManualResetEvent will let ALL threads to run. So if you want synchronization between them, consider using AutoReset event, or simply user TPL (Task Parallel Library)."); Thread.Sleep(5000); Console.WriteLine("Main thread reached to end! ThreadId: {0}", Thread.CurrentThread.ManagedThreadId); } public void Worker1() { for (int i = 1; i <= 10; i++) { Console.WriteLine("Worker1 is running {0}/10. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId); Thread.Sleep(5000); // this gets blocked until _autoReset gets signal _manualReset.WaitOne(); } Console.WriteLine("Worker1 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId); } public void Worker2() { for (int i = 1; i <= 10; i++) { Console.WriteLine("Worker2 is running {0}/10. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId); Thread.Sleep(5000); // this gets blocked until _autoReset gets signal _manualReset.WaitOne(); } Console.WriteLine("Worker2 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId); } public void Worker3() { for (int i = 1; i <= 10; i++) { Console.WriteLine("Worker3 is running {0}/10. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId); Thread.Sleep(5000); // this gets blocked until _autoReset gets signal _manualReset.WaitOne(); } Console.WriteLine("Worker3 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId); } } } Auto Reset Event using System; using System.Threading; namespace ConsoleApplicationDotNetBasics.ThreadingExamples { public class AutoResetEventSample { private readonly AutoResetEvent _autoReset = new AutoResetEvent(false); public void RunAll() { new Thread(Worker1).Start(); new Thread(Worker2).Start(); new Thread(Worker3).Start(); Console.WriteLine("All Threads Scheduled to RUN!. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId); Console.WriteLine("Main Thread is waiting for 15 seconds, observe 3 thread behaviour. All threads run once and stopped. Why? Because they call WaitOne() internally. They will wait until signals arrive, down below."); Thread.Sleep(15000); Console.WriteLine("1- Main will call AutoResetEvent.Set() in 5 seconds, watch out!"); Thread.Sleep(5000); _autoReset.Set(); Thread.Sleep(2000); Console.WriteLine("2- Main will call AutoResetEvent.Set() in 5 seconds, watch out!"); Thread.Sleep(5000); _autoReset.Set(); Thread.Sleep(2000); Console.WriteLine("3- Main will call AutoResetEvent.Set() in 5 seconds, watch out!"); Thread.Sleep(5000); _autoReset.Set(); Thread.Sleep(2000); Console.WriteLine("4- Main will call AutoResetEvent.Reset() in 5 seconds, watch out!"); Thread.Sleep(5000); _autoReset.Reset(); Thread.Sleep(2000); Console.WriteLine("Nothing happened. Why? Becasuse Reset Sets the state of the event to nonsignaled, causing threads to block. Since they are already blocked, it will not affect anything."); Thread.Sleep(10000); Console.WriteLine("This will go so on. Everytime you call Set(), AutoResetEvent will let another thread to run. It will make it automatically, so you do not need to worry about thread running order, unless you want it manually!"); Thread.Sleep(5000); Console.WriteLine("Main thread reached to end! ThreadId: {0}", Thread.CurrentThread.ManagedThreadId); } public void Worker1() { for (int i = 1; i <= 5; i++) { Console.WriteLine("Worker1 is running {0}/5. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId); Thread.Sleep(500); // this gets blocked until _autoReset gets signal _autoReset.WaitOne(); } Console.WriteLine("Worker1 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId); } public void Worker2() { for (int i = 1; i <= 5; i++) { Console.WriteLine("Worker2 is running {0}/5. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId); Thread.Sleep(500); // this gets blocked until _autoReset gets signal _autoReset.WaitOne(); } Console.WriteLine("Worker2 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId); } public void Worker3() { for (int i = 1; i <= 5; i++) { Console.WriteLine("Worker3 is running {0}/5. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId); Thread.Sleep(500); // this gets blocked until _autoReset gets signal _autoReset.WaitOne(); } Console.WriteLine("Worker3 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/153877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "575" }
Q: How do I add a multiline REG_SZ string to the registry from the command line? As part of a build setup on a windows machine I need to add a registry entry and I'd like to do it from a simple batch file. The entry is for a third party app so the format is fixed. The entry takes the form of a REG_SZ string but needs to contain newlines ie. 0xOA characters as separators. I've hit a few problems. First attempt used regedit to load a generated .reg file. This failed as it did not seem to like either either long strings or strings with newlines. I discovered that export works fine import fails. I was able to test export as the third party app adds similar entries directly through the win32 api. Second attempt used the command REG ADD but I can't find anyway to add the newline characters everything I try just ends up with a literal string being added. A: You can import multiline REG_SZ strings containing carriage return (CR) and linefeed (LF) end-of-line (EOL) breaks into the registry using .reg files as long as you do not mind translating the text as UTF-16LE hexadecimal encoded data. To import a REG_SZ with this text: 1st Line 2nd Line You might create a file called MULTILINETEXT.REG that contains this: Windows Registry Editor Version 5.00 [HKEY_CURRENT_USER\Environment] "MULTILINETEXT"=hex(1):31,00,73,00,74,00,20,00,4c,00,69,00,6e,00,65,00,0d,00,0a,00,\ 32,00,6e,00,64,00,20,00,4c,00,69,00,6e,00,65,00,0d,00,0a,00,\ 00,00 To encode ASCII into UTF-16LE, simply add a null byte following each ASCII code value. REG_SZ values must terminate with a null character (,00,00) in UTF-16LE notation. Import the registry change in the batch file REG.EXE IMPORT MULTILINETEXT.REG. The example uses the Environment key because it is convenient, not because it is particularly useful to add such data to environment variables. One may use RegEdit to verify that the imported REG_SZ data contains the CRLF characters. A: If you're not constrained to a scripting language, you can do it in C# with Registry.CurrentUser.OpenSubKey(@"software\classes\something", true).SetValue("some key", "sometext\nothertext", RegistryValueKind.String); A: You could create a VBScript(.vbs) file and just call it from a batch file, assuming you're doing other things in the batch other than this registry change. In vbscript you would be looking at something like: set WSHShell = CreateObject("WScript.Shell") WSHShell.RegWrite "HKEY_LOCAL_MACHINE\SOMEKEY", "value", "type" You should be able to find the possible type values using Google. A: Another approach -- that is much easier to read and maintain -- is to use a PowerShell script. Run PowerShell as Admin. # SetLegalNotice_AsAdmin.ps1 # Define multi-line legal notice registry entry Push-Location Set-Location -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\ $contentCaption="Legal Notice" $contentNotice= @" This is a very long string that runs to many lines. You are accessing a U.S. Government (USG) Information System (IS) that is provided for USG-authorized use only. By using this IS (which includes any device attached to this IS), you consent to the following conditions: -The USG routinely intercepts and monitors communications on this IS for purposes including, but not limited to, penetration testing, COMSEC monitoring, network operations and defense, personnel misconduct (PM), law enforcement (LE), and counterintelligence (CI) investigations. etc... "@ # Caption New-ItemProperty -Path . -Name legalnoticetext -PropertyType MultiString -Value $contentCaption -Force # Notice New-ItemProperty -Path . -Name legalnoticetext -PropertyType MultiString -Value $contentNotice -Force Pop-Location
{ "language": "en", "url": "https://stackoverflow.com/questions/153879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: When would you NOT want to use memcached in a Ruby on Rails app? Assuming a MySQL datastore, when would you NOT want to use memcached in a Ruby on Rails app? A: Memcache is a strong distributed cache, but isn't any faster than local caching for some content. Caching should allow you to avoid bottlenecks, which is usually database requests and network requests. If you can cache your full page locally as HTML because it doesn't change very often (isn't very dynamic), then your web server can serve this up much faster than querying memcache. This is especially true if your memcache server, like most memcached servers, are on seperate machines. Flip side of this is that I will sometimes use memcache locally instead of other caching options because I know someday I will need to move it off to its own server. A: The main benefit of memcached is that it is a distributed cache. That means you can generate once, and serve from cache across many servers (this is why memcached was created). All the previous answers seem to ignore this - it makes me wonder if they have ever had to build a highly scalable app (which is exactly what memcached is for) Danga Interactive developed memcached to enhance the speed of LiveJournal.com, a site which was already doing 20 million+ dynamic page views per day for 1 million users with a bunch of webservers and a bunch of database servers. memcached dropped the database load to almost nothing, yielding faster page load times for users, better resource utilization, and faster access to the databases on a memcache miss. (My bolding) So the answer is: if your application is only ever likely to be deployed on a single server. If you are ever likely to use more than one server (for scalability and redundancy) memcached is (nearly) always a good idea. A: Don't use memcached if your application is able to handle all requests quickly. Adding memcached is extra mental overhead when it comes to coding your app, so don't do it unless you need it. Scaling's "one swell problem to have". A: When you want to have fine-grained control about things expiring. From my tests, memcached only seems to have a timing resolution of about a second. EG: if you tell something to expire in 1 second, it could stay around for between 1 and just over 2 seconds.
{ "language": "en", "url": "https://stackoverflow.com/questions/153889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Printing leading 0's in C I'm trying to find a good way to print leading 0, such as 01001 for a ZIP Code. While the number would be stored as 1001, what is a good way to do it? I thought of using either case statements or if to figure out how many digits the number is and then convert it to an char array with extra 0's for printing, but I can't help but think there may be a way to do this with the printf format syntax that is eluding me. A: printf("%05d", zipCode); The 0 indicates what you are padding with and the 5 shows the width of the integer number. Example 1: If you use "%02d" (useful for dates) this would only pad zeros for numbers in the ones column. E.g., 06 instead of 6. Example 2: "%03d" would pad 2 zeros for one number in the ones column and pad 1 zero for a number in the tens column. E.g., number 7 padded to 007 and number 17 padded to 017. A: printf allows various formatting options. Example: printf("leading zeros %05d", 123); A: You place a zero before the minimum field width: printf("%05d", zipcode); A: You will save yourself a heap of trouble (long term) if you store a ZIP Code as a character string, which it is, rather than a number, which it is not. A: The correct solution is to store the ZIP Code in the database as a STRING. Despite the fact that it may look like a number, it isn't. It's a code, where each part has meaning. A number is a thing you do arithmetic on. A ZIP Code is not that. A: sprintf(mystring, "%05d", myInt); Here, "05" says "use 5 digits with leading zeros". A: If you are on a *nix machine: man 3 printf This will show a manual page, similar to: 0 The value should be zero padded. For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, the converted value is padded on the left with zeros rather than blanks. If the 0 and - flags both appear, the 0 flag is ignored. If a precision is given with a numeric conversion (d, i, o, u, x, and X), the 0 flag is ignored. For other conversions, the behavior is undefined. Even though the question is for C, this page may be of aid. A: ZIP Code is a highly localised field, and many countries have characters in their postcodes, e.g., UK, Canada. Therefore, in this example, you should use a string / varchar field to store it if at any point you would be shipping or getting users, customers, clients, etc. from other countries. However, in the general case, you should use the recommended answer (printf("%05d", number);). A: There are two ways to output your number with leading zeroes: Using the 0 flag and the width specifier: int zipcode = 123; printf("%05d\n", zipcode); // Outputs 00123 Using the precision specifier: int zipcode = 123; printf("%.5d\n", zipcode); // Outputs 00123 The difference between these is the handling of negative numbers: printf("%05d\n", -123); // Outputs -0123 (pad to 5 characters) printf("%.5d\n", -123); // Outputs -00123 (pad to 5 digits) ZIP Codes are unlikely to be negative, so it should not matter. Note however that ZIP Codes may actually contain letters and dashes, so they should be stored as strings. Including the leading zeroes in the string is straightforward so it solves your problem in a much simpler way. Note that in both examples above, the 5 width or precision values can be specified as an int argument: int width = 5; printf("%0*d\n", width, 123); // Outputs 00123 printf("%.*d\n", width, 123); // Outputs 00123 There is one more trick to know: a precision of 0 causes no output for the value 0: printf("|%0d|%0d|\n", 0, 1); // Outputs |0|1| printf("|%.0d|%.0d|\n", 0, 1); // Outputs ||1| A: More flexible.. Here's an example printing rows of right-justified numbers with fixed widths, and space-padding. //---- Header std::string getFmt ( int wid, long val ) { char buf[64]; sprintf ( buf, "% *ld", wid, val ); return buf; } #define FMT (getFmt(8,x).c_str()) //---- Put to use printf ( " COUNT USED FREE\n" ); printf ( "A: %s %s %s\n", FMT(C[0]), FMT(U[0]), FMT(F[0]) ); printf ( "B: %s %s %s\n", FMT(C[1]), FMT(U[1]), FMT(F[1]) ); printf ( "C: %s %s %s\n", FMT(C[2]), FMT(U[2]), FMT(F[2]) ); //-------- Output COUNT USED FREE A: 354 148523 3283 B: 54138259 12392759 200391 C: 91239 3281 61423 The function and macro are designed so the printfs are more readable. A: If you need to store the ZIP Code in a character array, zipcode[], you can use this: snprintf(zipcode, 6, "%05.5d", atoi(zipcode));
{ "language": "en", "url": "https://stackoverflow.com/questions/153890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "401" }
Q: Why is my JavaScript function sometimes "not defined"? I call my JavaScript function. Why do I sometimes get the error 'myFunction is not defined' when it is defined? For example. I'll occasionally get 'copyArray is not defined' even in this example: function copyArray( pa ) { var la = []; for (var i=0; i < pa.length; i++) la.push( pa[i] ); return la; } Function.prototype.bind = function( po ) { var __method = this; var __args = []; // Sometimes errors -- in practice I inline the function as a workaround. __args = copyArray( arguments ); return function() { /* bind logic omitted for brevity */ } } As you can see, copyArray is defined right there, so this can't be about the order in which script files load. I've been getting this in situations that are harder to work around, where the calling function is located in another file that should be loaded after the called function. But this was the simplest case I could present, and appears to be the same problem. It doesn't happen 100% of the time, so I do suspect some kind of load-timing-related problem. But I have no idea what. @Hojou: That's part of the problem. The function in which I'm now getting this error is itself my addLoadEvent, which is basically a standard version of the common library function. @James: I understand that, and there is no syntax error in the function. When that is the case, the syntax error is reported as well. In this case, I am getting only the 'not defined' error. @David: The script in this case resides in an external file that is referenced using the normal <script src="file.js"></script> method in the page's head section. @Douglas: Interesting idea, but if this were the case, how could we ever call a user-defined function with confidence? In any event, I tried this and it didn't work. @sk: This technique has been tested across browsers and is basically copied from the Prototype library. A: It shouldn't be possible for this to happen if you're just including the scripts on the page. The "copyArray" function should always be available when the JavaScript code starts executing no matter if it is declared before or after it -- unless you're loading the JavaScript files in dynamically with a dependency library. There are all sorts of problems with timing if that's the case. A: My guess is, somehow the document is not fully loaded by the time the method is called. Have your code executing after the document is ready event. A: Verify your code with JSLint. It will usually find a ton of small errors, so the warning "JSLint may hurt your feelings" is pretty spot on. =) A: I had this function not being recognized as defined in latest Firefox for Linux, though Chromium was dealing fine with it. What happened in my case was that I had a former SCRIPT block, before the block that defined the function with problem, stated in the following way: <SCRIPT src="mycode.js"/> (That is, without the closing tag.) I had to redeclare this block in the following way. <SCRIPT src="mycode.js"></SCRIPT> And then what followed worked fine... weird huh? A: A syntax error in the function -- or in the code above it -- may cause it to be undefined. A: If you're changing the prototype of the built-in 'function' object it's possible you're running into a browser bug or race condition by modifying a fundamental built-in object. Test it in multiple browsers to find out. A: This doesn't solve your original problem, but you could always replace the call to copyArray() with: __args = Array.prototype.slice.call(arguments); More information available from Google. I've tested the above in the following browsers: IE6, 7 & 8B2, Firefox 2.0.0.17 & 3.0.3, Opera 9.52, Safari for Windows 3.1.2 and Google Chrome (whatever the latest version was at the time of this post) and it works across all browsers. A: This has probably been corrected, but... apparently firefox has a caching problem which is the cause of javascript functions not being recognized.. I really don't know the specifics, but if you clear your cache that will fix the problem (until your cache is full again... not a good solution).. I've been looking around to see if firefox has a real solution to this, but so far nothing... oh not all versions, I think it may be only in some 3.6.x versions, not sure... A: Solved by removing a "async" load: <script type="text/javascript" src="{% static 'js/my_js_file.js' %}" async></script> changed for: <script type="text/javascript" src="{% static 'js/my_js_file.js' %}"></script> A: Use an anonymous function to protect your local symbol table. Something like: (function() { function copyArray(pa) { // Details } Function.prototype.bind = function ( po ) { __args = copyArray( arguments ); } })(); This will create a closure that includes your function in the local symbol table, and you won't have to depend on it being available in the global namespace when you call the function. A: I'm afraid, when you add a new method to a Function class (by prtotyping), you are actually adding it to all declared functions, AS WELL AS to your copyArray(). In result your copyArray() function gets recursivelly self-referenced. I.e. there should exist copyArray().bind() method, which is calling itself. In this case some browsers might prevent you from creating such reference loops and fire "function not defined" error. Inline code would be better solution in such case. A: This can happen when using framesets. In one frame, my variables and methods were defined. In another, they were not. It was especially confusing when using the debugger and seeing my variable defined, then undefined at a breakpoint inside a frame. A: I think your javascript code should be placed between tag,there is need of document load
{ "language": "en", "url": "https://stackoverflow.com/questions/153909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "42" }
Q: How to get list of keys from ASP.NET session state backed by SQL server? I'm looking for a good way to visualize ASP.NET session state data stored in SQL server, preferably without creating a throwaway .aspx page. Is there a good way to get a list of the keys (and serialized data, if possible) directly from SQL server? Ideally, I'd like to run some T-SQL commands directly against the database to get a list of session keys that have been stored for a given session ID. It would be nice to see the serialized data for each key as well. A: Can you elaborate slightly, is there no reference to a HttpContext available (You can use this from backend code as well FYI), which prevents you from utilizing the built in serialization and keys dictionary? EDIT, in response to your update. I believe the ASPState database creates and destroys temporary tables as needed, it does not have permanent tables you can query, take a look at the stored procedures and you should find one along the lines of "TempGetItem", you can either use this sproc directly, or examine its source for more insight. A: When you run asp.net application with sql server session mode, it creates two tables, dbo.ASPStateTempApplications and dbo.ASPStateTempSessions. You can find your application from first table and use it to query open sessions from second table. The ASPStateTempSessions table stores two columns SessionDataShort and SessionDataLong. All session information is binary. You need to know object types being stored in session if you want to deserialize them back again and view the contents. I have tried this recently and it works fine. In fact, for a complex application it is worth having some tools to view and parse session data to make sure we dont store unwanted objects and leave it in database for long - it has potential of slowing things down.
{ "language": "en", "url": "https://stackoverflow.com/questions/153912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php + unixODBC + DB2 + DESCRIBE = token not valid? Code I am trying to run: $query = "DESCRIBE TABLE TABLENAME"; $result = odbc_exec($h, $query); The result: PHP Warning: odbc_exec(): SQL error: [unixODBC][IBM][iSeries Access ODBC Driver][DB2 UDB]SQL0104 - Token TABLENAME was not valid. Valid tokens: INTO., SQL state 37000 in SQLExecDirect in ... There were no other problems with SELECT, INSERT, UPDATE or DELETE queries on the same connection. Is this a syntax error? A: The iSeries flavor of DB2 does not support the SQL DESCRIBE statement. Instead, you have to query the system table: select * from qsys2.columns where table_schema = 'my_schema' and table_name = 'my_table' A: This statement can only be embedded in an application program. It is an executable statement that cannot be dynamically prepared. It must not be specified in Java. From the iSeries DB2 SQL Reference. A: To me it looks like you need to provide a way for the statement to return a value "Valid tokens: INTO" tells me that. I haven't used DESCRIBE before, but I would imagine that it returns something. Interactive SQL doesn't allow the command so I can't really help you much further than that. BTW, add the iSeries tag to your question. You might get a few more answers that way. A: If you just need the column names try select * from <TABLE> where 0 = 1 I don't know how to get the column types, indexes, keys, &c
{ "language": "en", "url": "https://stackoverflow.com/questions/153920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I see TFS file history with labels? We currently are using both Visual Source Safe and Team Foundation Server at work (VSS for old projects, TFS for current or new projects). We have always used Labels in source control for each build. In VSS if you chose to see a file history you could include labels. In TFS I cannot find an option to include the lables in the history window. Since one of the most common questions that I get asked by support or management is 'What version did we fix/add/remove/change xxxx?', I have always relied on our build labels showing up in the history. Can I get Labels to show up in a file history? A: This very issue has been killing us. The best solution I've found is with the use of a third party tool called Team Foundation SideKicks available for free here http://www.attrice.info/cm/tfs/. Under the "History Sidekick" there is a label tab. You can highlight any folder or file and it will show you every label that was dropped on that folder or file and at what changeset. Unfortunately you can not see a full view of a folder or file's history with labels included. Under the "Label Sidekick" you can highlight any specific label at it can tell you what folders/files and changesets are in the label. This functionality is pretty much the same as what is available from within Visual Studio and is not as helpful. One caveat is the need for a TFS server 2008 or above. Using the tool with TFS server 2005 is painfully slow and basically unusable. -ephi A: [due to the complexity of TFS-style labels this is a quite difficult problem when applied to folders; based on a comment above I'm going to assume searching for labels on a file is sufficient] Unfortunately this is one of the very few edge cases of the TFS client API that is not exposed anywhere in tf.exe or VS2008. You'll have to call the API directly. Please see http://msdn.microsoft.com/en-us/library/bb138967.aspx - the "versionFilterItem" parameter does what you're looking for. A: In the 2008 version of TFS, you don't see labels in the standard history of files and folders. If you really want to know why - see Brian Harry's blog post "Why TFS Labels are not like VSS Labels". To find labels in Visual Studio, go to File, Source Control, Label, Find Label... From that you can see what versions of files were included in that label. The team have definitely heard that this is not ideal, and the next version of TFS (Team Foundation Server 2010, codenamed "Rosario") will include improvements to the History view to make labels easier to find - see http://go.microsoft.com/?linkid=7807943 for the spec of improvements to the History view in TFS 2010. BTW - I actually moved to changeset based build numbering with TFS which makes labelling less necessary. See http://www.woodwardweb.com/vsts/changeset_based.html for more details. Hope that helps, Martin. A: TFS 2010 has a very useful "Labels" view (rather than "Changesets") in the history of any branch. Unfortunately, it only shows labels in the branch you have chosen, rather than labels in all child branches/folders. A: I started to play with trying to create my own SQL to do this and run it directly against the TFS database(s) themselves. This SQL was run against TFS 2008. This little snippet will show ALL the labels and changesets for ALL the branches ordered with the most recently created branch/modified label first. The next step in developing this would be to somehow traverse the changesets and the labels to only bring back areas I'm interested in (like 'Main' or some particluar branch). I imagine if I created SQL that would do all of this, it would be dog slow, and wouldn't have the full GUI I want to dive into the history for a particular file, see labels with that, etc. Sigh. select DisplayName, cs.CreationDate, Comment, 'CheckIn' from TfsVersionControl.dbo.tbl_Identity i, TfsVersionControl.dbo.tbl_ChangeSet cs where cs.ownerid = i.IdentityId union select DisplayName, LastModified, Comment, 'Label' from TfsVersionControl.dbo.tbl_Identity i, TfsVersionControl.dbo.tbl_Label l where l.ownerid = i.IdentityId order by 2 desc A: I've used TFS branch history for this before. It's not the greatest UI in the world and only lets you show history per file but it gets the job done.
{ "language": "en", "url": "https://stackoverflow.com/questions/153928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: How do I reference the calling dom element in a jquery ajax success function? I'm trying to modify the class of an element if an ajax call based on that element is successful <script type='text/javascript'> $("#a.toggle").click(function(e){ $.ajax({ url: '/changeItem.php', dataType: 'json', type: 'POST', success: function(data,text){ if(data.error=='') { if($(this).hasClass('class1')) { $(this).removeClass('class1'); $(this).addClass('class2'); } else if($(this).hasClass('class2')) { $(this).removeClass('class2'); $(this).addClass('class1'); } } else(alert(data.error)); } }); return false; }); </script> <a class="toggle class1" title='toggle-this'>Item</a> My understanding of the problem is that in the success function this references the ajax object parameters, NOT the calling dom element like it does within other places of the click function. So, how do I reference the calling dom element and check / add / remove classes? A: jQuery passes the target of the event, along with some other information about it, to your handler function. See http://docs.jquery.com/Events_%28Guide%29 for more info about this. In your code, it'd be referenced like $(e.target). A: Better set ajax parameter : context: this. Example: $.ajax({ url: '/changeItem.php', dataType: 'json', type: 'POST', context: this, success: function(data,text){ if(data.error=='') { if($(this).hasClass('class1')) { $(this).removeClass('class1'); $(this).addClass('class2'); } else if($(this).hasClass('class2')) { $(this).removeClass('class2'); $(this).addClass('class1'); } } else(alert(data.error)); } }); A: I know it's old but you can use the 'e' parameter from the click function. A: You can just store it in a variable. Example: $("#a.toggle").click(function(e) { var target = $(this); $.ajax({ url: '/changeItem.php', dataType: 'json', type: 'POST', success: function(data,text) { if(data.error=='') { if(target.hasClass('class1')) { target .removeClass('class1') .addClass('class2'); } else if(target.hasClass('class2')) { target .removeClass('class2') .addClass('class1'); } } else(alert(data.error)); } }); return false; });
{ "language": "en", "url": "https://stackoverflow.com/questions/153934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: What causes Visual Studio 2008 SP1 to crash when switch to Design View of a WPF application After developing a WPF application without Source Control, I decided to add the solution to TFS. After doing so whenever I opened the main window.xaml file in Design View Visual Studio would disappear and the following event would be logged in the Application Event log: .NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (7A035E00) (80131506) For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp. A: The problem was caused by a Visual Studio add-in named, "Power Commands for Visual Studio 2008". After uninstalling them and restarting Visual Studio, the design view for xaml files began working normally. A: Same issue, but without Power Commands installed. The only workaround I've been able to consistently use is to Clean/Rebuild the solution before opening ANY xaml file. If you can't get into your solution because the XAML is loading on start up, delete the suo. A: If you wish to keep Power Commands for Visual Studio 2008 installed, see this workaround here: PowerCommands crashing VS2008 SP1 But basically: a work around which is a simple modification to the devenv.exe.config file. This will exist in (64 bit systems) C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE Or (32 bit systems) C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE Add this XML token to the dependentAssembly list. They had me add it after the office one, but im not sure if that matters. <dependentAssembly> <assemblyIdentity name="office" publicKeyToken="71e9bce111e9429c" culture="neutral"/> <codeBase version="12.0.0.0" href="PrivateAssemblies\Office12\Office.dll"/> </dependentAssembly> <!-NEW STUFF--> <dependentAssembly> <assemblyIdentity name="Microsoft.PowerCommands" publicKeyToken="null" culture="neutral"/> <!-- For 64-bit systems, uncomment this one <codeBase version="1.1.0.0" href="C:\Program Files (x86)\PowerCommands\Microsoft.PowerCommands.dll"/> --> <!-- For 32-bit systems, uncomment this one <codeBase version="1.1.0.0" href="href="C:\Program Files\PowerCommands\Microsoft.PowerCommands.dll"/> --> </dependentAssembly> This worked nicely for me. A: I just came across an answer that worked in my situation. Using the ngen utility to delete the native image cache fixed the problem. I don't know which image it was exactly, as I did not go through then one at a time, but it worked and I was able to keep PowerCommands! The command is: ngen /delete * For a full recount of my tale I've posted it on my blog, including what I found out about ngen and the native image cache. I think I still have some more to learn about it, but it's a start. A: I didn't have PowerCommands installed, but had the same problem. Starting in safe mode and deleting any exotic tabs in the toolbox solved the problem (you can start in normal mode afterwards). This is one of many possible causes of this error, as some Googling will show you. A: There is an hot-fix available from Microsoft: Microsoft Connect. I found this link on this blog. This fix solved the problem after a restart for me. A: I had this problem for quite a while. I never had Power Commands installed, deleting the .suo files and cleaning/rebuilding didn't help. What fixed it for me was to turn off the auto-population of the toolbox. Just go to Tools | Options | Windows Form Designer, then the bottom options is AutoToolboxPopulate which I set to false. Then I reloaded the solution into VS2008 and I was able to open WPF files in either Xaml or designer mode. A: I have been experiencing this kind of crashes. Make sure your code behind contains the class of the xaml you are editing (this is by default)
{ "language": "en", "url": "https://stackoverflow.com/questions/153942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Is SQL syntax case sensitive? Is SQL case sensitive? I've used MySQL and SQL Server which both seem to be case insensitive. Is this always the case? Does the standard define case-sensitivity? A: No. MySQL is not case sensitive, and neither is the SQL standard. It's just common practice to write the commands upper-case. Now, if you are talking about table/column names, then yes they are, but not the commands themselves. So SELECT * FROM foo; is the same as select * from foo; but not the same as select * from FOO; A: I found this blog post to be very helpful (I am not the author). Summarizing (please read, though): ...delimited identifiers are case sensitive ("table_name" != "Table_Name"), while non quoted identifiers are not, and are transformed to upper case (table_name => TABLE_NAME). He found DB2, Oracle and Interbase/Firebird are 100% compliant: PostgreSQL ... lowercases every unquoted identifier, instead of uppercasing it. MySQL ... file system dependent. SQLite and SQL Server ... case of the table and field names are preserved on creation, but they are completely ignored afterwards. A: I don't think SQL Server is case sensitive, at least not by default. When I'm querying manually via SQL Server Management Studio, I mess up case all the time and it cheerfully accepts it: select cOL1, col2 FrOM taBLeName WheRE ... A: This isn't strictly SQL language, but in SQL Server if your database collation is case-sensitive, then all table names are case-sensitive. A: The SQL-92 specification states that identifiers might be quoted, or unquoted. If both sides are unquoted then they are always case insensitive, e.g., table_name == TAble_nAmE. However, quoted identifiers are case sensitive, e.g., "table_name" != "TAble_naME". Also based on the specification if you wish to compare unquoted identifiers with quoted ones, then unquoted and quoted identifiers can be considered the same, if the unquoted characters are uppercased, e.g. TABLE_NAME == "TABLE_NAME", but TABLE_NAME != "table_name" or TABLE_NAME != "TAble_NaMe". Here is the relevant part of the specification (section 5.2.13): *A <regular identifier> and a <delimited identifier> are equivalent if the <identifier body> of the <regular identifier> (with every letter that is a lower-case letter replaced by the equivalent upper-case letter or letters) and the <delimited identifier body> of the <delimited identifier> (with all occurrences of <quote> replaced by <quote symbol> and all occurrences of <doublequote symbol> replaced by <double quote>), considered as the repetition of a <character string literal> that specifies a <character set specification> of SQL_TEXT and an implementation- defined collation that is sensitive to case, compare equally according to the comparison rules in Subclause 8.2, "<comparison predicate>". Note, that just like with other parts of the SQL standard, not all databases follow this section fully. PostgreSQL for example stores all unquoted identifiers lowercased instead of uppercased, so table_name == "table_name" (which is exactly the opposite of the standard). Also some databases are case insensitive all the time, or case-sensitiveness depend on some setting in the DB or are dependent on some of the properties of the system, usually whether the file system is case sensitive or not. Note that some database tools might send identifiers quoted all the time, so in instances where you mix queries generated by some tool (like a CREATE TABLE query generated by Liquibase or other DB migration tool), with hand made queries (like a simple JDBC select in your application) you have to make sure that the cases are consistent, especially on databases where quoted and unquoted identifiers are different (DB2, PostgreSQL, etc.) A: The SQL keywords are case insensitive (SELECT, FROM, WHERE, etc), but they are often written in all caps. However, in some setups, table and column names are case sensitive. MySQL has a configuration option to enable/disable it. Usually case sensitive table and column names are the default on Linux MySQL and case insensitive used to be the default on Windows, but now the installer asked about this during setup. For SQL Server it is a function of the database's collation setting. Here is the MySQL page about name case-sensitivity Here is the article in MSDN about collations for SQL Server A: SQL keywords are case insensitive themselves. Names of tables, columns, etc., have a case sensitivity which is database dependent - you should probably assume that they are case sensitive unless you know otherwise (in many databases they aren't though; in MySQL table names are sometimes case sensitive, but most other names are not). Comparing data using =, >, <, etc., has a case awareness which is dependent on the collation settings which are in use on the individual database, table or even column in question. It's normal however, to keep collation fairly consistent within a database. We have a few columns which need to store case sensitive values; they have a collation specifically set. A: In SQL Server it is an option. Turning it on sucks. I'm not sure about MySQL. A: Identifiers and reserved words should not be case sensitive, although many follow a convention to use capitals for reserved words and upper camel case for identifiers. See SQL-92 Sec. 5.2 A: My understanding is that the SQL standard calls for case-insensitivity. I don't believe any databases follow the standard completely, though. MySQL has a configuration setting as part of its "strict mode" (a grab bag of several settings that make MySQL more standards-compliant) for case sensitive or insensitive table names. Regardless of this setting, column names are still case-insensitive, although I think it affects how the column-names are displayed. I believe this setting is instance-wide, across all databases within the RDBMS instance, although I'm researching today to confirm this (and hoping the answer is no). I like how Oracle handles this far better. In straight SQL, identifiers like table and column names are case insensitive. However, if for some reason you really desire to get explicit casing, you can enclose the identifier in double-quotes (which are quite different in Oracle SQL from the single-quotes used to enclose string data). So: SELECT fieldName FROM tableName; will query fieldname from tablename, but SELECT "fieldName" FROM "tableName"; will query fieldName from tableName. I'm pretty sure you could even use this mechanism to insert spaces or other non-standard characters into an identifier. In this situation if for some reason you found explicitly-cased table and column names desirable it was available to you, but it was still something I would highly caution against. My convention when I used Oracle on a daily basis was that in code I would put all Oracle SQL keywords in uppercase and all identifiers in lowercase. In documentation I would put all table and column names in uppercase. It was very convenient and readable to be able to do this (although sometimes a pain to type so many capitals in code -- I'm sure I could've found an editor feature to help, here). In my opinion MySQL is particularly bad for differing about this on different platforms. We need to be able to dump databases on Windows and load them into Unix, and doing so is a disaster if the installer on Windows forgot to put the RDBMS into case-sensitive mode. (To be fair, part of the reason this is a disaster is our coders made the bad decision, long ago, to rely on the case-sensitivity of MySQL on UNIX.) The people who wrote the Windows MySQL installer made it really convenient and Windows-like, and it was great to move toward giving people a checkbox to say "Would you like to turn on strict mode and make MySQL more standards-compliant?" But it is very convenient for MySQL to differ so significantly from the standard, and then make matters worse by turning around and differing from its own de facto standard on different platforms. I'm sure that on differing Linux distributions this may be further compounded, as packagers for different distros probably have at times incorporated their own preferred MySQL configuration settings. Here's another Stack Overflow question that gets into discussing if case-sensitivity is desirable in an RDBMS. A: Have the best of both worlds These days you can just write all your SQL statements in lowercase and if you ever need to have it formatted then just install a plugin that will do it for you. This is only applicable if your code editor has those plug-ins available. Visual Studio Code has many extensions that can do this. Here's a couple you can use: vscode-sql-formatter and SqlFormatter-VSCode
{ "language": "en", "url": "https://stackoverflow.com/questions/153944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "228" }
Q: Open source .net windows form based controls like: gantt chart, calendar and scheduler Is there any open source or free .net ui toolkit containing at least one of the following controls: *gantt chart (ms project like) *calendar (google calendar like or ms outlook 2003, 2007 like) *scheduler (outlook 2007 like) Thanks A: Here is a free gantt chart from CodeProject. http://www.codeproject.com/KB/vb/Gantt_Chart.aspx A: Here is a Calendar Dayview like Outlook http://www.codeproject.com/KB/selection/Calendardayview.aspx it's not bad at all... A: Here is a list of open source charting libraries: http://csharp-source.net/open-source/charting-and-reporting
{ "language": "en", "url": "https://stackoverflow.com/questions/153945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: GLIBC: debugging memory leaks: how to interpret output of mtrace() I’m trying to debug a memory leak problem. I’m using mtrace() to get a malloc/free/realloc trace. I’ve ran my prog and have now a huge log file. So far so good. But I have problems interpreting the file. Look at these lines: @ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x1502570 0x68 @ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x1502620 0x30 @ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x2aaab43a1700 0xa80 @ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x1501460 0xa64 The strange about this is that one call (same return address) is responsible for 4 allocations. Even stranger: @ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x2aaab43a1700 0xa2c … @ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x2aaab43a1700 0xa80 Between those two lines the block 0x2aaab43a1700 is never being freed. Does anyone know how to explain this? How could one call result in 4 allocations? And how could malloc return an address which was already allocated previously? edit 2008/09/30: The script to analyze the mtrace() output provided by GLIBC (mtrace.pl) isn't of any help here. It will just say: Alloc 0x2aaab43a1700 duplicate. But how could this happen? A: You're looking at the direct output of mtrace, which is extremely confusing and counterintuitive. Luckily, there is a perl script (called mtrace, found within glibc-utils) which can very easily help the parsing of this output. Compile your build with debugging on, and run mtrace like such: $ gcc -g -o test test.c $ MALLOC_TRACE=mtrace.out ./test $ mtrace test mtrace.out Memory not freed: ----------------- Address Size Caller 0x094d9378 0x400 at test.c:6 The output should be a lot easier to digest. A: The function that is allocating the memory is being called more than once. The caller address points to the code that did the allocation, and that code is simply being run more than once. Here is an example in C: void *allocate (void) { return (malloc(1000)); } int main() { mtrace(); allocate(); allocate(); } The output from mtrace is: Memory not freed: ----------------- Address Size Caller 0x0000000000601460 0x3e8 at 0x4004f6 0x0000000000601850 0x3e8 at 0x4004f6 Note how the caller address is identical? This is why the mtrace analysing script is saying they are identical, because the same bug is being seen more that once, resulting in several memory leaks. Compiling with debugs flags (-g) is helpful if you can: Memory not freed: ----------------- Address Size Caller 0x0000000000601460 0x3e8 at /home/andrjohn/development/playground/test.c:6 0x0000000000601850 0x3e8 at /home/andrjohn/development/playground/test.c:6 A: One possible explanation is that the same function is allocating different buffer sizes? One such example is strdup. For the second question, it is possible that the runtime is allocating some "static" scratch area which is not intended to be freed until the process is terminated. And at that point, the OS will clean-up after the process anyway. Think about it this way: in Java, there are no destructors, and no guarantees that finalization will be ever called for any object. A: Try running your app under valgrind. It might give you a better view about what is actually being leaked.
{ "language": "en", "url": "https://stackoverflow.com/questions/153953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Python GUI Application redistribution I need to develop a small-medium sized desktop GUI application, preferably with Python as a language of choice because of time constraints. What GUI library choices do I have which allow me to redistribute my application standalone, assuming that the users don't have a working Python installation and obviously don't have the GUI libraries I'm using either? Also, how would I go about packaging everything up in binaries of reasonable size for each target OS? (my main targets are Windows and Mac OS X) Addition: I've been looking at WxPython, but I've found plenty of horror stories of packaging it with cx_freeze and getting 30mb+ binaries, and no real advice on how to actually do the packaging and how trust-worthy it is. A: This may help: How can I make an EXE file from a Python program? A: http://wiki.wxpython.org/CreatingStandaloneExecutables It shouldn't be that large unless you have managed to include the debug build of wx. I seem to rememebr about 4Mb for the python.dll and similair for wx. A: Python has an embedded GUI toolkit named TKinter which is based on Tk library from TCL programming language. It is very basic and does not have all the functionality you expect in Windows Forms or GTK for example but if you must have platform independent toolkit I see no other choice taking in mind that you also dont want to grow that much the binary. Tkinter is not hard at all to use since it doesnt have millions of widgets/controls and options and is the default toolkit included in most python distributions, at least on Windows, OSX and Linux. GTK and QT are prettier and more powerful but they have a one big disadvantage for you: they are heavy and deppend upon third libraries, especially GTK which has a lot of dependencies that makes it a little hard to distribute it embeded in your software. As for the binary creation I know there is py2exe which converts python code to win32 executable code (.exe's) but im not sure if there is something similar for OSX. Are you worried because people could see the source code or just so you can bundle all in a single package? If you just want to bundle everything you dont need to create a standalone executable, you could easily create an installer: Creating distributable in python That's a guide on how to distribute your software when it's done. A: http://Gajim.org for Windows uses python and PyGtk. You can check, how they did it. Also, there's PyQt for GUI (and wxpython mentioned earlier). A: I don't have any experience building stand-alone apps for any platform other than Windows. That said: Tkinter: works fine with py2exe. Python Megawidgets (an "expansion library" for Tkinter) works fine also, but it does funky things with dynamic imports, so you need to combine all the components into a big file "pmw.py" and add it to your project (well, you'll also have pmwblt.py and pmwcolor.py). There are instructions for how to do this somewhere (either on py2exe wiki or in the PMW docs). Tix (an extension to Tk that you can use with Tkinter) doesn't work with py2exe, or at least that was my experience about four years ago. wxPython also works fine with py2exe. I just checked an app I have; the whole distribution came to around 11MB. Most of that was the wx DLLs and .pyd files, but I can't see how you'd avoid that. If you are targetting Windows XP, you need to include a manifest in your setup.py or else it will look ugly. See this email for details. A: I've used py2Exe myself - it's really easy (at least for small apps). A: Combination that I am familiar with: wxPython, py2exe, upx The key to resolving your last concern about the size of the distribution is using upx to compress the DLLs. It looks like they support MacOS executables. You will pay an initial decompression penalty when the DLLs are first loaded.
{ "language": "en", "url": "https://stackoverflow.com/questions/153956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Viewing a MOSS 2007 page as another user would see it - without logging in as that user In Moss 2007 you have the ability to set the target audience for each individual web part within a page. Is there a way to preview how the page will look to another user without logging in as that user? What I am looking for is a way for someone with full control/design permissions on a site to be able to preview how the site will be displayed to another user. Any suggestions? I have a few test accounts that our IS department uses to preview pages, however we do not allow non-IS departamental staff to use those accounts. Those staff members only have access to their one account. So, if a user makes changes the target audience on a web part on one of their pages, right now they have no way to preview how the page will look to someone else other than asking someone else to login & watching over their shoulder. I can't give out the account information for the test accounts, nor can I create new test accounts. Thanks! Edit: I have the ability to preview. The problem is that other users with full control of a site can't preview the page. Here's a scenarios: In my school division each school has a site. The principal has full control of his school's site. On the landing page, he wants all the school announcements to be visible. However, some should only be visible to teaching staff, while others need to be visible to the students. He uses audience targetting but cannot preview to see at a glance that the targetting is correct. A lot of the users are not computer savy so things need to be as simple as possible. Also, that was just one scenario, there are other scenarios that are not divided by school. There are many users with full control of a site with different requirements - so it's not feasible to create test accounts for all scenarios. A: First I don't think it is possible to have a preview feature if you are using NT security. Maybe it is something you can do with forms authentication but I never used it. On that subject. I think when you are developing new features or integrating stuff on a MOSS/WSS server you need a little flexibility. With what I see you have to following things you can do. It is surely more cost effective than developing a custom solution. I assume you are using NT Security. * *User accounts : Ask your domain administrator to have dedicated user accounts to play with. *Virtual Machines : Ask to have some virual machines to be able to play with that server combined with tests accounts *Sandboxed environment : Ask your IT dept to create a sandboxed MOSS environment to have to possibility to replicate your actual MOSS environment and create custom user scenarios. A: Edit: After re-reading the question I released that you want the users to be able to preview a page. I think you will need to look into writing a preview control that uses Impersonation to load the page. Not sure how feasible this is, but surely someone has created a preview feature. Sounds like a pretty common scenario to me. Old Answer: Could you not fire up a non MS browser such as Firefox, which will prompt for the username and password. You can then just clear the session cookies to be prompted to log in as someone else. This is the technique I used for an ASP.Net site that used authentication against the domain in a similar manner to SharePoint. A: For previewing target audiences only, the only way to do it is to create a target audience that runs based on a properties in the SSP User Profile Properties. You can then have a control that allows the editor to change the value stored thier profile, re-compile the profiles and voila (for some description of voila) the user will have change thier audience targetting values to something else. This would need quite a bit of coding and some thought put into the rules for the audience targetting. At the end of the day, the most cost effective way is to push back to your infrastructure guys for an account solution that will allow you to have an "reader" account people can use for this function. A: Alternatively, you can create a control/webpart that hooks into the audiences for the site and displays the audience membership to the user (maybe from the GetMembership call). This does not preview the site, but it will give your editors a heads up on who is in each audience. Something that will help them get the audiences correct. We have made a similar webpart for security group membership. A: I think there are two approaches you can take: * *Do make use of test accounts to preview the pages. You can ease the "pain" to log in as another user by making use of the RUNAS command (http://technet.microsoft.com/en-us/library/bb490994.aspx). So it's possible to just create a shortcut on the desktop that opens a browser making use of another account's credentials. Only that browser instance will work with the test account. *Make a copy (or more copies) of the page that you want to preview, store it in a secured site (so it's only accessible for the principal for example), and tweak the Audience Targetting properties of the web parts on that page/pages.
{ "language": "en", "url": "https://stackoverflow.com/questions/153961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Encapsulating an algorithm into a class I'm wondering how (un)common it is to encapsulate an algorithm into a class? More concretely, instead of having a number of separate functions that forward common parameters between each other: void f(int common1, int param1, int *out1); void g(int common1, int common2, int param1, int *out2) { f(common1, param1, ..); } to encapsulate common parameters into a class and do all of the work in the constructor: struct Algo { int common1; int common2; Algo(int common1, int common2, int param) { // do most of the work } void f(int param1, int *out1); void g(int param1, int *out2); }; It seems very practical not having to forward common parameters and intermediate results through function arguments.. But I haven't seen this "pattern" being widely used.. What are the possible downsides? A: There's a design pattern that addresses the issue; it's called "Strategy Design Pattern" - you can find some good info on it here. The nice thing about "Strategy" is that it lets you define a family of algorithms and then use them interchangeably without having to modify the clients that use the algorithms. A: It's not a bad strategy at all. In fact, if you have the ability in your language (which you do in C++) to define some type of abstract superclass which defines an opaque interface to the underlying functionality, you can swap different algorithms in and out at runtime (think sorting algorithms, for example). If your chosen language has reflection, you can even have code that is infinitely extensible, allowing algorithms to be loaded and used that may not have even existed when the consumer of said algorithms was written. This also allows you to loosely couple your other functional classes and algorithmic classes, which is helpful in refactoring and in keeping your sanity intact when working on large projects. Of course, anytime you start to build a complex class structure, there will be extra architecture - and therefore code - that will need to be built and maintained. However, in my opinion the benefits in the long run outweigh this minor inconvenience. One final suggestion: do not do your work in the constructor. Constructors should only be used to initialize a classes internal structure to reasonable defaults. Yes, this may include calling other methods to finish initialization, but initialization is not operation. The two should be separate, even if it requires one more call in your code to run the particular algorithm you were looking for. A: Could your question be more generally phrased like, "how do we use object oriented design when the main idea of the software is just running an algorithm?" In that case, I think that a design like you offered is a good first step, but these things are often problem-dependent. I think a good general design is like what you have there. . . class InputData {}; class OutputData {}; class TheAlgorithm { private: //functions and common data public: TheAlgorithm(InputData); //other functions Run(); ReturnOutputData(); }; Then, let that interact with the main() or your GUI however you want. A: I usually create a functor or Function Object to encapsulate my algorithms. I usually use the following template class MyFunctor { public: MyFunctor( /* List of Parameters */ ); bool execute(); private: /* Local storage for parameters and intermediary data structures */ } Then I used my functors this way: bool success = MyFunctor( /*Parameter*/ ).execute(); A: Perhaps a better approach (unless I'm missing something) is to ecapsualte the algorithm in a class and have it execute through a method call. You can either pass in all the parameters to public properties, through a constructor, or create a struct that ecapsulates all the parameters that gets passed in to a class that contains the algorithm. But typically it's not a good idea to execute things in the constructor like that. First and foremost because it's not intuitive. public class MyFooConfigurator { public MyFooConfigurator(string Param1, int, Param2) //Etc... { //Set all the internal properties here //Another option would also be to expose public properties that the user could //set from outside, or you could create a struct that ecapsulates all the //parameters. _Param1 = Param1; //etc... } Public ConfigureFoo() { If(!FooIsConfigured) return; Else //Process algorithm here. } } A: If you would ever need to call both methods with the constructor parameters then i would do it. If you would never need to call both methods with the same parameters then I wouldn't.
{ "language": "en", "url": "https://stackoverflow.com/questions/153974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Creating an instance of a nested Java class in ColdFusion I’m trying to create an instance of: java.awt.geom.Point2D.Double in ColdFusion. Point2D.Double is a nested class inside of the abstract class Point2D. I have tried to instantiate the class using: <cfset PointClass = createObject("java", "java.awt.geom.Point2D.Double")> This fails because ColdFusion cannot find the class. And <cfset PointClass = createObject("java", "java.awt.geom.Point2D")> which does not work because Point2D is an abstract class and there is not a public constructor on which you can call PointClass.init(x,y). Right now, I’ve resorted to making my own Point class that wraps the Point2D.Double class so that I can instantiate it in ColdFusion. I don’t think this is ideal and am looking for ideas about how to directly create a Point2D.Double class in ColdFusion. I'm also using ColdFusion 8. A: Try with: <cfset PointClass = createObject("java", "java.awt.geom.Point2D$Double")> For nested classes, use $
{ "language": "en", "url": "https://stackoverflow.com/questions/153975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Are there any better command prompts for Windows? For some reason the Windows command prompt is "special" in that you have to go to a properties dialog to resize it horizontally rather than just dragging the corner of the window like every other app. Unsurprisingly this feature made it into P-P-P-Powershell as well -- is there any way around this via command prompt replacement or Windows hackery? A: 2019 Update: * *Microsoft has released the terminal app on Github & the Windows Store, and it has tabs, panels, acrylic transparency, and other features. 2016 Update: * *Windows 10's default conhost UI has more features, including free resize, transparency, etc (this includes cmd & powershell) *I now use ConEmu (walkthrough here) which has many features including tabs & split panes. *Other options include Cmder (which comes with additional tools built in), and ConsoleZ (a fork of Console2). *Console appears to no longer be updated A: If you don't mind installing cygwin you can use it with xterm or rxvt. You'll also be able to use Bash as the shell instead of cmd.exe which is much nicer. A: This isn't quite what you're looking for, but the way I get around it is by using cygwin's rootless X-Windows mode and XTerms. I prefer the unix command line environment more then Windows' env, and the XTerm windows act just like any other window. As for straight replacements, a quick google search shows these: * *Console *econsole I haven't tried them, so I'm not sure if they have what you're looking for, but they might be worth a shot. A: PowerShell v2.0 ships with an interactive shell, called the PowerShell Integrated Script Environment (ISE). It's not fantastic, but it's usually better than the console subsystem. Good * *Includes a PowerShell script editor, with colorization *Colorization as a type at the prompt *I can have multiple PowerShell sessions, including remote sessions, as tabs. *The ISE is PowerShell-aware, so I can manipulate and extend it with PowerShell. For example, see the "IsePack", which adds a ton of features, including copy-as-HTML. *Can easily scale the text *Conventional Windows resizing, cursor navigation, selection, copy, paste, fonts, etc. Bad * *Interactive console applications block waiting for input, and thus hang. *Console applications that detect whether their standard IO are redirected will think that is so, and thus act oddly. The worst is TFS's tf.exe. For example, 'tf submit' will submit without prompting, even though the prompt is GUI, not CLI. *A limited feature set out of the box. It's obvious they would like to make a much richer PowerShell IDE but did not. A: Way after the fact, but things have improved in the meantime. ConEmu is highly configurable, and can be resized horizontally and vertically. It has the somewhat odd (to me anyway) behavior of resizing the font as the window is resized. There's some discussion about it here. And Scott Hanselman has written about it, including integration with FarManager. A: I don't know if this is what you want: Resizing the Powershell Console Window. If so, I got this awhile ago: Just type: resize and use the arrow keys to adjust width and height. ## ## Author : Roman Kuzmin ## Synopsis : Resize console window/buffer using arrow keys ## function Size($w, $h) { New-Object System.Management.Automation.Host.Size($w, $h) } function resize() { Write-Host '[Arrows] resize [Esc] exit ...' $ErrorActionPreference = 'SilentlyContinue' for($ui = $Host.UI.RawUI;;) { $b = $ui.BufferSize $w = $ui.WindowSize switch($ui.ReadKey(6).VirtualKeyCode) { 37 { $w = Size ($w.width - 1) $w.height $ui.WindowSize = $w $ui.BufferSize = Size $w.width $b.height break } 39 { $w = Size ($w.width + 1) $w.height $ui.BufferSize = Size $w.width $b.height $ui.WindowSize = $w break } 38 { $ui.WindowSize = Size $w.width ($w.height - 1) break } 40 { $w = Size $w.width ($w.height + 1) if ($w.height -gt $b.height) { $ui.BufferSize = Size $b.width $w.height } $ui.WindowSize = $w break } 27 { return } } } } A: You might consider installing FAR. It's an excellent text mode file manager and much more. It could also be resized by dragging the corner of the window :) A: If you set the property 'Layout/Screen Buffer Size/Width' then, when prompted, choose 'Modify shortcut that started this window' it will remember the buffer width. Then when you start another command prompt it will be, for example, the original 80 wide, but you can now stretch it to whatever you set the buffer width to. Command Prompt will not wrap at the current window width, only at the buffer width. Thus if you've set the buffer width to 120, but the window is only 80 wide the lines will wrap at 120 and you'll have to scroll to read characters past 80.
{ "language": "en", "url": "https://stackoverflow.com/questions/153983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: How can I copy data records between two instances of an SQLServer database I need to copy some records from our SQLServer 2005 test server to our live server. It's a flat lookup table, so no foreign keys or other referential integrity to worry about. I could key-in the records again on the live server, but this is tiresome. I could export the test server records and table data in its entirety into an SQL script and run that, but I don't want to overwrite the records present on the live system, only add to them. How can I select just the records I want and get them transferred or otherwise into the live server? We don't have Sharepoint, which I understand would allow me to copy them directly between the two instances. A: If your production SQL server and test SQL server can talk, you could just do in with a SQL insert statement. first run the following on your test server: Execute sp_addlinkedserver PRODUCTION_SERVER_NAME Then just create the insert statement: INSERT INTO [PRODUCTION_SERVER_NAME].DATABASE_NAME.dbo.TABLE_NAME (Names_of_Columns_to_be_inserted) SELECT Names_of_Columns_to_be_inserted FROM TABLE_NAME A: An SSIS package would be best suited to do the transfer, it would take literally seconds to setup! A: I use SQL Server Management Studio and do an Export Task by right-clicking the database and going to Task>Export. I think it works across servers as well as databases but I'm not sure. A: I would just script to sql and run on the other server for quick and dirty transferring. If this is something that you will be doing often and you need to set up a mechanism, SQL Server Integration Services (SSIS) which is similar to the older Data Transformation Services (DTS) are designed for this sort of thing. You develop the solution in a mini-Visual Studio environment and can build very complex solutions for moving and transforming data.
{ "language": "en", "url": "https://stackoverflow.com/questions/153988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: How do I get the scroll position / range from a wx.TextCtrl control in wxPython I have a little logging app (written in wxPython) that receives data from a bit of kit we're developing, and I want to display the text in a scrolling window. As it stands I'm using a wx.TextCtrl for the text display, but I'm having some issues with the scrolling behaviour. Basically, I'd like it so that if the scrollbar is at the bottom of the window (i.e. the end of the incoming data), adding more data should scroll the view onwards. If, however the view has been scrolled up a little (i.e. the user is looking at something interesting like an error message), the app should just add the text on the end without scrolling any more. I've got two problems at the moment: * *I can't work out how to retrieve the current scroll position (calls to GetScrollPos() don't seem to work - they just return 0). *I can't work out how to retrieve the current range of the scroll bar (calls to GetScrollRange() just return 1). I've googled a bit and there seem to be a few hints that suggest GetScrollPos and GetScrollRange won't work for a wx.TextCtrl? Has anyone else had any experience in this area? Is there a nice easy way to solve the problem or am I going to have to roll my own wx.TextCtrl? A: Okay, so here's where I've got to: import wx from threading import Timer import time class Form1(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) self.logger = wx.TextCtrl(self,5, "",wx.Point(20,20), wx.Size(200,200), \ wx.TE_MULTILINE | wx.TE_READONLY)# | wx.TE_RICH2) t = Timer(0.1, self.AddText) t.start() def AddText(self): # Resart the timer t = Timer(0.25, self.AddText) t.start() # Work out if we're at the end of the file currentCaretPosition = self.logger.GetInsertionPoint() currentLengthOfText = self.logger.GetLastPosition() if currentCaretPosition != currentLengthOfText: self.holdingBack = True else: self.holdingBack = False timeStamp = str(time.time()) # If we're not at the end of the file, we're holding back if self.holdingBack: print "%s FROZEN"%(timeStamp) self.logger.Freeze() (currentSelectionStart, currentSelectionEnd) = self.logger.GetSelection() self.logger.AppendText(timeStamp+"\n") self.logger.SetInsertionPoint(currentCaretPosition) self.logger.SetSelection(currentSelectionStart, currentSelectionEnd) self.logger.Thaw() else: print "%s THAWED"%(timeStamp) self.logger.AppendText(timeStamp+"\n") app = wx.PySimpleApp() frame = wx.Frame(None, size=(550,425)) Form1(frame) frame.Show(1) app.MainLoop() This simple demo app works almost perfectly. It scrolls neatly unless the user clicks a line which isn't at the end of the text. Thereafter it stays nice and still so you can select text (note: there's still a bug there in that if you select up not down it clears your selection). The biggest annoyance is that if I try and enable the "| wx.TE_RICH2" option, it all goes a bit pear-shaped. I really need this to do syntax highlighting of errors, but if I can't enable that option, I'm doomed to monochrome - boo! Any more ideas on how to hold back scrolling on the rich edit control? A: I just tested a simple example (checking GetScrollPos(0) and GetScrollRange(0) in EVT_TEXT event handler for wx.TextCtrl) and it works fine for me - they return index of currently shown line and total number of lines, respectively. Maybe the problem is your wxPython version? I used: >>> import wx >>> wx.version() '2.8.9.1 (msw-unicode)'
{ "language": "en", "url": "https://stackoverflow.com/questions/153989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generic type args which specificy the extending class? I want to have a class which implements an interface, which specifies the specific subclass as a parameter. public abstract Task implements TaskStatus<Task> { TaskStatus<T> listener; protected complete() { // ugly, unsafe cast callback.complete((T) this); } } public interface TaskStatus<T> { public void complete(T task); } But instead of just task, or , I want to guarantee the type-arg used is that of the specific class extending this one. So the best I've come up with is: public abstract Task<T extends Task> implements TaskStatus<T> { } You'd extend that by writing: public class MyTask extends Task<MyTask> { } But this would also be valid: public class MyTask extends Task<SomeOtherTask> { } And the invocation of callback will blow up with ClassCastException. So, is this approach just wrong and broken, or is there a right way to do this I've somehow missed? A: It is not clear what you are trying to do inside of Task. However, if you define the generic class Task<T> as follows: class Task<T extends Task<T>> { ... } The following two are possible: class MyTask extends Task<MyTask> { ... } class YourTask extends Task<MyTask> { ... } But the following is prohibited: class MyTask extends Task<String> { ... } The above definition of Task uses F-bounded polymorphism, a rather advanced feature. You can check the research paper "F-bounded polymorphism for object-oriented programming" for more information. A: I suggest adding a getThis which should return this appropriately typed. Sure a subclas could misbehave, but that's always true. What you avoid is the cast and the possibility of a ClassCastException. public abstract class Task<THIS extends Task<THIS>> { private TaskStatus<THIS> callback; public void setCallback(TaskStatus<THIS> callback) { this.callback = callback==null ? NullCallback.INSTANCE : callback; } protected void complete() { // ugly, unsafe cast callback.complete(getThis()); } protected abstract THIS getThis(); } public interface TaskStatus<T/* extends Task<T>*/> { void complete(T task); } public class MyTask extends Task<MyTask> { @Override protected MyTask getThis() { return this; } } This problem often comes up with builders. A: I'm having a little trouble understanding what you're trying to accomplish through this. Could you provide some more details? My read of the code says you have these tasks which will be sub-classed and after the tasks are complete, the executing thread will call complete() on the task. At this point you want to call a callback and pass it the sub-class object. I think this is the problem. You are trying to put knowledge of the potential sub-classes into your abstract class which is a no-no. This also raises the question of, if you could make this call, what is the callback going to do with the sub-class that would be different from the superclass? A: I can really only see this working if you in the constructor enforce the type arg. Via. introspection and the Class.getSuperType() you can inspect the type args, and verify that the type arg matches this class. Somthing along the lines of: assert getClass() == ((ParameterizedType) getSuperType()).getTypeArguments()[0]; (This is from the top off my head, check JavaDocs to verify). I am not sure where callback is created though in your code. You have omitted it's declaration in the top. A different route would be to remove the unsafe cast, as atm. I can't see the full flow to spot why you need the unsafe cast.
{ "language": "en", "url": "https://stackoverflow.com/questions/153994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Respecting XP themes when designing WinForms UI How do you deal with the different XP themes when designing a WinForms UI? Do you avoid hard coded color values or just accept that your UI will not look good on non standard themes? For instance, I have a light blue gradient panel that looks good against the standard control background color but would clash with other custom themes. What's a good approach to take? A: Avoid hex colors and colors with names like "White" or "Green". The color picker for most objects should be able to show you colors with names like "ActiveWindow" or "ForegroundText". Those are the colors you want to be using. They are available via code also, and you want to choose them so that the names have some relationship to how they're used. For example, don't set "ForegroundText" as your background color just because you want a black background. If you have a gradient, then use those colors to build the gradient. Also, there's an event you may need to handle for when the theme changes. That's if you choose to respect the themes. If you have a really out-there interface then you may want to specify your own colors. In that case, never use the windows colors, because they won't be reliable and you might end up with something real ugly. That means you'll need to go and change all the defaults in the standard controls, but if you're doing this you probably have your own controls anyway. In summary, the thing to remember is that it's an all or nothing shot: either respect themes and always use colors defined based on Windows widget elements, or don't use themes and never use those colors at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/153996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Passing in a text to a javascript function that may have a single quote I have a link that I dynamically create which looks something like the following: <a onclick="Edit('value from a text column here')" href="javascript:void(null);">Edit</a> with the Edit function then taking the passed in value and putting it into a Yahoo Rich Text Editor. This works well except for when there is a single quote in the text being passed. The obvious problem being that the link then looks something like: <a onclick="Edit('I'm a jelly donut')" href="javascript:void(null);">Edit</a> Any suggestions on what I can do? I'd rather not stray too far from the structure I am currently using because it is something of a standard (and maybe the standard sucks, but that's another question altogether). Note: I am using ASP as my server side language. A: You could just replace the ' with \' A: Convert quote charaters to their HTML equivalents, &quot; etc. before you insert them into the HTML. There's a long list of HTML/XML character codes on wikipedia. There may well be a function to do this for you, depending on how you're dynamically generating the code: PHP has htmlspecialchars, and though I'm not familiar with ASP etc, I'm sure there are similar routines. A: Run the text through an escape function to put a \ before the '. If you're generating the link on the server, we would need to know what server-side language you're using to give more specific advice. If you're generating the tag client-side as a string in javascript (don't do that, use document.createElement), use the String.replace method on the argument string to pick out characters that will break the syntax you're generating and replace them with escaped versions. A: I see at least three additional possibilities: JavaScript Unicode escape <a onclick="Edit('I\u0027m a jelly donut')" href="javascript:void(null);">Edit</a> as \u0027 is the javascript espace character for the quote. The others being less practical: JavaScript function <script>function getQuote() { return "'" }</script> <a onclick="Edit('I' + getQuote() + 'm a jelly donut')" href="javascript:void(null);">Edit</a> and: JavaScript global variable <script>var g_strJellyText = "I\u0027m a jelly donut"</script> <a onclick="Edit(g_strJellyText)" href="javascript:void(null);">Edit</a> But I believe you already considered theses solution (or their variants, or the HTML entity escape mentionned by Chris Johnson). Still, it's worth mentioning. A: So it seems there was more going on, most of these would probably work under most circumstances, but in the interest of posterity here's what I had to do. The information being pulled into the Rich Text Editor was in a YUI datatable and I am creating a link using the custom formatter prototype for said control. The problem with using the "Replace ' with \' " method was that I need to still view the text being displayed in the datatable the same way. The problem with using the ASP equivalent of htmlspecialchars (Server.HTMLEncode) was that it still had a problem in the javascript that was being generated from the custom formatter function. I don't know why exactly, but I did try it and it didn't work. That answer was closest to the answer that I came up with (and pushed me in the right direction) so I accepted that answer. What I did instead was used the javascript function 'escape' to pass into my edit function, and then unescape to set the inner HTML for the Rich Text Editor.
{ "language": "en", "url": "https://stackoverflow.com/questions/154004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to show article link and sub-feed link in an RSS feed? I'm working on some RSS feeds for a custom task system we have. The main feed will show a list of tasks assigned to the current user. The link attribute for each task returned points to the web page for that task. However, tasks themselves have an RSS feed for updates, and I want to be able to provide a link for that RSS feed with the main feed as well. How can I do both? The solution I'm thinking of right now is setting the article's title attribute to include an <a href="..." link to the actual article, and the it's link attribute to be a link to the feed (or vice versa). However, I'm not sure that will work well since most readers display the title as linking to the link (if that makes any sense to you). Also, is this something that's supported natively by atom? A: Make the content of each item in the original RSS feed HTML. (I believe you'll have to CDATA escape the block). Within this content put a hyperlink to the updates feed RSS. A: Why not add it to the entry summary as links?
{ "language": "en", "url": "https://stackoverflow.com/questions/154008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why won't Django auto-escape my A: You need to mark the values as | safe I think (I'm guessing that you're filling in the value from the database here(?)): {{ value|safe }} Could you post a sample of the template? Might make it easier to see what's wrong [Edit] ..or are you saying that you want it to escape the values (make them safe)? Have you tried manually escaping the field: {{ value|escape }} [Edit2] Maybe escapejs from the Django Project docs is relevent: escapejs New in Django 1.0. Escapes characters for use in JavaScript strings. This does not make the string safe for use in HTML, but does protect you from syntax errors when using templates to generate JavaScript/JSON. [Edit3] What about force_escape: {{ value|force_escape }} ...and I know it's an obvious one, but you're absolutely certain you've not got any caching going on in your browser? I've tripped over that one a few times myself ;-) A: Found the problem. The JSON string I'm using to render data to some Ext widgets is the culprit. Big thanks to Jon Cage. Answer accepted despite the problem being caused by another source.
{ "language": "en", "url": "https://stackoverflow.com/questions/154013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: .NET equivalent to Java thread groups? I'm trying to monitor the states of a group of threads in a Microsoft.NET application written in C#. I'd like to be able to also monitor any child threads spawned by the original threads. In Java, you can assign threads to a thread group, and their children will also belong to the group. Is there an equivalent in .NET? I briefly looked at ExecutionContext and LogicalCallContext, but I can't see how to find all the threads that are in a context. Raymond Chen has an article about a Win32 API method for enumerating threads, but I hope I don't have to go that low. A: You can enumerate the threads in your process using the Threads property of System.Diagnostics.Process. Note however, that the objects you get here are not of the same type as those you create to start threads yourself (i.e. are not System.Threading.Thread objects). A concept of thread groups does not exist however, AFAIK. A: They are working on something like that in their "Task" API, which is part of Parallel Extensions. A: Make it simple: Create your ThreadGroup class with a method wrapping the thread creation process. When this method is called, it adds the created thread to a Collection and there is your group.
{ "language": "en", "url": "https://stackoverflow.com/questions/154016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: In a java regex, how can I get a character class e.g. [a-z] to match a - minus sign? Pattern pattern = Pattern.compile("^[a-z]+$"); String string = "abc-def"; assertTrue( pattern.matcher(string).matches() ); // obviously fails Is it possible to have the character class match a "-" ? A: Escape the minus sign [a-z\\-] A: Inside a character class [...] a - is treated specially(as a range operator) if it's surrounded by characters on both sides. That means if you include the - at the beginning or at the end of the character class it will be treated literally(non-special). So you can use the regex: ^[a-z-]+$ or ^[-a-z]+$ Since the - that we added is being treated literally there is no need to escape it. Although it's not an error if you do it. Another (less recommended) way is to not include the - in the character class: ^(?:[a-z]|-)+$ Note that the parenthesis are not optional in this case as | has a very low precedence, so with the parenthesis: ^[a-z]|-+$ Will match a lowercase alphabet at the beginning of the string and one or more - at the end. A: I'd rephrase the "don't put it between characters" a little more concretely. Make the dash the first or last character in the character class. For example "[-a-z1-9]" matches lower-case characters, digits or dash. A: Don't put the minus sign between characters. "[a-z-]" A: This works for me Pattern p = Pattern.compile("^[a-z\\-]+$"); String line = "abc-def"; Matcher matcher = p.matcher(line); System.out.println(matcher.matches()); // true
{ "language": "en", "url": "https://stackoverflow.com/questions/154031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: How to turn on FastParse option in SSIS? The book that I purchased to help with my SSIS understanding seems to have glossed over this, and I wanted to know exactly what is the method to turn on FastParse in SSIS? A: To set fast parse (from here) * *Right-click the Flat File source or Data Conversion transformation, and then click Show Advanced Editor. *In the Advanced Editor dialog box, click the Input and Output Properties tab. *In the Inputs and Outputs pane, click the column for which you want to enable fast parse. *In the Properties window, expand the Custom Properties node, and then set the FastParse property to True. *Click OK.
{ "language": "en", "url": "https://stackoverflow.com/questions/154041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Spring-MVC Problem using @Controller on controller implementing an interface I'm using spring 2.5 and annotations to configure my spring-mvc web context. Unfortunately, I am unable to get the following to work. I'm not sure if this is a bug (seems like it) or if there is a basic misunderstanding on how the annotations and interface implementation subclassing works. For example, @Controller @RequestMapping("url-mapping-here") public class Foo { @RequestMapping(method=RequestMethod.GET) public void showForm() { ... } @RequestMapping(method=RequestMethod.POST) public String processForm() { ... } } works fine. When the context starts up, the urls this handler deals with are discovered, and everything works great. This however does not: @Controller @RequestMapping("url-mapping-here") public class Foo implements Bar { @RequestMapping(method=RequestMethod.GET) public void showForm() { ... } @RequestMapping(method=RequestMethod.POST) public String processForm() { ... } } When I try to pull up the url, I get the following nasty stack trace: javax.servlet.ServletException: No adapter for handler [com.shaneleopard.web.controller.RegistrationController@e973e3]: Does your handler implement a supported interface like Controller? org.springframework.web.servlet.DispatcherServlet.getHandlerAdapter(DispatcherServlet.java:1091) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:874) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501) javax.servlet.http.HttpServlet.service(HttpServlet.java:627) However, if I change Bar to be an abstract superclass and have Foo extend it, then it works again. @Controller @RequestMapping("url-mapping-here") public class Foo extends Bar { @RequestMapping(method=RequestMethod.GET) public void showForm() { ... } @RequestMapping(method=RequestMethod.POST) public String processForm() { ... } } This seems like a bug. The @Controller annotation should be sufficient to mark this as a controller, and I should be able to implement one or more interfaces in my controller without having to do anything else. Any ideas? A: There's no doubt that annotations and inheritance can get a little tricky, but I think that should work. Try explicitly adding the AnnotationMethodHandlerAdapter to your servlet context. http://static.springframework.org/spring/docs/2.5.x/reference/mvc.html#mvc-ann-setup If that doesn't work, a little more information would be helpful. Specifically, are the two annotated controller methods from the interface? Is Foo supposed to be RegistrationController? A: I know it is too late but i'm writing this for anyone have this problem if you are using annotation based configuration... the solution might be like this: @Configuration @ComponentScan("org.foo.controller.*") @EnableAspectJAutoProxy(proxyTargetClass=true) public class AppConfig { ...} A: What I needed to do was replace <tx:annotation-driven/> with <tx:annotation-driven proxy-target-class="true"/> This forces aspectj to use CGLIB for doing aspects instead of dynamic proxies - CGLIB doesn't lose the annotation since it extends the class, whereas dynamic proxies just expose the implemented interface. A: Ed is right, adding <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> works fine A: If you wish to use interfaces for your Spring MVC controllers then you need to move the annotations around a bit, as mentioned in the Spring docs: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping Using @RequestMapping On Interface Methods A common pitfall when working with annotated controller classes happens when applying functionality that requires creating a proxy for the controller object (e.g. @Transactional methods). Usually you will introduce an interface for the controller in order to use JDK dynamic proxies. To make this work you must move the @RequestMapping annotations to the interface as well as the mapping mechanism can only "see" the interface exposed by the proxy. Alternatively, you could activate proxy-target-class="true" in the configuration for the functionality applied to the controller (in our transaction scenario in ). Doing so indicates that CGLIB-based subclass proxies should be used instead of interface-based JDK proxies. For more information on various proxying mechanisms see Section 8.6, “Proxying mechanisms”. Unfortunately it doesn't give a concrete example of this. I have found a setup like this works: @Controller @RequestMapping(value = "/secure/exhibitor") public interface ExhibitorController { @RequestMapping(value = "/{id}") void exhibitor(@PathVariable("id") Long id); } @Controller public class ExhibitorControllerImpl implements ExhibitorController { @Secured({"ROLE_EXHIBITOR"}) @Transactional(readOnly = true) @Override public void exhibitor(final Long id) { } } So what you have here is an interface that declares the @Controller, @PathVariable and @RequestMapping annotations (the Spring MVC annotations) and then you can either put your @Transactional or @Secured annotations for instance on the concrete class. It is only the @Controller type annotations that you need to put on the interface because of the way Spring does its mappings. Note that you only need to do this if you use an interface. You don't necessarily need to do it if you are happy with CGLib proxies, but if for some reason you want to use JDK dynamic proxies, this might be the way to go. A: The true reason you need to use 'proxy-target-class="true"' is in DefaultAnnotationHandlerMapping#determineUrlsForHandler() method: though it uses ListableBeanFactory#findAnnotationOnBean for looking up a @RequestMapping annotation (and this takes care about any proxy issues), the additional lookup for @Controller annotation is done using AnnotationUtils#findAnnotation (which does not handles proxy issues)
{ "language": "en", "url": "https://stackoverflow.com/questions/154042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: How do I check for an empty/undefined/null string in JavaScript? Is there a string.Empty in JavaScript, or is it just a case of checking for ""? A: All these answers are nice. But I cannot be sure that variable is a string, doesn't contain only spaces (this is important for me), and can contain '0' (string). My version: function empty(str){ return !str || !/[^\s]+/.test(str); } empty(null); // true empty(0); // true empty(7); // false empty(""); // true empty("0"); // false empty(" "); // true Sample on jsfiddle. A: Try this: export const isEmpty = string => (!string || !string.length); A: Ignoring whitespace strings, you could use this to check for null, empty and undefined: var obj = {}; (!!obj.str) // Returns false obj.str = ""; (!!obj.str) // Returns false obj.str = null; (!!obj.str) // Returns false It is concise and it works for undefined properties, although it's not the most readable. A: There's no isEmpty() method, you have to check for the type and the length: if (typeof test === 'string' && test.length === 0){ ... The type check is needed in order to avoid runtime errors when test is undefined or null. A: I use: function empty(e) { switch (e) { case "": case 0: case "0": case null: case false: case undefined: return true; default: return false; } } empty(null) // true empty(0) // true empty(7) // false empty("") // true empty((function() { return "" })) // false A: Try this str.value.length == 0 A: You can easily add it to native String object in JavaScript and reuse it over and over... Something simple like below code can do the job for you if you want to check '' empty strings: String.prototype.isEmpty = String.prototype.isEmpty || function() { return !(!!this.length); } Otherwise if you'd like to check both '' empty string and ' ' with space, you can do that by just adding trim(), something like the code below: String.prototype.isEmpty = String.prototype.isEmpty || function() { return !(!!this.trim().length); } and you can call it this way: ''.isEmpty(); //return true 'alireza'.isEmpty(); //return false A: Performance I perform tests on macOS v10.13.6 (High Sierra) for 18 chosen solutions. Solutions works slightly different (for corner-case input data) which was presented in the snippet below. Conclusions * *the simple solutions based on !str,==,=== and length are fast for all browsers (A,B,C,G,I,J) *the solutions based on the regular expression (test,replace) and charAt are slowest for all browsers (H,L,M,P) *the solutions marked as fastest was fastest only for one test run - but in many runs it changes inside 'fast' solutions group Details In the below snippet I compare results of chosen 18 methods by use different input parameters * *"" "a" " "- empty string, string with letter and string with space *[] {} f- array, object and function *0 1 NaN Infinity - numbers *true false - Boolean *null undefined Not all tested methods support all input cases. function A(str) { let r=1; if (!str) r=0; return r; } function B(str) { let r=1; if (str == "") r=0; return r; } function C(str) { let r=1; if (str === "") r=0; return r; } function D(str) { let r=1; if(!str || 0 === str.length) r=0; return r; } function E(str) { let r=1; if(!str || /^\s*$/.test(str)) r=0; return r; } function F(str) { let r=1; if(!Boolean(str)) r=0; return r; } function G(str) { let r=1; if(! ((typeof str != 'undefined') && str) ) r=0; return r; } function H(str) { let r=1; if(!/\S/.test(str)) r=0; return r; } function I(str) { let r=1; if (!str.length) r=0; return r; } function J(str) { let r=1; if(str.length <= 0) r=0; return r; } function K(str) { let r=1; if(str.length === 0 || !str.trim()) r=0; return r; } function L(str) { let r=1; if ( str.replace(/\s/g,"") == "") r=0; return r; } function M(str) { let r=1; if((/^\s*$/).test(str)) r=0; return r; } function N(str) { let r=1; if(!str || !str.trim().length) r=0; return r; } function O(str) { let r=1; if(!str || !str.trim()) r=0; return r; } function P(str) { let r=1; if(!str.charAt(0)) r=0; return r; } function Q(str) { let r=1; if(!str || (str.trim()=='')) r=0; return r; } function R(str) { let r=1; if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "") r=0; return r; } // --- TEST --- console.log( ' "" "a" " " [] {} 0 1 NaN Infinity f true false null undefined '); let log1 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)} ${f(null)} ${f(undefined)}`); let log2 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)}`); let log3 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")}`); log1('A', A); log1('B', B); log1('C', C); log1('D', D); log1('E', E); log1('F', F); log1('G', G); log1('H', H); log2('I', I); log2('J', J); log3('K', K); log3('L', L); log3('M', M); log3('N', N); log3('O', O); log3('P', P); log3('Q', Q); log3('R', R); And then for all methods I perform speed test case str = "" for browsers Chrome v78.0.0, Safari v13.0.4, and Firefox v71.0.0 - you can run tests on your machine here A: I usually use something like: if (str == "") { //Do Something } else { //Do Something Else } A: Don't assume that the variable you check is a string. Don't assume that if this var has a length, then it's a string. The thing is: think carefully about what your app must do and can accept. Build something robust. If your method / function should only process a non empty string then test if the argument is a non empty string and don't do some 'trick'. As an example of something that will explode if you follow some advices here not carefully. var getLastChar = function (str) { if (str.length > 0) return str.charAt(str.length - 1) } getLastChar('hello') => "o" getLastChar([0,1,2,3]) => TypeError: Object [object Array] has no method 'charAt' So, I'd stick with if (myVar === '') ... A: You can use lodash: _.isEmpty(value). It covers a lot of cases like {}, '', null, undefined, etc. But it always returns true for Number type of JavaScript primitive data types like _.isEmpty(10) or _.isEmpty(Number.MAX_VALUE) both returns true. A: All the previous answers are good, but this will be even better. Use dual NOT operators (!!): if (!!str) { // Some code here } Or use type casting: if (Boolean(str)) { // Code here } Both do the same function. Typecast the variable to Boolean, where str is a variable. * *It returns false for null, undefined, 0, 000, "", false. *It returns true for all string values other than the empty string (including strings like "0" and " ") A: You should always check for the type too, since JavaScript is a duck typed language, so you may not know when and how the data changed in the middle of the process. So, here's the better solution: let undefinedStr; if (!undefinedStr) { console.log("String is undefined"); } let emptyStr = ""; if (!emptyStr) { console.log("String is empty"); } let nullStr = null; if (!nullStr) { console.log("String is null"); } A: You can able to validate following ways and understand the difference. var j = undefined; console.log((typeof j == 'undefined') ? "true":"false"); var j = null; console.log((j == null) ? "true":"false"); var j = ""; console.log((!j) ? "true":"false"); var j = "Hi"; console.log((!j) ? "true":"false"); A: Try this code: function isEmpty(strValue) { // Test whether strValue is empty if (!strValue || strValue.trim() === "" || (strValue.trim()).length === 0) { // Do something } } A: Empty string, undefined, null, ... To check for a truthy value: if (strValue) { // strValue was non-empty string, true, 42, Infinity, [], ... } To check for a falsy value: if (!strValue) { // strValue was empty string, false, 0, null, undefined, ... } Empty string (only!) To check for exactly an empty string, compare for strict equality against "" using the === operator: if (strValue === "") { // strValue was empty string } To check for not an empty string strictly, use the !== operator: if (strValue !== "") { // strValue was not an empty string } A: Very generic "All-In-One" Function (not recommended though): function is_empty(x) { return ( //don't put newline after return (typeof x == 'undefined') || (x == null) || (x == false) //same as: !x || (x.length == 0) || (x == 0) // note this line, you might not need this. || (x == "") || (x.replace(/\s/g,"") == "") || (!/[^\s]/.test(x)) || (/^\s*$/.test(x)) ); } However, I don't recommend to use that, because your target variable should be of specific type (i.e. string, or numeric, or object?), so apply the checks that are relative to that variable. A: var s; // undefined var s = ""; // "" s.length // 0 There's nothing representing an empty string in JavaScript. Do a check against either length (if you know that the var will always be a string) or against "" A: function tell() { var pass = document.getElementById('pasword').value; var plen = pass.length; // Now you can check if your string is empty as like if(plen==0) { alert('empty'); } else { alert('you entered something'); } } <input type='text' id='pasword' /> This is also a generic way to check if field is empty. A: I prefer to use not blank test instead of blank function isNotBlank(str) { return (str && /^\s*$/.test(str)); } A: The Underscore.js JavaScript library, http://underscorejs.org/, provides a very useful _.isEmpty() function for checking for empty strings and other empty objects. Reference: http://underscorejs.org/#isEmpty isEmpty _.isEmpty(object) Returns true if an enumerable object contains no values (no enumerable own-properties). For strings and array-like objects _.isEmpty checks if the length property is 0. _.isEmpty([1, 2, 3]); => false _.isEmpty({}); => true Other very useful Underscore.js functions include: * *http://underscorejs.org/#isNull _.isNull(object) *http://underscorejs.org/#isUndefined *_.isUndefined(value) *http://underscorejs.org/#has _.has(object, key) A: The following regular expression is another solution, that can be used for null, empty or undefined string. (/(null|undefined|^$)/).test(null) I added this solution, because it can be extended further to check empty or some value like as follow. The following regular expression is checking either string can be empty null undefined or it has integers only. (/(null|undefined|^$|^\d+$)/).test() A: The ultimate and shortest variant of the isBlank function: /** * Will return: * False for: for all strings with chars * True for: false, null, undefined, 0, 0.0, "", " ". * * @param str * @returns {boolean} */ function isBlank(str){ return (!!!str || /^\s*$/.test(str)); } // tests console.log("isBlank TRUE variants:"); console.log(isBlank(false)); console.log(isBlank(undefined)); console.log(isBlank(null)); console.log(isBlank(0)); console.log(isBlank(0.0)); console.log(isBlank("")); console.log(isBlank(" ")); console.log("isBlank FALSE variants:"); console.log(isBlank("0")); console.log(isBlank("0.0")); console.log(isBlank(" 0")); console.log(isBlank("0 ")); console.log(isBlank("Test string")); console.log(isBlank("true")); console.log(isBlank("false")); console.log(isBlank("null")); console.log(isBlank("undefined")); A: This is a falsy value. The first solution: const str = ""; return str || "Hello" The second solution: const str = ""; return (!!str) || "Hello"; // !!str is Boolean The third solution: const str = ""; return (+str) || "Hello"; // !!str is Boolean A: Try: if (str && str.trim().length) { //... } A: I would not worry too much about the most efficient method. Use what is most clear to your intention. For me that's usually strVar == "". As per the comment from Constantin, if strVar could some how end up containing an integer 0 value, then that would indeed be one of those intention-clarifying situations. A: It's a good idea too to check that you are not trying to pass an undefined term. function TestMe() { if((typeof str != 'undefined') && str) { alert(str); } }; TestMe(); var str = 'hello'; TestMe(); I usually run into the case where I want to do something when a string attribute for an object instance is not empty. Which is fine, except that attribute is not always present. A: You can check this using the typeof operator along with the length method. const isNonEmptyString = (value) => typeof(value) == 'string' && value.length > 0 A: Check if it's type string AND if it's not empty: const isNonEmptyString = (val) => typeof val === 'string' && !!val A: A lot of answers, and a lot of different possibilities! Without a doubt for quick and simple implementation the winner is: if (!str.length) {...} However, as many other examples are available. The best functional method to go about this, I would suggest: function empty(str) { if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "") return true; else return false; } A bit excessive, I know. A: You could also go with regular expressions: if((/^\s*$/).test(str)) { } Checks for strings that are either empty or filled with whitespace. A: * *check that var a; exist *trim out the false spaces in the value, then test for emptiness if ((a)&&(a.trim()!='')) { // if variable a is not empty do this } A: An alternative way, but I believe bdukes's answer is best. var myString = 'hello'; if(myString.charAt(0)){ alert('no empty'); } alert('empty'); A: I usually use something like this, if (!str.length) { // Do something } A: Also, in case you consider a whitespace filled string as "empty". You can test it with this regular expression: !/\S/.test(string); // Returns true if blank. A: If one needs to detect not only empty but also blank strings, I'll add to Goral's answer: function isEmpty(s){ return !s.length; } function isBlank(s){ return isEmpty(s.trim()); } A: if ((str?.trim()?.length || 0) > 0) { // str must not be any of: // undefined // null // "" // " " or just whitespace } Or in function form: const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0; const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0; A: For checking if a variable is falsey or if it has length attribute equal to zero (which for a string, means it is empty), I use: function isEmpty(str) { return (!str || str.length === 0 ); } (Note that strings aren't the only variables with a length attribute, arrays have them as well, for example.) Alternativaly, you can use the (not so) newly optional chaining and arrow functions to simplify: const isEmpty = (str) => (!str?.length); It will check the length, returning undefined in case of a nullish value, without throwing an error. In the case of an empty value, zero is falsy and the result is still valid. For checking if a variable is falsey or if the string only contains whitespace or is empty, I use: function isBlank(str) { return (!str || /^\s*$/.test(str)); } If you want, you can monkey-patch the String prototype like this: String.prototype.isEmpty = function() { // This doesn't work the same way as the isEmpty function used // in the first example, it will return true for strings containing only whitespace return (this.length === 0 || !this.trim()); }; console.log("example".isEmpty()); Note that monkey-patching built-in types are controversial, as it can break code that depends on the existing structure of built-in types, for whatever reason. A: The closest thing you can get to str.Empty (with the precondition that str is a String) is: if (!str.length) { ... A: I use a combination, and the fastest checks are first. function isBlank(pString) { if (!pString) { return true; } // Checks for a non-white space character // which I think [citation needed] is faster // than removing all the whitespace and checking // against an empty string return !/[^\s]+/.test(pString); } A: Starting with: return (!value || value == undefined || value == "" || value.length == 0); Looking at the last condition, if value == "", its length must be 0. Therefore drop it: return (!value || value == undefined || value == ""); But wait! In JavaScript, an empty string is false. Therefore, drop value == "": return (!value || value == undefined); And !undefined is true, so that check isn't needed. So we have: return (!value); And we don't need parentheses: return !value A: I have not noticed an answer that takes into account the possibility of null characters in a string. For example, if we have a null character string: var y = "\0"; // an empty string, but has a null character (y === "") // false, testing against an empty string does not work (y.length === 0) // false (y) // true, this is also not expected (y.match(/^[\s]*$/)) // false, again not wanted To test its nullness one could do something like this: String.prototype.isNull = function(){ return Boolean(this.match(/^[\0]*$/)); } ... "\0".isNull() // true It works on a null string, and on an empty string and it is accessible for all strings. In addition, it could be expanded to contain other JavaScript empty or whitespace characters (i.e. nonbreaking space, byte order mark, line/paragraph separator, etc.). A: If you need to make sure that the string is not just a bunch of empty spaces (I'm assuming this is for form validation) you need to do a replace on the spaces. if(str.replace(/\s/g,"") == ""){ } A: I did some research on what happens if you pass a non-string and non-empty/null value to a tester function. As many know, (0 == "") is true in JavaScript, but since 0 is a value and not empty or null, you may want to test for it. The following two functions return true only for undefined, null, empty/whitespace values and false for everything else, such as numbers, Boolean, objects, expressions, etc. function IsNullOrEmpty(value) { return (value == null || value === ""); } function IsNullOrWhiteSpace(value) { return (value == null || !/\S/.test(value)); } More complicated examples exists, but these are simple and give consistent results. There is no need to test for undefined, since it's included in (value == null) check. You may also mimic C# behaviour by adding them to String like this: String.IsNullOrEmpty = function (value) { ... } You do not want to put it in Strings prototype, because if the instance of the String-class is null, it will error: String.prototype.IsNullOrEmpty = function (value) { ... } var myvar = null; if (1 == 2) { myvar = "OK"; } // Could be set myvar.IsNullOrEmpty(); // Throws error I tested with the following value array. You can loop it through to test your functions if in doubt. // Helper items var MyClass = function (b) { this.a = "Hello World!"; this.b = b; }; MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } }; var z; var arr = [ // 0: Explanation for printing, 1: actual value ['undefined', undefined], ['(var) z', z], ['null', null], ['empty', ''], ['space', ' '], ['tab', '\t'], ['newline', '\n'], ['carriage return', '\r'], ['"\\r\\n"', '\r\n'], ['"\\n\\r"', '\n\r'], ['" \\t \\n "', ' \t \n '], ['" txt \\t test \\n"', ' txt \t test \n'], ['"txt"', "txt"], ['"undefined"', 'undefined'], ['"null"', 'null'], ['"0"', '0'], ['"1"', '1'], ['"1.5"', '1.5'], ['"1,5"', '1,5'], // Valid number in some locales, not in JavaScript ['comma', ','], ['dot', '.'], ['".5"', '.5'], ['0', 0], ['0.0', 0.0], ['1', 1], ['1.5', 1.5], ['NaN', NaN], ['/\S/', /\S/], ['true', true], ['false', false], ['function, returns true', function () { return true; } ], ['function, returns false', function () { return false; } ], ['function, returns null', function () { return null; } ], ['function, returns string', function () { return "test"; } ], ['function, returns undefined', function () { } ], ['MyClass', MyClass], ['new MyClass', new MyClass()], ['empty object', {}], ['non-empty object', { a: "a", match: "bogus", test: "bogus"}], ['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }], ['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }] ]; A: Meanwhile we can have one function that checks for all 'empties' like null, undefined, '', ' ', {}, []. So I just wrote this. var isEmpty = function(data) { if(typeof(data) === 'object'){ if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){ return true; }else if(!data){ return true; } return false; }else if(typeof(data) === 'string'){ if(!data.trim()){ return true; } return false; }else if(typeof(data) === 'undefined'){ return true; }else{ return false; } } Use cases and results. console.log(isEmpty()); // true console.log(isEmpty(null)); // true console.log(isEmpty('')); // true console.log(isEmpty(' ')); // true console.log(isEmpty(undefined)); // true console.log(isEmpty({})); // true console.log(isEmpty([])); // true console.log(isEmpty(0)); // false console.log(isEmpty('Hey')); // false A: I didn't see a good answer here (at least not an answer that fits for me) So I decided to answer myself: value === undefined || value === null || value === ""; You need to start checking if it's undefined. Otherwise your method can explode, and then you can check if it equals null or is equal to an empty string. You cannot have !! or only if(value) since if you check 0 it's going to give you a false answer (0 is false). With that said, wrap it up in a method like: public static isEmpty(value: any): boolean { return value === undefined || value === null || value === ""; } PS.: You don't need to check typeof, since it would explode and throw even before it enters the method A: There is a lot of useful information here, but in my opinion, one of the most important elements was not addressed. null, undefined, and "" are all falsy. When evaluating for an empty string, it's often because you need to replace it with something else. In which case, you can expect the following behavior. var a = "" var b = null var c = undefined console.log(a || "falsy string provided") // prints ->"falsy string provided" console.log(b || "falsy string provided") // prints ->"falsy string provided" console.log(c || "falsy string provided") // prints ->"falsy string provided" With that in mind, a method or function that can return whether or not a string is "", null, or undefined (an invalid string) versus a valid string is as simple as this: const validStr = (str) => str ? true : false validStr(undefined) // returns false validStr(null) // returns false validStr("") // returns false validStr("My String") // returns true A: Trimming whitespace with the null-coalescing operator: if (!str?.trim()) { // do something... } A: Here are some custom functions I use for handling this. Along with examples of how the code runs. const v1 = 0 const v2 = '4' const v2e = undefined const v2e2 = null const v3 = [1, 2, 3, 4] const v3e = [] const v4 = true const v4e = false const v5 = { test: 'value' } const v5e = {} const v6 = 'NotEmpty' const v6e = '' function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n) } function isEmpty(v, zeroIsEmpty = false) { /** * When doing a typeof check, null will always return "object" so we filter that out first * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#typeof_null */ if (v === null) { return true } if (v === true) { return false } if (typeof v === 'object') { return !Object.keys(v).length } if (isNumeric(v)) { return zeroIsEmpty ? parseFloat(v) === 0 : false } return !v || !v.length || v.length < 1 } console.log(isEmpty(v1), isEmpty(v1, true)) console.log(isEmpty(v2), isEmpty(v2e), isEmpty(v2e)) console.log(isEmpty(v3), isEmpty(v3e)) console.log(isEmpty(v4), isEmpty(v4e)) console.log(isEmpty(v5), isEmpty(v5e)) console.log(isEmpty(v6), isEmpty(v6e)) Also for reference, here's the source for Lodash isEmpty: A: To check if it is empty: var str = "Hello World!"; if(str === ''){alert("THE string str is EMPTY");} To check if it is of type string: var str = "Hello World!"; if(typeof(str) === 'string'){alert("This is a String");} A: var x =" "; var patt = /^\s*$/g; isBlank = patt.test(x); alert(isBlank); // Is it blank or not?? x = x.replace(/\s*/g, ""); // Another way of replacing blanks with "" if (x===""){ alert("ya it is blank") } A: Well, the simplest function to check this is... const checkEmpty = string => (string.trim() === "") || !string.trim(); Usage: checkEmpty(""); // returns true. checkEmpty("mystr"); // returns false. It's that dead simple. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/154059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3823" }
Q: Overriding namespaces in gSOAP I am using gSOAP as a Web Service toolkit and have generated the stub and proxy classes through soapcpp2 from multiple WSDLs all at once. Thus all the namespace bindings are in a single .nsmap file. Now the problem is that all the namespace bindings are being sent with all the method calls I make. The HTTP POST packet is unusually large and ugly. Is there a way to programatically override the namespace bindings ? A: Check soapcpp2 and its -q flag, it will help you. Other than that, the -penv flag will pack basic gSOAP-related methods within the executable, not including any service objects. Therefore the files generated with -penv can be shared across multiple namespaces, pertaining to different generated gSOAP Web Services.
{ "language": "en", "url": "https://stackoverflow.com/questions/154060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to filter a report object when saving through FileDialog in MS Access I am attempting to save an rtf file using FileDialog and would like to filter using a where clause. This is what I have: Set dlgSave = FileDialog(msoFileDialogSaveAs) With dlgSave .Title = "Provide the place to save this file" .ButtonName = "Save As..." .InitialFileName = Me.cmbPickAReportToPrint.Value & "-" & Format(Date, "mmddyy") & ".rtf" .InitialView = msoFileDialogViewDetails If .Show Then DoCmd.OutputTo acOutputReport, Me.cmbPickAReportToPrint.Value, acFormatRTF, .SelectedItems(1) End If End With Any ideas as to how I could add the where clause without otherwise changing the report? A: I've found that the easiest way to do this without touching the report code itself is to open the report in preview mode with the filter applied, and then output the report to whatever format you need. If .Show Then DoCmd.OpenReport Me.cmbPickAReportToPrint.Value, acViewPreview, , "fieldToFilterOn = 'value'" DoCmd.OutputTo acOutputReport, Me.cmbPickAReportToPrint.Value, acFormatRTF, .SelectedItems(1) End If
{ "language": "en", "url": "https://stackoverflow.com/questions/154064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using the "start" command with parameters passed to the started program I have a Virtual Machine in Virtual PC 2007. To start it from the desktop, I have the following command in a batch file: "c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc "MY-PC" -launch But that leaves a dos prompt on the host machine until the virtual machine shuts down, and I exit out of the Virtual PC console. That's annoying. So I changed my command to use the START command, instead: start "c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc MY-PC -launch But it chokes on the parameters passed into Virtual PC. START /? indicates that parameters do indeed go in that location. Has anyone used START to launch a program with multiple command-line arguments? A: You can use quotes by using the [/D"Path"] use /D only for specifying the path and not the path+program. It appears that all code on the same line that follows goes back to normal meaning you don't need to separate path and file. start /D "C:\Program Files\Internet Explorer\" IEXPLORE.EXE or: start /D "TITLE" "C:\Program Files\Internet Explorer\" IEXPLORE.EXE will start IE with default web page. start /D "TITLE" "C:\Program Files\Internet Explorer\" IEXPLORE.EXE www.bing.com starts with Bing, but does not reset your home page. /D stands for "directory" and using quotes is OK! WRONG EXAMPLE: start /D "TITLE" "C:\Program Files\Internet Explorer\IEXPLORE.EXE" gives: ERROR "The current directory is invalid." /D must only be followed by a directory path. Then space and the batchfile or program you wish to start/run Tested and works under XP but windows Vista/7/8 may need some adjustments to UAC. -Mrbios A: START has a peculiarity involving double quotes around the first parameter. If the first parameter has double quotes it uses that as the optional TITLE for the new window. I believe what you want is: start "" "c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc MY-PC -launch In other words, give it an empty title before the name of the program to fake it out. A: The spaces are DOSs/CMDs Problems so you should go to the Path via: cd "c:\program files\Microsoft Virtual PC" and then simply start VPC via: start Virtual~1.exe -pc MY-PC -launch ~1 means the first exe with "Virtual" at the beginning. So if there is a "Virtual PC.exe" and a "Virtual PC1.exe" the first would be the Virtual~1.exe and the second Virtual~2.exe and so on. Or use a VNC-Client like VirtualBox. A: None of these answers worked for me. Instead, I had to use the Call command: Call "\\Path To Program\Program.exe" <parameters> I'm not sure this actually waits for completion... the C++ Redistributable I was installing went fast enough that it didn't matter A: Instead of a batch file, you can create a shortcut on the desktop. Set the target to: "c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc "MY-PC" -launch and you're all set. Since you're not starting up a command prompt to launch it, there will be no DOS Box. A: If you want passing parameter and your .exe file in test folder of c: drive start "parameter" "C:\test\test1.exe" -pc My Name-PC -launch If you won't want passing parameter and your .exe file in test folder of c: drive start "" "C:\test\test1.exe" -pc My Name-PC -launch If you won't want passing parameter and your .exe file in test folder of H: (Any Other)drive start "" "H:\test\test1.exe" -pc My Name-PC -launch A: The answer in "peculiarity" is correct and directly answers the question. As TimF answered, since the first parameter is in quotes, it is treated as a window title. Also note that the Virtual PC options are being treated as options to the 'start' command itself, and are not valid for 'start'. This is true for all versions of Windows that have the 'start' command. This problem with 'start' treating the quoted parameter as a title is even more annoying that just the posted problem. If you run this: start "some valid command with spaces" You get a new command prompt window, with the obvious result for a window title. Even more annoying, this new window doesn't inherit customized font, colors or window size, it's just the default for cmd.exe. A: If you must use double quotation mark at any parameter, you can get error "'c:\somepath' is not recognized a an internal or external command, operable program or batch file". I suggest below solution when using double qoutation mark: https://stackoverflow.com/a/43467194/3835640 A: have you tried: start "c:\program files\Microsoft Virtual PC\Virtual PC.exe" "-pc MY-PC -launch" ? A: Put the command inside a batch file, and call that with the parameters. Also, did you try this yet? (Move end quote to encapsulate parameters) start "c:\program files\Microsoft Virtual PC\Virtual PC.exe -pc MY-PC -launch" A: Change The "Virtual PC.exe" to a name without space like "VirtualPC.exe" in the folder. When you write start "path" with "" the CMD starts a new cmd window with the path as the title. Change the name to a name without space,write this on Notepad and after this save like Name.cmd or Name.bat: CD\ CD Program Files CD Microsoft Virtual PC start VirtualPC.exe timeout 2 exit This command will redirect the CMD to the folder,start the VirualPC.exe,wait 2 seconds and exit. A: /b parameter start /b "" "c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc "MY-PC" -launch
{ "language": "en", "url": "https://stackoverflow.com/questions/154075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "255" }
Q: Why do my files need dos2unix? only in eclipse though When I open a file in eclipse it shows with the improper line spacing showing an extra line break between every line. When I open the file with notepad or wordpad it doesn't show these extra line breaks that only eclipse shows. How do I get eclipse to read these files like notepad and wordpad without those line breaks? -edit: I don't have this problem with all files but only a select few where I have made local changes > uploaded them to our sun station > then pulled those files back to my local workstation for future modifications. A: Eclipse should have a File -> Convert Line Delimiters To... option that may correct this for you. (If it doesn't work on your file, this article may help.) Really, though, you should have your file transfer program treat your source files as ascii instead of binary. Then your line ending problem should be moot. A: It's possible that the server (or something in-between) is replacing all your CR+LF with CR LF (separate)? Try specifically setting the Text File Encoding (Window->Preferences->General->Workspace), or alternatively use File->Convert Line Delimiters To->Windows every time you get the latest version (I know, not ideal). A: It turns out that the problem was solved by doing my ftp in binary only, and setting the Eclipse encoding to US-ASCII. I don't fully understand why this fixed the problem but it worked. Thanks for the 2 answers they both lead me to my solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/154078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the formula for alpha blending for a number of pixels? I have a number of RGBA pixels, each of them has an alpha component. So I have a list of pixels: (p0 p1 p2 p3 p4 ... pn) where p_0_ is the front pixel and p_n_ is the farthest (at the back). The last (or any) pixel is not necessary opaque, so the resulting blended pixel can be somehow transparent also. I'm blending from the beginning of the list to the end, not vice-versa (yes, it is raytracing). So if the result at any moment becomes opaque enough I can stop with correct enough result. I'll apply the blending algorithm in this way: ((((p0 @ p1) @ p2) @ p3) ... ) Can anyone suggest me a correct blending formula not only for R, G and B, but for A component also? UPD: I wonder how is it possible that for determined process of blending colors we can have many formulas? Is it some kind of aproximation? This looks crazy, as for me: formulas are not so different that we really gain efficiency or optimization. Can anyone clarify this? A: There are various possible ways of doing this, depending on how the RGBA values actually represent the properties of the materials. Here's a possible algorithm. Start with final pixel colours lightr=lightg=lightb=0, lightleft=1; For each r,g,b,a pixel encountered evaluate: lightr += lightleft*r*(1-a) lightg += lightleft*g*(1-a) lightb += lightleft*b*(1-a) lightleft *= 1-a; (The RGBA values are normalised between 0 and 1, and I'm assuming that a=1 means opaque, a=0 means wholly transparent) If the first pixel encountered is blue with opacity 50%, then 50% of the available colour is set to blue, and the rest unknown. If a red pixel with opacity 50% is next, then 25% of the remaining light is set to red, so the pixel has 50% blue, 25% red. If a green pixel with opacity 60% is next, then the pixel is 50% blue, 25% red, 15% green, with 10% of the light remaining. The physical materials that correspond to this function are light-emitting but partially opaque materials: thus, a pixel in the middle of the stack can never darken the final colour: it can only prevent light behind it from increasing the final colour (by being black and fully opaque). A: Alpha-blending is one of those topics that has more depth than you might think. It depends on what the alpha value means in your system, and if you guess wrong, then you'll end up with results that look kind of okay, but that display weird artifacts. Check out Porter and Duff's classic paper "Compositing Digital Images" for a great, readable discussion and all the formulas. You probably want the "over" operator. It sounds like you're doing something closer to volume rendering. For a formula and references, see the Graphics FAQ, question 5.16 "How do I perform volume rendering?".
{ "language": "en", "url": "https://stackoverflow.com/questions/154079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Mute Windows Volume using C# Anyone know how to programmatically mute the Windows XP Volume using C#? A: What you can use for Windows Vista/7 and probably 8 too: You can use NAudio. Download the latest version. Extract the DLLs and reference the DLL NAudio in your C# project. Then add the following code to iterate through all available audio devices and mute it if possible. try { //Instantiate an Enumerator to find audio devices NAudio.CoreAudioApi.MMDeviceEnumerator MMDE = new NAudio.CoreAudioApi.MMDeviceEnumerator(); //Get all the devices, no matter what condition or status NAudio.CoreAudioApi.MMDeviceCollection DevCol = MMDE.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.All, NAudio.CoreAudioApi.DeviceState.All); //Loop through all devices foreach (NAudio.CoreAudioApi.MMDevice dev in DevCol) { try { //Show us the human understandable name of the device System.Diagnostics.Debug.Print(dev.FriendlyName); //Mute it dev.AudioEndpointVolume.Mute = true; } catch (Exception ex) { //Do something with exception when an audio endpoint could not be muted } } } catch (Exception ex) { //When something happend that prevent us to iterate through the devices } A: See How to programmatically mute the Windows XP Volume using C#? void SetPlayerMute(int playerMixerNo, bool value) { Mixer mx = new Mixer(); mx.MixerNo = playerMixerNo; DestinationLine dl = mx.GetDestination(Mixer.Playback); if (dl != null) { foreach (MixerControl ctrl in dl.Controls) { if (ctrl is MixerMuteControl) { ((MixerMuteControl)ctrl).Value = (value) ? 1 : 0; break; } } } } A: Declare this for P/Invoke: private const int APPCOMMAND_VOLUME_MUTE = 0x80000; private const int WM_APPCOMMAND = 0x319; [DllImport("user32.dll")] public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); And then use this line to mute/unmute the sound. SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr) APPCOMMAND_VOLUME_MUTE); A: This is a slightly improved version of Mike de Klerks answer that doesn't require "on error resume next" code. Step 1: Add the NAudio NuGet-package to your project (https://www.nuget.org/packages/NAudio/) Step 2: Use this code: using (var enumerator = new NAudio.CoreAudioApi.MMDeviceEnumerator()) { foreach (var device in enumerator.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.Render, NAudio.CoreAudioApi.DeviceState.Active)) { if (device.AudioEndpointVolume?.HardwareSupport.HasFlag(NAudio.CoreAudioApi.EEndpointHardwareSupport.Mute) == true) { Console.WriteLine(device.FriendlyName); device.AudioEndpointVolume.Mute = false; } } } A: CoreAudioDevice defaultPlaybackDevice = new CoreAudioController().DefaultPlaybackDevice; if (!defaultPlaybackDevice.IsMuted) defaultPlaybackDevice.ToggleMute();
{ "language": "en", "url": "https://stackoverflow.com/questions/154089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: What's in your .emacs? I've switched computers a few times recently, and somewhere along the way I lost my .emacs. I'm trying to build it up again, but while I'm at it, I thought I'd pick up other good configurations that other people use. So, if you use Emacs, what's in your .emacs? Mine is pretty barren right now, containing only: * *Global font-lock-mode! (global-font-lock-mode 1) *My personal preferences with respect to indentation, tabs, and spaces. *Use cperl-mode instead of perl-mode. *A shortcut for compilation. What do you think is useful? A: This is not the whole kit and kaboodle, but it is some of the more useful snippets I've gathered: (defadvice show-paren-function (after show-matching-paren-offscreen activate) "If the matching paren is offscreen, show the matching line in the echo area. Has no effect if the character before point is not of the syntax class ')'." (interactive) (let ((matching-text nil)) ;; Only call `blink-matching-open' if the character before point ;; is a close parentheses type character. Otherwise, there's not ;; really any point, and `blink-matching-open' would just echo ;; "Mismatched parentheses", which gets really annoying. (if (char-equal (char-syntax (char-before (point))) ?\)) (setq matching-text (blink-matching-open))) (if (not (null matching-text)) (message matching-text)))) ;;;;;;;;;;;;;;; ;; UTF-8 ;;;;;;;;;;;;;;;;;;;; ;; set up unicode (prefer-coding-system 'utf-8) (set-default-coding-systems 'utf-8) (set-terminal-coding-system 'utf-8) (set-keyboard-coding-system 'utf-8) ;; This from a japanese individual. I hope it works. (setq default-buffer-file-coding-system 'utf-8) ;; From Emacs wiki (setq x-select-request-type '(UTF8_STRING COMPOUND_TEXT TEXT STRING)) ;; Wwindows clipboard is UTF-16LE (set-clipboard-coding-system 'utf-16le-dos) (defun jonnay-timestamp () "Spit out the current time" (interactive) (insert (format-time-string "%Y-%m-%d"))) (defun jonnay-sign () "spit out my name, email and the current time" (interactive) (insert "-- Jonathan Arkell (jonathana@criticalmass.com)") (jonnay-timestamp)) ;; Cygwin requires some seriosu setting up to work the way i likes it (message "Setting up Cygwin...") (let* ((cygwin-root "c:") (cygwin-bin (concat cygwin-root "/bin")) (gambit-bin "/usr/local/Gambit-C/4.0b22/bin/") (snow-bin "/usr/local/snow/current/bin") (mysql-bin "/wamp/bin/mysql/mysql5.0.51a/bin/")) (setenv "PATH" (concat cygwin-bin ";" ; snow-bin ";" gambit-bin ";" mysql-bin ";" ".;") (getenv "PATH")) (setq exec-path (cons cygwin-bin exec-path))) (setq shell-file-name "bash") (setq explicit-shell-file-name "bash") (require 'cygwin-mount) (cygwin-mount-activate) (message "Setting up Cygwin...Done") ; Completion isn't perfect, but close (defun my-shell-setup () "For Cygwin bash under Emacs 20+" (setq comint-scroll-show-maximum-output 'this) (setq comint-completion-addsuffix t) (setq comint-eol-on-send t) (setq w32-quote-process-args ?\") (make-variable-buffer-local 'comint-completion-addsuffix)) (setq shell-mode-hook 'my-shell-setup) (add-hook 'emacs-startup-hook 'cygwin-shell) ; Change how home key works (global-set-key [home] 'beginning-or-indentation) (substitute-key-definition 'beginning-of-line 'beginning-or-indentation global-map) (defun yank-and-down () "Yank the text and go down a line." (interactive) (yank) (exchange-point-and-mark) (next-line)) (defun kill-syntax (&optional arg) "Kill ARG sets of syntax characters after point." (interactive "p") (let ((arg (or arg 1)) (inc (if (and arg (< arg 0)) 1 -1)) (opoint (point))) (while (not (= arg 0)) (if (> arg 0) (skip-syntax-forward (string (char-syntax (char-after)))) (skip-syntax-backward (string (char-syntax (char-before))))) (setq arg (+ arg inc))) (kill-region opoint (point)))) (defun kill-syntax-backward (&optional arg) "Kill ARG sets of syntax characters preceding point." (interactive "p") (kill-syntax (- 0 (or arg 1)))) (global-set-key [(control shift y)] 'yank-and-down) (global-set-key [(shift backspace)] 'kill-syntax-backward) (global-set-key [(shift delete)] 'kill-syntax) (defun insert-file-name (arg filename) "Insert name of file FILENAME into buffer after point. Set mark after the inserted text. Prefixed with \\[universal-argument], expand the file name to its fully canocalized path. See `expand-file-name'." ;; Based on insert-file in Emacs -- ashawley 2008-09-26 (interactive "*P\nfInsert file name: ") (if arg (insert (expand-file-name filename)) (insert filename))) (defun kill-ring-save-filename () "Copy the current filename to the kill ring" (interactive) (kill-new (buffer-file-name))) (defun insert-file-name () "Insert the name of the current file." (interactive) (insert (buffer-file-name))) (defun insert-directory-name () "Insert the name of the current directory" (interactive) (insert (file-name-directory (buffer-file-name)))) (defun jonnay-toggle-debug () "Toggle debugging by toggling icicles, and debug on error" (interactive) (toggle-debug-on-error) (icicle-mode)) (defvar programming-modes '(emacs-lisp-mode scheme-mode lisp-mode c-mode c++-mode objc-mode latex-mode plain-tex-mode java-mode php-mode css-mode js2-mode nxml-mode nxhtml-mode) "List of modes related to programming") ; Text-mate style indenting (defadvice yank (after indent-region activate) (if (member major-mode programming-modes) (indent-region (region-beginning) (region-end) nil))) A: I have a lot of others that have already been mentioned, but these are absolutely necessary in my opinion: (transient-mark-mode 1) ; makes the region visible (line-number-mode 1) ; makes the line number show up (column-number-mode 1) ; makes the column number show up A: You can look here: http://www.dotemacs.de/ And my .emacs is pretty long to put it here as well, so it will make the answer not too readable. Anyway, if you wish I can sent it to you. Also I would recomend you to read this: http://steve.yegge.googlepages.com/my-dot-emacs-file A: Here are some key mappings that I've become dependent upon: (global-set-key [(control \,)] 'goto-line) (global-set-key [(control \.)] 'call-last-kbd-macro) (global-set-key [(control tab)] 'indent-region) (global-set-key [(control j)] 'join-line) (global-set-key [f1] 'man) (global-set-key [f2] 'igrep-find) (global-set-key [f3] 'isearch-forward) (global-set-key [f4] 'next-error) (global-set-key [f5] 'gdb) (global-set-key [f6] 'compile) (global-set-key [f7] 'recompile) (global-set-key [f8] 'shell) (global-set-key [f9] 'find-next-matching-tag) (global-set-key [f11] 'list-buffers) (global-set-key [f12] 'shell) Some other miscellaneous stuff, mostly for C++ development: ;; Use C++ mode for .h files (instead of plain-old C mode) (setq auto-mode-alist (cons '("\\.h$" . c++-mode) auto-mode-alist)) ;; Use python-mode for SCons files (setq auto-mode-alist (cons '("SConstruct" . python-mode) auto-mode-alist)) (setq auto-mode-alist (cons '("SConscript" . python-mode) auto-mode-alist)) ;; Parse CppUnit failure reports in compilation-mode (require 'compile) (setq compilation-error-regexp-alist (cons '("\\(!!!FAILURES!!!\nTest Results:\nRun:[^\n]*\n\n\n\\)?\\([0-9]+\\)) test: \\([^(]+\\)(F) line: \\([0-9]+\\) \\([^ \n]+\\)" 5 4) compilation-error-regexp-alist)) ;; Enable cmake-mode from http://www.cmake.org/Wiki/CMake_Emacs_mode_patch_for_comment_formatting (require 'cmake-mode) (setq auto-mode-alist (append '(("CMakeLists\\.txt\\'" . cmake-mode) ("\\.cmake\\'" . cmake-mode)) auto-mode-alist)) ;; "M-x reload-buffer" will revert-buffer without requiring confirmation (defun reload-buffer () "revert-buffer without confirmation" (interactive) (revert-buffer t t)) A: To refresh the webpage you're editing from within Emacs (defun moz-connect() (interactive) (make-comint "moz-buffer" (cons "127.0.0.1" "4242")) (global-set-key "\C-x\C-g" '(lambda () (interactive) (save-buffer) (comint-send-string "*moz-buffer*" "this.BrowserReload()\n")))) Used in combination with http://hyperstruct.net/projects/mozlab A: You can find my configuration (both in html & in tar'ed archive) on my site. It contains lot of settings for different modes A: Use the ultimate dotfiles site. Add your '.emacs' here. Read the '.emacs' of others. A: This block is the most important for me: (setq locale-coding-system 'utf-8) (set-terminal-coding-system 'utf-8) (set-keyboard-coding-system 'utf-8) (set-selection-coding-system 'utf-8) (prefer-coding-system 'utf-8) I've never been clear on the difference between those, though. Cargo cult, I guess... A: I try to keep my .emacs organized. The configuration will always be a work in progress, but I'm starting to be satisfied with the overall structure. All stuff is under ~/.elisp, a directory that is under version control (I use git, if that's of interest). ~/.emacs simply points to ~/.elisp/dotemacs which itself just loads ~/.elisp/cfg/init. That file in turn imports various configuration files via require. This means that the configuration files need to behave like modes: they import stuff they depend on and they provide themselves at the end of the file, e.g. (provide 'my-ibuffer-cfg). I prefix all identifiers that are defined in my configuration with my-. I organize the configuration in respect to modes/subjects/tasks, not by their technical implications, e.g. I don't have a separate config file in which all keybindings or faces are defined. My init.el defines the following hook to make sure that Emacs recompiles configuration files whenever saved (compiled Elisp loads a lot faster but I don't want to do this step manually): ;; byte compile config file if changed (add-hook 'after-save-hook '(lambda () (when (string-match (concat (expand-file-name "~/.elisp/cfg/") ".*\.el$") buffer-file-name) (byte-compile-file buffer-file-name)))) This is the directory structure for ~/.elisp: ~/.elisp/todo.org: Org-mode file in which I keep track of stuff that still needs to be done (+ wish list items). ~/.elisp/dotemacs: Symlink target for ~/.emacs, loads ~/.elisp/cfg/init. ~/.elisp/cfg: My own configuration files. ~/.elisp/modes: Modes that consist only of a single file. ~/.elisp/packages: Sophisticated modes with lisp, documentation and probably resource files. I use GNU Emacs, that version does not have real support for packages. Therefore I organize them manually, usually like this: ~/.elisp/packages/foobar-0.1.3 is the root directory for the package. Subdirectory lisp holds all the lisp files and info is where the documentation goes. ~/.elisp/packages/foobar is a symlink that points to the currently used version of the package so that I don't need to change my configuration files when I update something. For some packages I keep an ~/.elisp/packages/foobar.installation file around in which I keep notes about the installation process. For performance reasons I compile all elisp files in newly installed packages, should this not be the case by default. A: Here's a couple of my own stuff: Inserts date in ISO 8601 format: (defun insertdate () (interactive) (insert (format-time-string "%Y-%m-%d"))) (global-set-key [(f5)] 'insertdate) For C++ programmers, creates a class skeleton (class's name will be the same as the file name without extension): (defun createclass () (interactive) (setq classname (file-name-sans-extension (file-name-nondirectory buffer-file-name))) (insert "/** * " classname".h * * Author: Your Mom * Modified: " (format-time-string "%Y-%m-%d") " * Licence: GNU GPL */ #ifndef "(upcase classname)" #define "(upcase classname)" class " classname " { public: "classname"(); ~"classname"(); private: }; #endif ")) Automatically create closing parentheses: (setq skeleton-pair t) (setq skeleton-pair-on-word t) (global-set-key (kbd "[") 'skeleton-pair-insert-maybe) (global-set-key (kbd "(") 'skeleton-pair-insert-maybe) (global-set-key (kbd "{") 'skeleton-pair-insert-maybe) (global-set-key (kbd "<") 'skeleton-pair-insert-maybe) A: i use paredit for easy (e)lisp handling and ido-mode minibuffer completions. A: It's hard to answer this question, because everyone uses Emacs for very different purposes. Further more, a better practice may be to KISS your dotemacs. Since the Easy Customization Interface is widely supported amongst Emacs' modes, you should store all your customization in your custom-file (which may be a separate place in your dotemacs), and for the dotemacs, put in it only load path settings, package requires, hooks, and key bindings. Once you start using Emacs Starter Kit, a whole useful bunch of settings may removed from your dotemacs, too. A: See EmacsWiki's DotEmacs category. It provides lots of links to pages addressing this question. A: My favorite snippet. The ultimate in Emacs eye candy: ;; real lisp hackers use the lambda character ;; courtesy of stefan monnier on c.l.l (defun sm-lambda-mode-hook () (font-lock-add-keywords nil `(("\\<lambda\\>" (0 (progn (compose-region (match-beginning 0) (match-end 0) ,(make-char 'greek-iso8859-7 107)) nil)))))) (add-hook 'emacs-lisp-mode-hook 'sm-lambda-mode-hook) (add-hook 'lisp-interactive-mode-hook 'sm-lamba-mode-hook) (add-hook 'scheme-mode-hook 'sm-lambda-mode-hook) So you see i.e. the following when editing lisp/scheme: (global-set-key "^Cr" '(λ () (interactive) (revert-buffer t t nil))) A: I have this to change yes or no prompt to y or n prompts: (fset 'yes-or-no-p 'y-or-n-p) I have these to start Emacs without so much "fanfare" which I got from this question. (setq inhibit-startup-echo-area-message t) (setq inhibit-startup-message t) And Steve Yegge's function to rename a file that you're editing along with its corresponding buffer: (defun rename-file-and-buffer (new-name) "Renames both current buffer and file it's visiting to NEW-NAME." (interactive "sNew name: ") (let ((name (buffer-name)) (filename (buffer-file-name))) (if (not filename) (message "Buffer '%s' is not visiting a file!" name) (if (get-buffer new-name) (message "A buffer named '%s' already exists!" new-name) (progn (rename-file name new-name 1) (rename-buffer new-name) (set-visited-file-name new-name) (set-buffer-modified-p nil)))))) A: One thing that can prove very useful: Before it gets too big, try to split it into multiple files for various tasks: My .emacs just sets my load-path and the loads a bunch of files - I've got all my mode-specific settings in mode-configs.el, keybindings in keys.el, et cetera A: My .emacs is only 127 lines, here are the most useful little snippets: ;; keep backup files neatly out of the way in .~/ (setq backup-directory-alist '(("." . ".~"))) This makes the *~ files which I find clutter up the directory go into a special directory, in this case .~ ;; uniquify changes conflicting buffer names from file<2> etc (require 'uniquify) (setq uniquify-buffer-name-style 'reverse) (setq uniquify-separator "/") (setq uniquify-after-kill-buffer-p t) ; rename after killing uniquified (setq uniquify-ignore-buffers-re "^\\*") ; don't muck with special buffers This sets up uniquify which changes those ugly file<2> etc. buffer names you get when multiple files have the same name into a much neater unambiguous name using as much of the whole path of the file as it has to. That's about it... the rest is pretty standard stuff that I'm sure everyone knows about. A: (put 'erase-buffer 'disabled nil) (put 'downcase-region 'disabled nil) (set-variable 'visible-bell t) (set-variable 'tool-bar-mode nil) (set-variable 'menu-bar-mode nil) (setq load-path (cons (expand-file-name "/usr/share/doc/git-core/contrib/emacs") load-path)) (require 'vc-git) (when (featurep 'vc-git) (add-to-list 'vc-handled-backends 'git)) (require 'git) (autoload 'git-blame-mode "git-blame" "Minor mode for incremental blame for Git." t) A: I set up some handy shortcuts to web pages and searches using webjump (require 'webjump) (global-set-key [f2] 'webjump) (setq webjump-sites (append '( ("Reddit Search" . [simple-query "www.reddit.com" "http://www.reddit.com/search?q=" ""]) ("Google Image Search" . [simple-query "images.google.com" "images.google.com/images?hl=en&q=" ""]) ("Flickr Search" . [simple-query "www.flickr.com" "flickr.com/search/?q=" ""]) ("Astar algorithm" . "http://www.heyes-jones.com/astar") ) webjump-sample-sites)) Blog post about how this works here http://justinsboringpage.blogspot.com/2009/02/search-reddit-flickr-and-google-from.html Also I recommend these: (setq visible-bell t) ; no beeping (setq transient-mark-mode t) ; visually show region (setq line-number-mode t) ; show line numbers (setq global-font-lock-mode 1) ; everything should use fonts (setq font-lock-maximum-decoration t) Also I get rid of some of the superfluous gui stuff (if (fboundp 'scroll-bar-mode) (scroll-bar-mode -1)) (if (fboundp 'tool-bar-mode) (tool-bar-mode -1)) (if (fboundp 'menu-bar-mode) (menu-bar-mode -1))) A: One line to amend the load path One line to load my init library One line to load my emacs init files Of course, the "emacs init files" are quite numerous, one per specific thing, loaded in a deterministic order. A: emacs-starter-kit as a base, then I've added.. vimpulse.el, whitespace.el, yasnippet, textmate.el and newsticker.el. In my ~/.emacs.d/$USERNAME.el (dbr.el) file: (add-to-list 'load-path (concat dotfiles-dir "/vendor/")) ;; Snippets (add-to-list 'load-path "~/.emacs.d/vendor/yasnippet/") (require 'yasnippet) (yas/initialize) (yas/load-directory "~/.emacs.d/vendor/yasnippet/snippets") ;; TextMate module (require 'textmate) (textmate-mode 'on) ;; Whitespace module (require 'whitespace) (add-hook 'ruby-mode-hook 'whitespace-mode) (add-hook 'python-mode-hook 'whitespace-mode) ;; Misc (flyspell-mode 'on) (setq viper-mode t) (require 'viper) (require 'vimpulse) ;; IM (eval-after-load 'rcirc '(require 'rcirc-color)) (setq rcirc-default-nick "_dbr") (setq rcirc-default-user-name "_dbr") (setq rcirc-default-user-full-name "_dbr") (require 'jabber) ;;; Google Talk account (custom-set-variables '(jabber-connection-type (quote ssl)) '(jabber-network-server "talk.google.com") '(jabber-port 5223) '(jabber-server "mysite.tld") '(jabber-username "myusername")) ;; Theme (color-theme-zenburn) ;; Key bindings (global-set-key (kbd "M-z") 'undo) (global-set-key (kbd "M-s") 'save-buffer) (global-set-key (kbd "M-S-z") 'redo) A: Always save my config in svn http://my-trac.assembla.com/ez-conf/browser/emacs.d A: After reading this, I figured it would be good to have a simple site just for the best .emacs modifications. Feel free to post and vote on them here: http://dotemacs.slinkset.com/ A: For Scala coders ;; Load the ensime lisp code... http://github.com/aemoncannon/ensime (add-to-list 'load-path "ENSIME_ROOT/elisp/") (require 'ensime) ;; This step causes the ensime-mode to be started whenever ;; scala-mode is started for a buffer. You may have to customize this step ;; if you're not using the standard scala mode. (add-hook 'scala-mode-hook 'ensime-scala-mode-hook) ;; MINI HOWTO: ;; Open .scala file. M-x ensime (once per project) A: https://b7j0c.org/stuff/dotemacs.html A: I'm new to emacs, in my .emacs file there are * *indentation configuration *color theme *php mode, coffee mode and js2 mode *ido mode A: FWIW, my .emacs is here: http://svn.red-bean.com/repos/kfogel/trunk/.emacs A: lots of stuff: https://github.com/tavisrudd/emacs.d el-get has made managing it and dependencies a lot easier: https://github.com/tavisrudd/emacs.d/blob/master/dss-init-el-get.el A: My emacs configuration has grown up pretty big over the years and I have lot of useful stuff for me there but if I have two functions it probably would have been those ones. Define C-x UP and C-x DOWN to move the current line or down keeping the cursor at the right place : ;Down/UP the current line (global-set-key '[(control x) (up)] 'my-up-line) (global-set-key '[(control x) (down)] 'my-down-line) (defun my-down-line() (interactive) (let ((col (current-column))) (forward-line 1) (transpose-lines 1) (forward-line -1) (forward-char col) ) ) (defun my-up-line() (interactive) (let ((col (current-column))) (transpose-lines 1) (forward-line -2) (forward-char col) ) )
{ "language": "en", "url": "https://stackoverflow.com/questions/154097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "53" }
Q: Sharing application preferences across multiple projects We have a fairly large .NET solution with multiple executable projects (winforms and command line programs). Currently each of these projects has its own app.config that contains connection strings, mail server settings and the like. As you can imagine it's not that convenient to make a change in every app.config file whenever a particular setting needs to be updated. What do you reckon is the best practice for centralized management of these settings? So far I've thought about two different approaches. The first is using a custom class (or classes) that contains the settings and is serialized into and deserialized from XML. The second approach is defining an app.config file only for a single project and using ConfigurationManager.OpenExeConfiguration() to access it. A: Create the App.config on your startup project and link statically to it on the other projects. You can link statically by going to Add->Existing Item, and when clicking the Add button on the File Browser Window, there is a small down arrow on the Add button. Click there and the "Add as link" option will be shown. That will place the same App.Config on both projects, with only one actual file. If your projects have different App.Config with only 'some' settings that are the same, consider checking the file parameter; I mean, you can have more than one App.Config in a project: http://weblogs.asp.net/pwilson/archive/2003/04/09/5261.aspx Just create a central common.config file and point to it. A: Use the ConfigSource directive to have all of the settings loaded from a central file with the shared values. A: Personally I would advise against introducing a needless dependency on a .config file from another assembly. Using a custom class with serializing sounds cleaner in this scenario, but you expose yourself to potential versioning problems and you lose the potential advantages offered by app.config (section handlers, etc.).
{ "language": "en", "url": "https://stackoverflow.com/questions/154101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Custom Compiler Warnings When using the ObsoleteAtribute in .Net it gives you compiler warnings telling you that the object/method/property is obsolete and somthing else should be used. I'm currently working on a project that requires a lot of refactoring an ex-employees code. I want to write a custom attribute that I can use to mark methods or properties that will generate compiler warnings that give messages that I write. Something like this [MyAttribute("This code sux and should be looked at")] public void DoEverything() { } <MyAttribute("This code sux and should be looked at")> Public Sub DoEverything() End Sub I want this to generate a compiler warning that says, "This code sux and should be looked at". I know how to create a custom attribute, the question is how do I cause it to generate compiler warnings in visual studio. A: In VS 2008 (+sp1) #warnings don't show properly in Error List after Clean Soultion & Rebuild Solution, no all of them. Some Warnings are showed in the Error List only after I open particular class file. So I was forced to use custom attribute: [Obsolete("Mapping ToDo")] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] public class MappingToDo : System.Attribute { public string Comment = ""; public MappingToDo(string comment) { Comment = comment; } public MappingToDo() {} } So when I flag some code with it [MappingToDo("Some comment")] public class MembershipHour : Entity { // ..... } It produces warnings like this: Namespace.MappingToDo is obsolete: 'Mapping ToDo'. I can't change the text of the warning, 'Some comment' is not showed it Error List. But it will jump to proper place in file. So if you need to vary such warning messages, create various attributes. A: In some compilers you can use #warning to issue a warning: #warning "Do not use ABC, which is deprecated. Use XYZ instead." In Microsoft compilers, you can typically use the message pragma: #pragma message ( "text" ) You mentioned .Net, but didn't specify whether you were programming with C/C++ or C#. If you're programming in C#, than you should know that C# supports the #warning format. A: We're currently in the middle of a lot of refactoring where we couldn't fix everything right away. We just use the #warning preproc command where we need to go back and look at code. It shows up in the compiler output. I don't think you can put it on a method, but you could put it just inside the method, and it's still easy to find. public void DoEverything() { #warning "This code sucks" } A: Update This is now possible with Roslyn (Visual Studio 2015). You can build a code analyzer to check for a custom attribute Original outdated answer: I don't believe it's possible. ObsoleteAttribute is treated specially by the compiler and is defined in the C# standard. Why on earth is ObsoleteAttribute not acceptable? It seems to me like this is precisely the situation it was designed for, and achieves precisely what you require! Also note that Visual Studio picks up the warnings generated by ObsoleteAttribute on the fly too, which is very useful. Don't mean to be unhelpful, just wondering why you're not keen on using it... Unfortunately ObsoleteAttribute is sealed (probably partly due to the special treatment) hence you can't subclass your own attribute from it. From the C# standard:- The attribute Obsolete is used to mark types and members of types that should no longer be used. If a program uses a type or member that is decorated with the Obsolete attribute, the compiler issues a warning or an error. Specifically, the compiler issues a warning if no error parameter is provided, or if the error parameter is provided and has the value false. The compiler issues an error if the error parameter is specified and has the value true. Doesn't that sum up your needs?... you're not going to do better than that I don't think. A: Here is the Roslyn Implementation, so you can create your own attributes that give warnings or errors on the fly. I've create an attribute Type Called IdeMessage which will be the attribute which generates warnings: [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)] public class IDEMessageAttribute : Attribute { public string Message; public IDEMessageAttribute(string message); } In order to do this you need to install the Roslyn SDK first and start a new VSIX project with analyzer. I've omitted some of the less relevant piece like the messages, you can figure out how to do that. In your analyzer you do this public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzerInvocation, SyntaxKind.InvocationExpression); } private static void AnalyzerInvocation(SyntaxNodeAnalysisContext context) { var invocation = (InvocationExpressionSyntax)context.Node; var methodDeclaration = (context.SemanticModel.GetSymbolInfo(invocation, context.CancellationToken).Symbol as IMethodSymbol); //There are several reason why this may be null e.g invoking a delegate if (null == methodDeclaration) { return; } var methodAttributes = methodDeclaration.GetAttributes(); var attributeData = methodAttributes.FirstOrDefault(attr => IsIDEMessageAttribute(context.SemanticModel, attr, typeof(IDEMessageAttribute))); if(null == attributeData) { return; } var message = GetMessage(attributeData); var diagnostic = Diagnostic.Create(Rule, invocation.GetLocation(), methodDeclaration.Name, message); context.ReportDiagnostic(diagnostic); } static bool IsIDEMessageAttribute(SemanticModel semanticModel, AttributeData attribute, Type desiredAttributeType) { var desiredTypeNamedSymbol = semanticModel.Compilation.GetTypeByMetadataName(desiredAttributeType.FullName); var result = attribute.AttributeClass.Equals(desiredTypeNamedSymbol); return result; } static string GetMessage(AttributeData attribute) { if (attribute.ConstructorArguments.Length < 1) { return "This method is obsolete"; } return (attribute.ConstructorArguments[0].Value as string); } There are no CodeFixProvider for this you can remove it from the solution. A: I don't think you can. As far as I know support for ObsoleteAttribute is essentially hardcoded into the C# compiler; you can't do anything similar directly. What you might be able to do is use an MSBuild task (or a post-build event) that executes a custom tool against the just-compiled assembly. The custom tool would reflect over all types/methods in the assembly and consume your custom attribute, at which point it could print to System.Console's default or error TextWriters. A: Looking at the source for ObsoleteAttribute, it doesn't look like it's doing anything special to generate a compiler warning, so I would tend to go with @technophile and say that it is hard-coded into the compiler. Is there a reason you don't want to just use ObsoleteAttribute to generate your warning messages? A: What you are trying to do is a misuse of attributes. Instead use the Visual Studio Task List. You can enter a comment in your code like this: //TODO: This code sux and should be looked at public class SuckyClass(){ //TODO: Do something really sucky here! } Then open View / Task List from the menu. The task list has two categories, user tasks and Comments. Switch to Comments and you will see all of your //Todo:'s there. Double clicking on a TODO will jump to the comment in your code. Al A: This is worth a try. You can't extend Obsolete, because it's final, but maybe you can create your own attribute, and mark that class as obsolete like this: [Obsolete("Should be refactored")] public class MustRefactor: System.Attribute{} Then when you mark your methods with the "MustRefactor" attribute, the compile warnings will show. It generates a compile time warning, but the error message looks funny, you should see it for yourself and choose. This is very close to what you wanted to achieve. UPDATE: With this code It generates a warning (not very nice, but I don't think there's something better). public class User { private String userName; [TooManyArgs] // Will show warning: Try removing some arguments public User(String userName) { this.userName = userName; } public String UserName { get { return userName; } } [MustRefactor] // will show warning: Refactor is needed Here public override string ToString() { return "User: " + userName; } } [Obsolete("Refactor is needed Here")] public class MustRefactor : System.Attribute { } [Obsolete("Try removing some arguments")] public class TooManyArgs : System.Attribute { } A: There are several comments that suggest to insert warnings or pragma. Obsolete works in a very different way! Marking obsolete a function of a library L, the obsolete message raises when a program calls the function even if the caller program is not in the library L. Warning raises the message ONLY when L is compiled.
{ "language": "en", "url": "https://stackoverflow.com/questions/154109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "134" }
Q: C# Potential Interview Question…Too hard? Without running this code, identify which Foo method will be called: class A { public void Foo( int n ) { Console.WriteLine( "A::Foo" ); } } class B : A { /* note that A::Foo and B::Foo are not related at all */ public void Foo( double n ) { Console.WriteLine( "B::Foo" ); } } static void Main( string[] args ) { B b = new B(); /* which Foo is chosen? */ b.Foo( 5 ); } Which method? And why? No cheating by running the code. I found this puzzle on the web; I like it and I think I'm going to use it as an interview question...Opinions? EDIT: I wouldn't judge a candidate on getting this wrong, I'd use it as a way to open a fuller discussion about the C# and CLR itself, so I can get a good understanding of the candidates abilities. Source: http://netpl.blogspot.com/2008/06/c-puzzle-no8-beginner.html A: Console.WriteLine( "B::Foo"); Because it will cast automatictly and use the first without going further in the inheritance. I do not think it's a good interview question but it can be funny to try to solve without compiling the code. A: Not really fair as an interview question, as it's a bit of a trick question. The good answer I'd want from an interviewee would be more along the lines of "That needs refactoring". Unless you're looking to hire someone to work on compilers I'm not sure that you need to go that much in depth into the CLR. For interview questions I look for things that show the coder's level of understanding in their answer. This is more of an oddity/puzzle. A: This actually is a trick question. The answer is ambiguous as to what "should" happen. Sure, the C# compiler takes it out of the realm of ambiguity to the concrete; however, since these methods are overloading one another, and are neither overriding nor shadowing, it is reasonable to assume that the "best argument fit" should apply here, and therefore conclude that it is A::Foo(int n) that should be called when provided an integer as an argument. To prove that what "should" happen is unclear, the exact same code when run in VB.NET has the opposite result: Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button1.Click Dim b As New B b.Foo(5) ' A::Foo b.Foo(5.0) ' B::Foo End Sub End Class Class A Sub Foo(ByVal n As Integer) MessageBox.Show("A::Foo") End Sub End Class Class B Inherits A Overloads Sub Foo(ByVal n As Double) MessageBox.Show("B::Foo") End Sub End Class I realize that I am opening up the opportunity for the C# programmers to "bash" VB.NET for not complying with C# . But I think one could make a very strong argument that it is VB.NET that is making the proper interpretation here. Further, IntelliSense within the C# IDE suggests that there are two overloads for the class B (because there are, or at least should be!), but the B.Foo(int n) version actually can't be called (not without first explicitly casting to a class A). The result is that the C# IDE is not actually in synch with the C# compiler. Another way of looking at this is that the C# compiler is taking an intended overloads and turning it into a shadowed method. (This doesn't seem to be the right choice to me, but this is obviously just an opinion.) As an interview question, I think that it can be ok if you are interested in getting a discussion about the issues here. As for getting it "right" or "wrong", I think that the question verges on a trick question that could be easily missed, or even gotten right, for the wrong reasons. In fact, what the answer to the question "should be" is actually very debatable. A: I really wouldn't use this as an interview question. I know the answer and the reasoning behind it, but something like this should come up so rarely that it shouldn't be a problem. Knowing the answer really doesn't show much about a candidate's ability to code. Note that you'll get the same behaviour even if A.Foo is virtual and B overrides it. If you like C# puzzles and oddities, I've got a few too (including this one). A: I think it's a terrible question. I think any question is a terrible question when the real answer is "Run it and see!" If I needed to know this in real life, that's exactly what I'd do: Create a test project, key it in, and find out. Then I don't have to worry about abstract reasoning or the finer points in the C# spec. Just today I ran into such a question: If I fill the same typed DataTable twice with the same row, what will happen? One copy of the row, or two? And will it overwrite the first row even if I've changed it? I thought about asking someone, but I realized I could easily fire up a test project I already had that used DataSets, write a small method, and test it out. Answer: ...ah, but if I tell you, you'll miss the point. :) The point is, in programming you don't have to leave these things as hypotheticals, and you shouldn't if they can be reasonably tested. So I think it's a terrible question. Wouldn't you prefer to hire a developer who'll try it out and then know what happens, rather than a developer who'll try to dredge it up from his fading memory, or who'll ask someone else and accept an answer that might be wrong? A: That's a ridiculous question to ask - I could answer it in < 60 seconds with Snippet Compiler, and if I ever worked in a code base that depended on the functionality - it'd be quickly refactored out of existence. The best answer is "that's a stupid design, don't do that and you won't have to parse the language spec to know what it's going to do". If I was the interviewee, I'd think very highly of your geek trivia cred, and would perhaps invite you to the next game of Geek Trivial Pursuit. But, I'm not so sure I'd want to work with/for you. If that's your goal, by all means ask away. * *Note that in an informal situation, geek trivia like this can be fun and entertaining. But, to an interviewee, an interview is anything but fun or informal - why further agitate it with trivial questions that the interviewee doesn't know if you take seriously or not? A: Too hard? No, but what is your goal in the question? What are you expecting to get from your interviewee? That they know this particular syntactic quirk? That either means that they've studied the spec/language well (good for them) or that they've run into this problem (hopefully not from what they wrote, but if they did - yikes). Neither case really indicates that you've got a solid programmer/engineer/architect on your hand. I believe that what's important is not the question but the discussion surrounding the question. When I interview candidates, I usually ask one deceptively simple question which is based on a language semantic quirk - but I don't care if my interviewee knows it because that semantic quirk allows me to open up a lot of avenues that allow me to find out if my candidate is methodical, their communication style, if they're willing to say "I don't know", are they capable of thinking on their feet, do they understand language design and machine architecture, do they understand platform and portability issues - in short, I'm looking for a lot of ingredients that all add up to "do they get it?". This process takes an hour or more. In the end, I don't actually care about whether they know the answer to my question - the question is a ruse to let me get all the rest of that information indirectly without ever having to ask. If you don't have a valuable ulterior in this question, don't bother even asking it - you're wasting your time and your candidate's time. A: This smacks of a trick question to me. If you've been using the language for long enough, you've probably run into the problem and know the answer; but how long is long enough? It's also a question where your background might work against you. I know in C++ the definition in B would hide the definition in A, but I have no idea if it works the same in C#. In real life, I'd know it was a questionable area and try to look it up. In an interview I might try to guess, having been put on the spot. And I'd probably get it wrong. A: use it as a question only as long as you expect the candidate to tell you his thought processes as he describes what he thinks should be happening. Who cares about the right and wrongness of actual code in question - in the real world, the candidate would find code like this, find it not working and debug it with a combination of debugger and writeline calls, so its a useless question if you want candidates who know (or guess) the right answer. But those who can explain what they think would happen, that's a different matter. Hire them even if they get it wrong. A: It takes all of 5 seconds in a real work situation to figure out what went wrong. Compile, test, oops. I'm far more concerned on if someone can build good and maintainable code. Ask questions like * *How would you design for this, write simple abstract design, no code. *Here's an object design. The customer came and said they wanted this. Formulate a new design -or- discuss reasons why the requirements don't fulfill actual customer needs. A: Couldn't agree more with Joel there. I have 20+ years experience design and coding, and the first thing I thought of when I saw that was: It won't even compile. I made that assumption because I try to avoid overloads that differ by only a single datatype, and in looking at the code didn't even pick up on the int/double difference; I assumed there needed to be a new operator to allow a redefinition in B. In point of fact I had used a library a fellow programmer created for handling some text file generation that was a bit confusing because one of the methods had 8 different overloads and two of them differed only by datatype on the last argument. One was string and one was char. The likelihood that the value needed for the string version of the parameter was one character long was pretty good so hopefully you can see where this is headed. We had a devil of a time debugging problems because the consumer of the library inadvertently triggered the wrong call because of quoting differences, single versus double. Moral of the story, be grateful that the candidate doesn't know the answer because it may indicate good coding habits. A: Another vote against using it, but for a different reason. When put on the spot like this, a lot of really good programmers would come up with the wrong answer, but not because they don't know the concepts or couldn't figure it out. What happens is that they'll see something like this and think, "Aha, trick question!", and then proceed to out-think themselves in the response. This is especially true in an interview setting where they don't have the benefit of the IDE or Google or any other of the other helps a programmer takes for granted in their day to day programming. A: Try a similar sample given below: class Program { class P {} class Q : P {} class A { public void Fee(Q q) { Console.WriteLine("A::Fee"); } } class B : A { public void Fee(P p) { Console.WriteLine("B::Fee"); } } static void Main(string[] args) { B b = new B(); /* which Fee is chosen? */ b.Fee(new Q()); Console.ReadKey(); } } The compiler seems to prefer linking the "b.Fee()" call to an available method of the type rather than an inherited method (method of a base type) if the parameter can be implicitly cast to match any such method. I.e. implicit casting of the parameter takes precedence over base class method linking. Though honestly I find the opposite as more intuitive, because for me an inherited method is just as good as a directly introduced method. A: Code given in question will print B::Foo. A: As many have already stated, when I interview someone I want to find out if the candidate is capable of communicating, capable of writing code which makes sense and it can be easily understood by others, code which can be maintained and so forth. I personally don't like to spend time in exercises like the one proposed. Instead I'd rather give an exercise where the candidate will write code him/herself - even in a regular text editor - and from there opening a discussion based on code review, improvements as so forth. No need the code to compile: compiler will do its job, eventually. I know many people may disagree on this approach, but so far I have found this the best way of finding good candidates.
{ "language": "en", "url": "https://stackoverflow.com/questions/154112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Can an ASP.NET ASPX Page be Processed From a Source that is not the File System? Is there a way to execute a full ASPX source file where the page source is from a string/database/resource and not a file on the file system? It's straightfoward to render dynamic content/images/etc using HTTP Handlers and Modules and writing to the Response, but there doesn't seem to be a way to execute/compile ASPX source without a file on the file system. For example: * *HttpContext.Current.Server.Execute() overloads require a path to a file *System.Web.Compilation.BuildManager can only create from a virtual path The goal is to be able to execute a string source like the following from a Handler/Module/ViewEngine and not require a file on the file system (but get the source from another location): <%@ Page language="C#" MasterPageFile="~/Shared/Site.Master" Inherits="System.Web.UI.Page" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>ListView Example</title> </head> <body> <form id="form1" runat="server"> <h3>ListView Example</h3> <asp:ListView ID="List" runat="server" DataSourceID="ProductDataSource"> <LayoutTemplate><ol><asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder></ol></LayoutTemplate> <ItemTemplate><li><%# Eval("ProductName") %></li></ItemTemplate> </asp:ListView> <asp:AccessDataSource ID="ProductDataSource" runat="server"DataFile="~/App_Data/Northwind.mdb"SelectCommand="SELECT [ProductName], [QuantityPerUnit], [UnitPrice], [CategoryName] FROM [Alphabetical List of Products]"></asp:AccessDataSource> </form> </body> </html> (NOTE: The sample above is just a simple example, but shows using server controls, data binding syntax, a master page and possible user control declarations in page directives, etc...) I hope this makes sense! A: Perhaps you need a virtual path provider. It allows you to store the ASPX and codebehind in different media - RDBMS, xml file etc. A: Update: Check the post by korchev using virtualpathprovider, which is more suited for this scenario. Can you use a dummy file with a place holder literal control and replace the literal control with the actual source? These might not be useful but posting couple of links I found: Loading an ASP.NET Page Class dynamically in an HttpHandler How To: Dynamically Load A Page For Processing A: I knew that SharePoint Server used to keep the ASPX pages in the database and not on the file system. Details, however, I do not hold.
{ "language": "en", "url": "https://stackoverflow.com/questions/154117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Got .PNG file. Want embeddded icon resource displayed as icon on form title bar This was an interview question. Given Visual Studio 2008 and an icon saved as a .PNG file, they required the image as an embedded resource and to be used as the icon within the title bar of a form. I'm looking for what would have been the model answer to this question, Both (working!) code and any Visual Studio tricks. (Model answer is one that should get me the job if I meet it next time around.) Specifically I don't know how to load the image once it is an embedded resource nor how to get it as the icon for the title bar. As a part solution, ignoring the embedded bit, I copied the resource to the ouput directory and tried the following:- public partial class Form1 : Form { public Form1() { InitializeComponent(); this.Icon = new Icon("Resources\\IconImage.png"); } } This failed with the error "Argument 'picture' must be a picture that can be used as a Icon." I presuming that the .PNG file actually needed to be a .ICO, but I couldn't see how to make the conversion. Is this presumption correct or is there a different issue? A: Fire up VS, start new Windows Application. Open the properties sheet, add the .png file as a resource (in this example: glider.png ). From hereon, you can access the resource as a Bitmap file as WindowsFormsApplication10.Properties.Resources.glider Code for using it as an application icon: public Form1() { InitializeComponent(); Bitmap bmp = WindowsFormsApplication10.Properties.Resources.glider; this.Icon = Icon.FromHandle(bmp.GetHicon()); } A: Icon.FromHandle will cause problems with a PNG, because PNGs have more than one bit of transparency. This type of issue can be solved with a library like IconLib. Chances are they didn't know how to do it and they were trying to squeeze the answer out of potential employees. Furthermore, setting the icon of the form from a PNG is an unnecessary performance hit, it should have been an ICO in the first place. A: Go here: http://www.getpaint.net/ (free) And here: Paint.NET ico Plugin (free) Install Paint.NET. Put the ico plugin (second link) into the Paint.NET\FileTypes folder. Start up Paint.NET. Open your .png and save it as an .ico. Free and easy. A: A good resource on the subject in C# 2.0 Convert Bitmap to Icon. A: This worked for my purposes since all of my resources were PNG files: [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = CharSet.Auto)] extern static bool DestroyIcon(IntPtr handle); // From http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.gethicon.aspx private Icon bitmapToIcon(Bitmap myBitmap) { // Get an Hicon for myBitmap. IntPtr Hicon = myBitmap.GetHicon(); // Create a new icon from the handle. Icon newIcon = Icon.FromHandle(Hicon); return newIcon; }
{ "language": "en", "url": "https://stackoverflow.com/questions/154119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: Typical pitfalls of cross-browser compatibility What are the most common browser compatibility issues across the major desktop browsers? No dups please. Up-vote problems you've run into. I'm hoping for the list to self-sort. "IE sux" is not a pitfall, but a call for down-vote. [Edit] Yes, I know it's a poll - I'm not posting answers in this to gather points - I'm actually interested in knowing what people typically run into. A: Transparent PNGs in Internet Explorer 6, especially because the common, JavaScript-less workaround of using the AlphaImageLoader can have the side effect of locking up IE6. A: CSS - largely sorted out in the modern browsers, but still an issue - particularly as pertains to layout. Note that this is not critical - but it is a compatibility issue I almost always end up coming back to when designing a site. A: caching, and previous page hashes. A: Memory management can be an issue - different garbage collectors choke on different types of circular references, although firefox is getting pretty good at cleaning up complex objects properly. A: I've found that IE 6 has pretty small limits to the allowed stack depth. At one point I was using a nice recursive function to get the position of an element in the document: function getOffsetTop (element) { var offset = 0; if (element.offsetTop) offset = offset + element.offsetTop; if (element.offsetParent) offset = offset + getOffsetTop(element.offsetParent); return offset; } Unfortunately when calling this method for elements in a very deep node hierarchy, IE complains of exceeding the maximum stack size (I forget the exact error message). To get around this I needed to use an iterative approach to keep the stack size small: function getOffsetTop (element) { var offset = 0; if (element.offsetTop) offset = offset + element.offsetTop; var parent = element.offsetParent; while (parent) { if (parent.offsetTop) offset = offset + parent.offsetTop; parent = parent.offsetParent; } return offset; } A: Floats. There are an endless number of float bugs in IE6/7 - Peekabo, guillotine, double margin, escaping floats, 3px gap, duplicate characters, a number of clearing bugs, bugs related to the available space... A: Quirksmode has a comprehensive list of a lot of differencies requiring attention !-) -- but he is, like most other sites and bloggers on the net, focused in his way, and that results in some minor or major bugs and inconsistencies ... A: The most common one I can think of -- and it's been a problem for me twice this week alone -- is IE6 and the box model bug. Look it up! Specifically, the problem I'm thinking of is when you have floated DIVs which the developer thinks all fit within a wrapper DIV, but they don't in IE6 because they're slightly bigger. So rather than three columns, you end up with two, and your third is down at the bottom of the screen somewhere -- you want: +-------------------------------+ |+------+ +-----------+ +------+| || | | | | || || foo | | bar | | baz || || | | | | || || | | | | || |+------+ +-----------+ +------+| +-------------------------------+ but you get: +-------------------------------+ |+--------+ +------------+ | || | | | | || foo | | bar | | || | | | | || | | | | |+--------+ +------------+ | |+------+ | || | | || | | || baz | | || | | || | | |+------+ | +-------------------------------+ A: When performing an XMLHttpRequest and executing a function 'onreadystatechange' the XMLHttpRequest.responseText property contains the data loaded at that point in Firefox, but not in IE (and maybe Safari). This prevents the capture of partial data in those browsers for use in displaying an execution progress meter. A: Every fixed width, centered site I've created -- i.e. using 'margin:0 auto' on some containing div to center everything up -- fails to work on IE6 until I test it and apply a 'hack'. This gets me every time.
{ "language": "en", "url": "https://stackoverflow.com/questions/154132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why use apparently meaningless do-while and if-else statements in macros? In many C/C++ macros I'm seeing the code of the macro wrapped in what seems like a meaningless do while loop. Here are examples. #define FOO(X) do { f(X); g(X); } while (0) #define FOO(X) if (1) { f(X); g(X); } else I can't see what the do while is doing. Why not just write this without it? #define FOO(X) f(X); g(X) A: The do ... while and if ... else are there to make it so that a semicolon after your macro always means the same thing. Let's say you had something like your second macro. #define BAR(X) f(x); g(x) Now if you were to use BAR(X); in an if ... else statement, where the bodies of the if statement were not wrapped in curly brackets, you'd get a bad surprise. if (corge) BAR(corge); else gralt(); The above code would expand into if (corge) f(corge); g(corge); else gralt(); which is syntactically incorrect, as the else is no longer associated with the if. It doesn't help to wrap things in curly braces within the macro, because a semicolon after the braces is syntactically incorrect. if (corge) {f(corge); g(corge);}; else gralt(); There are two ways of fixing the problem. The first is to use a comma to sequence statements within the macro without robbing it of its ability to act like an expression. #define BAR(X) f(X), g(X) The above version of bar BAR expands the above code into what follows, which is syntactically correct. if (corge) f(corge), g(corge); else gralt(); This doesn't work if instead of f(X) you have a more complicated body of code that needs to go in its own block, say for example to declare local variables. In the most general case the solution is to use something like do ... while to cause the macro to be a single statement that takes a semicolon without confusion. #define BAR(X) do { \ int i = f(X); \ if (i > 4) g(i); \ } while (0) You don't have to use do ... while, you could cook up something with if ... else as well, although when if ... else expands inside of an if ... else it leads to a "dangling else", which could make an existing dangling else problem even harder to find, as in the following code. if (corge) if (1) { f(corge); g(corge); } else; else gralt(); The point is to use up the semicolon in contexts where a dangling semicolon is erroneous. Of course, it could (and probably should) be argued at this point that it would be better to declare BAR as an actual function, not a macro. In summary, the do ... while is there to work around the shortcomings of the C preprocessor. When those C style guides tell you to lay off the C preprocessor, this is the kind of thing they're worried about. A: For some reasons I can't comment on the first answer... Some of you showed macros with local variables, but nobody mentioned that you can't just use any name in a macro! It will bite the user some day! Why? Because the input arguments are substituted into your macro template. And in your macro examples you've use the probably most commonly used variabled name i. For example when the following macro #define FOO(X) do { int i; for (i = 0; i < (X); ++i) do_something(i); } while (0) is used in the following function void some_func(void) { int i; for (i = 0; i < 10; ++i) FOO(i); } the macro will not use the intended variable i, that is declared at the beginning of some_func, but the local variable, that is declared in the do ... while loop of the macro. Thus, never use common variable names in a macro! A: @jfm3 - You have a nice answer to the question. You might also want to add that the macro idiom also prevents the possibly more dangerous (because there's no error) unintended behavior with simple 'if' statements: #define FOO(x) f(x); g(x) if (test) FOO( baz); expands to: if (test) f(baz); g(baz); which is syntactically correct so there's no compiler error, but has the probably unintended consequence that g() will always be called. A: The above answers explain the meaning of these constructs, but there is a significant difference between the two that was not mentioned. In fact, there is a reason to prefer the do ... while to the if ... else construct. The problem of the if ... else construct is that it does not force you to put the semicolon. Like in this code: FOO(1) printf("abc"); Although we left out the semicolon (by mistake), the code will expand to if (1) { f(X); g(X); } else printf("abc"); and will silently compile (although some compilers may issue a warning for unreachable code). But the printf statement will never be executed. do ... while construct does not have such problem, since the only valid token after the while(0) is a semicolon. A: Explanation do {} while (0) and if (1) {} else are to make sure that the macro is expanded to only 1 instruction. Otherwise: if (something) FOO(X); would expand to: if (something) f(X); g(X); And g(X) would be executed outside the if control statement. This is avoided when using do {} while (0) and if (1) {} else. Better alternative With a GNU statement expression (not a part of standard C), you have a better way than do {} while (0) and if (1) {} else to solve this, by simply using ({}): #define FOO(X) ({f(X); g(X);}) And this syntax is compatible with return values (note that do {} while (0) isn't), as in: return FOO("X"); A: I don't think it was mentioned so consider this while(i<100) FOO(i++); would be translated into while(i<100) do { f(i++); g(i++); } while (0) notice how i++ is evaluated twice by the macro. This can lead to some interesting errors. A: Macros are copy/pasted pieces of text the pre-processor will put in the genuine code; the macro's author hopes the replacement will produce valid code. There are three good "tips" to succeed in that: Help the macro behave like genuine code Normal code is usually ended by a semi-colon. Should the user view code not needing one... doSomething(1) ; DO_SOMETHING_ELSE(2) // <== Hey? What's this? doSomethingElseAgain(3) ; This means the user expects the compiler to produce an error if the semi-colon is absent. But the real real good reason is that at some time, the macro's author will perhaps need to replace the macro with a genuine function (perhaps inlined). So the macro should really behave like one. So we should have a macro needing semi-colon. Produce a valid code As shown in jfm3's answer, sometimes the macro contains more than one instruction. And if the macro is used inside a if statement, this will be problematic: if(bIsOk) MY_MACRO(42) ; This macro could be expanded as: #define MY_MACRO(x) f(x) ; g(x) if(bIsOk) f(42) ; g(42) ; // was MY_MACRO(42) ; The g function will be executed regardless of the value of bIsOk. This means that we must have to add a scope to the macro: #define MY_MACRO(x) { f(x) ; g(x) ; } if(bIsOk) { f(42) ; g(42) ; } ; // was MY_MACRO(42) ; Produce a valid code 2 If the macro is something like: #define MY_MACRO(x) int i = x + 1 ; f(i) ; We could have another problem in the following code: void doSomething() { int i = 25 ; MY_MACRO(32) ; } Because it would expand as: void doSomething() { int i = 25 ; int i = 32 + 1 ; f(i) ; ; // was MY_MACRO(32) ; } This code won't compile, of course. So, again, the solution is using a scope: #define MY_MACRO(x) { int i = x + 1 ; f(i) ; } void doSomething() { int i = 25 ; { int i = 32 + 1 ; f(i) ; } ; // was MY_MACRO(32) ; } The code behaves correctly again. Combining semi-colon + scope effects? There is one C/C++ idiom that produces this effect: The do/while loop: do { // code } while(false) ; The do/while can create a scope, thus encapsulating the macro's code, and needs a semi-colon in the end, thus expanding into code needing one. The bonus? The C++ compiler will optimize away the do/while loop, as the fact its post-condition is false is known at compile time. This means that a macro like: #define MY_MACRO(x) \ do \ { \ const int i = x + 1 ; \ f(i) ; g(i) ; \ } \ while(false) void doSomething(bool bIsOk) { int i = 25 ; if(bIsOk) MY_MACRO(42) ; // Etc. } will expand correctly as void doSomething(bool bIsOk) { int i = 25 ; if(bIsOk) do { const int i = 42 + 1 ; // was MY_MACRO(42) ; f(i) ; g(i) ; } while(false) ; // Etc. } and is then compiled and optimized away as void doSomething(bool bIsOk) { int i = 25 ; if(bIsOk) { f(43) ; g(43) ; } // Etc. } A: While it is expected that compilers optimize away the do { ... } while(false); loops, there is another solution which would not require that construct. The solution is to use the comma operator: #define FOO(X) (f(X),g(X)) or even more exotically: #define FOO(X) g((f(X),(X))) While this will work well with separate instructions, it will not work with cases where variables are constructed and used as part of the #define : #define FOO(X) (int s=5,f((X)+s),g((X)+s)) With this one would be forced to use the do/while construct. A: Jens Gustedt's P99 preprocessor library (yes, the fact that such a thing exists blew my mind too!) improves on the if(1) { ... } else construct in a small but significant way by defining the following: #define P99_NOP ((void)0) #define P99_PREFER(...) if (1) { __VA_ARGS__ } else #define P99_BLOCK(...) P99_PREFER(__VA_ARGS__) P99_NOP The rationale for this is that, unlike the do { ... } while(0) construct, break and continue still work inside the given block, but the ((void)0) creates a syntax error if the semicolon is omitted after the macro call, which would otherwise skip the next block. (There isn't actually a "dangling else" problem here, since the else binds to the nearest if, which is the one in the macro.) If you are interested in the sorts of things that can be done more-or-less safely with the C preprocessor, check out that library.
{ "language": "en", "url": "https://stackoverflow.com/questions/154136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "905" }
Q: Changing embedded google videos src I'm trying to recreate the functionality on Google Video where you can access certain parts of a video by putting #1h1m1m in the URL. So I have an embedded Google Video and links to the right that I want to link to at certain times in that video. I can do this with a page refresh but I'm trying to do it via javascript so I don't have to. I can't seem to get the src of an embed element via javascript for whatever reason. I don't have a link because I haven't figured it out yet. I just want to skip to a different section of a Google Video without reloading the page. A: If the google video you are embedding is a YouTube video, there are documented APIs for causing the player to seek to a specified time (expressed in secondes). See: YouTube Javascript API Reference
{ "language": "en", "url": "https://stackoverflow.com/questions/154148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Developer Machine Justification Looking for good techniques to justify "great than normal" machine for developers. The company I work for buys the same underpowered $500 dollar systems for everyone, and looking for ways to prove ROI or arguments to use. Sorry, I didn't say this in the initial question, the stack is VS 2008, SQL 2005/2008. As duties dictate we are SQL admins as well as Web/Winform/WebService Developers. So its very typical to have 2 VS sessions and at least one SQL session open at the same time. A: A good one is: Extra time per compile X number of compiles per hour X hours in working day X days in month X number of developers This highlights how much of your (expensive) time is being wasted waiting for the machine to finish. You can do the same for test runs etc... A: Don't forget to include multiple display devices in your request: having a second screen to have the code on one, debugger on the other (eg) is invaluable. Or to be coding in one screen with the language reference in another. Do you have a central server where building is done? If so, arguing for a "greater than normal" development workstation may be hard. Being able to cut build times by a factor of 2-3, though, is a logical reason to buy bigger hardware. OTOH, if a company is so worried about how much they're spending that they only ever get the Walmart specials (which are fine for "normal" work (typing, email, scheduling, presentations)), they're going to scare-off their actual technical folks, like yourself, who actually want to get work done, and who have a more complex job, than, say, the administrative assistant. A: Unless you're hiring incompetent developers or your developers are making extremely ridiculous demands, the return on investment is almost always orders of magnitude higher than the cost of a workstation. Even a high-powered machine with a 30" monitor is cheap compared to a good developer's salary, anyway. It's so easy to please developers with a few shiny gadgets. If you don't do it, the company next door will! Everything you get from your developer is channeled through his or her tools. The slightest inadequacy in those tools will be compounded a thousand times over the lifetime of those tools (expect to have to upgrade them within two years). These inadequacies kill your developer's productivity and may even generate a lot of frustration. Why would you want to skimp on the most important resource for your developers? I bet if you look deeply, you'll find much greater waste elsewhere in your company. A: Figure out how long you spend in the edit -> build -> debug cycle, then total that up over the course of a year. Then guesstimate (with some justifiable inflation) what a good computer would do to that number. Multiply the time improvement by your hourly rate, and present it as a business case. A: Expressed as code: AnnualSavings := DeveloperCostPerHour * (AnnualWaitHours(OldPC) - AnnualWaitHours(NewPC)); if AnnualSavings > (MachineCost(NewPC) - MachineCost(OldPC)) then ShowMessage('Time to pony up for a new machine!!') else ShowMessage('Sorry bub, gotta keep the old clunker.'); A: Testing, at least, should be occurring on a system as close as possible to the environment it will be released into. Most developers do at least some testing on their desktop, so that's a reason to not be any worse than your live environment. If your live environment is an underpowered $500 system, then well, that's your environment. Perhaps you should work on that? Hard to say what other things you should bring up without any idea of what kind of development you're doing. Application? Server? An interpreted language or a compiled language? A: My saying is "The answer to programmer productivity is not to give everyone slow machines" Volunteer for as many dog and pony shows as you can (opportunities to show off what you've done to important people like the VP and so forth). At some point your machine will bog down. They'll ask why everything is taking so long. Explain that you have a painfully slow computer. Also point out how you're going to risk missing a deadline because of it. Point out how the hard drive never stops grinding. Playing the numbers, point out how expensive your time is compared to the one-time cost of upgrading you now. A: I can contribute from my own experience why would stronger machine would be helpful: * *Testing the code under different configurations. This would require running some virtualization solution. Such solutions requires a strong machine. *Running a sand box. Many times the application developed requires a DB, a Web Server or other complementary product. Again, such software might require strong machine. *Parallel development. At times, it might be very helpful to run multiple instances of the development environment. To do that, multiply the system requirement of a single instance. A: Being cheap on hardware is stupid. People are way more expensive to find, hire, and retain than hardware. The difference in cost between minimal and great hardware is usually equivalent to a few weeks of programmer salary. You should give developers a top-end machine of their choice and at least 2 screens. If your company won't give you the tools for you (and thus them) to be successful, they aren't worth your time. A: If you are a salaried drone working insane hours and getting everything done that is asked of you, don't waste your time squeezing blood from the turnip. The company is exploiting you, you allow it, and there is no reason for them to change. Either spend your own money (buying yourself some additional time each day), find some way that the current situation causes pain upstairs, or put up with it. If on the other hand you are working a reasonable amount of hours or are paid by the hour, you should be able to justify the request, either through reduced hours (= reduced cost) or through improved productivity (= things getting done faster). You need to decide which the organization is more interested in and present your request in those terms. Identify (and quantify if possible) how the under-powered machine impedes your productivity and slows you down. Then apply that to EITHER reduced hours for the same work OR to more work done in the same time. Good luck! A: Danimal has a good formula there. You might include in that business case a spread sheet showing the base machine compared to what an "average" developer for your company needs, and wants. Things like Ram, CPU speed, preinstalled applications, GPU and so on. A: partly because of productivity and responsiveness of the machine for a developer who would otherwise play chair-jousting during compiles; but also because a developer is going to install the biggest, resource-hungry applications you'll see outside a production server. Visual Studio takes up a lot of disc, RAM and masses of CPU. Eclipse (I'm told) is just the same. Any developer why is doing something useful will also have source control, development versions of production systems (eg a local DB to develop against), etc. All those apps take up lots of ram and CPU too. Unless you're remotely developing on a server somewhere, you'll need tons of resources just to install half the bloaty apps they want you to use! A: Yeah I hear you. The basic justification is always the same for me : Slower machine -> Slower developement ; Faster machine -> Faster developement. Altough if your boss is too much focused on numbers Microsoft is not helping either. Visual Studio setup requirements : System Requirements for Installing Visual Studio 2005 Processor Minimum: 600 megahertz (MHz) Pentium processor Recommended: 1 gigahertz (GHz) Pentium processor RAM Minimum: 192 megabytes (MB) Recommended: 256 MB A: I'm guessing that you probably don't work for a software company - like me, you probably are part of a software group within a manufacturing/hardware company, or maybe a financial or educational institution, etc? For me, working with/for these types of companies, it's usually not that the company wants to deny people the tools they need to get their work done, but rather a matter of not understanding "why" developers need better machines than sales people. Maybe try using an analogy that makes sense to the person(s) holding the checkbook. Why do sales people take clients to a steakhouse when McDonald's is right across the street? Why do mechanics spend extra money to buy Snap-On tools when Wal-Mart sells Buffalo brand screw drivers? (sure, I have some Buffalo screw drivers at home - but I'm not a mechanic) A: This is just rediculous, developers are very expensive to hire and pay, hardware is very cheap. Giving everyone a decent machine on their desktop plus a well spec'd server ( 8G ram should be ok) in the server room is the minimum that you should expect. Otherwise, how are they going to be able to run a decent amount of VMs at once? Strictly speaking, their desktop machine doesn't matter too much provided they have a decent development server (I'm assuming this is not games development etc here). Two screens is a good idea though. A: Tell them that you will pay the difference between their cheap machines and the machine that you want. If you are confident that it will boost your productivity significantly then you will make the money back easily in performance bonuses / salary increases. Also, if you put your money where your mouth is then chances are they will not follow through on making you pay for it because it will cause too many problems in accounting. One of the reasons companies standardize on machines to buy is to avoid the bickering that goes on when employee A gets one thing and employee B gets something better. If you paid for it then no-one is going to complain that you have a better PC. If they still say no then at least you know where you stand. They don't take you seriously and they don't take the role of developer seriously. Dust off the CV.
{ "language": "en", "url": "https://stackoverflow.com/questions/154159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Detect virtualized OS from an application? I need to detect whether my application is running within a virtualized OS instance or not. I've found an article with some useful information on the topic. The same article appears in multiple places, I'm unsure of the original source. VMware implements a particular invalid x86 instruction to return information about itself, while VirtualPC uses a magic number and I/O port with an IN instruction. This is workable, but appears to be undocumented behavior in both cases. I suppose a future release of VMWare or VirtualPC might change the mechanism. Is there a better way? Is there a supported mechanism for either product? Similarly, is there a way to detect Xen or VirtualBox? I'm not concerned about cases where the platform is deliberately trying to hide itself. For example, honeypots use virtualization but sometimes obscure the mechanisms that malware would use to detect it. I don't care that my app would think it is not virtualized in these honeypots, I'm just looking for a "best effort" solution. The application is mostly Java, though I'm expecting to use native code plus JNI for this particular function. Windows XP/Vista support is most important, though the mechanisms described in the referenced article are generic features of x86 and don't rely on any particular OS facility. A: On virtualbox, assuming you have control over the VM guest and you have dmidecode, you can use this command: dmidecode -s bios-version and it will return VirtualBox A: On linux systemd provides a command for detecting if the system is running as a virtual machine or not. Command: $ systemd-detect-virt If the system is virtualized then it outputs name of the virtualization softwarwe/technology. If not then it outputs none For instance if the system is running KVM then: $ systemd-detect-virt kvm You don't need to run it as sudo. A: Have you heard about blue pill, red pill?. It's a technique used to see if you are running inside a virtual machine or not. The origin of the term stems from the matrix movie where Neo is offered a blue or a red pill (to stay inside the matrix = blue, or to enter the 'real' world = red). The following is some code that will detect whether you are running inside 'the matrix' or not: (code borrowed from this site which also contains some nice information about the topic at hand): int swallow_redpill () { unsigned char m[2+4], rpill[] = "\x0f\x01\x0d\x00\x00\x00\x00\xc3"; *((unsigned*)&rpill[3]) = (unsigned)m; ((void(*)())&rpill)(); return (m[5]>0xd0) ? 1 : 0; } The function will return 1 when you are running inside a virutal machine, and 0 otherwise. A: I'd like to recommend a paper posted on Usenix HotOS '07, Comptibility is Not Transparency: VMM Detection Myths and Realities, which concludes several techniques to tell whether the application is running in a virtualized environment. For example, use sidt instruction as redpill does(but this instruction can also be made transparent by dynamic translation), or compare the runtime of cpuid against other non-virtualized instructions. A: While installing the newes Ubuntu I discovered the package called imvirt. Have a look at it at http://micky.ibh.net/~liske/imvirt.html A: This C function will detect VM Guest OS: (Tested on Windows, compiled with Visual Studio) #include <intrin.h> bool isGuestOSVM() { unsigned int cpuInfo[4]; __cpuid((int*)cpuInfo,1); return ((cpuInfo[2] >> 31) & 1) == 1; } A: Under Linux, you can report on /proc/cpuinfo. If it's in VMware, it usually comes-up differently than if it is on bare metal, but not always. Virtuozzo shows a pass-through to the underlying hardware. A: Try by reading the SMBIOS structures, especially the structs with the BIOS information. In Linux you can use the dmidecode utility to browse the information. A: Check the tool virt-what. It uses previously mentioned dmidecode to determine if you are on a virtualized host and the type. A: I Tried A Different approach suggested by my friend.Virtual Machines run on VMWARE doesnt have CPU TEMPERATURE property. i.e They Dont Show The Temperature of the CPU. I am using CPU Thermometer Application For Checking The CPU Temperature. (Windows Running In VMWARE) (Windows Running On A Real CPU) So I Code a Small C Programme to detect the temperature Senser #include "stdafx.h" #define _WIN32_DCOM #include <iostream> using namespace std; #include <comdef.h> #include <Wbemidl.h> #pragma comment(lib, "wbemuuid.lib") int main(int argc, char **argv) { HRESULT hres; // Step 1: -------------------------------------------------- // Initialize COM. ------------------------------------------ hres = CoInitializeEx(0, COINIT_MULTITHREADED); if (FAILED(hres)) { cout << "Failed to initialize COM library. Error code = 0x" << hex << hres << endl; return 1; // Program has failed. } // Step 2: -------------------------------------------------- // Set general COM security levels -------------------------- hres = CoInitializeSecurity( NULL, -1, // COM authentication NULL, // Authentication services NULL, // Reserved RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation NULL, // Authentication info EOAC_NONE, // Additional capabilities NULL // Reserved ); if (FAILED(hres)) { cout << "Failed to initialize security. Error code = 0x" << hex << hres << endl; CoUninitialize(); return 1; // Program has failed. } // Step 3: --------------------------------------------------- // Obtain the initial locator to WMI ------------------------- IWbemLocator *pLoc = NULL; hres = CoCreateInstance( CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *)&pLoc); if (FAILED(hres)) { cout << "Failed to create IWbemLocator object." << " Err code = 0x" << hex << hres << endl; CoUninitialize(); return 1; // Program has failed. } // Step 4: ----------------------------------------------------- // Connect to WMI through the IWbemLocator::ConnectServer method IWbemServices *pSvc = NULL; // Connect to the root\cimv2 namespace with // the current user and obtain pointer pSvc // to make IWbemServices calls. hres = pLoc->ConnectServer( _bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace NULL, // User name. NULL = current user NULL, // User password. NULL = current 0, // Locale. NULL indicates current NULL, // Security flags. 0, // Authority (for example, Kerberos) 0, // Context object &pSvc // pointer to IWbemServices proxy ); if (FAILED(hres)) { cout << "Could not connect. Error code = 0x" << hex << hres << endl; pLoc->Release(); CoUninitialize(); return 1; // Program has failed. } cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl; // Step 5: -------------------------------------------------- // Set security levels on the proxy ------------------------- hres = CoSetProxyBlanket( pSvc, // Indicates the proxy to set RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx NULL, // Server principal name RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx NULL, // client identity EOAC_NONE // proxy capabilities ); if (FAILED(hres)) { cout << "Could not set proxy blanket. Error code = 0x" << hex << hres << endl; pSvc->Release(); pLoc->Release(); CoUninitialize(); return 1; // Program has failed. } // Step 6: -------------------------------------------------- // Use the IWbemServices pointer to make requests of WMI ---- // For example, get the name of the operating system IEnumWbemClassObject* pEnumerator = NULL; hres = pSvc->ExecQuery( bstr_t("WQL"), bstr_t(L"SELECT * FROM Win32_TemperatureProbe"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator); if (FAILED(hres)) { cout << "Query for operating system name failed." << " Error code = 0x" << hex << hres << endl; pSvc->Release(); pLoc->Release(); CoUninitialize(); return 1; // Program has failed. } // Step 7: ------------------------------------------------- // Get the data from the query in step 6 ------------------- IWbemClassObject *pclsObj = NULL; ULONG uReturn = 0; while (pEnumerator) { HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) { break; } VARIANT vtProp; // Get the value of the Name property hr = pclsObj->Get(L"SystemName", 0, &vtProp, 0, 0); wcout << " OS Name : " << vtProp.bstrVal << endl; VariantClear(&vtProp); VARIANT vtProp1; VariantInit(&vtProp1); pclsObj->Get(L"Caption", 0, &vtProp1, 0, 0); wcout << "Caption: " << vtProp1.bstrVal << endl; VariantClear(&vtProp1); pclsObj->Release(); } // Cleanup // ======== pSvc->Release(); pLoc->Release(); pEnumerator->Release(); CoUninitialize(); return 0; // Program successfully completed. } Output On a Vmware Machine Output On A Real Cpu A: Under Linux I used the command: dmidecode ( I have it both on CentOS and Ubuntu ) from the man: dmidecode is a tool for dumping a computer's DMI (some say SMBIOS) table contents in a human-readable format. So I searched the output and found out its probably Microsoft Hyper-V Handle 0x0001, DMI type 1, 25 bytes System Information Manufacturer: Microsoft Corporation Product Name: Virtual Machine Version: 5.0 Serial Number: some-strings UUID: some-strings Wake-up Type: Power Switch Handle 0x0002, DMI type 2, 8 bytes Base Board Information Manufacturer: Microsoft Corporation Product Name: Virtual Machine Version: 5.0 Serial Number: some-strings Another way is to search to which manufacturer the MAC address of eth0 is related to: http://www.coffer.com/mac_find/ If it return Microsoft, vmware & etc.. then its probably a virtual server. A: I use this C# class to detect if the Guest OS is running inside a virtual environment (windows only): sysInfo.cs using System; using System.Management; using System.Text.RegularExpressions; namespace ConsoleApplication1 { public class sysInfo { public static Boolean isVM() { bool foundMatch = false; ManagementObjectSearcher search1 = new ManagementObjectSearcher("select * from Win32_BIOS"); var enu = search1.Get().GetEnumerator(); if (!enu.MoveNext()) throw new Exception("Unexpected WMI query failure"); string biosVersion = enu.Current["version"].ToString(); string biosSerialNumber = enu.Current["SerialNumber"].ToString(); try { foundMatch = Regex.IsMatch(biosVersion + " " + biosSerialNumber, "VMware|VIRTUAL|A M I|Xen", RegexOptions.IgnoreCase); } catch (ArgumentException ex) { // Syntax error in the regular expression } ManagementObjectSearcher search2 = new ManagementObjectSearcher("select * from Win32_ComputerSystem"); var enu2 = search2.Get().GetEnumerator(); if (!enu2.MoveNext()) throw new Exception("Unexpected WMI query failure"); string manufacturer = enu2.Current["manufacturer"].ToString(); string model = enu2.Current["model"].ToString(); try { foundMatch = Regex.IsMatch(manufacturer + " " + model, "Microsoft|VMWare|Virtual", RegexOptions.IgnoreCase); } catch (ArgumentException ex) { // Syntax error in the regular expression } return foundMatch; } } } Usage: if (sysInfo.isVM()) { Console.WriteLine("VM FOUND"); } A: I came up with universal way to detect every type of windows virtual machine with just 1 line of code. It supports win7--10 (xp not tested yet). Why we need universal way ? Most common used way is to search and match vendor values from win32. But what if there are 1000+ VM manufacturers ? then you would have to write a code to match 1000+ VM signatures. But its time waste. Even after sometime, there would be new other VMs launched and your script would be wasted. Background I worked on it for many months. I done many tests upon which I observed that: win32_portconnector always null and empty on VMs. Please see full report //asked at: https://stackoverflow.com/q/64846900/14919621 what win32_portconnector is used for ? This question have 3 parts. 1) What is the use case of win32_portconnector ? //https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-portconnector 2) Can I get state of ports using it like Mouse cable, charger, HDMI cables etc ? 3) Why VM have null results on this query : Get-WmiObject Win32_PortConnector ? On VM: PS C:\Users\Administrator> Get-WmiObject Win32_PortConnector On Real environment: PS C:\Users\Administrator> Get-WmiObject Win32_PortConnector Tag : Port Connector 0 ConnectorType : {23, 3} SerialNumber : ExternalReferenceDesignator : PortType : 2 Tag : Port Connector 1 ConnectorType : {21, 2} SerialNumber : ExternalReferenceDesignator : PortType : 9 Tag : Port Connector 2 ConnectorType : {64} SerialNumber : ExternalReferenceDesignator : PortType : 16 Tag : Port Connector 3 ConnectorType : {22, 3} SerialNumber : ExternalReferenceDesignator : PortType : 28 Tag : Port Connector 4 ConnectorType : {54} SerialNumber : ExternalReferenceDesignator : PortType : 17 Tag : Port Connector 5 ConnectorType : {38} SerialNumber : ExternalReferenceDesignator : PortType : 30 Tag : Port Connector 6 ConnectorType : {39} SerialNumber : ExternalReferenceDesignator : PortType : 31 Show me Code Based upon these tests, I have made an tiny program which can detect windows VMs. //@graysuit //https://graysuit.github.io //https://github.com/Back-X/anti-vm using System; using System.Windows.Forms; public class Universal_VM_Detector { static void Main() { if((new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_PortConnector")).Get().Count == 0) { MessageBox.Show("VM detected !"); } else { MessageBox.Show("VM NOT detected !"); } } } You can read code or get compiled executable. Stability It is tested on many environments and is very stable. * *Detects Visrtualbox *Detects Vmware *Detects Windows Server *Detects RDP *Detects Virustotal *Detects any.run etc... A: VMware has a Mechanisms to determine if software is running in a VMware virtual machine Knowledge base article which has some source code. Microsoft also has a page on "Determining If Hypervisor Is Installed". MS spells out this requirement of a hypervisor in the IsVM TEST" section of their "Server Virtualization Validation Test" document The VMware and MS docs both mention using the CPUID instruction to check the hypervisor-present bit (bit 31 of register ECX) The RHEL bugtracker has one for "should set ISVM bit (ECX:31) for CPUID leaf 0x00000001" to set bit 31 of register ECX under the Xen kernel. So without getting into vendor specifics it looks like you could use the CPUID check to know if you're running virtually or not. A: No. This is impossible to detect with complete accuracy. Some virtualization systems, like QEMU, emulate an entire machine down to the hardware registers. Let's turn this around: what is it you're trying to do? Maybe we can help with that. A: I think that going forward, relying on tricks like the broken SIDT virtualization is not really going to help as the hardware plugs all the holes that the weird and messy x86 architecture have left. The best would be to lobby the Vm providers for a standard way to tell that you are on a VM -- at least for the case when the user has explicitly allowed that. But if we assume that we are explicitly allowing the VM to be detected, we can just as well place visible markers in there, right? I would suggest just updating the disk on your VMs with a file telling you that you are on a VM -- a small text file in the root of the file system, for example. Or inspect the MAC of ETH0, and set that to a given known string.
{ "language": "en", "url": "https://stackoverflow.com/questions/154163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "76" }