text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: How does string.unpack work in Ruby? Can someone explain why how the result for the following unpack is computed?
"aaa".unpack('h2H2') #=> ["16", "61"]
In binary, 'a' = 0110 0001. I'm not sure how the 'h2' can become 16 (0001 0000) or 'H2' can become 61 (0011 1101).
A: Not 16 - it is showing 1 and then 6. h is giving the hex value of each nibble, so you get 0110 (6), then 0001 (1), depending on whether its the high or low bit you're looking at. Use the high nibble first and you get 61, which is hex for 97 - the value of 'a'
A: Check out the Programming Ruby reference on unpack. Here's a snippet:
Decodes str (which may contain binary
data) according to the format string,
returning an array of each value
extracted. The format string consists
of a sequence of single-character
directives, summarized in Table 22.8
on page 379. Each directive may be
followed by a number, indicating the
number of times to repeat with this
directive. An asterisk ("*") will
use up all remaining elements. The
directives sSiIlL may each be followed
by an underscore ("_") to use the
underlying platform's native size for
the specified type; otherwise, it uses
a platform-independent consistent
size. Spaces are ignored in the format
string. See also Array#pack on page
286.
And the relevant characters from your example:
H Extract hex nibbles from each character (most significant first).
h Extract hex nibbles from each character (least significant first).
A: The hex code of char a is 61.
Template h2 is a hex string (low nybble first), H2 is the same with high nibble first.
Also see the perl documentation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: How do you calculate accumulative time in C#? I want to calculate the time span between 2 times which I saved in a database.
So literally I want to know the length of time between the 2 values.
14:10:20 - 10:05:15 = 02:05:05
So the result would be 02:05:05.
How would I be able to achieve this using C#?
14:10:20 is the format I saved it in in my database.
A: Read the two time values into TimeSpan variables, then perform a .Subtract() on the bigger TimeSpan variable to get the TimeSpan result.
E.g. TimeSpan difference = t1.Subtract(t2);.
A: Your first step will be to get the timevalues stored in your database into .NET DateTime structs.
If you stored them as SQL-DateTime values in the database you can get them directly as DateTime. It would look something like this:
SQLCommand getTimeCommand = new SQLCommand("SELECT time FROM table", dbConnection);
SQLDataReader myReader = getTimeCommand.ExecuteReader();
while (myReader.Read())
{
DateTime time = myReader.GetDateTime(0);
}
myReader.Close();
Your implementation might differ, refer to the ADO.NET documentation in the MSDN library.
If you already got a string representing the time you can parse the string into a DateTime using the static methods
DateTime.Parse
or
DateTime.ParseExact
In your case you might need to use ParseExact, which can pe provided with a format-string defining how to read the string. Examples should be found in the MSDN library.
Durations in .NET are stored inside a TimeSpan struct. Getting the elapsed time between to datetimes is easy:
DateTime time1, time2; //filled with your timevalues from the db
TimeSpan elapsed = d2 - d1;
elapsed now contains the timespan between the two DateTimes. There are several members for the struct to access the TimeSpan. Look into the MSDN-Library to find the ones you need.
A: DateTime objects support the "-" operator so you can just read your times into such objects and subtract them. To test, check this out:
DateTime then = DateTime.Now;
Thread.Sleep(500);
DateTime now = DateTime.Now;
TimeSpan time = now - then;
MessageBox.Show(time.ToString());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is putting thread on hold optimal? Application has an auxiliary thread. This thread is not meant to run all the time, but main process can call it very often.
So, my question is, what is more optimal in terms of CPU performance: suspend thread when it is not being used or keep it alive and use WaitForSingleObject function in order to wait for a signal from main process?
A: I would assume Andrei doesn't use Delphi to write .NET and therefore Suspend doesn't translate to System.Threading.Thread.Suspend but to SuspendThread Win32 API.
I would strongly suggest against it. If you suspend the thread in an arbitrary moment, then you don't know what's going to happen (for example, you may suspend the thread in such a state the some shared resource is blocked). If you however already know that the thread is in suspendable state, then simply use WaitForSingleObject (or any other WaitFor call) - it will be equally effective as suspending the thread, i.e. thread will use zero CPU time until it is awaken.
A: In terms of CPU resources used, both solutions are the same - the thread which is suspended and thread which is waiting in WaitForSingleObject for an object which is not signalled both get no CPU cycles at all.
That said, WaitForSingleObject is almost always a prefered solution because the code using it will be much more "natural" - easier to read, and easier to make right. Suspending/Resuming threads can be dangerous, because you need to take a lot of care to make sure you know you are suspending a thread in a state where suspending it will do no harm (imagine suspending a thread which is currently holding a mutex).
A: What do you mean by "suspend"? WaitForSingleObject will suspend the thread, i.e., it will not consume any CPU, until the signal arrives.
A: If it's a worker thread that has units of work given to it externally, it should definitely be using signalling objects as that will ensure it doesn't use CPU needlessly.
If it has any of its own work to do as well, that's another matter. I wouldn't suspend the thread from another thread (what happens if there's two threads delivering work to it?) - my basic rule is that threads should control their own lifetime with suggestions from other threads. This localizes all control in the thread itself.
A: See the excellent tutorial on multi-threading in Delphi :
Multi Threading Tutorial
A: Another option would be the TMonitor introduced in Delphi 2009, which has functions like Wait, Pulse and PulseAll to keep threads inactive when there is nothing to do for them, and notify them as soon as they should continue with their work. It is loosely modeled after the object locks in Java. Like there, Delphi object now have a "lock" field which can be used for thread synchrinozation.
A blog which gives an example for a threaded queue class can be found at http://delphihaven.wordpress.com/2011/05/04/using-tmonitor-1/
Unfortunately there was a bug in the TMonitor implementation, which seems to be fixed in XE2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: JSP pagination without retrieving the whole result set? I need to display the log entries from a database.
Of course the log data is huge, so I have to show the results on several pages, and that **without** getting **all** the log data at once, but as the user navigates through the pages.
I know about DisplayTag and TableTags, but it seems to me that they both fetch all the data before applying pagination.
Before I start developing my own JSP tag, does anyone know of a 3rd party solution for this problem?
Thanks,Marius
A: About DisplayTag: it does support Value List design pattern.
A: Best solution on this is Jmesa
A: Inside your JSP is not really the good place to solve the whole problem.
In a typical layered approach, you separate the presentation (JSP here) from the data access (where you do your query).
Your displaytag/jsp tag should pass to the data access layer which page it wants (eg I need the next 30 and am on page 5), and your data access layer then takes care of a paginated query.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: how do I find the angle of rotation of the major axis of an ellipse given its bounding rectangle? I have an ellipse centered at (0,0) and the bounding rectangle is x = [-5,5], y = [-6,6]. The ellipse intersects the rectangle at (-5,3),(-2.5,6),(2.5,-6),and (5,-3)
I know nothing else about the ellipse, but the only thing I need to know is what angle the major axis is rotated at.
seems like the answer must be really simple but I'm just not seeing it... thanks for the help!
A: If (0, 0) is the center, than equation of Your ellipse is:
F(x, y) = Ax^2 +By^2 + Cxy + D = 0
For any given ellipse, not all of the coefficients A, B, C and D are uniquely determined. One can multiply the equation by any nonzero constant and obtain new equation of the same ellipse.
4 points You have, give You 4 equations, but since those points are two pairs of symmetrical points, those equations won't be independent. You will get 2 independent equations. You can get 2 more equations by using the fact, that the ellipse is tangent to the rectangle in hose points (that's how I understand it).
So if F(x, y) = Ax^2 +By^2 + Cxy + D Your conditions are:
dF/dx = 0 in points (-2.5,6) and (2.5,-6)
dF/dy = 0 in points (-5,3) and (5,-3)
Here are four linear equations that You get
F(5, -3) = 5^2 * A + (-3)^2 * B + (-15) * C + D = 0
F(2.5, -6) = (2.5)^2 * A + (-6)^2 * B + (-15) * C + D = 0
dF(2.5, -6)/dx = 2*(2.5) * A + (-6) * C = 0
dF(5, -3)/dy = 2*(-3) * B + 5 * C = 0
After a bit of cleaning:
25A + 9B - 15C + D = 0 //1
6.25A + 36B - 15C + D = 0 //2
5A - 6C = 0 //3
- 6B + 5C = 0 //4
Still not all 4 equations are independent and that's a good thing. The set is homogeneous and if they were independent You would get unique but useless solution A = 0, B = 0, C = 0, D = 0.
As I said before coefficients are not uniquely determined, so You can set one of the coefficient as You like and get rid of one equation. For example
25A + 9B - 15C = 1 //1
5A - 6C = 0 //3
- 6B + 5C = 0 //4
From that You get: A = 4/75, B = 1/27, C = 2/45 (D is of course -1)
Now, to get to the angle, apply transformation of the coordinates:
x = ξcos(φ) - ηsin(φ)
y = ξsin(φ) + ηcos(φ)
(I just couldn't resist to use those letters :) )
to the equation F(x, y) = 0
F(x(ξ, η), y(ξ, η)) = G(ξ, η) =
A (ξ^2cos^2(φ) + η^2sin^2(φ) - 2ξηcos(φ)sin(φ))
+ B (ξ^2sin^2(φ) + η^2cos^2(φ) + 2ξηcos(φ)sin(φ))
+ C (ξ^2cos(φ)sin(φ) - η^2cos(φ)sin(φ) + ξη(cos^2(φ) - sin^2(φ))) + D
Using those two identities:
2cos(φ)sin(φ) = sin(2φ)
cos^2(φ) - sin^2(φ) = cos(2φ)
You will get coefficient C' that stands by the product ξη in G(ξ, η) to be:
C' = (B-A)sin(2φ) + Ccos(2φ)
Now your question is: For what angle φ coefficient C' disappears (equals zero)
There is more than one angle φ as there is more than one axis. In case of the main axis B' > A'
A: The gradient of the ellipse is identical to the gradient of the intersects with the bounding rectangle along one side of the ellipse. In your case, that's the line from (-2.5,6) to (5,-3), the top side of your ellipse. That line has a vertical drop of 9 and a horizontal run of 7.5.
So we end up with the following right-angled triangle.
(-2.5,6)
*-----
|\x
| \
| \
9 | \
| \
| x\
+------* (5,-3)
7.5
The angle we're looking for is x which is the same in both locations.
We can calculate it as:
-1
tan (9/7.5)
which gives us an angle of -50.19 degrees
A: *
*Set the angle of the ellipse = 0
*Calculate the 4 points of intersection
*Work out the error between the calculated intersection points and the desired ones (i.e. sum the 4 distances).
*If error is too large use the secant method or Newton-Rhapson to work out a new angle for the ellipse and go to 2.
I used a similar approach to work out another ellipse problem:
http://successfulsoftware.net/2008/07/18/a-mathematical-digression/
http://successfulsoftware.net/2008/08/25/a-mathematical-digression-revisited/
See also:
http://en.wikipedia.org/wiki/Secant_method
http://en.wikipedia.org/wiki/Newton_Rhapson
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Best way to go about serializing and deserializing an object without losing its listeners? I have a serializiable object with listeners registered. Currently the list of listeners is stored in the object as transient. When the object is serialized and then deserialized, obviously the listeners are no longer registered.
What would be the safest and best way to go about re-registering the listeners automatically once the object is deserialized? Is there a good design pattern that would help here?
A: If you implement readObject(), you can reconstruct transient state as part of deserialization. You should treat deserialization as object construction (because it is).
private void readObject(ObjectInputStream in)
throws ClassNotFoundException, IOException {
// do normal serialization first!
in.defaultReadObject();
// put code here that can somehow reconstruct your listeners
// presumably you have someplace you can look them up
}
A: You could use a proxy object which acts as both a listener and a broadcaster of events and assign the real listeners to it, and then assign it as a listener of the to-be-serialized object. When you serialize it and then de-serialize it, just reassign it as a listener of the de-serialized object.
A: I would build a decoupled event framework, meaning that the event producer would be not bound directly to the event consumer.
This could consist of a EventManager, an EventProducer and an EventListener working together with publish/subscribe semantics.
*
*When the system starts up (or on the first use) a EventManager is created.
*The EventListener registers itself to receive a specific kind of events.
*The EventProducer is producing events an publishes them to the EventManager
public interface EventManager {
public void postEvent(Event event);
public void addListener(Class eventType, EventListener listener);
}
public interface EventListener {
public void handleEvent(Event event);
}
In this way when you serialize the producer then the EventManager still maintains the list of the subscribed listeners. when the object is deserialized then it can still post events to the EventManager.
A: In general I did not recognize any useful pattern for this. But the combination of several will be OK :). The question is how you handle deserialization? If using standard way you can introduce lookup mechanism which will be used to locate local listeners and re-bound them to the freshly deserialized instance. If you have own deserializer, the way will be more simple. Just deserialize object and register local listeners. The deserializer can act as proxy listener if possible. Introducing some decoupled model should be also helpful as Panagiotis said. The exact solution depends of your real need but don't forget to KISS it.
A: Use a registry that both your publisher and subscribers register with. As was posted by Korros, it is referred to as a Whiteboard Pattern in OSGI land.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Are there naming conventions for ASP.NET web application directory structures? Currently I am developing a site with about seven partial classes, a few icons, three pages and an App_Themes folder. I was interested to know, is there an industry standard directory structure for anything larger than a small project?
For example, I want to keep the classes in separate folders, the images in separate folders etc. My current directory structure is as follows (not exact, this is from memory):
*
*(root) contains the codebehind and forms
*/App_Data
*/App_Themes
*/Bin
*/Images
*/Models - I stole the name from MVC. It sounded more appropriate then 'classes'
*/FusionCharts - a flash charting library
I briefly played with MVC, and it looked like a nice directory structure, however, I am using ASP.NET Ajax.
So, I guess the question is, is there a way to make this directory structure more orderly in your own opinion? Please give answers as to why you made your decision also :).
A: The only "standard" name you are missing for ASP.NET would be App_Code.
Use the convention that makes sense to you and the people that will be maintaining the code. There is no industry standard for this that I've come across in 4+ years of doing ASP.NET development.
A: I also follow the same structure as mentioned by you. The only additions that I make is have separate folders for scripts,CSS, and resources. As far as I am aware of there is no such industry standard.
A: I like having a Content folder under which I can put my Css, Js, and Images folders.
A: I like to be inspired by Microsoft standards, since we are using a Microsoft technology. Plus a somewhat good standard is better than no standard, especially if you work in a larger team.
App_Code is standard of course, because it has a function in ASP.NET, not just a best practice.
I sort of like the MVC standard project's structure:
*
*Content -- Contains subdirectories with Images, Css, Javascript
*Controllers -- Maybe N/A in WebForms
*Views -- Also maybe overkill in WebForms
The "Content" folder is maybe the key, since it's the lowest common denominator for ASP.NET projects. So if you work with both WebForms and MVC you'll feel at home in all projects, if you know you have your static resources in that folder.
A: Many ASP.Net Web Forms projects will also have a Controls folder for the ASCX controls.
For css styling, we generally use a styles folder, images for image content (sorta an obvious one), js.
You might have a schemas folder, App_Code for ASHX handlers and other types of application code, and a MasterPages folder.
Some auto-created you might see in a Web Forms project are folders are Properties, App_Data, bin, obj, Packages, and TestResults.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Algorithm for implementing C# yield statement I'd love to figure it out myself but I was wondering roughly what's the algorithm for converting a function with yield statements into a state machine for an enumerator? For example how does C# turn this:
IEnumerator<string> strings(IEnumerable<string> args)
{ IEnumerator<string> enumerator2 = getAnotherEnumerator();
foreach(var arg in arg)
{ enumerator2.MoveNext();
yield return arg+enumerator.Current;
}
}
into this:
bool MoveNext()
{ switch (this.state)
{
case 0:
this.state = -1;
this.enumerator2 = getAnotherEnumerator();
this.argsEnumerator = this.args.GetEnumerator();
this.state = 1;
while (this.argsEnumerator.MoveNext())
{
this.arg = this.argsEnumerator.Current;
this.enumerator2.MoveNext();
this.current = this.arg + this.enumerator2.Current;
this.state = 2;
return true;
state1:
this.state = 1;
}
this.state = -1;
if (this.argsEnumerator != null) this.argsEnumerator.Dispose();
break;
case 2:
goto state1;
}
return false;
}
Of course the result can be completely different depending on the original code.
A: Just spotted this question - I wrote an article on it recently. I'll have to add the other links mentioned here to the article though...
A: Raymond Chen answers this here.
A: The particular code sample you are looking at involves a series of transformations.
Please note that this is an approximate description of the algorithm. The actual names used by the compiler and the exact code it generates may be different. The idea is the same, however.
The first transformation is the "foreach" transformation, which transforms this code:
foreach (var x in y)
{
//body
}
into this code:
var enumerator = y.GetEnumerator();
while (enumerator.MoveNext())
{
var x = enumerator.Current;
//body
}
if (y != null)
{
enumerator.Dispose();
}
The second transformation finds all the yield return statements in the function body, assigns a number to each (a state value), and creates a "goto label" right after the yield.
The third transformation lifts all the local variables and function arguments in the method body into an object called a closure.
Given the code in your example, that would look similar to this:
class ClosureEnumerable : IEnumerable<string>
{
private IEnumerable<string> args;
private ClassType originalThis;
public ClosureEnumerator(ClassType origThis, IEnumerable<string> args)
{
this.args = args;
this.origianlThis = origThis;
}
public IEnumerator<string> GetEnumerator()
{
return new Closure(origThis, args);
}
}
class Closure : IEnumerator<string>
{
public Closure(ClassType originalThis, IEnumerable<string> args)
{
state = 0;
this.args = args;
this.originalThis = originalThis;
}
private IEnumerable<string> args;
private IEnumerator<string> enumerator2;
private IEnumerator<string> argEnumerator;
//- Here ClassType is the type of the object that contained the method
// This may be optimized away if the method does not access any
// class members
private ClassType originalThis;
//This holds the state value.
private int state;
//The current value to return
private string currentValue;
public string Current
{
get
{
return currentValue;
}
}
}
The method body is then moved from the original method to a method inside "Closure" called MoveNext, which returns a bool, and implements IEnumerable.MoveNext.
Any access to any locals is routed through "this", and any access to any class members are routed through this.originalThis.
Any "yield return expr" is translated into:
currentValue = expr;
state = //the state number of the yield statement;
return true;
Any yield break statement is translated into:
state = -1;
return false;
There is an "implicit" yield break statement at the end of the function.
A switch statement is then introduced at the beginning of the procedure that looks at the state number and jumps to the associated label.
The original method is then translated into something like this:
IEnumerator<string> strings(IEnumerable<string> args)
{
return new ClosureEnumerable(this,args);
}
The fact that the state of the method is all pushed into an object and that the MoveNext method uses a switch statement / state variable is what allows the iterator to behave as if control is being passed back to the point immediately after the last "yield return" statement the next time "MoveNext" is called.
It is important to point out, however, that the transformation used by the C# compiler is not the best way to do this. It suffers from poor performance when trying to use "yield" with recursive algorithms. There is a good paper that outlines a better way to do this here:
http://research.microsoft.com/en-us/projects/specsharp/iterators.pdf
It's worth a read if you haven't read it yet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
}
|
Q: What are possible reasons for java.io.IOException: "The filename, directory name, or volume label syntax is incorrect" I am trying to copy a file using the following code:
File targetFile = new File(targetPath + File.separator + filename);
...
targetFile.createNewFile();
fileInputStream = new FileInputStream(fileToCopy);
fileOutputStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[64*1024];
int i = 0;
while((i = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, i);
}
For some users the targetFile.createNewFile results in this exception:
java.io.IOException: The filename, directory name, or volume label syntax is incorrect
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:850)
Filename and directory name seem to be correct. The directory targetPath is even checked for existence before the copy code is executed and the filename looks like this: AB_timestamp.xml
The user has write permissions to the targetPath and can copy the file without problems using the OS.
As I don't have access to a machine this happens on yet and can't reproduce the problem on my own machine I turn to you for hints on the reason for this exception.
A: Try this, as it takes more care of adjusting directory separator characters in the path between targetPath and filename:
File targetFile = new File(targetPath, filename);
A: I just encountered the same problem. I think it has to something do with write access permission. I got the error while trying to write to c:\ but on changing to D:\ everything worked fine.
Apparently Java did not have permission to write to my System Drive (Running Windows 7 installed on C:)
A: This can occur when filename has timestamp with colons, eg. myfile_HH:mm:ss.csv Removing colons fixed the issue.
A: Here is the test program I use
import java.io.File;
public class TestWrite {
public static void main(String[] args) {
if (args.length!=1) {
throw new IllegalArgumentException("Expected 1 argument: dir for tmp file");
}
try {
File.createTempFile("bla",".tmp",new File(args[0]));
} catch (Exception e) {
System.out.println("exception:"+e);
e.printStackTrace();
}
}
}
A: Try to create the file in a different directory - e.g. "C:\" after you made sure you have write access to that directory. If that works, the path name of the file is wrong.
Take a look at the comment in the Exception and try to vary all the elements in the path name of the file. Experiment. Draw conclusions.
A: Remove any special characters in the file/folder name in the complete path.
A: Do you check that the targetPath is a directory, or just that something exists with that name? (I know you say the user can copy it from the operating system, but maybe they're typing something else).
Does targetPath end with a File.separator already?
(It would help if you could log and tell us what the value of targetPath and filename are on a failing case)
A: Maybe the problem is that it is copying the file over the network, to a shared drive? I think java can have problems when writing files using NFS when the path is something like \mypc\myshared folder.
What is the path where this problem happens?
A: Try adding some logging to see exactly what is the name and path the file is trying to create, to ensure that the parent is well a directory.
In addition, you can also take a look at Channels instead of using a loop. ;-)
A: You say "for some users" - so it works for others? What is the difference here, are the users running different instances on different machines, or is this a server that services concurrent users?
If the latter, I'd say it is a concurrency bug somehow - two threads check try to create the file with WinNTFileSystem.createFileExclusively(Native Method) simultaniously.
Neither createNewFile or createFileExclusively are synchronized when I look at the OpenJDK source, so you may have to synchronize this block yourself.
A: Maybe the file already exists. It could be the case if your timestamp resolution is not good enough. As it is an IOException that you are getting, it might not be a permission issue (in which case you would get a SecurityException).
I would first check for file existence before trying to create the file and try to log what's happening.
Look at public boolean createNewFile() for more information on the method you are using.
A: As I was not able to reproduce the error on my own machine or get hands on the machine of the user where the code failed I waited until now to declare an accepted answer.
I changed the code to the following:
File parentFolder = new File(targetPath);
... do some checks on parentFolder here ...
File targetFile = new File(parentFolder, filename);
targetFile.createNewFile();
fileInputStream = new FileInputStream(fileToCopy);
fileOutputStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[64*1024];
int i = 0;
while((i = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, i);
}
After that it worked for the user reporting the problem.
So it seems Alexanders answer did the trick - although I actually use a slightly different constructor than he gave, but along the same lines.
I yet have to talk that user into helping me verifying that the code change fixed the error (instead of him doing something differently) by running the old version again and checking if it still fails.
btw. logging was in place and the logged path seemed ok - sorry for not mentioning that. I took that for granted and found it unnecessarily complicated the code in the question.
Thanks for the helpful answers.
A: A very similar error:-
" ... java.io.IOException: The filename, directory name, or volume label syntax is incorrect"
was generated in Eclipse for me when the TOMCAT home setting had a training backslash.
The minor edit suggested at:-
http://www.coderanch.com/t/556633/Tomcat/java-io-IOException-filename-directory
fixed it for me.
A: FileUtils.copyFile(src,new File("C:\\Users\\daiva\\eclipse-workspace\\PracticeProgram\\Screenshot\\adi.png"));
Try to copy file like this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: What are the security concerns of evaluating user code? I am wondering what security concerns there are to implementing a PHP evaluator like this:
<?php eval($_POST['codeInput']); %>
This is in the context of making a PHP sandbox so sanitising against DB input etc. isn't a massive issue.
Users destroying the server the file is hosted on is.
I've seen Ruby simulators so I was curious what's involved security wise (vague details at least).
Thanks all. I'm not even sure on which answer to accept because they are all useful.
Owen's answer summarises what I suspected (the server itself would be at risk).
arin's answer gives a great example of the potential problems.
Geoff's answer and randy's answer echo the general opinion that you would need to write your own evaluator to achieve simulation type capabilities.
A: The eval() function is hard to sanitize and even if you did there would surely be a way around it. Even if you filtered exec, all you need to do is to somehow glue the string exec into a variable, and then do $variable(). You'd need to really cripple the language to achieve at least some sort of imaginary security.
A: could potentially be in really big trouble if you eval()'d something like
<?php
eval("shell_exec(\"rm -rf {$_SERVER['DOCUMENT_ROOT']}\");");
?>
it's an extreme example but it that case your site would just get deleted. hopefully your permissions wouldn't allow it but, it helps illustrate the need for sanitization & checks.
A: There are a lot of things you could say.. The concerns are not specific to PHP.
Here's the simple answer:
Any input to your machine (or database) needs to be sanitized.
The code snippet you've posted pretty much lets a user run any code they want, so it's especially dangerous.
There is a pretty good introductory article on code injection here:
Wikipedia on Code Injection.
A: If you allow arbitrary code to be run on your server, it's not your server any more.
A: Dear god NO. I cringe even at the title. Allowing user to run any kind of arbitrary code is like handing the server over to them
I know the people above me already said that. But believe me. That's never enough times that someone can tell you to sanitize your input.
If you really, really want to allow user to run some kind of code. Make a subset of the commands available to the user by creating some sort of psudo language that the user can use to do that. A-la the way bbcode or markdown works.
A: If you are looking to build an online PHP interpreter, you will need to build an actual REPL interpreter and not use eval.
Otherwise, never ever execute arbitrary user code. Ever.
A: Do NOT allow unfiltered code to be executed on your server, period.
If you'd like to create a tool that allows for interactive demonstration of a language such as the tool seen here: http://tryruby.hobix.com/ I would work on coding a sub portion of the language yourself. Ideally, you'll be using it to demonstrate simple concepts to new programmers, so it's irrelevant if you properly implement all the features.
By doing this you can control the input via a white list of known acceptable input. If the input isn't on the white list it isn't executed.
Best of luck!
A: don't do that.
they basically have access to anything you can do in PHP (look around the file system, get/set any sort of variables, open connections to other machines to insert code to run, etc...)
A: As already answered, you need to sanitize your inputs. I guess you could use some regex-filtring of some kind to remove unwanted commands such as "exec" and basically every malicious command PHP has got to offer (or which could be exploited), and that's a lot.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Creating a local mailbox for NIS account What is the way of creating a local mailbox for a user that have a NIS account, but doesn't have any local one?
A: I solved the issue by creating a local account with exactly the same login name, UID and GID that it has in NIS. This way a mail box is created for the user and after the user with NIS account logs in it has that mailbox working.
A: Im not sure it's directly possible. Maybe you could add the user as local with Nologin shell and that way give ham an account with mail?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Recommendations for a good C#/ .NET based lexical analyser Can anyone recommend a good .NET based lexical analyser, preferably written in C#?
A: Download the Visual Studio SDK; it includes a managed parser/lexer generator.
(Edit: It was written on my university campus, apparantly :D)
A: ANTLR has a C# target
A: gplex and cs_lex
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why do my hot-deployed files disappear sometimes? (I think Apache eats them) Here's my situation:
*
*Windows Server
*Apache
*CruiseControl
The last step of my CruiseControl deploy scripts copies the build to Apache's htdocs folder, in a "demos" folder (I believe this is referred to as a "hot deploy"?)
All is good and dandy, except that SOMETIMES (not common, but it happens enough that it bugs me), the demos folder doesn't contain the files I built! The old one is gone and the new one isn't there, just vanished.
My gut feeling is that if I try to overwrite a file while someone on the web is downloading it, Apache just deletes it after the download is done? I don't know, it doesn't make any sense.
I looked everywhere and couldn't find even a hint...let's see how good this StackOverflow community really is! :)
Here's the "deploy" target in my ANT script:
<target name="deploy" depends="revertVersionFile">
<copy todir="${deploy.dir}">
<fileset dir="${bin.dir}"/>
</copy>
<copy todir="${deploy.dir}">
<fileset dir="${bin.dir}"/>
</copy>
<available file="${deploy.dir}/MockupsLive.swf" property="mockupsFile"/>
<fail unless="mockupsFile" message="MockupsLive doesn't exist!"/>
<available file="${deploy.dir}/skins/sketch/sketch.swf" property="skinFile"/>
<fail unless="skinFile" message="sketch.swf doesn't exist!"/>
</target>
A: I would suggest creating a backup of the old files prior to copying the new files out. Name the old files with the timestamp for when they were replaced. Doing this and then seeing what is in the directory the next time it fails will most likely give you a clue as to where to look next.
A: Apache won't delete the contents of the directory. Something in the script is removing the contents would be my guess. Does the script create a backup of any kind? Maybe it moves the contents to a backup folder and then copies the build.
You could add a bit of security to that folder to prevent its deletion. Maybe then an error would pop up somewhere and give you an idea as to what is conveniently deleting the directory. :) My guess is its in the script.
A: I think the problem might be somewhere in the CruiseControl file. Most likely what is happening is that the CruiseControl process is tidying up the files somewhere, but maybe due to a lock on the files (potentially by Apache) it cannot write the files back into that folder.
Either way, since "deploy" seems to be the last step, previous steps probably clear the directory and deploy is failing to run, leaving your folder empty at the end of the steps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I read a time value and then insert it into a TimeSpan variable How do I read a time value and then insert it into a TimeSpan variables?
A: If I understand you correctly you're trying to get some user input in the form of "08:00" and want to store the time in a timespan variable?
So.. something like this?
string input = "08:00";
DateTime time;
if (!DateTime.TryParse(input, out time))
{
// invalid input
return;
}
TimeSpan timeSpan = new TimeSpan(time.Hour, time.Minute, time.Second);
A: From MSDN: A TimeSpan object represents a time interval, or duration of time, measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The largest unit of time used to measure duration is a day.
Here's how you can initialize it to CurrentTime (in ticks):
TimeSpan ts = new TimeSpan(DateTime.Now.Ticks);
A: TimeSpan span = new TimeSpan(days,hours,minutes,seconds,milliseonds);
Or, if you mean DateTime:
DateTime time = new DateTime(year,month,day,minutes,seconds,milliseconds);
Where all of the parameters are ints.
A: Perhaps using:
var span = new TimeSpan(hours, minutes, seconds);
If you mean adding two timespans together use:
var newSpan = span.Add(new TimeSpan(hours, minutes, seconds));
For more information see msdn.
A: You can't change the properties of a TimeSpan. You need to create a new instance and pass the new values there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Keyboard shortcut to paste clipboard content into command prompt window (Win XP) Is there a keyboard shortcut for pasting the content of the clipboard into a command prompt window on Windows XP (instead of using the right mouse button)?
The typical Shift+Insert does not seem to work here.
A: Here's a free tool that will do it on Windows. I prefer it to a script as it's easy to set up. It runs as a fast native app, works on XP and up, has configuration settings that allow to remap copy/paste/selection keys for command windows:
Plus I know the developers.
A: Yes.. but awkward. Link
alt + Space, e, k <-- for copy and
alt + Space, e, p <-- for paste.
A: Thanks, Pablo, for referring to AutoHotkey utility.
Since I have Launchy installed which uses Alt+Space I had to modify it a but to add Shift key as shown:
; Paste in command window
^V::
; Spanish menu (Editar->Pegar, I suppose English version is the same, Edit->Paste)
Send !+{Space}ep
return
A: simplest method is just the copy the text that you want to paste it in cmd and open cmd goto "properties"---> "option" tab----> check the (give tick mark) "quickEdit mode" and click "ok" .....now you can paste any text from clipboard by doing right click from ur mouse.
Thank you..
A: Thanks Pablo, just what I was looking for! However, if I can take the liberty of improving your script slightly, I suggest replacing your ^V macro with the following:
; Use backslash instead of backtick (yes, I am a C++ programmer).
#EscapeChar \
; Paste in command window.
^V::
StringReplace clipboard2, clipboard, \r\n, \n, All
SendInput {Raw}%clipboard2%
return
The advantage of using SendInput is that
*
*it doesn't rely on the command prompt system menu having an "Alt+Space E P" menu item to do the pasting (works for English and Spanish, but not for all languages).
*it avoids that nasty flicker you get as the menu is created and destroyed.
Note, it's important to include the "{Raw}" in the SendInput command, in case the clipboard happens to contain "!", "+", "^" or "#".
Note, it uses StringReplace to remove excess Windows carriage return characters. Thanks hugov for that suggestion!
A: This is not really a shortcut but just a quick access to the control menu: Alt-space E P
If you can use your mouse, right click on the cmd window works as paste when I tried it.
A: Theoretically, the application in DOS Prompt has its own clipboard and shortcuts. To import text from Windows clipboard is "extra". However you can use Alt-Space to open system menu of Prompt window, then press E, P to select Edit, Paste menu. However, MS could provide shortcut using Win-key. There is no chance to be used in DOS application.
A: It took me a small while to figure out why your AutoHotkey script does not work with me:
; Use backslash instead of backtick (yes, I am a C++ programmer).
#EscapeChar \
; Paste in command window.
^V::
StringReplace clipboard2, clipboard, \r\n, \n, All
SendInput {Raw}%clipboard2%
return
In fact, it relies on keystrokes and consequently on keyboard layout!
So when you are, as I am, unfortunate to have only an AZERTY keyboard, your suggestion just does not work. And worse, I found no easy way to replace SendInput method or twist its environment to fix this. For example SendInput "1" just does not send digit 1.
I had to turn every character into its unicode to make it work on my computer:
#EscapeChar \
; Paste in command window.
^V::
StringReplace clipboard2, clipboard, \r\n, \n, All
clipboard3 := ""
Loop {
if (a_index>strlen(clipboard2))
break
char_asc := Asc(SubStr(clipboard2, a_Index, 1))
if (char_asc > 127 and char_asc < 256)
add_zero := "0"
else
add_zero := ""
clipboard3 := clipboard3 . "{Asc " . add_zero . char_asc . "}"
}
SendInput %clipboard3%
return
Not very simple...
A: I followed @PabloG's steps as follows
*
*goto http://www.autohotkey.com/ - download autohotkey
*follow simple installation steps
*after installation create new *.ahk file as follows right click on desktop > new > Autohotkey Script > giveAnyFileName.ahk
*right click on this file > Edit
*copy paste autohotkey script given by @PabloG in his answer
*save and close
*double click on file to run
*Done now you should be able to use Ctrl+v for paste in command prompt
A: If you use the clipboard manager Ditto (open source, gratis), you can simply use the shortcut to paste from Ditto, and it will paste the clipboard in CMD for you.
A: There is also a great open source tool called clink, which extends cmd by many features. One of them is being able to use ctrl+v to insert text.
A: I personally use a little AutoHotkey script to remap certain keyboard functions, for the console window (CMD) I use:
; Redefine only when the active window is a console window
#IfWinActive ahk_class ConsoleWindowClass
; Close Command Window with Ctrl+w
$^w::
WinGetTitle sTitle
If (InStr(sTitle, "-")=0) {
Send EXIT{Enter}
} else {
Send ^w
}
return
; Ctrl+up / Down to scroll command window back and forward
^Up::
Send {WheelUp}
return
^Down::
Send {WheelDown}
return
; Paste in command window
^V::
; Spanish menu (Editar->Pegar, I suppose English version is the same, Edit->Paste)
Send !{Space}ep
return
#IfWinActive
A: On Windows 10, you can enable Ctrl + C and Ctrl + V to work in the command prompt:
A: Not really programming related, but I found this on Google, there is not a direct keyboard shortcut, but makes it a little quicker.
To enable or disable QuickEdit mode:
*
*Open the MS-DOS program, or the command prompt.
*Right-click the title bar and press Properties.
*Select the Options tab.
*Check or un-check the QuickEdit Mode box.
*Press OK.
*In the Apply Properties To Shortcut dialog, select the Apply properties to current window only if you wish to change the QuickEdit setting for this session of this window only, or select Modify shortcut that started this window to change the QuickEdit setting for all future invocations of the command prompt, or MS-DOS program.
To Copy text when QuickEdit is enabled:
*
*Click and drag the mouse pointer over the text you want.
*Press Enter (or right-click anywhere in the window) to copy the text to the clipboard.
To Paste text when QuickEdit is enabled:
*
*Right-click anywhere in the window.
To Copy text when QuickEdit is disabled:
*
*Right-click the title bar, press Edit on the menu, and press Mark.
*Drag the mouse over the text you want to copy.
*Press Enter (or right-click anywhere in the window) to copy the text to the clipboard.
To Paste text when QuickEdit is disabled:
*
*Right-click the title bar, press Edit on the menu, and press Paste.
A: You could try using Texter and create something unlikely like:
./p , triggered by space and replacing the text with %c
I just tested it and it works fine. The only gotcha is to use a rare sequence, as Texter cannot restrict this to just cmd.
There are probably other utilities of this kind which could work, and even AutoHotKey, upon which Texter is built could do it better, but Texter is easy :-)
A: A simpler way is to use windows powershell instead of cmd. itworks fine with texter.
A: I've recently found that command prompt has support for context menu via the right mouse click. You can find more details here: http://www.askdavetaylor.com/copy_paste_within_microsoft_windows_command_prompt.html
A: Pretty simple solution may be Console 2, redefine keys and you go.
A: If you're a Cygwin user, you can append the following to your ~/.bashrc file:
stty lnext ^q stop undef start undef
And the following to your ~/.inputrc file:
"\C-v": paste-from-clipboard
"\C-C": copy-to-clipboard
Restart your Cygwin terminal.
(Note, I've used an uppercase C for copy, since CTRL+c is assigned to the break function on most consoles. Season to taste.)
Source
A: Instead of "right click"....start your session (once you're in the command prompt window) by keying Alt/SpaceBar. That will open the Command Prompt window menu and you'll see your familiar, underlined keyboard command shortcuts, just like in Windows GUI.
Good luck!
A: Under VISTA Command prompt:
Click on the System Icon
Select Defaults from the Menu
On the Options tab in the Options group I have
"Quick Edit Mode", "Insert Mode", and "Auto Complete" selected
I think that "Quick Edit Mode" is what makes it work.
To paste whatever is in the Clipboard at the insertion point: Right Click.
To copy from the Command Window
Select by holding down the left mouse button and dragging the pointer across what you want to copy
Once selected, right click
To paste at the insertion point, right click again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "305"
}
|
Q: What are the benefits of dependency injection containers? I understand benefits of dependency injection itself. Let's take Spring for instance. I also understand benefits of other Spring featureslike AOP, helpers of different kinds, etc. I'm just wondering, what are the benefits of XML configuration such as:
<bean id="Mary" class="foo.bar.Female">
<property name="age" value="23"/>
</bean>
<bean id="John" class="foo.bar.Male">
<property name="girlfriend" ref="Mary"/>
</bean>
compared to plain old java code such as:
Female mary = new Female();
mary.setAge(23);
Male john = new Male();
john.setGirlfriend(mary);
which is easier debugged, compile time checked and can be understood by anyone who knows only java.
So what is the main purpose of a dependency injection framework? (or a piece of code that shows its benefits.)
UPDATE:
In case of
IService myService;// ...
public void doSomething() {
myService.fetchData();
}
How can IoC framework guess which implementation of myService I want to be injected if there is more than one? If there is only one implementation of given interface, and I let IoC container automatically decide to use it, it will be broken after a second implementation appears. And if there is intentionally only one possible implementation of an interface then you do not need to inject it.
It would be really interesting to see small piece of configuration for IoC which shows it's benefits. I've been using Spring for a while and I can not provide such example. And I can show single lines which demonstrate benefits of hibernate, dwr, and other frameworks which I use.
UPDATE 2:
I realize that IoC configuration can be changed without recompiling. Is it really such a good idea? I can understand when someone wants to change DB credentials without recompiling - he may be not developer. In your practice, how often someone else other than developer changes IoC configuration? I think that for developers there is no effort to recompile that particular class instead of changing configuration. And for non-developer you would probably want to make his life easier and provide some simpler configuration file.
UPDATE 3:
External configuration of mapping between interfaces and their concrete implementations
What is so good in making it extenal? You don't make all your code external, while you definitely can - just place it in ClassName.java.txt file, read and compile manually on the fly - wow, you avoided recompiling. Why should compiling be avoided?!
You save coding time because you provide mappings declaratively, not in a procedural code
I understand that sometimes declarative approach saves time. For example, I declare only once a mapping between a bean property and a DB column and hibernate uses this mapping while loading, saving, building SQL based on HSQL, etc. This is where the declarative approach works. In case of Spring (in my example), declaration had more lines and had the same expressiveness as corresponding code. If there is an example when such declaration is shorter than code - I would like to see it.
Inversion of Control principle allows for easy unit testing because you can replace real implementations with fake ones (like replacing SQL database with an in-memory one)
I do understand inversion of control benefits (I prefer to call the design pattern discussed here as Dependency Injection, because IoC is more general - there are many kinds of control, and we are inverting only one of them - control of initialization). I was asking why someone ever needs something other than a programming language for it. I definitely can replace real implementations with fake ones using code. And this code will express same thing as configuration - it will just initialize fields with fake values.
mary = new FakeFemale();
I do understand benefits of DI. I do not understand what benefits are added by external XML configuration compared to configuring code that does the same. I do not think that compiling should be avoided - I compile every day and I'm still alive. I think configuration of DI is bad example of declarative approach. Declaration can be useful if is declared once AND is used many times in different ways - like hibernate cfg, where mapping between bean property and DB column is used for saving, loading, building search queries, etc. Spring DI configuration can be easily translated to configuring code, like in the beginning of this question, can it not? And it is used only for bean initialization, isn't it? Which means a declarative approach does not add anything here, does it?
When I declare hibernate mapping, I just give hibernate some information, and it works based on it - I do not tell it what to do. In case of spring, my declaration tells spring exactly wht to do - so why declare it, why not just do it?
LAST UPDATE:
Guys, a lot of answers are telling me about dependency injection, which I KNOW IS GOOD.
The question is about purpose of DI configuration instead of initializing code - I tend to think that initializing code is shorter and clearer.
The only answer I got so far to my question, is that it avoids recompiling, when the configuration changes. I guess I should post another question, because it is a big secret for me, why compiling should be avoided in this case.
A: This is a bit of a loaded question, but I tend to agree that huge amounts of xml configuration doesn't really amount to much benefit. I like my applications to be as light on dependencies as possible, including the hefty frameworks.
They simplify the code a lot of the times, but they also have an overhead in complexity that makes tracking down problems rather difficult (I have seen such problems first hand, and straight Java I would be a lot more comfortable dealing with).
I guess it depends on style a bit, and what you are comfortable with... do you like to fly your own solution and have the benefit of knowing it inside out, or bank on existing solutions that may prove difficult when the configuration isn't just right? It's all a tradeoff.
However, XML configuration is a bit of a pet peeve of mine... I try to avoid it at all costs.
A: Any time you can change your code to data you're making a step in the right direction.
Coding anything as data means that your code itself is more general and reusable. It also means that your data may be specified in a language that fits it exactly.
Also, an XML file can be read into a GUI or some other tool and easily manipulated pragmatically. How would you do that with the code example?
I'm constantly factoring things most people would implement as code into data, it makes what code is left MUCH cleaner. I find it inconceivable that people will create a menu in code rather than as data--it should be obvious that doing it in code is just plain wrong because of the boilerplate.
A: For myself one of the main reasons to use an IoC (and make use of external configuration) is around the two areas of:
*
*Testing
*Production maintenance
Testing
If you split your testing into 3 scenarios (which is fairly normal in large scale development):
*
*Unit testing
*Integration testing
*Black box testing
What you will want to do is for the last two test scenarios (Integration & Black box), is not recompile any part of the application.
If any of your test scenarios require you to change the configuration (ie: use another component to mimic a banking integration, or do a performance load), this can be easily handled (this does come under the benefits of configuring the DI side of an IoC though.
Additionally if your app is used either at multiple sites (with different server and component configuration) or has a changing configuration on the live environment you can use the later stages of testing to verify that the app will handle those changes.
Production
As a developer you don't (and should not) have control of the production environment (in particular when your app is being distributed to multiple customers or seperate sites), this to me is the real benefit of using both an IoC and external configuration, as it is up to the infrastructure/production support to tweak and adjust the live environment without having to go back to developers and through test (higher cost when all they want to do is move a component).
Summary
The main benefits that external configuration of an IoC come from giving others (non-developers) the power to configure your application, in my experience this is only useful under a limited set of circumstances:
*
*Application is distributed to multiple sites/clients where environments will differ.
*Limited development control/input over the production environment and setup.
*Testing scenarios.
In practice I've found that even when developing something that you do have control over the environment it will be run on, over time it is better to give someone else the capabilities to change the configuration:
*
*When developing you don't know when it will change (the app is so useful your company sells it to someone else).
*I don't want to be stuck with changing the code every time a slight change is requested that could have been handled by setting up and using a good configuration model.
Note: Application refers to the complete solution (not just the executable), so all files required for the application to run.
A: The reason for using a DI container are that you don't have to have a billion properties pre-configured in your code that are simply getters and setters. Do you really want to hardcode all those with new X()? Sure, you can have a default, but the DI container allows the creation of singletons which is extremely easy and allows you to focus on the details of the code, not the miscellaneous task of initializing it.
For example, Spring allows you to implement the InitializingBean interface and add an afterPropertiesSet method (you may also specify an "init-method" to avoid coupling your code to Spring). These methods will allow you to ensure that any interface specified as a field in your class instance is configured correctly upon startup, and then you no longer have to null-check your getters and setters (assuming you do allow your singletons to remain thread-safe).
Furthermore, it is much easier to do complex initializations with a DI container instead of doing them yourself. For instance, I assist with using XFire (not CeltiXFire, we only use Java 1.4). The app used Spring, but it unfortunately used XFire's services.xml configuration mechanism. When a Collection of elements needed to declare that it had ZERO or more instances instead of ONE or more instances, I had to override some of the provided XFire code for this particular service.
There are certain XFire defaults defined in its Spring beans schema. So, if we were using Spring to configure the services, the beans could have been used. Instead, what happened was that I had to supply an instance of a specific class in the services.xml file instead of using the beans. To do this, I needed to provide the constructor and set up the references declared in the XFire configuration. The real change that I needed to make required that I overload a single class.
But, thanks to the services.xml file, I had to create four new classes, setting their defaults according to their defaults in the Spring configuration files in their constructors. If we had been able to use the Spring configuration, I could have just stated:
<bean id="base" parent="RootXFireBean">
<property name="secondProperty" ref="secondBean" />
</bean>
<bean id="secondBean" parent="secondaryXFireBean">
<property name="firstProperty" ref="thirdBean" />
</bean>
<bean id="thirdBean" parent="thirdXFireBean">
<property name="secondProperty" ref="myNewBean" />
</bean>
<bean id="myNewBean" class="WowItsActuallyTheCodeThatChanged" />
Instead, it looked more like this:
public class TheFirstPointlessClass extends SomeXFireClass {
public TheFirstPointlessClass() {
setFirstProperty(new TheSecondPointlessClass());
setSecondProperty(new TheThingThatWasHereBefore());
}
}
public class TheSecondPointlessClass extends YetAnotherXFireClass {
public TheSecondPointlessClass() {
setFirstProperty(TheThirdPointlessClass());
}
}
public class TheThirdPointlessClass extends GeeAnotherXFireClass {
public TheThirdPointlessClass() {
setFirstProperty(new AnotherThingThatWasHereBefore());
setSecondProperty(new WowItsActuallyTheCodeThatChanged());
}
}
public class WowItsActuallyTheCodeThatChanged extends TheXFireClassIActuallyCareAbout {
public WowItsActuallyTheCodeThatChanged() {
}
public overrideTheMethod(Object[] arguments) {
//Do overridden stuff
}
}
So the net result is that four additional, mostly pointless Java classes had to be added to the codebase to achieve the affect that one additional class and some simple dependency container information achieved. This isn't the "exception that proves the rule", this IS the rule...handling quirks in code is much cleaner when the properties are already provided in a DI container and you're simply changing them to suit a special situation, which happens more often than not.
A: I have your answer
There are obviously trade offs in each approach, but externalized XML configuration files are useful for enterprise development in which build systems are used to compile the code and not your IDE. Using the build system, you may want to inject certain values into your code - for example the version of the build (which could be painful to have to update manually each time you compile). The pain is greater when your build system pulls code off of some version control system. Modifying simple values at compile time would require you to change a file, commit it, compile, and then revert each time for each change. These aren't changes that you want to commit into your version control.
Other useful use cases regarding the build system and external configs:
*
*injecting styles/stylesheets for a single code base for different builds
*injecting different sets of dynamic content (or references to them) for your single code base
*injecting localization context for different builds/clients
*changing a webservice URI to a backup server (when the main one goes down)
Update:
All the above examples were on things that didn't necessarily require dependencies on classes. But you can easily build up cases where both a complex object and automation is necessary - for example:
*
*Imagine you had a system in which it monitored the traffic of your website. Depending on the # of concurrent users, it turns on/off a logging mechanism. Perhaps while the mechanism is off, a stub object is put in its place.
*Imagine you had a web conferencing system in which depending on the # of users, you want to switch out the ability to do P2P depending on # of participants
A: You don't need to recompile your code each time you change something in configuration. It will simplify program deployment and maintenance. For example you can swap one component with another with just 1 change in config file.
A: You can slot in a new implementation for girlfriend. So new female can be injected without recompiling your code.
<bean id="jane" class="foo.bar.HotFemale">
<property name="age" value="19"/>
</bean>
<bean id="mary" class="foo.bar.Female">
<property name="age" value="23"/>
</bean>
<bean id="john" class="foo.bar.Male">
<property name="girlfriend" ref="jane"/>
</bean>
(The above assumes Female and HotFemale implement the same GirlfFriend interface)
A: Dependency injection is a coding style that has its roots in the observation that object delegation is usually a more useful design pattern than object inheritance (i.e., the object has-a relationship is more useful than the object is-a relationship). One other ingredient is necessary however for DI to work, that of creating object interfaces. Combining these two powerful design patterns software engineers quickly realized that they could create flexible loosely coupled code and thus the concept of Dependency Injection was born. However it wasn't until object reflection became available in certain high level languages that DI really took off. The reflection component is core to most of today's DI systems today because the really cool aspects of DI require the ability to programmatically select objects and configure and inject them into other objects using a system external and independent to the objects themselves.
A language must provide good support for both normal Object Oriented programming techniques as well as support for object interfaces and object reflection (for example Java and C#). While you can build programs using DI patterns in C++ systems its lack of reflection support within the language proper prevents it from supporting application servers and other DI platforms and hence limits the expressiveness of the DI patterns.
Strengths of a system built using DI patterns:
*
*DI code is much easier to reuse as the 'depended' functionality is extrapolated into well defined interfaces, allowing separate objects whose configuration is handled by a suitable application platform to be plugged into other objects at will.
*DI code is much easier to test. The functionality expressed by the object can be tested in a black box by building 'mock' objects implementing the interfaces expected by your application logic.
*DI code is more flexible. It is innately loosely coupled code -- to an extreme. This allows the programmer to pick and choose how objects are connected based exclusively on their required interfaces on one end and their expressed interfaces on the other.
*External (Xml) configuration of DI objects means that others can customize your code in unforeseen directions.
*External configuration is also a separation of concern pattern in that all problems of object initialization and object interdependency management can be handled by the application server.
*Note that external configuration is not required to use the DI pattern, for simple interconnections a small builder object is often adequate. There is a tradeoff in flexibility between the two. A builder object is not as flexible an option as an externally visible configuration file. The developer of the DI system must weigh the advantages of flexibility over convenience, taking care that small scale, fine grain control over object construction as expressed in a configuration file may increase confusion and maintenance costs down the line.
Definitely DI code seems more cumbersome, the disadvantages of having all of those XML files that configure objects to be injected into other objects appears difficult. This is, however, the point of DI systems. Your ability to mix and match code objects as a series of configuration settings allows you to build complex systems using 3rd party code with minimal coding on your part.
The example provided in the question merely touches on the surface of the expressive power that a properly factored DI object library can provide. With some practice and a lot of self discipline most DI practitioners find that they can build systems that have 100% test coverage of application code. This one point alone is extraordinary. This is not 100% test coverage of a small application of a few hundred lines of code, but 100% test coverage of applications comprising hundreds of thousands of lines of code. I am at a loss of being able to describe any other design pattern that provides this level of testability.
You are correct in that an application of a mere 10s of lines of code is easier to understand than several objects plus a series of XML configuration files. However as with most powerful design patterns, the gains are found as you continue to add new features to the system.
In short, large scale DI based applications are both easier to debug and easier to understand. While the Xml configuration is not 'compile time checked' all application services that this author is aware of will provide the developer with error messages if they attempt to inject an object having an incompatible interface into another object. And most provide a 'check' feature that covers all known objects configurations. This is easily and quickly done by checking that the to-be-injected object A implements the interface required by object B for all configured object injections.
A: In the .NET world, most of IoC frameworks provide both XML and Code configuration.
StructureMap and Ninject, for example, use fluent interfaces to configure containers. You are no longer constrained to use XML configuration files. Spring, which also exists in .NET, heavily relies on XML files since it is his historical main configuration interface, but it is still possible to configure containers programmatically.
A: Ease of combining partial configurations into a final complete configuration.
For example, in web applications, the model, view and controllers are typically specified in separate configuration files. Use the declarative approach, you can load, for example:
UI-context.xml
Model-context.xml
Controller-context.xml
Or load with a different UI and a few extra controllers:
AlternateUI-context.xml
Model-context.xml
Controller-context.xml
ControllerAdditions-context.xml
To do the same in code requires an infrastructure for combining partial configurations. Not impossible to do in code, but certainly easier to do using an IoC framework.
A: Often, the important point is who is changing the configuration after the program was written. With configuration in code you implicitly assume that person changing it has the same skills and access to source code etc as the original author had.
In production systems it is very practical to extract some subset of settings (e.g. age in you example) to XML file and allow e.g. system administrator or support personal to change the value without giving them the full power over source code or other settings - or just to isolate them from complexities.
A: From a Spring perspecitve I can give you two answers.
First the XML configuration isn't the only way to define the configuration. Most things can be configured using annotations and the things that must be done with XML are configuration for code that you aren't writing anyways, like a connection pool that you are using from a library. Spring 3 includes a method for defining the DI configuration using Java similar to the hand rolled DI configuration in your example. So using Spring does not mean that you have to use an XML based configuration file.
Secondly Spring is a lot more than just a DI framework. It has lots of other features including transaction management and AOP. The Spring XML configuration mixes all these concepts together. Often in the same configuration file I'm specifying bean dependencies, transaction settings and adding session scoped beans that actually handled using AOP in the background. I find the XML configuration provides a better place to manage all these features. I also feel that the annotation based configuration and XML configuration scale up better than doing Java based configuration.
But I do see your point and there isn't anything wrong with defining the dependency injection configuration in Java. I normally do that myself in unit tests and when I'm working on a project small enough that I haven't added a DI framework. I don't normally specify configuration in Java because to me that's the kind plumbing code that I'm trying to get away from writing when I chose to use Spring. That's a preference though, it doesn't mean that XML configuration is superior to Java based configuration.
A: Spring also has a properties loader. We use this method to set variables that are dependant on the environment (e.g. development, testing, acceptance, production, ...). This could be for example the queue to listen to.
If there is no reason why the property would change, there is also no reason to configure it in this way.
A: Your case is very simple and therefore doesn't need an IoC (Inversion of Control) container like Spring. On the other hand, when you "program to interfaces, not implementations" (which is a good practice in OOP), you can have code like this:
IService myService;
// ...
public void doSomething() {
myService.fetchData();
}
(note that the type of myService is IService -- an interface, not a concrete implementation). Now it can be handy to let your IoC container automatically provide the correct concrete instance of IService during initialization - when you have many interfaces and many implementations, it can be cumbersome to do that by hand. Main benefits of an IoC container (dependency injection framework) are:
*
*External configuration of mapping between interfaces and their concrete implementations
*IoC container handles some tricky issues like resolving complicated dependency graphs, managing component's lifetime etc.
*You save coding time because you provide mappings declaratively, not in a procedural code
*Inversion of Control principle allows for easy unit testing because you can replace real implementations with fake ones (like replacing SQL database with an in-memory one)
A: Initializing in an XML config file will simplify your debugging / adapting work with a client who has your app deployed on their computers. (Because it doesn't require recompilation + binary files replacement)
A: One of the most appealing reasons is the "Hollywood principle": don't call us, we'll call you. A component is not required to do the lookups to other components and services itself; instead they are provided to it automatically. In Java, this means that it is no longer necessary to do JNDI lookups inside the component.
It is also lots easier to unit test a component in isolation: instead of giving it an actual implementation of the components it needs, you simply use (possibly auto generated) mocks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "105"
}
|
Q: Which program in Visual Studio lets me look into DLLs to see its API? See the question. I want to see the methods and classes offered by a DLLs library.
A: *
*ILSpy is an open-source tool which allows you to browse an assembly's packages and classes and also to decompile code.
*Another free-of-charge tool is JetBrain's dotPeek.
A: There's also the DLL export viewer if you don't have VS installed on a machine.
A: If the DLL is a .NET assembly you might want to take a look at Reflector for a more detailed view.
A: This is exactly what the Object Browser is for.
*
*Add a reference to the DLL.
*Right click it in the list.
*Click View in Object Browser.
A: If you have limited options to download: In Visual Studio you could use Visual Studio Developer Command Prompt.
Open it from windows menu -> All programs -> Visual Studio XX -> Visual Studio Tools -> Developer Command Prompt.
Then: run command: ildasm
Example ildasm:
ildasm c:\MyNetAssembly.dll
If you have access to download any program you could use better options:
IlSpy
dotPeek
.net reflector
JustDecompile
A: There's a dependency tracker tool that comes with the Windows SDK (formerly the Platform SDK), it's got a reasonable GUI for looking inside executables and DLL's.
There are also some command line tools that you can use to see inside of dll's, dumpbin in particular - check the MSDN help in visual studio for more information. You can run these tools from the command prompt in the Visual Studio start menu folder.
A: For those coming from the old Visual Studio 6.0 days:
Dependency Walker is a nice free tool, that was formerly part of Visual Studio.
http://www.dependencywalker.com/
I like it still. Here is a screen shot:
A: Outside of Visual Studio, you can use a dependency tool which is able to inspect DLL and EXE imports and exports, it integrates with the shell and is very easy to use. It comes with some Microsoft SDKs. If you want to avoid the hassle of downloading and installing SDK just because of this, easy download links for all 32b/64b platforms are available at http://www.dependencywalker.com/
Microsoft documentation (no download) is available at MicroSoft Technet
Similar functionality is also available in SysInternals Process Explorer - best suited when inspecting running processes.
A: In Visual Studio 2022 (and without creating or opening a solution) you can view a DLL's members.
*
*Open the Object Browser Tool Window (from the View option in the Main Menu).
*In that window it'll probably show a list of .NET components, but near the top there's a browse button (three dots). Click this.
*Here you'll add any DLLs you want to create a "Custom Component Set". Once you select and Add your DLL, then click OK.
You should see your DLL members in the Object Browser now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "56"
}
|
Q: How do I get a list of all subdomains of a domain? I want to find out all the subdomains of a given domain. I found a hint which tells me to dig the authoritative Nameserver with the following option:
dig @ns1.foo.example example.com axfr
But this never works. Has anyone a better idea/approach
A: You can only do this if you are connecting to a DNS server for the domain -and- AXFR is enabled for your IP address. This is the mechanism that secondary systems use to load a zone from the primary. In the old days, this was not restricted, but due to security concerns, most primary name servers have a whitelist of: secondary name servers + a couple special systems.
If the nameserver you are using allows this then you can use dig or nslookup.
For example:
#nslookup
>ls example.com
NOTE: because nslookup is being deprecated for dig and other newere tools, some versions of nslookup do not support "ls", most notably macOS X's bundled version.
A: robotex tools which are free will let you do this but they make you enter the ip of the domain first:
*
*find out the ip (there's a good ff plugin which does this but I can't post the link cos this is my first post here!)
*do an ip search on robotex: http://www.robtex.com/ip/
*in the results page that follows click on the domain you're interested in>
*you are taken to a page that lists all subdomains + a load of other information such as mail server info
A: In Windows nslookup the command is
ls -d example.com > outfile.txt
which stores the subdomain list in outfile.txt
few domains these days allow this
A: You can use:
$ host -l example.com
Under the hood, this uses the AXFR query mentioned above. You might not be allowed to do this though. In that case, you'll get a transfer failed message.
A: If the DNS server is configured properly, you won't be able to get the entire domain. If for some reason is allows zone transfers from any host, you'll have to send it the correct packet to make that request. I suspect that's what the dig statement you included does.
A: *
*dig example.com soa
*dig @ns.SOA.example example.com axfr
A: The hint (using axfr) only works if the NS you're querying (ns1.foo.example in your example) is configured to allow AXFR requests from the IP you're using; this is unlikely, unless your IP is configured as a secondary for the domain in question.
Basically, there's no easy way to do it if you're not allowed to use axfr. This is intentional, so the only way around it would be via brute force (i.e. dig a.example.com, dig b.example.com, ...), which I can't recommend, as it could be viewed as a denial of service attack.
A: If you can't get this information from DNS (e.g. you aren't authorized) then one alternative is to use Wolfram Alpha.
*
*Enter the domain into the search box and run the search. (E.g. stackexchange.com)
*In the 3rd section from the top (named "Web statistics for all of stackexchange.com") click Subdomains
*In the Subdomains section click More
You will be able to see a list of sub-domains there. Although I suspect it does not show ALL sub-domains.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "273"
}
|
Q: How do you treat the deployment of configuration files on different systems in Subversion? Subversion is a great way to update our web applications on our servers. With a simple svn update all changed files get... well, changed.
Except for the omnipresent configuration files such as config.php which hold the database access configuration, server paths etc. And are therefore different on my local development system and the remote server.
With the update command, a file modified on the server won't get overwritten, but if I change the file locally and commit it, the server gets the wrong configuration file.
But I don't want to set the svn:ignore property either, since the config file belongs to the project.
Is there a Subversion-mechanism which will allow me to easily handle these kind of files? Or is the only way to solve this problem to make a system switch within the config file which will determine the executing system and sets the configuration accordingly?
A: Create a template for the file (e.g. config.php-default) and let the user copy the template. She can also do a diff to see what changed between versions to incorporate these changes in the locally deployed version of the file.
A: You may want to consider the fact that developers won't (And probably shouldn't) have access to the username/passwords for the production machine.
To cope with this, such configuration should be considered to be 'deployment details', rather than overall application configuration.
Even when you make this conceptual distinction, you still need to deal with the different deployment environments but, as you seem to be dealing with PHP, I can't comment on specifics for your case.
As Lars mentioned, one possible J2EE solution is to store such details under JNDI, making the exact same application binary deployable on any environment, leaving DBAs/Admins to set the username/password for each machine.
A: On the projects I am currently working on we have 2 properties files for the database schema information - one for the production environment and one for development. We have a class that loads all of our properties for the module being executed, with logic that determines which file to load.
Since our development environment locally is a Windows file system and the production servers operate on UNIX file systems, our solution was to determine the operating system of the host and load the correct file.
We keep these directly within our source control in order to keep a history of any changes made. I think we learned a lesson from our (internal) client finger pointing in regards to INSANELY FREQUENT REQUIREMENTS CHANGES, in that we needed to be able to defend any of the past changes to the files.
This may be unique for our situation, but I've found this to be extremely helpful, especially if I am trying to replicate a test run from a previous revision.
A: Some possible solutions:
If you are using a J2EE app server, you can look up properties through JNDI, there are tools to easily set and view them on the server.
You can have a default properties file in your subversion server, but look elsewhere on the servers (outside the parts of the project that are checked into svn) for the real properties file, but then you usually get OS dependent paths and have to remember to update the real properties files manually when you add new properties in your svn file.
You can set the properties in a properties file as part of the build, and pass in a parameter to the build command to tell it which server environment to build for. This can feel a bit roundabout, and you have to remember to update the build script with new properties. But it can work well - if you set up a Continuous Integration server, it can build for all the different environments and test the bundles for you. Then you know you have something deployment ready.
A: I find the easiest way is to switch on the machine's hostname. I have a .ini file with a general section that also overrides this for production, testing and development systems.
[general]
info=misc
db.password=secret
db.host=localhost
[production : general]
info=only on production system
db.password=secret1
[testing : general]
info=only on test system
db.password=secret2
[dev : general]
info=only on dev system
db.password=secret3
So dev:db.password == 'secret3', but dev:db.host == 'localhost', from the original 'general' group.
The 'production', 'testing' and 'dev' could be the machine hostnames, or they are aliases for them set from some other mechanism in a configuration control script.
A: You can also make your config file domain depended. This way you can create a configuration for you local machine and for the production server(s). You do need to build the logic of course to handle this.
If you run apache webserver you can easily configure it to have every developer using their own (sub)domain on their local box instead of just using localhost. This way, every developer can use their own configuration.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/131993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Deployment of custom content type, forms, cqwp, and xsl Right now I have a visual studio project which contains a custom content type that I made. It also contains all the necessary files for making a sharepoint solution (wsp) file and a script to generate this.
Now, I would like to do 2 things.
First, I'd like to create a custom display form for the content type and include it in my solution so that it is automatically deployed when I deploy my solution. How do I include this in my solution and make my content type use it?
Secondly, you can query this type with the CQWP. I've thought about exporting it, adding more common view fields, and then modifying the XSL that is used to render it. How do I include this into my solution so that it is also deployed. I know i can export the CQWP webpart once it's all setup and include it in my project as a feature. But what abuot the XSL?
Looking forward to see your suggestions, cheers.
Did as described in the first answer. Worked like a charm.
A: Use STSDev to create the solution package.
That should help with creating the WSP. The custom form, CQWP webpart and the .xls file should also be deployable within the project.
To deploy the xslt, your feature will have an
<ElementManifest Location="mywebpartManifest.xml">
This then points to a files such as
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Module Name="Yourfile.xslt" Url="Style Library" Path="" RootWebOnly="TRUE">
<File Url="yourfile.xslt" Type="GhostableInLibrary" />
</Module>
</Elements>
for the webpart:
<Module Name="myWebpart" List="113" Url="_catalogs/wp" RootWebOnly="FALSE">
<File Url="myWebpart.webpart" Type="GhostableInLibrary" />
</Module>
Now that file will need to be contained in the solution manifest.xml. This is done automatically from the STSDev project.
e.g.
<Resources>
<Resource Location="SimpleFeature\Feature.xml"/>
The actual schemas are:
Site
Solution
Feature
and a link to someone else with the issue
A: But where in the folder structure do you deploy the form and the .xsl to?
A: I have followed your guide and although it deploys the xslt to the feature in 12 Hive it does not place it in the correct style library folder
A: You need to deactivate / reactivate the feature. This will give you any error messages that are associated with copying the file over.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Send To/Mail Recipient from WSH I am trying to implement in windows scripting host the same function as windows Send To/Mail Recipient does. Did not find anything usefull on google except steps to instantiate Outlook.Application and directly calling its methods.
I need to go the same path as windows do, as there is a mix of Outlook and Lotus Notes installed, I don't see it good to perform some sort of testing and deciding which object to talk to...
What I have found is that the actual work is done by sendmail.dll, there is a handler defined in registry under HKEY_CLASSES_ROOT\CLSID\{9E56BE60-C50F-11CF-9A2C-00A0C90A90CE}. I would like either to use this dll somehow or to simulate the same steps it does.
Thanks for your input.
A: The contents of the sent to menu in Windows is a bunch of files (usually links) in the C:\Documents and Settings\username\SendTo folder. You need to add your script - or a link to it - there.
For your script you could check if certain registry keys exist to detect Outlook and Lotus Notes.
Or if you don't care if the message shows up in sent items, just use CDOSYS.NewMail to send the message directly to the SMTP-server.
CDOSYS documentation
A: I found one item on CodeProject from 2003 that might be relevant.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to send Email through a C++ program? How can I send an email from C++? Is there a good cross-platform (MS Windows, Linux etc) library that I can use? I'm using GCC (cygwin on MS Windows).
A: Check out C-Client
*
*Apache license
*Very established library ( makers of Pine email reader, UW-IMAP Server, etc. )
*Supports IMAP, POP, SMTP, and NNTP
*Unix and Windows
A: Look at VMime.
VMime is an all-in-one Internet mail library. This well designed, powerful C++ class library allows you to parse/build/modify MIME messages. With the messaging module, you can connect to POP3/IMAP/SMTP/Maildir very easily, and with the same code!
A: Check out jwSMTP - a cross-platform SMTP class.
http://johnwiggins.net/jwsmtp/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: image archive VS image strip i've noticed that plenty of games / applications (very common on mobile builds) pack numerous images into an image strip.
I figured that the advantages in this are making the program more tidy (file system - wise) and reducing (un)installation time. During the runtime of the application, the entire image strip is allocated and copied from FS to RAM.
On the contrary, images can be stored in an image archive and unpacked during runtime to a number of image structures in RAM.
The way I see it, the image strip approach is less efficient because of worse caching performance and because that even if the optimal rectangle packing algorithm is used, there will be empty spaces between the stored images in the strip, causing a waste of RAM.
What are the advantages in using an image strip over using an image archive file?
A: Caching will not be as much of an issue as you think, if the images in the strip are likely to appear at the same time - i.e. are all part of an animation.
As far as packing algorithms are concerned, most generic algorithms produce similar levels of efficiency - to get huge increases in packing efficiency you normally have to write an algorithm that is optimised for the dataset involved.
As is usually the case with optimization of any kind - caching or packing - don't worry about it until it's been proved to be an issue, and then you need to approach the problem with a good understanding of the context.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Servlet for serving static content I deploy a webapp on two different containers (Tomcat and Jetty), but their default servlets for serving the static content have a different way of handling the URL structure I want to use (details).
I am therefore looking to include a small servlet in the webapp to serve its own static content (images, CSS, etc.). The servlet should have the following properties:
*
*No external dependencies
*Simple and reliable
*Support for If-Modified-Since header (i.e. custom getLastModified method)
*(Optional) support for gzip encoding, etags,...
Is such a servlet available somewhere? The closest I can find is example 4-10 from the servlet book.
Update: The URL structure I want to use - in case you are wondering - is simply:
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/static/*</url-pattern>
</servlet-mapping>
So all requests should be passed to the main servlet, unless they are for the static path. The problem is that Tomcat's default servlet does not take the ServletPath into account (so it looks for the static files in the main folder), while Jetty does (so it looks in the static folder).
A: I came up with a slightly different solution. It's a bit hack-ish, but here is the mapping:
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>myAppServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
This basically just maps all content files by extension to the default servlet, and everything else to "myAppServlet".
It works in both Jetty and Tomcat.
A: I found great tutorial on the web about some workaround. It is simple and efficient, I used it in several projects with REST urls styles approach:
http://www.kuligowski.pl/java/rest-style-urls-and-url-mapping-for-static-content-apache-tomcat,5
A: There is no need for completely custom implementation of the default servlet in this case, you can use this simple servlet to wrap request to the container's implementation:
package com.example;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DefaultWrapperServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
RequestDispatcher rd = getServletContext().getNamedDispatcher("default");
HttpServletRequest wrapped = new HttpServletRequestWrapper(req) {
public String getServletPath() { return ""; }
};
rd.forward(wrapped, resp);
}
}
A: I did this by extending the tomcat DefaultServlet (src) and overriding the getRelativePath() method.
package com.example;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.servlets.DefaultServlet;
public class StaticServlet extends DefaultServlet
{
protected String pathPrefix = "/static";
public void init(ServletConfig config) throws ServletException
{
super.init(config);
if (config.getInitParameter("pathPrefix") != null)
{
pathPrefix = config.getInitParameter("pathPrefix");
}
}
protected String getRelativePath(HttpServletRequest req)
{
return pathPrefix + super.getRelativePath(req);
}
}
... And here are my servlet mappings
<servlet>
<servlet-name>StaticServlet</servlet-name>
<servlet-class>com.example.StaticServlet</servlet-class>
<init-param>
<param-name>pathPrefix</param-name>
<param-value>/static</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>StaticServlet</servlet-name>
<url-pattern>/static/*</url-pattern>
</servlet-mapping>
A: I've had good results with FileServlet, as it supports pretty much all of HTTP (etags, chunking, etc.).
A: Abstract template for a static resource servlet
Partly based on this blog from 2007, here's a modernized and highly reusable abstract template for a servlet which properly deals with caching, ETag, If-None-Match and If-Modified-Since (but no Gzip and Range support; just to keep it simple; Gzip could be done with a filter or via container configuration).
public abstract class StaticResourceServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final long ONE_SECOND_IN_MILLIS = TimeUnit.SECONDS.toMillis(1);
private static final String ETAG_HEADER = "W/\"%s-%s\"";
private static final String CONTENT_DISPOSITION_HEADER = "inline;filename=\"%1$s\"; filename*=UTF-8''%1$s";
public static final long DEFAULT_EXPIRE_TIME_IN_MILLIS = TimeUnit.DAYS.toMillis(30);
public static final int DEFAULT_STREAM_BUFFER_SIZE = 102400;
@Override
protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException ,IOException {
doRequest(request, response, true);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doRequest(request, response, false);
}
private void doRequest(HttpServletRequest request, HttpServletResponse response, boolean head) throws IOException {
response.reset();
StaticResource resource;
try {
resource = getStaticResource(request);
}
catch (IllegalArgumentException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
if (resource == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String fileName = URLEncoder.encode(resource.getFileName(), StandardCharsets.UTF_8.name());
boolean notModified = setCacheHeaders(request, response, fileName, resource.getLastModified());
if (notModified) {
response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
setContentHeaders(response, fileName, resource.getContentLength());
if (head) {
return;
}
writeContent(response, resource);
}
/**
* Returns the static resource associated with the given HTTP servlet request. This returns <code>null</code> when
* the resource does actually not exist. The servlet will then return a HTTP 404 error.
* @param request The involved HTTP servlet request.
* @return The static resource associated with the given HTTP servlet request.
* @throws IllegalArgumentException When the request is mangled in such way that it's not recognizable as a valid
* static resource request. The servlet will then return a HTTP 400 error.
*/
protected abstract StaticResource getStaticResource(HttpServletRequest request) throws IllegalArgumentException;
private boolean setCacheHeaders(HttpServletRequest request, HttpServletResponse response, String fileName, long lastModified) {
String eTag = String.format(ETAG_HEADER, fileName, lastModified);
response.setHeader("ETag", eTag);
response.setDateHeader("Last-Modified", lastModified);
response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME_IN_MILLIS);
return notModified(request, eTag, lastModified);
}
private boolean notModified(HttpServletRequest request, String eTag, long lastModified) {
String ifNoneMatch = request.getHeader("If-None-Match");
if (ifNoneMatch != null) {
String[] matches = ifNoneMatch.split("\\s*,\\s*");
Arrays.sort(matches);
return (Arrays.binarySearch(matches, eTag) > -1 || Arrays.binarySearch(matches, "*") > -1);
}
else {
long ifModifiedSince = request.getDateHeader("If-Modified-Since");
return (ifModifiedSince + ONE_SECOND_IN_MILLIS > lastModified); // That second is because the header is in seconds, not millis.
}
}
private void setContentHeaders(HttpServletResponse response, String fileName, long contentLength) {
response.setHeader("Content-Type", getServletContext().getMimeType(fileName));
response.setHeader("Content-Disposition", String.format(CONTENT_DISPOSITION_HEADER, fileName));
if (contentLength != -1) {
response.setHeader("Content-Length", String.valueOf(contentLength));
}
}
private void writeContent(HttpServletResponse response, StaticResource resource) throws IOException {
try (
ReadableByteChannel inputChannel = Channels.newChannel(resource.getInputStream());
WritableByteChannel outputChannel = Channels.newChannel(response.getOutputStream());
) {
ByteBuffer buffer = ByteBuffer.allocateDirect(DEFAULT_STREAM_BUFFER_SIZE);
long size = 0;
while (inputChannel.read(buffer) != -1) {
buffer.flip();
size += outputChannel.write(buffer);
buffer.clear();
}
if (resource.getContentLength() == -1 && !response.isCommitted()) {
response.setHeader("Content-Length", String.valueOf(size));
}
}
}
}
Use it together with the below interface representing a static resource.
interface StaticResource {
/**
* Returns the file name of the resource. This must be unique across all static resources. If any, the file
* extension will be used to determine the content type being set. If the container doesn't recognize the
* extension, then you can always register it as <code><mime-type></code> in <code>web.xml</code>.
* @return The file name of the resource.
*/
public String getFileName();
/**
* Returns the last modified timestamp of the resource in milliseconds.
* @return The last modified timestamp of the resource in milliseconds.
*/
public long getLastModified();
/**
* Returns the content length of the resource. This returns <code>-1</code> if the content length is unknown.
* In that case, the container will automatically switch to chunked encoding if the response is already
* committed after streaming. The file download progress may be unknown.
* @return The content length of the resource.
*/
public long getContentLength();
/**
* Returns the input stream with the content of the resource. This method will be called only once by the
* servlet, and only when the resource actually needs to be streamed, so lazy loading is not necessary.
* @return The input stream with the content of the resource.
* @throws IOException When something fails at I/O level.
*/
public InputStream getInputStream() throws IOException;
}
All you need is just extending from the given abstract servlet and implementing the getStaticResource() method according the javadoc.
Concrete example serving from file system:
Here's a concrete example which serves it via an URL like /files/foo.ext from the local disk file system:
@WebServlet("/files/*")
public class FileSystemResourceServlet extends StaticResourceServlet {
private File folder;
@Override
public void init() throws ServletException {
folder = new File("/path/to/the/folder");
}
@Override
protected StaticResource getStaticResource(HttpServletRequest request) throws IllegalArgumentException {
String pathInfo = request.getPathInfo();
if (pathInfo == null || pathInfo.isEmpty() || "/".equals(pathInfo)) {
throw new IllegalArgumentException();
}
String name = URLDecoder.decode(pathInfo.substring(1), StandardCharsets.UTF_8.name());
final File file = new File(folder, Paths.get(name).getFileName().toString());
return !file.exists() ? null : new StaticResource() {
@Override
public long getLastModified() {
return file.lastModified();
}
@Override
public InputStream getInputStream() throws IOException {
return new FileInputStream(file);
}
@Override
public String getFileName() {
return file.getName();
}
@Override
public long getContentLength() {
return file.length();
}
};
}
}
Concrete example serving from database:
Here's a concrete example which serves it via an URL like /files/foo.ext from the database via an EJB service call which returns your entity having a byte[] content property:
@WebServlet("/files/*")
public class YourEntityResourceServlet extends StaticResourceServlet {
@EJB
private YourEntityService yourEntityService;
@Override
protected StaticResource getStaticResource(HttpServletRequest request) throws IllegalArgumentException {
String pathInfo = request.getPathInfo();
if (pathInfo == null || pathInfo.isEmpty() || "/".equals(pathInfo)) {
throw new IllegalArgumentException();
}
String name = URLDecoder.decode(pathInfo.substring(1), StandardCharsets.UTF_8.name());
final YourEntity yourEntity = yourEntityService.getByName(name);
return (yourEntity == null) ? null : new StaticResource() {
@Override
public long getLastModified() {
return yourEntity.getLastModified();
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(yourEntityService.getContentById(yourEntity.getId()));
}
@Override
public String getFileName() {
return yourEntity.getName();
}
@Override
public long getContentLength() {
return yourEntity.getContentLength();
}
};
}
}
A: I ended up rolling my own StaticServlet. It supports If-Modified-Since, gzip encoding and it should be able to serve static files from war-files as well. It is not very difficult code, but it is not entirely trivial either.
The code is available: StaticServlet.java. Feel free to comment.
Update: Khurram asks about the ServletUtils class which is referenced in StaticServlet. It is simply a class with auxiliary methods that I used for my project. The only method you need is coalesce (which is identical to the SQL function COALESCE). This is the code:
public static <T> T coalesce(T...ts) {
for(T t: ts)
if(t != null)
return t;
return null;
}
A: Judging from the example information above, I think this entire article is based on a bugged behavior in Tomcat 6.0.29 and earlier. See https://issues.apache.org/bugzilla/show_bug.cgi?id=50026. Upgrade to Tomcat 6.0.30 and the behavior between (Tomcat|Jetty) should merge.
A: try this
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
<url-pattern>*.css</url-pattern>
<url-pattern>*.ico</url-pattern>
<url-pattern>*.png</url-pattern>
<url-pattern>*.jpg</url-pattern>
<url-pattern>*.htc</url-pattern>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
Edit: This is only valid for the servlet 2.5 spec and up.
A: I had the same problem and I solved it by using the code of the 'default servlet' from the Tomcat codebase.
https://github.com/apache/tomcat/blob/master/java/org/apache/catalina/servlets/DefaultServlet.java
The DefaultServlet is the servlet that serves the static resources (jpg,html,css,gif etc) in Tomcat.
This servlet is very efficient and has some the properties you defined above.
I think that this source code, is a good way to start and remove the functionality or depedencies you don't need.
*
*References to the org.apache.naming.resources package can be removed or replaced with java.io.File code.
*References to the org.apache.catalina.util package are propably only utility methods/classes that can be duplicated in your source code.
*References to the org.apache.catalina.Globals class can be inlined or removed.
A: To serve all requests from a Spring app as well as /favicon.ico and the JSP files from /WEB-INF/jsp/* that Spring's AbstractUrlBasedView will request you can just remap the jsp servlet and default servlet:
<servlet>
<servlet-name>springapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>/WEB-INF/jsp/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/favicon.ico</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
We can't rely on the *.jsp url-pattern on the standard mapping for the jsp servlet because the path pattern '/*' is matched before any extension mapping is checked. Mapping the jsp servlet to a deeper folder means it's matched first. Matching '/favicon.ico' exactly happens before path pattern matching. Deeper path matches will work, or exact matches, but no extension matches can make it past the '/*' path match. Mapping '/' to default servlet doesn't appear to work. You'd think the exact '/' would beat the '/*' path pattern on springapp.
The above filter solution doesn't work for forwarded/included JSP requests from the application. To make it work I had to apply the filter to springapp directly, at which point the url-pattern matching was useless as all requests that go to the application also go to its filters. So I added pattern matching to the filter and then learned about the 'jsp' servlet and saw that it doesn't remove the path prefix like the default servlet does. That solved my problem, which was not exactly the same but common enough.
A: Checked for Tomcat 8.x: static resources work OK if root servlet map to "".
For servlet 3.x it could be done by @WebServlet("")
A: Use org.mortbay.jetty.handler.ContextHandler. You don't need additional components like StaticServlet.
At the jetty home,
$ cd contexts
$ cp javadoc.xml static.xml
$ vi static.xml
...
<Configure class="org.mortbay.jetty.handler.ContextHandler">
<Set name="contextPath">/static</Set>
<Set name="resourceBase"><SystemProperty name="jetty.home" default="."/>/static/</Set>
<Set name="handler">
<New class="org.mortbay.jetty.handler.ResourceHandler">
<Set name="cacheControl">max-age=3600,public</Set>
</New>
</Set>
</Configure>
Set the value of contextPath with your URL prefix, and set the value of resourceBase as the file path of the static content.
It worked for me.
A: See StaticFile in JSOS: http://www.servletsuite.com/servlets/staticfile.htm
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "151"
}
|
Q: Showing the stack trace from a running Python application I have this Python application that gets stuck from time to time and I can't find out where.
Is there any way to signal Python interpreter to show you the exact code that's running?
Some kind of on-the-fly stacktrace?
Related questions:
*
*Print current call stack from a method in Python code
*Check what a running process is doing: print stack trace of an uninstrumented Python program
A: I am almost always dealing with multiple threads and main thread is generally not doing much, so what is most interesting is to dump all the stacks (which is more like the Java's dump). Here is an implementation based on this blog:
import threading, sys, traceback
def dumpstacks(signal, frame):
id2name = dict([(th.ident, th.name) for th in threading.enumerate()])
code = []
for threadId, stack in sys._current_frames().items():
code.append("\n# Thread: %s(%d)" % (id2name.get(threadId,""), threadId))
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
if line:
code.append(" %s" % (line.strip()))
print("\n".join(code))
import signal
signal.signal(signal.SIGQUIT, dumpstacks)
A: On Solaris, you can use pstack(1) No changes to the python code are necessary. eg.
# pstack 16000 | grep : | head
16000: /usr/bin/python2.6 /usr/lib/pkg.depotd --cfg svc:/application/pkg/serv
[ /usr/lib/python2.6/vendor-packages/cherrypy/process/wspbus.py:282 (_wait) ]
[ /usr/lib/python2.6/vendor-packages/cherrypy/process/wspbus.py:295 (wait) ]
[ /usr/lib/python2.6/vendor-packages/cherrypy/process/wspbus.py:242 (block) ]
[ /usr/lib/python2.6/vendor-packages/cherrypy/_init_.py:249 (quickstart) ]
[ /usr/lib/pkg.depotd:890 (<module>) ]
[ /usr/lib/python2.6/threading.py:256 (wait) ]
[ /usr/lib/python2.6/Queue.py:177 (get) ]
[ /usr/lib/python2.6/vendor-packages/pkg/server/depot.py:2142 (run) ]
[ /usr/lib/python2.6/threading.py:477 (run)
etc.
A: If you're on a Linux system, use the awesomeness of gdb with Python debug extensions (can be in python-dbg or python-debuginfo package). It also helps with multithreaded applications, GUI applications and C modules.
Run your program with:
$ gdb -ex r --args python <programname>.py [arguments]
This instructs gdb to prepare python <programname>.py <arguments> and run it.
Now when you program hangs, switch into gdb console, press Ctr+C and execute:
(gdb) thread apply all py-list
See example session and more info here and here.
A: I was looking for a while for a solution to debug my threads and I found it here thanks to haridsv. I use slightly simplified version employing the traceback.print_stack():
import sys, traceback, signal
import threading
import os
def dumpstacks(signal, frame):
id2name = dict((th.ident, th.name) for th in threading.enumerate())
for threadId, stack in sys._current_frames().items():
print(id2name[threadId])
traceback.print_stack(f=stack)
signal.signal(signal.SIGQUIT, dumpstacks)
os.killpg(os.getpgid(0), signal.SIGQUIT)
For my needs I also filter threads by name.
A: Getting a stack trace of an unprepared python program, running in a stock python without debugging symbols can be done with pyrasite. Worked like a charm for me in on Ubuntu Trusty:
$ sudo pip install pyrasite
$ echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
$ sudo pyrasite 16262 dump_stacks.py # dumps stacks to stdout/stderr of the python program
(Hat tip to @Albert, whose answer contained a pointer to this, among other tools.)
A: I hacked together some tool which attaches into a running Python process and injects some code to get a Python shell.
See here: https://github.com/albertz/pydbattach
A: You can use the hypno package, like so:
hypno <pid> "import traceback; traceback.print_stack()"
This would print a stack trace into the program's stdout.
Alternatively, if you don't want to print anything to stdout, or you don't have access to it (a daemon for example), you could use the madbg package, which is a python debugger that allows you to attach to a running python program and debug it in your current terminal. It is similar to pyrasite and pyringe, but newer, doesn't require gdb, and uses IPython for the debugger (which means colors and autocomplete).
To see the stack trace of a running program, you could run:
madbg attach <pid>
And in the debugger shell, enter:
bt
Disclaimer - I wrote both packages
A: >>> import traceback
>>> def x():
>>> print traceback.extract_stack()
>>> x()
[('<stdin>', 1, '<module>', None), ('<stdin>', 2, 'x', None)]
You can also nicely format the stack trace, see the docs.
Edit: To simulate Java's behavior, as suggested by @Douglas Leeder, add this:
import signal
import traceback
signal.signal(signal.SIGUSR1, lambda sig, stack: traceback.print_stack(stack))
to the startup code in your application. Then you can print the stack by sending SIGUSR1 to the running Python process.
A: I have module I use for situations like this - where a process will be running for a long time but gets stuck sometimes for unknown and irreproducible reasons. Its a bit hacky, and only works on unix (requires signals):
import code, traceback, signal
def debug(sig, frame):
"""Interrupt running process, and provide a python prompt for
interactive debugging."""
d={'_frame':frame} # Allow access to frame object.
d.update(frame.f_globals) # Unless shadowed by global
d.update(frame.f_locals)
i = code.InteractiveConsole(d)
message = "Signal received : entering python shell.\nTraceback:\n"
message += ''.join(traceback.format_stack(frame))
i.interact(message)
def listen():
signal.signal(signal.SIGUSR1, debug) # Register handler
To use, just call the listen() function at some point when your program starts up (You could even stick it in site.py to have all python programs use it), and let it run. At any point, send the process a SIGUSR1 signal, using kill, or in python:
os.kill(pid, signal.SIGUSR1)
This will cause the program to break to a python console at the point it is currently at, showing you the stack trace, and letting you manipulate the variables. Use control-d (EOF) to continue running (though note that you will probably interrupt any I/O etc at the point you signal, so it isn't fully non-intrusive.
I've another script that does the same thing, except it communicates with the running process through a pipe (to allow for debugging backgrounded processes etc). Its a bit large to post here, but I've added it as a python cookbook recipe.
A: The traceback module has some nice functions, among them: print_stack:
import traceback
traceback.print_stack()
A: It's worth looking at Pydb, "an expanded version of the Python debugger loosely based on the gdb command set". It includes signal managers which can take care of starting the debugger when a specified signal is sent.
A 2006 Summer of Code project looked at adding remote-debugging features to pydb in a module called mpdb.
A: Since Austin 3.3, you can use the -w/--where option to emit the current stack trace. See https://stackoverflow.com/a/70905181/1838793
If you want to peek at a running Python application to see the "live" call stack in a top-like fashon you can use austin-tui (https://github.com/p403n1x87/austin-tui). You can install it from PyPI with e.g.
pipx install austin-tui
Note that it requires the austin binary to work (https://github.com/p403n1x87/austin), but then you can attach to a running Python process with
austin-tui -p <pid>
A: You can try the faulthandler module. Install it using pip install faulthandler and add:
import faulthandler, signal
faulthandler.register(signal.SIGUSR1)
at the beginning of your program. Then send SIGUSR1 to your process (ex: kill -USR1 42) to display the Python traceback of all threads to the standard output. Read the documentation for more options (ex: log into a file) and other ways to display the traceback.
The module is now part of Python 3.3. For Python 2, see http://faulthandler.readthedocs.org/
A: What really helped me here is spiv's tip (which I would vote up and comment on if I had the reputation points) for getting a stack trace out of an unprepared Python process. Except it didn't work until I modified the gdbinit script. So:
*
*download https://svn.python.org/projects/python/trunk/Misc/gdbinit and put it in ~/.gdbinit
*edit it, changing PyEval_EvalFrame to PyEval_EvalFrameEx [edit: no longer needed; the linked file already has this change as of 2010-01-14]
*Attach gdb: gdb -p PID
*Get the python stack trace: pystack
A: pyringe is a debugger that can interact with running python processes, print stack traces, variables, etc. without any a priori setup.
While I've often used the signal handler solution in the past, it can still often be difficult to reproduce the issue in certain environments.
A: The suggestion to install a signal handler is a good one, and I use it a lot. For example, bzr by default installs a SIGQUIT handler that invokes pdb.set_trace() to immediately drop you into a pdb prompt. (See the bzrlib.breakin module's source for the exact details.) With pdb you can not only get the current stack trace (with the (w)here command) but also inspect variables, etc.
However, sometimes I need to debug a process that I didn't have the foresight to install the signal handler in. On linux, you can attach gdb to the process and get a python stack trace with some gdb macros. Put http://svn.python.org/projects/python/trunk/Misc/gdbinit in ~/.gdbinit, then:
*
*Attach gdb: gdb -p PID
*Get the python stack trace: pystack
It's not totally reliable unfortunately, but it works most of the time. See also https://wiki.python.org/moin/DebuggingWithGdb
Finally, attaching strace can often give you a good idea what a process is doing.
A: python -dv yourscript.py
That will make the interpreter to run in debug mode and to give you a trace of what the interpreter is doing.
If you want to interactively debug the code you should run it like this:
python -m pdb yourscript.py
That tells the python interpreter to run your script with the module "pdb" which is the python debugger, if you run it like that the interpreter will be executed in interactive mode, much like GDB
A: It can be done with excellent py-spy. It's a sampling profiler for Python programs, so its job is to attach to a Python processes and sample their call stacks. Hence, py-spy dump --pid $SOME_PID is all you need to do to dump call stacks of all threads in the $SOME_PID process. Typically it needs escalated privileges (to read the target process' memory).
Here's an example of how it looks like for a threaded Python application.
$ sudo py-spy dump --pid 31080
Process 31080: python3.7 -m chronologer -e production serve -u www-data -m
Python v3.7.1 (/usr/local/bin/python3.7)
Thread 0x7FEF5E410400 (active): "MainThread"
_wait (cherrypy/process/wspbus.py:370)
wait (cherrypy/process/wspbus.py:384)
block (cherrypy/process/wspbus.py:321)
start (cherrypy/daemon.py:72)
serve (chronologer/cli.py:27)
main (chronologer/cli.py:84)
<module> (chronologer/__main__.py:5)
_run_code (runpy.py:85)
_run_module_as_main (runpy.py:193)
Thread 0x7FEF55636700 (active): "_TimeoutMonitor"
run (cherrypy/process/plugins.py:518)
_bootstrap_inner (threading.py:917)
_bootstrap (threading.py:885)
Thread 0x7FEF54B35700 (active): "HTTPServer Thread-2"
accept (socket.py:212)
tick (cherrypy/wsgiserver/__init__.py:2075)
start (cherrypy/wsgiserver/__init__.py:2021)
_start_http_thread (cherrypy/process/servers.py:217)
run (threading.py:865)
_bootstrap_inner (threading.py:917)
_bootstrap (threading.py:885)
...
Thread 0x7FEF2BFFF700 (idle): "CP Server Thread-10"
wait (threading.py:296)
get (queue.py:170)
run (cherrypy/wsgiserver/__init__.py:1586)
_bootstrap_inner (threading.py:917)
_bootstrap (threading.py:885)
A: I would add this as a comment to haridsv's response, but I lack the reputation to do so:
Some of us are still stuck on a version of Python older than 2.6 (required for Thread.ident), so I got the code working in Python 2.5 (though without the thread name being displayed) as such:
import traceback
import sys
def dumpstacks(signal, frame):
code = []
for threadId, stack in sys._current_frames().items():
code.append("\n# Thread: %d" % (threadId))
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
if line:
code.append(" %s" % (line.strip()))
print "\n".join(code)
import signal
signal.signal(signal.SIGQUIT, dumpstacks)
A: Take a look at the faulthandler module, new in Python 3.3. A faulthandler backport for use in Python 2 is available on PyPI.
A: You can use PuDB, a Python debugger with a curses interface to do this. Just add
from pudb import set_interrupt_handler; set_interrupt_handler()
to your code and use Ctrl-C when you want to break. You can continue with c and break again multiple times if you miss it and want to try again.
A: I am in the GDB camp with the python extensions. Follow https://wiki.python.org/moin/DebuggingWithGdb, which means
*
*dnf install gdb python-debuginfo or sudo apt-get install gdb python2.7-dbg
*gdb python <pid of running process>
*py-bt
Also consider info threads and thread apply all py-bt.
A: How to debug any function in console:
Create function where you use pdb.set_trace(), then function you want debug.
>>> import pdb
>>> import my_function
>>> def f():
... pdb.set_trace()
... my_function()
...
Then call created function:
>>> f()
> <stdin>(3)f()
(Pdb) s
--Call--
> <stdin>(1)my_function()
(Pdb)
Happy debugging :)
A: I don't know of anything similar to java's response to SIGQUIT, so you might have to build it in to your application. Maybe you could make a server in another thread that can get a stacktrace on response to a message of some kind?
A: There is no way to hook into a running python process and get reasonable results. What I do if processes lock up is hooking strace in and trying to figure out what exactly is happening.
Unfortunately often strace is the observer that "fixes" race conditions so that the output is useless there too.
A: use the inspect module.
import inspect
help(inspect.stack)
Help on function stack in module inspect:
stack(context=1)
Return a list of records for the stack above the caller's frame.
I find it very helpful indeed.
A: In Python 3, pdb will automatically install a signal handler the first time you use c(ont(inue)) in the debugger. Pressing Control-C afterwards will drop you right back in there. In Python 2, here's a one-liner which should work even in relatively old versions (tested in 2.7 but I checked Python source back to 2.4 and it looked okay):
import pdb, signal
signal.signal(signal.SIGINT, lambda sig, frame: pdb.Pdb().set_trace(frame))
pdb is worth learning if you spend any amount of time debugging Python. The interface is a bit obtuse but should be familiar to anyone who has used similar tools, such as gdb.
A: In case you need to do this with uWSGI, it has Python Tracebacker built-in and it's just matter of enabling it in the configuration (number is attached to the name for each worker):
py-tracebacker=/var/run/uwsgi/pytrace
Once you have done this, you can print backtrace simply by connecting to the socket:
uwsgi --connect-and-read /var/run/uwsgi/pytrace1
A: At the point where the code is run, you can insert this small snippet to see a nicely formatted printed stack trace. It assumes that you have a folder called logs at your project's root directory.
# DEBUG: START DEBUG -->
import traceback
with open('logs/stack-trace.log', 'w') as file:
traceback.print_stack(file=file)
# DEBUG: END DEBUG --!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "386"
}
|
Q: How do I check that I removed required data only? I have a really big database (running on PostgreSQL) containing a lot of tables with sophisticated relations between them (foreign keys, on delete cascade and so on).
I need remove some data from a number of tables, but I'm not sure what amount of data will be really deleted from database due to cascade removals.
How can I check that I'll not delete data that should not be deleted?
I have a test database - just a copy of real one where I can do what I want :)
The only idea I have is dump database before and after and check it. But it not looks comfortable.
Another idea - dump part of database, that, as I think, should not be affected by my DELETE statements and check this part before and after data removal. But I see no simple ways to do it (there are hundreds of tables and removal should work with ~10 of them). Is there some way to do it?
Any other ideas how to solve the problem?
A: You can query the information_schema to draw yourself a picture on how the constraints are defined in the database. Then you'll know what is going to happen when you delete. This will be useful not only for this case, but always.
Something like (for constraints)
select table_catalog,table_schema,table_name,column_name,rc.* from
information_schema.constraint_column_usage ccu,
information_schema.referential_constraints rc
where ccu.constraint_name = rc.constraint_name
A: Using psql, start a transaction, perform your deletes, then run whatever checking queries you can think of. You can then either rollback or commit.
A: If the worry is keys left dangling (i.e.: pointing to a deleted record) then run the deletion on your test database, then use queries to find any keys that now point to invalid targets. (while you're doing this you can also make sure the part that should be unaffected did not change)
A better solution would be to spend time mapping out the delete cascades so you know what to expect - knowing how your database works is pretty valuable so the effort spent on this will be useful beyond this particular deletion.
And no matter how sure you are back the DB up before doing big changes!
A: Thanks for answers!
Vinko, your answer is very useful for me and I'll study it dipper.
actually, for my case, it was enough to compare tables counts before and after records deletion and check what tables were affected by it.
it was done by simple commands described below
psql -U U_NAME -h`hostname` -c '\d' | awk '{print $3}' > tables.list
for i in `cat tables.list `; do echo -n "$i: " >> tables.counts; psql -U U_NAME -h`hostname` -t -c "select count(*) from $i" >> tables.counts; done
for i in `cat tables.list `; do echo -n "$i: " >> tables.counts2; psql -U U_NAME -h`hostname` -t -c "select count(*) from $i" >> tables.counts2; done
diff tables.counts tables.counts2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is your favourite MATLAB/Octave programming trick? I think everyone would agree that the MATLAB language is not pretty, or particularly consistent. But nevermind! We still have to use it to get things done.
What are your favourite tricks for making things easier? Let's have one per answer so people can vote them up if they agree. Also, try to illustrate your answer with an example.
A: cellfun and arrayfun for automated for loops.
A: The colon operator for the manipulation of arrays.
@ScottieT812, mentions one: flattening an array, but there's all the other variants of selecting bits of an array:
x=rand(10,10);
flattened=x(:);
Acolumn=x(:,10);
Arow=x(10,:);
y=rand(100);
firstSix=y(1:6);
lastSix=y(end-5:end);
alternate=y(1:2:end);
A: Oh, and reverse an array
v = 1:10;
v_reverse = v(length(v):-1:1);
A: conditional arguments in the left-hand side of an assignment:
t = (0:0.005:10)';
x = sin(2*pi*t);
x(x>0.5 & t<5) = 0.5;
% This limits all values of x to a maximum of 0.5, where t<5
plot(t,x);
A: Know your axis properties! There are all sorts of things you can set to tweak the default plotting properties to do what you want:
set(gca,'fontsize',8,'linestyleorder','-','linewidth',0.3,'xtick',1:2:9);
(as an example, sets the fontsize to 8pt, linestyles of all new lines to all be solid and their width 0.3pt, and the xtick points to be [1 3 5 7 9])
Line and figure properties are also useful, but I find myself using axis properties the most.
A: Be strict with specifying dimensions when using aggregation functions like min, max, mean, diff, sum, any, all,...
For instance the line:
reldiff = diff(a) ./ a(1:end-1)
might work well to compute relative differences of elements in a vector, however in case the vector degenerates to just one element the computation fails:
>> a=rand(1,7);
>> diff(a) ./ a(1:end-1)
ans =
-0.5822 -0.9935 224.2015 0.2708 -0.3328 0.0458
>> a=1;
>> diff(a) ./ a(1:end-1)
??? Error using ==> rdivide
Matrix dimensions must agree.
If you specify the correct dimensions to your functions, this line returns an empty 1-by-0 matrix, which is correct:
>> diff(a, [], 2) ./ a(1, 1:end-1)
ans =
Empty matrix: 1-by-0
>>
The same goes for a min-function which usually computes minimums over columns on a matrix, until the matrix only consists of one row. - Then it will return the minimum over the row unless the dimension parameter states otherwise, and probably break your application.
I can almost guarantee you that consequently setting the dimensions of these aggregation functions will save you quite some debugging work later on.
At least that would have been the case for me. :)
A: In order to be able to quickly test a function, I use nargin like so:
function result = multiply(a, b)
if nargin == 0 %no inputs provided, run using defaults for a and b
clc;
disp('RUNNING IN TEST MODE')
a = 1;
b = 2;
end
result = a*b;
Later on, I add a unit test script to test the function for different input conditions.
A: Using ismember() to merge data organized by text identfiers. Useful when you are analyzing differing periods when entries, in my case company symbols, come and go.
%Merge B into A based on Text identifiers
UniverseA = {'A','B','C','D'};
UniverseB = {'A','C','D'};
DataA = [20 40 60 80];
DataB = [30 50 70];
MergeData = NaN(length(UniverseA),2);
MergeData(:,1) = DataA;
[tf, loc] = ismember(UniverseA, UniverseB);
MergeData(tf,2) = DataB(loc(tf));
MergeData =
20 30
40 NaN
60 50
80 70
A: Asking 'why' (useful for jarring me out of a Matlab runtime-fail debugging trance at 3am...)
A: Using the built-in profiler to see where the hot parts of my code are:
profile on
% some lines of code
profile off
profile viewer
or just using the built in tic and toc to get quick timings:
tic;
% some lines of code
toc;
A: Directly extracting the elements of a matrix that satisfy a particular condition, using logical arrays:
x = rand(1,50) .* 100;
xpart = x( x > 20 & x < 35);
Now xpart contains only those elements of x which lie in the specified range.
A: Vectorization:
function iNeedle = findClosest(hay,needle)
%FINDCLOSEST find the indicies of the closest elements in an array.
% Given two vectors [A,B], findClosest will find the indicies of the values
% in vector A closest to the values in vector B.
[hay iOrgHay] = sort(hay(:)'); %#ok must have row vector
% Use histogram to find indices of elements in hay closest to elements in
% needle. The bins are centered on values in hay, with the edges on the
% midpoint between elements.
[iNeedle iNeedle] = histc(needle,[-inf hay+[diff(hay)/2 inf]]); %#ok
% Reversing the sorting.
iNeedle = iOrgHay(iNeedle);
A: Executing a Simulink model directly from a script (rather than interactively) using the sim command. You can do things like take parameters from a workspace variable, and repeatedly run sim in a loop to simulate something while varying the parameter to see how the behavior changes, and graph the results with whatever graphical commands you like. Much easier than trying to do this interactively, and it gives you much more flexibility than the Simulink "oscilloscope" blocks when visualizing the results. (although you can't use it to see what's going on in realtime while the simulation is running)
A really important thing to know is the DstWorkspace and SrcWorkspace options of the simset command. These control where the "To Workspace" and "From Workspace" blocks get and put their results. Dstworkspace defaults to the current workspace (e.g. if you call sim from inside a function the "To Workspace" blocks will show up as variables accessible from within that same function) but SrcWorkspace defaults to the base workspace and if you want to encapsulate your call to sim you'll want to set SrcWorkspace to current so there is a clean interface to providing/retrieving simulation input parameters and outputs. For example:
function Y=run_my_sim(t,input1,params)
% runs "my_sim.mdl"
% with a From Workspace block referencing I1 as an input signal
% and parameters referenced as fields of the "params" structure
% and output retrieved from a To Workspace block with name O1.
opt = simset('SrcWorkspace','current','DstWorkspace','current');
I1 = struct('time',t,'signals',struct('values',input1,'dimensions',1));
Y = struct;
Y.t = sim('my_sim',t,opt);
Y.output1 = O1.signals.values;
A: Contour plots with [c,h]=contour and clabel(c,h,'fontsize',fontsize). I usually use the fontsize parameter to reduce the font size so the numbers don't run into each other. This is great for viewing the value of 2-D functions without having to muck around with 3D graphs.
A: Using persistent (static) variables when running an online algorithm. It may speed up the code in areas like Bayesian machine learning where the model is trained iteratively for the new samples. For example, for computing the independent loglikelihoods, I compute the loglikelihood initially from scratch and update it by summing this previously computed loglikelihood and the additional loglikelihood.
Instead of giving a more specialized machine learning problem, let me give a general online averaging code which I took from here:
function av = runningAverage(x)
% The number of values entered so far - declared persistent.
persistent n;
% The sum of values entered so far - declared persistent.
persistent sumOfX;
if x == 'reset' % Initialise the persistent variables.
n = 0;
sumOfX = 0;
av = 0;
else % A data value has been added.
n = n + 1;
sumOfX = sumOfX + x;
av = sumOfX / n; % Update the running average.
end
Then, the calls will give the following results
runningAverage('reset')
ans = 0
>> runningAverage(5)
ans = 5
>> runningAverage(10)
ans = 7.5000
>> runningAverage(3)
ans = 6
>> runningAverage('reset')
ans = 0
>> runningAverage(8)
ans = 8
A: Provide quick access to other function documentation by adding a "SEE ALSO" line to the help comments. First, you must include the name of the function in all caps as the first comment line. Do your usual comment header stuff, then put SEE ALSO with a comma separated list of other related functions.
function y = transmog(x)
%TRANSMOG Transmogrifies a matrix X using reverse orthogonal eigenvectors
%
% Usage:
% y = transmog(x)
%
% SEE ALSO
% UNTRANSMOG, TRANSMOG2
When you type "help transmog" at the command line, you will see all the comments in this comment header, with hyperlinks to the comment headers for the other functions listed.
A: Turn a matrix into a vector using a single colon.
x = rand(4,4);
x(:)
A: Vectorizing loops. There are lots of ways to do this, and it is entertaining to look for loops in your code and see how they can be vectorized. The performance is astonishingly faster with vector operations!
A: Anonymous functions, for a few reasons:
*
*to make a quick function for one-off uses, like 3x^2+2x+7. (see listing below) This is useful for functions like quad and fminbnd that take functions as arguments. It's also convenient in scripts (.m files that don't start with a function header) since unlike true functions you can't include subfunctions.
*for closures -- although anonymous functions are a little limiting as there doesn't seem to be a way to have assignment within them to mutate state.
.
% quick functions
f = @(x) 3*x.^2 + 2*x + 7;
t = (0:0.001:1);
plot(t,f(t),t,f(2*t),t,f(3*t));
% closures (linfunc below is a function that returns a function,
% and the outer functions arguments are held for the lifetime
% of the returned function.
linfunc = @(m,b) @(x) m*x+b;
C2F = linfunc(9/5, 32);
F2C = linfunc(5/9, -32*5/9);
A: I'm surprised that while people mentioned the logical array approach of indexing an array, nobody mentioned the find command.
e.g. if x is an NxMxO array
x(x>20) works by generating an NxMxO logical array and using it to index x (which can be bad if you have large arrays and are looking for a small subset
x(find(x>20)) works by generating list (i.e. 1xwhatever) of indices of x that satisfy x>20, and indexing x by it. "find" should be used more than it is, in my experience.
More what I would call 'tricks'
you can grow/append to arrays and cell arrays if you don't know the size you'll need, by using end + 1 (works with higher dimensions too, so long as the dimensions of the slice match -- so you'll have to initialize x to something other than [] in that case). Not good for numerics but for small dynamic lists of things (or cell arrays), e.g. parsing files.
e.g.
>> x=[1,2,3]
x = 1 2 3
>> x(end+1)=4
x = 1 2 3 4
Another think many people don't know is that for works on any dim 1 array, so to continue the example
>> for n = x;disp(n);end
1
2
3
4
Which means if all you need is the members of x you don't need to index them.
This also works with cell arrays but it's a bit annoying because as it walks them the element is still wrapped in a cell:
>> for el = {1,2,3,4};disp(el);end
[1]
[2]
[3]
[4]
So to get at the elements you have to subscript them
>> for el = {1,2,3,4};disp(el{1});end
1
2
3
4
I can't remember if there is a nicer way around that.
A: -You can make a Matlab shortcut to an initialization file called startup.m. Here, I define formatting, precision of the output, and plot parameters for my Matlab session (for example, I use a larger plot axis/font size so that .fig's can be seen plainly when I put them in presentations.) See a good blog post from one of the developers about it http://blogs.mathworks.com/loren/2009/03/03/whats-in-your-startupm/ .
-You can load an entire numerical ascii file using the "load" function. This isn't particularly fast, but gets the job done quickly for prototyping (shouldn't that be the Matlab motto?)
-As mentioned, the colon operator and vectorization are lifesavers. Screw loops.
A:
x=repmat([1:10],3,1); % say, x is an example array of data
l=x>=3; % l is a logical vector (1s/0s) to highlight those elements in the array that would meet a certain condition.
N=sum(sum(l));% N is the number of elements that meet that given condition.
cheers -- happy scripting!
A: Here's what I use frequently:
% useful abbreviations
flat=@(x) x(:);
% print basic statistics
stats=@(x) sprintf('mean +/- s.d. \t= %f +/- %f\nmin, max \t\t= %f, %f\nmedian, mode \t= %f, %f', ...
mean(flat(x)), std(flat(x)), min(flat(x)), max(flat(x)), median(flat(x)), mode(flat(x)) );
nrows=@(x) size(x,1);
ncols=@(x) size(x,2);
nslices=@(x) size(x,3);
% this is just like ndims except it returns 0 for an empty matrix and
% ignores dimensions of size 0.
ndim=@(x) length(find(size(x)));
These abbreviations are useful for finding the mean and standard deviation of pixel values in a small area of an image. I would use the following logic:
phantomData = phantom();
stats( phantomData(50:80, 50:80) )
What if I wanted to put the size of an image in its title?
imagesc( phantomData );
title( sprintf('The image size is %d by %d by %d.', nrows(phantomData), ncols(phantomData), nslices(phantomData)) )
A: Matlab's bsxfun, arrayfun, cellfun, and structfun are quite interesting and often save a loop.
M = rand(1000, 1000);
v = rand(1000, 1);
c = bsxfun(@plus, M, v);
This code, for instance, adds column-vector v to each column of matrix M.
Though, in performance critical parts of your application you should benchmark these functions versus the trivial for-loop because often loops are still faster.
A: LaTeX mode for formulas in graphs: In one of the recent releases (R2006?) you add the additional arguments ,'Interpreter','latex' at the end of a function call and it will use LaTeX rendering. Here's an example:
t=(0:0.001:1);
plot(t,sin(2*pi*[t ; t+0.25]));
xlabel('t');
ylabel('$\hat{y}_k=sin 2\pi (t+{k \over 4})$','Interpreter','latex');
legend({'$\hat{y}_0$','$\hat{y}_1$'},'Interpreter','latex');
Not sure when they added it, but it works with R2006b in the text(), title(), xlabel(), ylabel(), zlabel(), and even legend() functions. Just make sure the syntax you are using is not ambiguous (so with legend() you need to specify the strings as a cell array).
A: Using xlim and ylim to draw vertical and horizontal lines. Examples:
*
*Draw a horizontal line at y=10:
line(xlim, [10 10])
*Draw vertical line at x=5:
line([5 5], ylim)
A: Here's a quick example:
I find the comma separated list syntax quite useful for building function calls:
% Build a list of args, like so:
args = {'a', 1, 'b', 2};
% Then expand this into arguments:
output = func(args{:})
A: Here's a bunch of nonobvious functions that are useful from time to time:
*
*mfilename (returns the name of the currently running MATLAB script)
*dbstack (gives you access to the names & line numbers of the matlab function stack)
*keyboard (stops execution and yields control to the debugging prompt; this is why there's a K in the debug prompt K>>
*dbstop error (automatically puts you in debug mode stopped at the line that triggers an error)
A: Invoking Java code from Matlab
A: Using nargin to set default values for optional arguments and using nargout to set optional output arguments. Quick example
function hLine=myplot(x,y,plotColor,markerType)
% set defaults for optional paramters
if nargin<4, markerType='none'; end
if nargin<3, plotColor='k'; end
hL = plot(x,y,'linetype','-', ...
'color',plotColor, ...
'marker',markerType, ...
'markerFaceColor',plotColor,'markerEdgeColor',plotColor);
% return handle of plot object if required
if nargout>0, hLine = hL; end
A: I like using function handles for lots of reasons. For one, they are the closest thing I've found in MATLAB to pointers, so you can create reference-like behavior for objects. There are a few neat (and simpler) things you can do with them, too. For example, replacing a switch statement:
switch number,
case 1,
outargs = fcn1(inargs);
case 2,
outargs = fcn2(inargs);
...
end
%
%can be turned into
%
fcnArray = {@fcn1, @fcn2, ...};
outargs = fcnArray{number}(inargs);
I just think little things like that are cool.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "73"
}
|
Q: How to Google for --depend? The latest makefiles we've received from a third party vendor contain rules with --depend on the end of build rules, so I thought I would look it up on Google, but try as I might, I can't persuade it to display any pages with exactly the characters --depend
I've tried surrounding it with quotes "--depend": I've tried the Advanced Search: I've tried backslashes "\-\-depend" in the (vain) hope that there is some sort of unpublished regular expression search available.
Am I missing something blindingly obvious?
Please note that this is NOT a question about what --depend does, I know that, it's a question about how you Google for very precise, programmer oriented, text.
A: You can specifiy literal symbols in a Google Code Search but not Google Web Search.
Examples;
Google Code Search for +"--depend"
Google Web Search for +"--depend"
A: I remember to have read somewhere that google's web search does not index non alphanumeric characters, treating them as word separators, so that's not possible.
A: I had the same issue searching for 'syntax-rules'. You would think they would have solved this by now.
A: Reason for this problem is that a minus sign at the start of a token indicates that you want to EXCLUDE it from the search.
This is how you can filter out really popular results that really have nothing to do with you want.
For example, try searching for "wow". Then try searching for "wow -warcraft".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Does Windows XP support TLS1.1 with AES256? Is TLS 1.1 support included in Windows XP SP3?
A: No TLS 1.1 support is included only in Windows Vista.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Heisenbug: WinApi program crashes on some computers Please help! I'm really at my wits' end.
My program is a little personal notes manager (google for "cintanotes").
On some computers (and of course I own none of them) it crashes with an unhandled exception just after start.
Nothing special about these computers could be said, except that they tend to have AMD CPUs.
Environment: Windows XP, Visual C++ 2005/2008, raw WinApi.
Here is what is certain about this "Heisenbug":
1) The crash happens only in the Release version.
2) The crash goes away as soon as I remove all GDI-related stuff.
3) BoundChecker has no complains.
4) Writing a log shows that the crash happens on a declaration of a local int variable! How could that be? Memory corruption?
Any ideas would be greatly appreciated!
UPDATE: I've managed to get the app debugged on a "faulty" PC. The results:
"Unhandled exception at 0x0044a26a in CintaNotes.exe: 0xC000001D: Illegal Instruction."
and code breaks on
0044A26A cvtsi2sd xmm1,dword ptr [esp+14h]
So it seems that the problem was in the "Code Generation/Enable Enhanced Instruction Set" compiler option. It was set to "/arch:SSE2" and was crashing on the machines that didn't support SSE2. I've set this option to "Not Set" and the bug is gone. Phew!
Thank you all very much for help!!
A: So it doesnnt crash when configuration is DEBUG Configuration? There are many things different than a RELEASE configruation:
1.) Initialization of globals
2.) Actual machine Code generated etc..
So first step is find out what are exact settings for each parameter in the RELEASE mode as compared to the DEBUG mode.
-AD
A:
1) The crash happens only in the Release version.
That's usually a sign that you're relying on some behaviour that's not guaranteed, but happens to be true in the debug build. For example, if you forget to initialize your variables, or access an array out of bounds. Make sure you've turned on all the compiler checks (/RTCsuc). Also check things like relying on the order of evaluation of function parameters (which isn't guaranteed).
2) The crash goes away as soon as I remove all GDI-related stuff.
Maybe that's a hint that you're doing something wrong with the GDI related stuff? Are you using HANDLEs after they've been freed, for example?
A: Download the Debugging tools for Windows package. Set the symbol paths correctly, then run your application under WinDbg. At some point, it will break with an Access Violation. Then you should run the command "!analyze -v", which is quite smart and should give you a hint on whats going wrong.
A:
4) Writig a log shows that the crash happen on a declaration of a local int variable! how could that be? Memory corruption?
What is the underlying code in the executable / assembly? Declaration of int is no code at all, and as such cannot crash. Do you initialize the int somehow?
To see the code where the crash happened you should perform what is called a postmortem analysis.
Windows Error Reporting
If you want to analyse the crash, you should get a crash dump. One option for this is to register for Windows Error Reporting - requires some money (you need a digital code signing ID) and some form filling. For more visit https://winqual.microsoft.com/ .
Get the crash dump intended for WER directly from the customer
Another option is to get in touch witch some user who is experiencing the crash and get a crash dump intended for WER from him directly. The user can do this when he clicks on the Technical details before sending the crash to Microsoft - the crash dump file location can be checked there.
Your own minidump
Another option is to register your own exception handler, handle the exception and write a minidump anywhere you wish. Detailed description can be found at Code Project Post-Mortem Debugging Your Application with Minidumps and Visual Studio .NET article.
A: Most heisenbugs / release-only bugs are due to either flow of control that depends on reads from uninitialised memory / stale pointers / past end of buffers, or race conditions, or both.
Try overriding your allocators so they zero out memory when allocating. Does the problem go away (or become more reproducible?)
Writig a log shows that the crash happens on a declaration of a local int variable! How could that be? Memory corruption?
Stack overflow! ;)
A: Sounds like stack corruption to me. My favorite tool to track those down is IDA Pro. Of course you don't have that access to the user's machine.
Some memory checkers have a hard time catching stack corruption ( if it indeed that ). The surest way to get those I think is runtime analysis.
This can also be due to corruption in an exception path, even if the exception was handled. Do you debug with 'catch first-chance exceptions' turned on? You should as long as you can. It does get annoying after a while in many cases.
Can you send those users a checked version of your application? Check out Minidump Handle that exception and write out a dump. Then use WinDbg to debug on your end.
Another method is writing very detailed logs. Create a "Log every single action" option, and ask the user to turn that on and send it too you. Dump out memory to the logs. Check out '_CrtDbgReport()' on MSDN.
Good Luck!
EDIT:
Responding to your comment: An error on a local variable declaration is not surprising to me. I've seen this a lot. It's usually due to a corrupted stack.
Some variable on the stack may be running over it's boundaries for example. All hell breaks loose after that. Then stack variable declarations throw random memory errors, virtual tables get corrupted, etc.
Anytime I've seen those for a prolong period of time, I've had to go to IDA Pro. Detailed runtime disassembly debugging is the only thing I know that really gets those reliably.
Many developers use WinDbg for this kind of analysis. That's why I also suggested Minidump.
A:
4) Writig a log shows that the crash happen on a declaration of a local int variable!how could that be? Memory corruption
I've found the cause to numerous "strange crashes" to be dereferencing of a broken this inside a member function of said object.
A: Try Rational (IBM) PurifyPlus. It catches a lot of errors that BoundsChecker doesn't.
A: What does the crash say ? Access violation ? Exception ? That would be the further clue to solve this with
Ensure you have no preceeding memory corruptions using PageHeap.exe
Ensure you have no stack overflow (CBig array[1000000])
Ensure that you have no un-initialized memory.
Further you can run the release version also inside the debugger, once you generate debug symbols (not the same as creating debug version) for the process. Step through and see if you are getting any warnings in the debugger trace window.
A: "4) Writing a log shows that the crash happens on a declaration of a local int variable! How could that be? Memory corruption?"
This could be a sign that the hardware is in fact faulty or being pushed too hard. Find out if they've overclocked their computer.
A: When I get this type of thing, i try running the code through gimpels PC-Lint (static code analysis) as it checks different classes of errors to BoundsChecker. If you are using Boundschecker, turn on the memory poisoning options.
You mention AMD CPUs. Have you investigated whether there is a similar graphics card / driver version and / or configuration in place on the machines that crash? Does it always crash on these machines or just occasionally? Maybe run the System Information tool on these machines and see what they have in common,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: How to get the real request URL in Struts with Tiles? When you're using Tiles with Struts and do...
request.getRequestURL()
...you get the URL to e.g. /WEB-INF/jsp/layout/newLayout.jsp instead of the real URL that was entered/clicked by the user, something like /context/action.do.
In newer Struts versions, 1.3.x and after, you can use the solution mentioned on javaranch and get the real URL using the request attribute ORIGINAL_URI_KEY.
But how to do this in Struts 1.2.x?
A: When you query request.getRequestURL() from your view/jsp/tiles layer, it's already another rewritten request.
As Mwanji Ezana mentions, the most suitable way is to save it to separate property on the action execution phase. You may want to automate this process with the help of interceptors in Struts2.
A: I use this, which also works on Spring:
<% out.println(request.getAttribute("javax.servlet.forward.request_uri")); %>
If you also need the query string (contributed by matchew):
<% out.println(request.getAttribute("javax.servlet.forward.query_string")); %>
A: I don't know if Struts 1.2.x has a similar Globals constant, but you could create your own in at least two ways:
*
*get the original request URL in the Action and set it on the request, and call that from the JSP
*use a Servlet Filter to do the same thing
A: This works in Struts 1.2
private String getOriginalUri(HttpServletRequest request) {
String targetUrl = request.getServletPath();
if (request.getQueryString() != null) {
targetUrl += "?" + request.getQueryString();
}
return targetUrl;
}
A: You just need to do this in your action:
request.getAttribute("javax.servlet.forward.request_uri")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: What makes a pthread defunct? i'm working with a multi-threaded program (using pthreads) that currently create a background thread (PTHREAD_DETACHED) and then invokes pthread_exit(0). My problem is that the process is then listed as "defunct" and curiously do not seems to "really exists" in /proc (which defeats my debugging strategies)
I would like the following requirements to be met:
*
*the program should run function A in a loop and function B once
*given the PID of the program /proc/$pid/exe, /proc/$pid/maps and /proc/$pid/fd must be accessible (when the process is defunct, they are all empty or invalid links)
*it must be possible to suspend/interrupt the program with CTRL+C and CTRL+Z as usual
edit: I hesitate changing the program's interface for having A in the "main" thread and B in a spawned thread (they are currently in the other way). Would it solve the problem ?
A: You can either suspend the execution of the main process waiting for a signal, or don't detach the thread (using the default PHTREAD_CRATE_JOINABLE) waiting for its termination with a pthread_join().
A: Is there a reason you can't do things the other way round: have the main thread run the loop, and do the one-off task in the background thread?
A: Not the most elegant design but maybe you could block the main thread before exiting with:
while(1) {
pause();
}
Then you can install a signal handler for SIGINT and SIGTERM that breaks the loop. The easiest way for that is: exit(0) :-).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is it worth investing time in learning Visual Studio Macro System (usage-creation)? I have used Visual Studio for a long time, but one feature I have never used is the macro system. I saw a post where someone mentioned he used macros (no elaboration) so I was wondering is it really worth the time investing in learning how to create macros?
If so, what kind of stuff do you make?
There was similar post(s), but I am trying to lean this question more towards: Is it worth learning? I tend to rather know how something works than just using it if it's possible and/or worth it.
A: Macros are not difficult to learn, and can make your life easier!
For an interesting appllication of macros see this question
A: You use macros to make repetitive tasks easier. That is, if you find yourself doing 5 or 6 individual tasks regularly, then it may be worth converting it to a macro, so that you can do it with a single click of the button.
Other things that might be of interest are a switching to a .h file from a .cpp file, if you use C++.
A: Yes!
Although I haven't been using them much - learning VS macros is easy so the "investment" is very little and you get a new tool you can use.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: XML namespace problem in Visual Studio generated service reference I'm connecting to a web service hosted by a third-party provider. I've added a service reference in my project to the web service, VS has generated all the references and classes needed.
I'm connecting with this piece of code (client name and methods anonymized):
using (var client = new Client())
{
try
{
client.Open();
var response = client.Method(...);
return response.Status;
}
catch (SoapException ex)
{
throw CreateServiceException(ex);
}
finally
{
client.Close();
}
}
When reaching the client.Open(), I get an exception with this message:
The top XML element '_return' from
namespace '' references distinct types
System.Boolean and
Service.Status.
Use XML attributes to specify another
XML name or namespace for the element
or types.
In reference.cs, I can see that the "_return" variable is decorated with
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="", Order=0)]
Is there a problem with the wsdl, the generated service reference or in my code?
Update: Generating the service as an old school Web Service solves the problem. I've marked Sixto's answer as accepted for now, but I'm still curious what could've caused the problem and if any parameters to the service generator could solve the original problem.
A: If you were able to create a service reference then the WSDL is valid. The exception message is saying you have namespace/type ambiguity problem with _return. The generated code is probably using it in some context as a boolean and in another context as a Service.Status type.
I don’t call the ClientBase.Open method before invoking a service method because I’ve never seen the need for it. I do always call the Close & Abort methods as appropriate. The Open method basically just changes the state of the client to no longer be configurable. I’m not sure how that would trigger code in the generated class since it is an inherited method. I’d try just removing that line and see if you get the same exception. Otherwise, if you haven’t already done so, search the generated code for all the places _return is used and see if you can manually sort-out the appropriate type. You may need different names for each context.
Another way to troubleshoot the WSDL is to create a Web Reference (assuming it’s an HTTP based service) and see if the generate code works as expected. If it does work, go with the ASMX client unless you have a need for WCF proxy capabilities.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: User Interface - Dropdown What is the best way to design an interface so that very long drop down values that get trucated due to size limits do not create a very bad user experience. My question is for web applications.
Could you please send your suggestions.
Thanks.
A: One option is to use 'type-ahead' with postback (AJAX) to reduce the size of the list.
A: You can use a another window (div?) with list/grid with paging instead of dropdown.
Its very intuitive for general users.
A: Well, what I have done in such a case is:
*
*Using autocomplete (so that the user can start typing and get at the intended option faster).
*Have the dropdown of a fixed length like 30 chars. Now, if the value of the drop down is longer I just truncate it to 25 with a '...' at the end. A hover on this value will make the full text appear as a 'title' or similar.
A: have a tooltip for each item in the dropdown list so when a user hovers his mouse pointer to an item, he'll still be able to see the full description of the item.
or have your dropdown width auto-resize to the longest description in the list.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: PHP - Security what is best way? What is the best way to secure an intranet website developed using PHP from outside attacks?
A: If it is on an internal network, why is it even possible to get to the app from the outside? Firewall rules should be in place at the very least.
A: That's a stunningly thought-provoking question, and I'm surprised that you haven't received better answers.
Summary
Everything you would do for an external-facing application, and then some.
Thought Process
If I'm understanding you correctly, then you are asking a question which very few developers are asking themselves. Most companies have poor defence in depth, and once an attacker is in, he's in. Clearly you want to take it up a level.
So, what kind of attack are we thinking about?
If I'm the attacker and I'm attacking your intranet application, then I must have got access to your network somehow. This may not be as difficult as it sounds - I might try spearphishing (targetting email to individuals in your organisation, containing either malware attachements or links to sites which install malware) to get a trojan installed on an internal machine.
Once I've done this (and got control of an internal PC), I'll try all the same attacks I would try against any internet application.
However, that's not the end of the story. I've got more options: if I've got one of your user's PCs, then I might well be able to use a keylogger to gather usernames and passwords, as well as watching all your email for names and phone numbers.
Armed with these, I may be able to log into your application directly. I may even learn an admin username/password. Even if I don't, a list of names and phone numbers along with a feel for company lingo gives me a decent shot at socially engineering my way into wider access within your company.
Recommendations
*
*First and foremost, before all technical solutions: TRAIN YOUR USERS IN SECURITY
The common answers to securing a web app:
*
*Use multi-factor authentication
*
*e.g. username/password and some kind of pseudo-random number gadget.
*Sanitise all your input.
*
*to protect against cross-site scripting and SQL injection.
*Use SSL (otherwise known as HTTPS).
*
*this is a pain to set up (EDIT: actually that's improving), but it makes for much better security.
*Adhere to the principals of "Segregation of Duties" and "Least Priviledge"
*
*In other words, by ensuring that all users have only the permissions they need to do their jobs (and nobody else's jobs) you make sure they have the absolute minimum ability to do damage.
A: The best way? Disable direct external access!
If employees need to use it (like an extranet-style site), you should make them VPN in. Through VPN you have a lot more authentication options and most of them are a great deal more secure than leaving your intranet server accessible from the internet.
Another option, and this only works if the data is public-safe, is scheduling your intranet server to push the data to another server that is externally accessible. I say push because you really don't want this server to have access to your network. Let your network server do the work.
A: The best way to secure it? Don't connect it to a network. Make your users physically enter a guarded room with a single console, running Mosaic.
Oh, you want it to be easy to use?
*
*Always verify every single input that can come from an untrusted source.
*Don't trust any data sources.
*When storing passwords, ALWAYS store an encrypted hash of the password.
*When storing passwords, NEVER store passwords directly.
*Never collect or store any data that you don't actually need.
*Never allow yourself to be tempted into adding additional bells & whistles.
*Read everything that Bruce Schneier has written on security and encryption.
If you forget these simple rules, you could find your application starring on the front pages of newspapers everywhere, just like Yahoo mail.
A: I would echo @Oli and favour the VPN method if possible. However, if for any reason you need more arbitrary access than this, you should use SSL to secure any authentication. And in addition to password authentication / IP address authentication it would be well worth looking at using SSL with client side certificates.
A: You could only allow access from internal IPs from the php app itself. Also dont ignore the usual security and best practices. Input validation and output encoding(whitelisting only), user accounts with hashed passwords etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: IE6 displaying components in a hidden div (when they should be hidden!) Does anyone know if IE6 ever misrenders pages with hidden divs? We currently have several divs which we display in the same space on the page, only showing one at a time and hiding all others.
The problem is that the hidden divs components (specifically option menus) sometimes show through. If the page is scrolled, removing the components from view, and then scrolled back down, the should-be-hidden components then disappear.
How do we fix this?
A: One hack you could use is to move your div outside the screen:
MyDiv.style.left = "-1000px";
And then put it back on its original position when you want to show it.
A: How are they hidden? using display:none; or visibility:hidden; ? are they absolutely positioned by any chance? IE6 has a z-Index problem and there are several hacks to deal with it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Asp.net hosting provider with build capabilities and source control Can you suggest an asp.net 3.5 hosting provider with continuous integration (cctray – nant builds) and source control facilities (svn)?
My requirement would be something like this:
*
*I checkin to a svn branch (say trunk) on the hosting provider space.
*CruiseControl.NET on the server fires off a build.
*I see success/failure on my cctray.
*On success my peers go to the website (say http://trunk.mywebsite.com) and see changes
A: I would also have to suggest a VPS as I have yet to see a Shared Hosting provider with compilers installed.
On the code repository side Assembla.com has free svn hosting and they also provide a way to kick off a build process by allowing you to specify a URL to post to when a check-in occurs. This URL can kick off a script that pulls the latest code and builds it. You can find more details on how to set this up here.
A: Shared hosting providers doesn't have that. You'll probably have to go with VPS, or maybe even Dedicated if services are consuming too much processor/ram.
A: I agree with everyone here. For every custom demands, it would be cheaper to look on a VPS / dedicated server to perform what you ask. You may find what you need, but at a high cost.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Loop termination conditions These for-loops are among the first basic examples of formal correctness proofs of algorithms. They have different but equivalent termination conditions:
1 for ( int i = 0; i != N; ++i )
2 for ( int i = 0; i < N; ++i )
The difference becomes clear in the postconditions:
*
*The first one gives the strong guarantee that i == N after the loop terminates.
*The second one only gives the weak guarantee that i >= N after the loop terminates, but you will be tempted to assume that i == N.
If for any reason the increment ++i is ever changed to something like i += 2, or if i gets modified inside the loop, or if N is negative, the program can fail:
*
*The first one may get stuck in an infinite loop. It fails early, in the loop that has the error. Debugging is easy.
*The second loop will terminate, and at some later time the program may fail because of your incorrect assumption of i == N. It can fail far away from the loop that caused the bug, making it hard to trace back. Or it can silently continue doing something unexpected, which is even worse.
Which termination condition do you prefer, and why? Are there other considerations? Why do many programmers who know this, refuse to apply it?
A: I tend to use the second form, simply because then I can be more sure that the loop will terminate. I.e. it's harder to introduce a non-termination bug by altering i inside the loop.
Of course, it also has the slightly lazy advantage of being one less character to type ;)
I would also argue, that in a language with sensible scope rules, as i is declared inside the loop construct, it shouldn't be available outside the loop. This would mitigate any reliance on i being equal to N at the end of the loop...
A: We shouldn't look at the counter in isolation - if for any reason someone changed the way the counter is incremented they would change the termination conditions and the resulting logic if it's required for i==N.
I would prefer the the second condition since it's more standard and will not result in endless loop.
A: In C++, using the != test is preferred for generality. Iterators in C++ have various concepts, like input iterator, forward iterator, bidirectional iterator, random access iterator, each of which extends the previous one with new capabilities. For < to work, random access iterator is required, whereas != merely requires input iterator.
A: If you trust your code, you can do either.
If you want your code to be readable and easily understood (and thus more tolerant to change from someone who you've got to assume to be a klutz), I'd use something like;
for ( int i = 0 ; i >= 0 && i < N ; ++i)
A: I always use #2 as then you can be sure the loop will terminate... Relying on it being equal to N afterwards is relying on a side effect... Wouldn't you just be better using the variable N itself?
[edit] Sorry...I meant #2
A: I think most programmers use the 2nd one, because it helps figure out what goes on inside the loop. I can look at it, and "know" that i will start as 0, and will definitely be less than N.
The 1st variant doesn't have this quality. I can look at it, and all I know is that i will start as 0 and that it won't ever be equal to N. Not quite as helpful.
Irrespective of how you terminate the loop, it is always good to be very wary of using a loop control variable outside the loop. In your examples you (correctly) declare i inside the loop, so it is not in scope outside the loop and the question of its value is moot...
Of course, the 2nd variant also has the advantage that it's what all of the C references I have seen use :-)
A: In general I would prefer
for ( int i = 0; i < N; ++i )
The punishment for a buggy program in production, seems a lot less severe, you will not have a thread stuck forever in a for loop, a situation that can be very risky and very hard to diagnose.
Also, in general I like to avoid these kind of loops in favour of the more readable foreach style loops.
A: I prefer to use #2, only because I try not to extend the meaning of i outside of the for loop. If I were tracking a variable like that, I would create an additional test. Some may say this is redundant or inefficient, but it reminds the reader of my intent: At this point, i must equal N
@timyates - I agree one shouldn't rely on side-effects
A: I think you stated very well the difference between the two. I do have the following comments, though:
*
*This is not "language-agnostic", I can see your examples are in C++ but there
are languages where you are not allowed to modify the loop variable inside the
loop and others that don't guarantee that the value of the index is usable after
the loop (and some do both).
*You have declared the i
index within the for so I would not bet on the value of i after the loop.
The examples are a little bit misleading as they implictly assume that for is
a definite loop. In reality it is just a more convenient way of writing:
// version 1
{ int i = 0;
while (i != N) {
...
++i;
}
}
Note how i is undefined after the block.
If a programmer knew all of the above would not make general assumption of the value of i and would be wise enough to choose i<N as the ending conditions, to ensure that the the exit condition will be eventually met.
A: Using either of the above in c# would cause a compiler error if you used i outside the loop
A: I prefer this sometimes:
for (int i = 0; (i <= (n-1)); i++) { ... }
This version shows directly the range of values that i can have. My take on checking lower and upper bound of the range is that if you really need this, your code has too many side effects and needs to be rewritten.
The other version:
for (int i = 1; (i <= n); i++) { ... }
helps you determine how often the loop body is called. This also has valid use cases.
A: For general programming work I prefer
for ( int i = 0; i < N; ++i )
to
for ( int i = 0; i != N; ++i )
Because it is less error prone, especially when code gets refactored. I have seen this kind of code turned into an infinite loop by accident.
That argument made that "you will be tempted to assume that i == N", I don't believe is true. I have never made that assumption or seen another programmer make it.
A: From my standpoint of formal verification and automatic termination analysis, I strongly prefer #2 (<). It is quite easy to track that some variable is increased (before var = x, after var = x+n for some non-negative number n). However, it is not that easy to see that i==N eventually holds. For this, one needs to infer that i is increased by exactly 1 in each step, which (in more complicated examples) might be lost due to abstraction.
If you think about the loop which increments by two (i = i + 2), this general idea becomes more understandable. To guarantee termination one now needs to know that i%2 == N%2, whereas this is irrelevant when using < as the condition.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Vista Serial programmatically How do I obtain the serial number of the installed Vista system?
Also is there a tool that does the same thing so I can verify MY results?
A: A quick list of tools:
http://pcsupport.about.com/od/productkeysactivation/tp/topkeyfinder.htm
http://magicaljellybean.com/keyfinder/
http://techblissonline.com/find-product-key-cd-ley-windows-vista-xp-office-2007-sql-server-produkey/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to write an AssertTags test in SimpleTest with regex? I wish to test a function that will generate lorem ipsum text, but it does so within html tags. So I cant know in advance the textual content, but i know the html structure. That is what I want to test. And maybe that the length of the texts are within certain limits.
So what I am wondering is if the assertTags can do this in a way paraphrased bellow:
Result = "<p>Some text</p>";
Expected = array(
'<p' ,
'regex',
'/p'
);
assertTags(resutl, expected)
I am using SimpleTest with CakePHP, but I think it should be a general question.
A: $expected = array(
'<p',
'preg:/[A-Za-z\.\s\,]+/',
'/p'
);
A: Extend the SimpleExpectation class and then use your new Expectation class in the assert statement
see: http://www.lastcraft.com/expectation_documentation.php#extending
the example given is for validating an IP address but should be applicable to your problem:
class ValidIp extends SimpleExpectation {
function test($ip) {
return (ip2long($ip) != -1);
}
function testMessage($ip) {
return "Address [$ip] should be a valid IP address";
}
}
then in your test
$this->assert(new ValidIp(),$server->getIp());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PHP: Storing 'objects' inside the $_SESSION I just figured out that I can actually store objects in the $_SESSION and I find it quite cool because when I jump to another page I still have my object. Now before I start using this approach I would like to find out if it is really such a good idea or if there are potential pitfalls involved.
I know that if I had a single point of entry I wouldn't need to do that but I'm not there yet so I don't have a single point of entry and I would really like to keep my object because I don't lose my state like that. (Now I've also read that I should program stateless sites but I don't understand that concept yet.)
So in short: Is it ok to store objects in the session, are there any problems with it?
Edit:
Temporary summary: By now I understand that it is probably better to recreate the object even if it involves querying the database again.
Further answers could maybe elaborate on that aspect a bit more!
A: I would suggest don't use state unless you absolutely need it. If you can rebuild the object without using sessions do it.
Having states in your webapplication makes the application more complex to build, for every request you have to see what state the user is in. Ofcourse there are times where you cannot avoid using session (example: user have to be kept login during his session on the webapplication).
Last I would suggest keeping your session object as small as possible as it impacts performance to serialize and unserialize large objects.
A: You'll have to remember that resource types (such as db connections or file pointers) wont persist between page loads, and you'll need to invisibly re-create these.
Also consider the size of the session, depending how it is stored, you may have size restrictions, or latency issues.
A: HTTP is a stateless protocol for a reason. Sessions weld state onto HTTP. As a rule of thumb, avoid using session state.
UPDATE:
There is no concept of a session at the HTTP level; servers provide this by giving the client a unique ID and telling the client to resubmit it on every request. Then the server uses that ID as a key into a big hashtable of Session objects. Whenever the server gets a request, it looks up the Session info out of its hashtable of session objects based on the ID the client submitted with the request. All this extra work is a double whammy on scalability (a big reason HTTP is stateless).
*
*Whammy One: It reduces the work a single server can do.
*Whammy Two: It makes it harder to scale out because now you can't just route a request to any old server - they don't all have the same session. You can pin all the requests with a given session ID to the same server. That's not easy, and it's a single point of failure (not for the system as a whole, but for big chunks of your users). Or, you could share the session storage across all servers in the cluster, but now you have more complexity: network-attached memory, a stand-alone session server, etc.
Given all that, the more info you put in the session, the bigger the impact on performance (as Vinko points out). Also as Vinko points out, if your object isn't serializable, the session will misbehave. So, as a rule of thumb, avoid putting more than absolutely necessary in the session.
@Vinko You can usually work around having the server store state by embedding the data you're tracking in the response you send back and having the client resubmit it, e.g., sending the data down in a hidden input. If you really need server-side tracking of state, it should probably be in your backing datastore.
(Vinko adds: PHP can use a database for storing session information, and having the client resubmit the data each time might solve potential scalability issues, but opens a big can of security issues you must pay attention to now that the client's in control of all your state)
A: *
*Objects which cannot be serialized (or which contain unserializable members) will not come out of the $_SESSION as you would expect
*Huge sessions put a burden on the server (serializing and deserializing megs of state each time is expensive)
Other than that I've seen no problems.
A: I know this topic is old, but this issue keeps coming up and has not been addressed to my satisfaction:
Whether you save objects in $_SESSION, or reconstruct them whole cloth based on data stashed in hidden form fields, or re-query them from the DB each time, you are using state. HTTP is stateless (more or less; but see GET vs. PUT) but almost everything anybody cares to do with a web app requires state to be maintained somewhere. Acting as if pushing the state into nooks and crannies amounts to some kind of theoretical win is just wrong. State is state. If you use state, you lose the various technical advantages gained by being stateless. This is not something to lose sleep over unless you know in advance that you ought to be losing sleep over it.
I am especially flummoxed by the blessing received by the "double whammy" arguments put forth by Hank Gay. Is the OP building a distributed and load-balanced e-commerce system? My guess is no; and I will further posit that serializing his $User class, or whatever, will not cripple his server beyond repair. My advice: use techniques that are sensible to your application. Objects in $_SESSION are fine, subject to common sense precautions. If your app suddenly turns into something rivaling Amazon in traffic served, you will need to re-adapt. That's life.
A: it's OK as long as by the time the session_start() call is made, the class declaration/definition has already been encountered by PHP or can be found by an already-installed autoloader. otherwise it would not be able to deserialize the object from the session store.
A: In my experience, it's generally not worth it for anything more complicated than an StdClass with some properties. The cost of unserializing has always been more than recreating from a database given a session-stored Identifier. It seems cool, but (as always), profiling is the key.
A: I would also bring up when upgrading software libraries - we upgraded our software and the old version had objects in session with the V1 software's class names, the new software was crashing when it tried to build the objects that were in the session - as the V2 software didn't use those same classes anymore, it couldn't find them. We had to put in some fix code to detect session objects, delete the session if found, reload the page. The biggest pain initially mind you was recreating this bug when it was first reported (all too familiar, "well, it works for me" :) as it only affected people who where in and out the old and new systems recently - however, good job we did find it before launch as all of our users would surely have had the old session variables in their sessions and would have potentially crashed for all, would have been a terrible launch :)
Anyway, as you suggest in your amendment, I also think it's better to re-create the object. So maybe just storing id and then on each request pulling the object from the database, is better/safer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "193"
}
|
Q: What is the best operating system for a server? What would you suggest would be the best operating system for a web server?
If possible, please enumerate the advantages and disadvantages if there are any...
A: Use an operating system you have an administrator account for.
A mainstream flavour of Linux is a great choice for stability, but if no one knows how to look after it it's a bad idea. The same goes for any other platform you can name.
A: If the language is PHP, then go with a Linux system. Windows also supports it, but it seems to me that Linux is what most people use for PHP, and therefore there is more documentation to set up a decent Linux server with PHP.
I have no idea what distribution of Linux to use though, but I'm sure someone does :)
A: I would say CentOS - famous for its stability. I used to work as an administrator for a hosting provider - we used it and never had problems with it.
A: Personally, I prefer Solaris or a BSD for stability. However, both Linux and Windows are easier to operate and offer many more standard features with only slightly less reliability.
Go with what you know best and you'll get the best results.
A: It really depends on the function of the webserver. What services should it provide? Should there be a homepage, and what language should that be in, etc.
A: Either Linux or Windows will do the job fine. If you're doing this for yourself then Linux is an easier route because there are many free options.
If you're asking on behalf of a company who doesn't mind paying for things then it really depends on what the employees have experience in.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Distributed Processing: C++ equivalent of JTA I'm developing a mission-critical solution where data integrity is paramount and performance a close second. If data gets stuffed up, it's gonna be cata$trophic.
So, I'm looking for the C/C++ version of JTA (Java Transaction API). Does anyone know of any C or C++ libraries that supports distributed transactions? And yes, I've googled it ... unsuccessfully.
I'd hate to be told that there isn't one and I'd need to implement the protocol specified by Distributed TP: The XA Specification.
Please help!
Edit (responding to kervin): If I need to insert records across multiple database servers and I need to commit them atomically, products like Oracle will have solutions for it. If I've written my own message queue server and I want to commit messages to multiple servers atomically, I'll need something like JTA to make sure that I don't stuff up the atomicity of the transaction.
A: Encina, DCE-RPC, TUXEDO, possibly CORBA (though I hesitate to suggest using CORBA), MTS (again, hmm).
These are the kind of things you want for distributed transaction processing.
Encina used to have a lot of good documentation for its DCE-based system.
A: There are hundreds. Seriously.
As far as general areas go. Check out Service Oriented Architecture, most of the new products are coming out in that area. Eg. RogueWave HydraSCA
I would start with plain Rogue Wave Suite, then see if I needed an Enterprise Service Bus after looking at that design.
That probably depends a lot on your design requirements and budget.
A: Oracle Tuxedo is the 800 pound gorilla in this space and was actually the basis for much of the XA specification. It provides distributed transaction management and can handle 100's of thousands of requests/second.
For more information: http://www.oracle.com/tuxedo
Also, if you like SCA (Service Component Architecture), there is an add-on product for Tuxedo called SALT that provides an SCA container for programming in C++, Python, Ruby, and PHP.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Dealing with command line arguments and Spring When I'm writing a Spring command line application which parses command line arguments, how do I pass them to Spring? Would I want to have my main() structured so that it first parses the command line args and then inits Spring? Even so, how would it pass the object holding the parsed args to Spring?
A: Have a look at my Spring-CLI library - at http://github.com/sazzer/spring-cli - as one way of doing this. It gives you a main class that automatically loads spring contexts and has the ability to use Commons-CLI for parsing command line arguments automatically and injecting them into your beans.
A: Starting from Spring 3.1 there is no need in any custom code suggested in other answers. Check CommandLinePropertySource, it provides a natural way to inject CL arguments into your context.
And if you are a lucky Spring Boot developer you could simplify your code one step forward leveraging the fact that SpringApplication gives you the following:
By default class will perform the following steps to bootstrap your
application:
...
Register a CommandLinePropertySource to expose command line arguments
as Spring properties
And if you are interested in the Spring Boot property resolution order please consult this page.
A: You can also pass an Object array as a second parameter to getBean which will be used as arguments to the constructor or factory.
public static void main(String[] args) {
Mybean m = (Mybean)context.getBean("mybean", new Object[] {args});
}
A: Two possibilities I can think of.
1) Set a static reference. (A static variable, although typically frowned upon, is OK in this case, because there can only be 1 command line invocation).
public class MyApp {
public static String[] ARGS;
public static void main(String[] args) {
ARGS = args;
// create context
}
}
You can then reference the command line arguments in Spring via:
<util:constant static-field="MyApp.ARGS"/>
Alternatively (if you are completely opposed to static variables), you can:
2) Programmatically add the args to the application context:
public class MyApp2 {
public static void main(String[] args) {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
// Define a bean and register it
BeanDefinition beanDefinition = BeanDefinitionBuilder.
rootBeanDefinition(Arrays.class, "asList")
.addConstructorArgValue(args).getBeanDefinition();
beanFactory.registerBeanDefinition("args", beanDefinition);
GenericApplicationContext cmdArgCxt = new GenericApplicationContext(beanFactory);
// Must call refresh to initialize context
cmdArgCxt.refresh();
// Create application context, passing command line context as parent
ApplicationContext mainContext = new ClassPathXmlApplicationContext(CONFIG_LOCATIONS, cmdArgCxt);
// See if it's in the context
System.out.println("Args: " + mainContext.getBean("args"));
}
private static String[] CONFIG_LOCATIONS = new String[] {
"applicationContext.xml"
};
}
Parsing the command line arguments is left as an exercise to the reader.
A: Consider the following class:
public class ExternalBeanReferneceFactoryBean
extends AbstractFactoryBean
implements BeanNameAware {
private static Map<String, Object> instances = new HashMap<String, Object>();
private String beanName;
/**
* @param instance the instance to set
*/
public static void setInstance(String beanName, Object instance) {
instances.put(beanName, instance);
}
@Override
protected Object createInstance()
throws Exception {
return instances.get(beanName);
}
@Override
public Class<?> getObjectType() {
return instances.get(beanName).getClass();
}
@Override
public void setBeanName(String name) {
this.beanName = name;
}
}
along with:
/**
* Starts the job server.
* @param args command line arguments
*/
public static void main(String[] args) {
// parse the command line
CommandLineParser parser = new GnuParser();
CommandLine cmdLine = null;
try {
cmdLine = parser.parse(OPTIONS, args);
} catch(ParseException pe) {
System.err.println("Error parsing command line: "+pe.getMessage());
new HelpFormatter().printHelp("command", OPTIONS);
return;
}
// create root beanFactory
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
// register bean definition for the command line
ExternalBeanReferneceFactoryBean.setInstance("commandLine", cmdLine);
beanFactory.registerBeanDefinition("commandLine", BeanDefinitionBuilder
.rootBeanDefinition(ExternalBeanReferneceFactoryBean.class)
.getBeanDefinition());
// create application context
GenericApplicationContext rootAppContext = new GenericApplicationContext(beanFactory);
rootAppContext.refresh();
// create the application context
ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] {
"/commandlineapp/applicationContext.xml"
}, rootAppContext);
System.out.println(appContext.getBean("commandLine"));
}
A: Here is an example to boot strap spring for a Main method, simply grab the passed params as normal then make the function you call on your bean (in the case deployer.execute()) take them as Strings or via any format you feel suitable.
public static void main(String[] args) throws IOException, ConfigurationException {
Deployer deployer = bootstrapSpring();
deployer.execute();
}
private static Deployer bootstrapSpring()
{
FileSystemXmlApplicationContext appContext = new FileSystemXmlApplicationContext("spring/deployerContext.xml");
Deployer deployer = (Deployer)appContext.getBean("deployer");
return deployer;
}
A: I'm not sure what you are trying to achieve exactly, maybe you can add some details on what the command and the arguments will look like, and what outcome you expect from your application.
I think this is not what you need, but it might help other readers: Spring supports receiving properties from the command line using double hyphen (e.g. java -jar app.jar --my.property="Property Value"
Have a look at this documentation for more information:
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-command-line-args
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
}
|
Q: What to use for XML parsing / reading in PHP4 Unfortunatly I have to work in a older web application on a PHP4 server;
It now needs to parse a lot of XML for calling webservices (custom protocol, no SOAP/REST);
Under PHP5 I would use SimpleXML but that isn't available;
There is Dom XML in PHP4, but it isn't default any more in PHP5.
What are the other options?
I'm looking for a solution that still works on PHP5 once they migrate.
A nice extra would be if the XML can be validated with a schema.
A: There is a simpleXML backport avaliable: http://www.ister.org/code/simplexml44/index.html
If you can install that, then that will be the best solution.
A: I would second Rich Bradshaw's suggestion about the simpleXML backport, but if that's not an option, then xml_parse will do the job in PHP4, and still works after migration to 5.
$xml = ...; // Get your XML data
$xml_parser = xml_parser_create();
// _start_element and _end_element are two functions that determine what
// to do when opening and closing tags are found
xml_set_element_handler($xml_parser, "_start_element", "_end_element");
// How to handle each char (stripping whitespace if needs be, etc
xml_set_character_data_handler($xml_parser, "_character_data");
xml_parse($xml_parser, $xml);
There's a good tutorial here about parsing XML in PHP4 that may be of some use to you.
A: It might be a bit grass roots, but if it's applicable for the data you're working with, you could use XSLT to transform your XML in to something usable. Obviously once you upgrade to PHP5 the XSLT will still work and you can migrate as and when to DOM parsing.
Andrew
A: If you can use xml_parse, then go for that. It's robust, fast and compatible with PHP5. It is however not a DOM parser, but a simpler event-based one (Also called a SAX parser), so if you need to access a tree, you will have to marshal the stream into a tree your self. This is fairly simple to do; Use s stack, and push items to it on start-element and pop on end-element.
A: I would definitely recommend the SimpleXML backport, as long as its performance is good enough for your needs. The demonstrations of xml_parse look simple enough, but it can get very hairy very quickly in my experience. The content handler functions don't get any contextual information about where the parser is in the tree, unless you track it and provide it in the start and end tag handlers. So you're either calling functions for every start/end tag, or throwing around global variables to track where you are in the tree.
Obviously the SimpleXML backport will be a bit slower, as it's written in PHP and has to parse the whole document before it's available, but the ease of coding more than makes up for it.
A: Maybe also consider looking at the XML packages available in PEAR, particularly XML_Util, XML_Parser, and XML_Serializer...
A: XML Parser with parse_into_struct turned into a tree-array structure:
<?php
/**
* What to use for XML parsing / reading in PHP4
* @link http://stackoverflow.com/q/132233/367456
*/
$encoding = 'US-ASCII';
// https://gist.github.com/hakre/46386de578619fbd898c
$path = dirname(__FILE__) . '/time-series-example.xml';
$parser_creator = 'xml_parser_create'; // alternative creator is 'xml_parser_create_ns'
if (!function_exists($parser_creator)) {
trigger_error(
"XML Parsers' $parser_creator() not found. XML Parser "
. '<http://php.net/xml> is required, activate it in your PHP configuration.'
, E_USER_ERROR
);
return;
}
$parser = $parser_creator($encoding);
if (!$parser) {
trigger_error(sprintf('Unable to create a parser (Encoding: "%s")', $encoding), E_USER_ERROR);
return;
}
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
$data = file_get_contents($path);
if ($data === FALSE) {
trigger_error(sprintf('Unable to open file "%s" for reading', $path));
return;
}
$result = xml_parse_into_struct($parser, $data, $xml_struct_values);
unset($data);
xml_parser_free($parser);
unset($parser);
if ($result === 0) {
trigger_error(sprintf('Unable to parse data of file "%s" as XML', $path));
return;
}
define('TREE_NODE_TAG', 'tagName');
define('TREE_NODE_ATTRIBUTES', 'attributes');
define('TREE_NODE_CHILDREN', 'children');
define('TREE_NODE_TYPE_TAG', 'array');
define('TREE_NODE_TYPE_TEXT', 'string');
define('TREE_NODE_TYPE_NONE', 'NULL');
/**
* XML Parser indezies for parse into struct values
*/
define('XML_STRUCT_VALUE_TYPE', 'type');
define('XML_STRUCT_VALUE_LEVEL', 'level');
define('XML_STRUCT_VALUE_TAG', 'tag');
define('XML_STRUCT_VALUE_ATTRIBUTES', 'attributes');
define('XML_STRUCT_VALUE_VALUE', 'value');
/**
* XML Parser supported node types
*/
define('XML_STRUCT_TYPE_OPEN', 'open');
define('XML_STRUCT_TYPE_COMPLETE', 'complete');
define('XML_STRUCT_TYPE_CDATA', 'cdata');
define('XML_STRUCT_TYPE_CLOSE', 'close');
/**
* Tree Creator
* @return array
*/
function tree_create()
{
return array(
array(
TREE_NODE_TAG => NULL,
TREE_NODE_ATTRIBUTES => NULL,
TREE_NODE_CHILDREN => array(),
)
);
}
/**
* Add Tree Node into Tree a Level
*
* @param $tree
* @param $level
* @param $node
* @return array|bool Tree with the Node added or FALSE on error
*/
function tree_add_node($tree, $level, $node)
{
$type = gettype($node);
switch ($type) {
case TREE_NODE_TYPE_TEXT:
$level++;
break;
case TREE_NODE_TYPE_TAG:
break;
case TREE_NODE_TYPE_NONE:
trigger_error(sprintf('Can not add Tree Node of type None, keeping tree unchanged', $type, E_USER_NOTICE));
return $tree;
default:
trigger_error(sprintf('Can not add Tree Node of type "%s"', $type), E_USER_ERROR);
return FALSE;
}
if (!isset($tree[$level - 1])) {
trigger_error("There is no parent for level $level");
return FALSE;
}
$parent = & $tree[$level - 1];
if (isset($parent[TREE_NODE_CHILDREN]) && !is_array($parent[TREE_NODE_CHILDREN])) {
trigger_error("There are no children in parent for level $level");
return FALSE;
}
$parent[TREE_NODE_CHILDREN][] = & $node;
$tree[$level] = & $node;
return $tree;
}
/**
* Creator of a Tree Node
*
* @param $value XML Node
* @return array Tree Node
*/
function tree_node_create_from_xml_struct_value($value)
{
static $xml_node_default_types = array(
XML_STRUCT_VALUE_ATTRIBUTES => NULL,
XML_STRUCT_VALUE_VALUE => NULL,
);
$orig = $value;
$value += $xml_node_default_types;
switch ($value[XML_STRUCT_VALUE_TYPE]) {
case XML_STRUCT_TYPE_OPEN:
case XML_STRUCT_TYPE_COMPLETE:
$node = array(
TREE_NODE_TAG => $value[XML_STRUCT_VALUE_TAG],
// '__debug1' => $orig,
);
if (isset($value[XML_STRUCT_VALUE_ATTRIBUTES])) {
$node[TREE_NODE_ATTRIBUTES] = $value[XML_STRUCT_VALUE_ATTRIBUTES];
}
if (isset($value[XML_STRUCT_VALUE_VALUE])) {
$node[TREE_NODE_CHILDREN] = (array)$value[XML_STRUCT_VALUE_VALUE];
}
return $node;
case XML_STRUCT_TYPE_CDATA:
// TREE_NODE_TYPE_TEXT
return $value[XML_STRUCT_VALUE_VALUE];
case XML_STRUCT_TYPE_CLOSE:
return NULL;
default:
trigger_error(
sprintf(
'Unkonwn Xml Node Type "%s": %s', $value[XML_STRUCT_VALUE_TYPE], var_export($value, TRUE)
)
);
return FALSE;
}
}
$tree = tree_create();
while ($tree && $value = array_shift($xml_struct_values)) {
$node = tree_node_create_from_xml_struct_value($value);
if (NULL === $node) {
continue;
}
$tree = tree_add_node($tree, $value[XML_STRUCT_VALUE_LEVEL], $node);
unset($node);
}
if (!$tree) {
trigger_error('Parse error');
return;
}
if ($xml_struct_values) {
trigger_error(sprintf('Unable to process whole parsed XML array (%d elements left)', count($xml_struct_values)));
return;
}
// tree root is the first child of level 0
print_r($tree[0][TREE_NODE_CHILDREN][0]);
Output:
Array
(
[tagName] => dwml
[attributes] => Array
(
[version] => 1.0
[xmlns:xsd] => http://www.w3.org/2001/XMLSchema
[xmlns:xsi] => http://www.w3.org/2001/XMLSchema-instance
[xsi:noNamespaceSchemaLocation] => http://www.nws.noaa.gov/forecasts/xml/DWMLgen/schema/DWML.xsd
)
[children] => Array
(
[0] => Array
(
[tagName] => head
[children] => Array
(
[0] => Array
(
[tagName] => product
[attributes] => Array
(
[srsName] => WGS 1984
[concise-name] => time-series
[operational-mode] => official
)
[children] => Array
(
[0] => Array
(
[tagName] => title
[children] => Array
(
[0] => NOAA's National Weather Service Forecast Data
)
)
[1] => Array
(
[tagName] => field
[children] => Array
(
[0] => meteorological
)
)
[2] => Array
(
[tagName] => category
[children] => Array
(
[0] => forecast
)
)
[3] => Array
(
[tagName] => creation-date
[attributes] => Array
(
[refresh-frequency] => PT1H
)
[children] => Array
(
[0] => 2013-11-02T06:51:17Z
)
)
)
)
[1] => Array
(
[tagName] => source
[children] => Array
(
[0] => Array
(
[tagName] => more-information
[children] => Array
(
[0] => http://www.nws.noaa.gov/forecasts/xml/
)
)
[1] => Array
(
[tagName] => production-center
[children] => Array
(
[0] => Meteorological Development Laboratory
[1] => Array
(
[tagName] => sub-center
[children] => Array
(
[0] => Product Generation Branch
)
)
)
)
[2] => Array
(
[tagName] => disclaimer
[children] => Array
(
[0] => http://www.nws.noaa.gov/disclaimer.html
)
)
[3] => Array
(
[tagName] => credit
[children] => Array
(
[0] => http://www.weather.gov/
)
)
[4] => Array
(
[tagName] => credit-logo
[children] => Array
(
[0] => http://www.weather.gov/images/xml_logo.gif
)
)
[5] => Array
(
[tagName] => feedback
[children] => Array
(
[0] => http://www.weather.gov/feedback.php
)
)
)
)
)
)
[1] => Array
(
[tagName] => data
[children] => Array
(
[0] => Array
(
[tagName] => location
[children] => Array
(
[0] => Array
(
[tagName] => location-key
[children] => Array
(
[0] => point1
)
)
[1] => Array
(
[tagName] => point
[attributes] => Array
(
[latitude] => 40.00
[longitude] => -120.00
)
)
)
)
[1] => Array
(
[tagName] => moreWeatherInformation
[attributes] => Array
(
[applicable-location] => point1
)
[children] => Array
(
[0] => http://forecast.weather.gov/MapClick.php?textField1=40.00&textField2=-120.00
)
)
[2] => Array
(
[tagName] => time-layout
[attributes] => Array
(
[time-coordinate] => local
[summarization] => none
)
[children] => Array
(
[0] => Array
(
[tagName] => layout-key
[children] => Array
(
[0] => k-p24h-n4-1
)
)
[1] => Array
(
[tagName] => start-valid-time
[children] => Array
(
[0] => 2013-11-02T08:00:00-07:00
)
)
[2] => Array
(
[tagName] => end-valid-time
[children] => Array
(
[0] => 2013-11-02T20:00:00-07:00
)
)
[3] => Array
(
[tagName] => start-valid-time
[children] => Array
(
[0] => 2013-11-03T07:00:00-08:00
)
)
[4] => Array
(
[tagName] => end-valid-time
[children] => Array
(
[0] => 2013-11-03T19:00:00-08:00
)
)
[5] => Array
(
[tagName] => start-valid-time
[children] => Array
(
[0] => 2013-11-04T07:00:00-08:00
)
)
[6] => Array
(
[tagName] => end-valid-time
[children] => Array
(
[0] => 2013-11-04T19:00:00-08:00
)
)
[7] => Array
(
[tagName] => start-valid-time
[children] => Array
(
[0] => 2013-11-05T07:00:00-08:00
)
)
[8] => Array
(
[tagName] => end-valid-time
[children] => Array
(
[0] => 2013-11-05T19:00:00-08:00
)
)
)
)
[3] => Array
(
[tagName] => time-layout
[attributes] => Array
(
[time-coordinate] => local
[summarization] => none
)
[children] => Array
(
[0] => Array
(
[tagName] => layout-key
[children] => Array
(
[0] => k-p24h-n5-2
)
)
[1] => Array
(
[tagName] => start-valid-time
[children] => Array
(
[0] => 2013-11-01T20:00:00-07:00
)
)
[2] => Array
(
[tagName] => end-valid-time
[children] => Array
(
[0] => 2013-11-02T09:00:00-07:00
)
)
[3] => Array
(
[tagName] => start-valid-time
[children] => Array
(
[0] => 2013-11-02T19:00:00-07:00
)
)
...
[10] => Array
(
[tagName] => end-valid-time
[children] => Array
(
[0] => 2013-11-06T08:00:00-08:00
)
)
)
)
[4] => Array
(
[tagName] => time-layout
[attributes] => Array
(
[time-coordinate] => local
[summarization] => none
)
[children] => Array
(
[0] => Array
(
[tagName] => layout-key
[children] => Array
(
[0] => k-p12h-n9-3
)
)
[1] => Array
(
[tagName] => start-valid-time
[children] => Array
(
[0] => 2013-11-01T17:00:00-07:00
)
)
...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Hidden features of C I know there is a standard behind all C compiler implementations, so there should be no hidden features. Despite that, I am sure all C developers have hidden/secret tricks they use all the time.
A: C compilers implement one of several standards. However, having a standard does not mean that all aspects of the language are defined. Duff's device, for example, is a favorite 'hidden' feature that has become so popular that modern compilers have special purpose recognition code to ensure that optimization techniques do not clobber the desired effect of this often used pattern.
In general hidden features or language tricks are discouraged as you are running on the razor edge of whichever C standard(s) your compiler uses. Many such tricks do not work from one compiler to another, and often these kinds of features will fail from one version of a compiler suite by a given manufacturer to another version.
Various tricks that have broken C code include:
*
*Relying on how the compiler lays out structs in memory.
*Assumptions on endianness of integers/floats.
*Assumptions on function ABIs.
*Assumptions on the direction that stack frames grow.
*Assumptions about order of execution within statements.
*Assumptions about order of execution of statements in function arguments.
*Assumptions on the bit size or precision of short, int, long, float and double types.
Other problems and issues that arise whenever programmers make assumptions about execution models that are all specified in most C standards as 'compiler dependent' behavior.
A: When using sscanf you can use %n to find out where you should continue to read:
sscanf ( string, "%d%n", &number, &length );
string += length;
Apparently, you can't add another answer, so I'll include a second one here, you can use "&&" and "||" as conditionals:
#include <stdio.h>
#include <stdlib.h>
int main()
{
1 || puts("Hello\n");
0 || puts("Hi\n");
1 && puts("ROFL\n");
0 && puts("LOL\n");
exit( 0 );
}
This code will output:
Hi
ROFL
A: using INT(3) to set break point at the code is my all time favorite
A: My favorite "hidden" feature of C, is the usage of %n in printf to write back to the stack. Normally printf pops the parameter values from the stack based on the format string, but %n can write them back.
Check out section 3.4.2 here. Can lead to a lot of nasty vulnerabilities.
A: Gcc (c) has some fun features you can enable, such as nested function declarations, and the a?:b form of the ?: operator, which returns a if a is not false.
A: Compile-time assumption-checking using enums:
Stupid example, but can be really useful for libraries with compile-time configurable constants.
#define D 1
#define DD 2
enum CompileTimeCheck
{
MAKE_SURE_DD_IS_TWICE_D = 1/(2*(D) == (DD)),
MAKE_SURE_DD_IS_POW2 = 1/((((DD) - 1) & (DD)) == 0)
};
A: I discoverd recently 0 bitfields.
struct {
int a:3;
int b:2;
int :0;
int c:4;
int d:3;
};
which will give a layout of
000aaabb 0ccccddd
instead of without the :0;
0000aaab bccccddd
The 0 width field tells that the following bitfields should be set on the next atomic entity (char)
A: int8_t
int16_t
int32_t
uint8_t
uint16_t
uint32_t
These are an optional item in the standard, but it must be a hidden feature, because people are constantly redefining them. One code base I've worked on (and still do, for now) has multiple redefinitions, all with different identifiers. Most of the time it's with preprocessor macros:
#define INT16 short
#define INT32 long
And so on. It makes me want to pull my hair out. Just use the freaking standard integer typedefs!
A: The comma operator isn't widely used. It can certainly be abused, but it can also be very useful. This use is the most common one:
for (int i=0; i<10; i++, doSomethingElse())
{
/* whatever */
}
But you can use this operator anywhere. Observe:
int j = (printf("Assigning variable j\n"), getValueFromSomewhere());
Each statement is evaluated, but the value of the expression will be that of the last statement evaluated.
A: C99-style variable argument macros, aka
#define ERR(name, fmt, ...) fprintf(stderr, "ERROR " #name ": " fmt "\n", \
__VAR_ARGS__)
which would be used like
ERR(errCantOpen, "File %s cannot be opened", filename);
Here I also use the stringize operator and string constant concatentation, other features I really like.
A: initializing structure to zero
struct mystruct a = {0};
this will zero all stucture elements.
A: Function pointers. You can use a table of function pointers to implement, e.g., fast indirect-threaded code interpreters (FORTH) or byte-code dispatchers, or to simulate OO-like virtual methods.
Then there are hidden gems in the standard library, such as qsort(),bsearch(), strpbrk(), strcspn() [the latter two being useful for implementing a strtok() replacement].
A misfeature of C is that signed arithmetic overflow is undefined behavior (UB). So whenever you see an expression such as x+y, both being signed ints, it might potentially overflow and cause UB.
A: Variable size automatic variables are also useful in some cases. These were added i nC99 and have been supported in gcc for a long time.
void foo(uint32_t extraPadding) {
uint8_t commBuffer[sizeof(myProtocol_t) + extraPadding];
You end up with a buffer on the stack with room for the fixed-size protocol header plus variable size data. You can get the same effect with alloca(), but this syntax is more compact.
You have to make sure extraPadding is a reasonable value before calling this routine, or you end up blowing the stack. You'd have to sanity check the arguments before calling malloc or any other memory allocation technique, so this isn't really unusual.
A: Multi-character constants:
int x = 'ABCD';
This sets x to 0x41424344 (or 0x44434241, depending on architecture).
EDIT: This technique is not portable, especially if you serialize the int.
However, it can be extremely useful to create self-documenting enums. e.g.
enum state {
stopped = 'STOP',
running = 'RUN!',
waiting = 'WAIT',
};
This makes it much simpler if you're looking at a raw memory dump and need to determine the value of an enum without having to look it up.
A: I liked the variable sized structures you could make:
typedef struct {
unsigned int size;
char buffer[1];
} tSizedBuffer;
tSizedBuffer *buff = (tSizedBuffer*)(malloc(sizeof(tSizedBuffer) + 99));
// can now refer to buff->buffer[0..99].
Also the offsetof macro which is now in ANSI C but was a piece of wizardry the first time I saw it. It basically uses the address-of operator (&) for a null pointer recast as a structure variable.
A: Lambda's (e.g. anonymous functions) in GCC:
#define lambda(return_type, function_body) \
({ return_type fn function_body fn })
This can be used as:
lambda (int, (int x, int y) { return x > y; })(1, 2)
Which is expanded into:
({ int fn (int x, int y) { return x > y } fn; })(1, 2)
A: I like __LINE__ and __FILE__. See here: http://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html
A: I never used bit fields but they sound cool for ultra-low-level stuff.
struct cat {
unsigned int legs:3; // 3 bits for legs (0-4 fit in 3 bits)
unsigned int lives:4; // 4 bits for lives (0-9 fit in 4 bits)
// ...
};
cat make_cat()
{
cat kitty;
kitty.legs = 4;
kitty.lives = 9;
return kitty;
}
This means that sizeof(cat) can be as small as sizeof(char).
Incorporated comments by Aaron and leppie, thanks guys.
A: For clearing the input buffer you can't use fflush(stdin). The correct way is as follows: scanf("%*[^\n]%*c")
This will discard everything from the input buffer.
A: Interlacing structures like Duff's Device:
strncpy(to, from, count)
char *to, *from;
int count;
{
int n = (count + 7) / 8;
switch (count % 8) {
case 0: do { *to = *from++;
case 7: *to = *from++;
case 6: *to = *from++;
case 5: *to = *from++;
case 4: *to = *from++;
case 3: *to = *from++;
case 2: *to = *from++;
case 1: *to = *from++;
} while (--n > 0);
}
}
A: C has a standard but not all C compilers are fully compliant (I've not seen any fully compliant C99 compiler yet!).
That said, the tricks I prefer are those that are non-obvious and portable across platforms as they rely on the C semantic. They usually are about macros or bit arithmetic.
For example: swapping two unsigned integer without using a temporary variable:
...
a ^= b ; b ^= a; a ^=b;
...
or "extending C" to represent finite state machines like:
FSM {
STATE(x) {
...
NEXTSTATE(y);
}
STATE(y) {
...
if (x == 0)
NEXTSTATE(y);
else
NEXTSTATE(x);
}
}
that can be achieved with the following macros:
#define FSM
#define STATE(x) s_##x :
#define NEXTSTATE(x) goto s_##x
In general, though, I don't like the tricks that are clever but make the code unnecessarily complicated to read (as the swap example) and I love the ones that make the code clearer and directly conveying the intention (like the FSM example).
A: I'm very fond of designated initializers, added in C99 (and supported in gcc for a long time):
#define FOO 16
#define BAR 3
myStructType_t myStuff[] = {
[FOO] = { foo1, foo2, foo3 },
[BAR] = { bar1, bar2, bar3 },
...
The array initialization is no longer position dependent. If you change the values of FOO or BAR, the array initialization will automatically correspond to their new value.
A: Early versions of gcc attempted to run a game whenever it encountered "#pragma" in the source code. See also here.
A: I got shown this in a bit of code once, and asked what it did:
hexDigit = "0123456789abcdef"[someNybble];
Another favorite is:
unsigned char bar[100];
unsigned char *foo = bar;
unsigned char blah = 42[foo];
A: Conversion of types by using unusual typecasts. Though not hidden feature, its quite tricky.
Example:
If you needed to know how compiler stores float, just try this:
uint32_t Int;
float flt = 10.5; // say
Int = *(uint32_t *)&flt;
printf ("Float 10.5 is stored internally as %8X\n", Int);
or
float flt = 10.5; // say
printf ("Float 10.5 is stored internally as %8X\n", *(uint32_t *)&flt);
Note the clever use of typecasts. Converting address of variable (here &flt) to desired type (here (uint32_t * )) and extracting its content (applying '*').
This works other side of expression as well:
*(float *)&Int = flt;
This could also be accomplished using union:
typedef union
{
uint32_t Int;
float flt;
} FloatInt_type;
A: I only discovered this after 15+ years of C programming:
struct SomeStruct
{
unsigned a : 5;
unsigned b : 1;
unsigned c : 7;
};
Bitfields! The number after the colon is the number of bits the member requires, with members packed into the specified type, so the above would look like the following if unsigned is 16 bits:
xxxc cccc ccba aaaa
Skizz
A: C99 has some awesome any-order structure initialization.
struct foo{
int x;
int y;
char* name;
};
void main(){
struct foo f = { .y = 23, .name = "awesome", .x = -38 };
}
A: anonymous structures and arrays is my favourite one. (cf. http://www.run.montefiore.ulg.ac.be/~martin/resources/kung-f00.html)
setsockopt(yourSocket, SOL_SOCKET, SO_REUSEADDR, (int[]){1}, sizeof(int));
or
void myFunction(type* values) {
while(*values) x=*values++;
}
myFunction((type[]){val1,val2,val3,val4,0});
it can even be used to instanciate linked lists...
A: Well... I think that one of the strong points of C language is its portability and standardness, so whenever I find some "hidden trick" in the implementation I am currently using, I try not to use it because I try to keep my C code as standard and portable as possible.
A: gcc has a number of extensions to the C language that I enjoy, which can be found here. Some of my favorites are function attributes. One extremely useful example is the format attribute. This can be used if you define a custom function that takes a printf format string. If you enable this function attribute, gcc will do checks on your arguments to ensure that your format string and arguments match up and will generate warnings or errors as appropriate.
int my_printf (void *my_object, const char *my_format, ...)
__attribute__ ((format (printf, 2, 3)));
A: the (hidden) feature that "shocked" me when I first saw is about printf. this feature allows you to use variables for formatting format specifiers themselves. look for the code, you will see better:
#include <stdio.h>
int main() {
int a = 3;
float b = 6.412355;
printf("%.*f\n",a,b);
return 0;
}
the * character achieves this effect.
A: Not really a hidden feature, but it looked to me like voodoo, the first time I saw something like this:
void callback(const char *msg, void *data)
{
// do something with msg, e.g.
printf("%s\n", msg);
return;
data = NULL;
}
The reason for this construction is, that if you compile this with -Wextra and without the "data = NULL;"-line, gcc will spit out a warning about unused parameters. But with this useless line you don't get a warning.
EDIT: I know there are other (better) ways to prevent those warnings. It just looked strange to me, the first time I saw this.
A: intptr_t for declaring variables of type pointer. C99 specific and declared in stdint.h
A: Steve Webb has pointed out the __LINE__ and __FILE__ macros. It reminds me of how in my previous job I had hacked them to have in-memory logging.
I was working on a device where there was no port available to pass logging information from device to the PC being used for debugging. One could use breakpoints to halt and know the state of the program using debugger but there was no information on system trace.
Since all calls to debug logs were effectively a single global macro, we changed that macro to dump file name and line number on to a global array. This array contained series of file names and line numbers showing which debug calls were invoked, giving a fair idea of execution trace (not the actual log message though). One could pause the execution by debugger, dump these bytes onto a local file and then map this information to the code base using scripts. This was made possible because we had strict coding guidelines, so we could make had to make changes to the logging mechanism in one file.
A: When comparing a variable to a literal, it is better to put the literal to the left of the == operator, to make the sure the compiler gives an error when you mistakenly use the assignment operator instead.
if (0 == count) {
...
}
Might look weird at first glance, but it could save some headache (like if you happened to type if (count = 0) by mistake).
A: Compile-time assertions, as already discussed here.
//--- size of static_assertion array is negative if condition is not met
#define STATIC_ASSERT(condition) \
typedef struct { \
char static_assertion[condition ? 1 : -1]; \
} static_assertion_t
//--- ensure structure fits in
STATIC_ASSERT(sizeof(mystruct_t) <= 4096);
A: Constant string concatenation
I was quite surprised not seeing it allready in the answers, as all compilers I know of support it, but many programmers seems to ignore it. Sometimes it's really handy and not only when writing macros.
Use case I have in my current code:
I have a #define PATH "/some/path/" in a configuration file (really it is setted by the makefile). Now I want to build the full path including filenames to open ressources. It just goes to:
fd = open(PATH "/file", flags);
Instead of the horrible, but very common:
char buffer[256];
snprintf(buffer, 256, "%s/file", PATH);
fd = open(buffer, flags);
Notice that the common horrible solution is:
*
*three times as long
*much less easy to read
*much slower
*less powerfull at it set to an arbitrary buffer size limit (but you would have to use even longer code to avoid that without constant strings contatenation).
*use more stack space
A: Well, I've never used it, and I'm not sure whether I'd ever recommend it to anyone, but I feel this question would be incomplete without a mention of Simon Tatham's co-routine trick.
A: Struct assignment is cool. Many people don't seem to realize that structs are values too, and can be assigned around, there is no need to use memcpy(), when a simple assignment does the trick.
For example, consider some imaginary 2D graphics library, it might define a type to represent an (integer) screen coordinate:
typedef struct {
int x;
int y;
} Point;
Now, you do things that might look "wrong", like write a function that creates a point initialized from function arguments, and returns it, like so:
Point point_new(int x, int y)
{
Point p;
p.x = x;
p.y = y;
return p;
}
This is safe, as long (of course) as the return value is copied by value using struct assignment:
Point origin;
origin = point_new(0, 0);
In this way you can write quite clean and object-oriented-ish code, all in plain standard C.
A: When initializing arrays or enums, you can put a comma after the last item in the initializer list. e.g:
int x[] = { 1, 2, 3, };
enum foo { bar, baz, boom, };
This was done so that if you're generating code automatically you don't need to worry about eliminating the last comma.
A: More of a trick of the GCC compiler, but you can give branch indication hints to the compiler (common in the Linux kernel)
#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)
see: http://kerneltrap.org/node/4705
What I like about this is that it also adds some expressiveness to some functions.
void foo(int arg)
{
if (unlikely(arg == 0)) {
do_this();
return;
}
do_that();
...
}
A: Strange vector indexing:
int v[100]; int index = 10;
/* v[index] it's the same thing as index[v] */
A: register variables
I used to declare some variables with the register keyword to help speed things up. This would give a hint to the C compiler to use a CPU register as local storage. This is most likely no longer necessary as modern day C compilers do this automatically.
A: Excerpt:
In this page, you will find a list of
interesting C programming
questions/puzzles, These programs
listed are the ones which I have
received as e-mail forwards from my
friends, a few I read in some books, a
few from the internet, and a few from
my coding experiences in C.
http://www.gowrikumar.com/c/index.html
A: Say you have a struct with members of the same type:
struct Point {
float x;
float y;
float z;
};
You can cast instances of it to a float pointer and use array indices:
Point a;
int sum = 0, i = 0;
for( ; i < 3; i++)
sum += ((float*)a)[i];
Pretty elementary, but useful when writing concise code.
A: Here's three nice ones in gcc:
__FILE__
__FUNCTION__
__LINE__
A: The size of function pointers is not standard. At least not in the K&R book. Even though it talks about size of other types of pointers but (I think) sizeof of a function pointer is undefined behavior.
Also sizeof is a compile time operator, I see a lot of people asking if sizeof is a function or an operator in online forums.
One error that I have seen is as follows (a simplified example):
int j;
int i;
j = sizeof(i++)
the increment on i would not be executed as sizeof is evaluated at compile time. The programmer intended to hack both operations, increment on i and calculation of sizeof in one statement.
Operator precedence in C governs order of association not order of evaluation. For example if you have three functions f,g,h each returning an int, and their is an expression like:
f() + g() * h()
C standard doesn't give rule about order of evaluation of these functions. Result of g and h would be multiplied before adding result of f. This can lead to error if the functions share state and computation depends on order of evaluation of these functions. This can lead to portability issues.
A: Variable-sized structs, seen in common resolver libs among other places.
struct foo
{
int a;
int b;
char b[1]; // using [0] is no longer correct
// must come at end
};
char *str = "abcdef";
int len = strlen(str);
struct foo *bar = malloc(sizeof(foo) + len);
strcpy(bar.b, str); // try and stop me!
A: Wrap malloc and realloc like this:
#ifdef _DEBUG
#define mmalloc(bytes) malloc(bytes);printf("malloc: %d\t<%s@%d>\n", bytes, __FILE__, __LINE__);
#define mrealloc(pointer, bytes) realloc(pointer, bytes);printf("realloc: %d\t<%s@%d>\n", bytes, __FILE__, __LINE__);
#else //_DEBUG
#define mmalloc(bytes) malloc(bytes)
#define mrealloc(pointer, bytes) realloc(pointer, bytes)
In fact, here is my full arsenol (The BailIfNot is for OO c):
#ifdef _DEBUG
#define mmalloc(bytes) malloc(bytes);printf("malloc: %d\t<%s@%d>\n", bytes, __FILE__, __LINE__);
#define mrealloc(pointer, bytes) realloc(pointer, bytes);printf("realloc: %d\t<%s@%d>\n", bytes, __FILE__, __LINE__);
#define BAILIFNOT(Node, Check) if(Node->type != Check) return 0;
#define NULLCHECK(var) if(var == NULL) setError(__FILE__, __LINE__, "Null exception", " var ", FATAL);
#define ASSERT(n) if( ! ( n ) ) { printf("<ASSERT FAILURE@%s:%d>", __FILE__, __LINE__); fflush(0); __asm("int $0x3"); }
#define TRACE(n) printf("trace: %s <%s@%d>\n", n, __FILE__, __LINE__);fflush(0);
#else //_DEBUG
#define mmalloc(bytes) malloc(bytes)
#define mrealloc(pointer, bytes) realloc(pointer, bytes)
#define BAILIFNOT(Node, Check) {}
#define NULLCHECK(var) {}
#define ASSERT(n) {}
#define TRACE(n) {}
#endif //_DEBUG
Here is some example output:
malloc: 12 <hash.c@298>
trace: nodeCreate <hash.c@302>
malloc: 5 <hash.c@308>
malloc: 16 <hash.c@316>
malloc: 256 <hash.c@320>
trace: dataLoadHead <hash.c@441>
malloc: 270 <hash.c@463>
malloc: 262144 <hash.c@467>
trace: dataLoadRecursive <hash.c@404>
A: I just read this article. It has some C and several other languages "hidden features".
A: Object oriented C macros:
You need a constructor (init), a destructor (dispose), an equal (equal), a copier (copy), and some prototype for instantiation (prototype).
With the declaration, you need to declare a constant prototype to copy and derive from. Then you can do C_OO_NEW. I can post more examples if needed. LibPurple is a large object oriented C code base with a callback system (if you want to see one in use)
#define C_copy(to, from) to->copy(to, from)
#define true 1
#define false 0
#define C_OO_PROTOTYPE(type)\
void type##_init (struct type##_struct *my);\
void type##_dispose (struct type##_struct *my);\
char type##_equal (struct type##_struct *my, struct type##_struct *yours); \
struct type##_struct * type##_copy (struct type##_struct *my, struct type##_struct *from); \
const type type##__prototype = {type##_init, type##_dispose, type##_equal, type##_copy
#define C_OO_OVERHEAD(type)\
void (*init) (struct type##_struct *my);\
void (*dispose) (struct type##_struct *my);\
char (*equal) (struct type##_struct *my, struct type##_struct *yours); \
struct type##_struct *(*copy) (struct type##_struct *my, struct type##_struct *from);
#define C_OO_IN(ret, type, function, ...) ret (* function ) (struct type##_struct *my, __VA_ARGS__);
#define C_OO_OUT(ret, type, function, ...) ret type##_##function (struct type##_struct *my, __VA_ARGS__);
#define C_OO_PNEW(type, instance)\
instance = ( type *) malloc(sizeof( type ));\
memcpy(instance, & type##__prototype, sizeof( type ));
#define C_OO_NEW(type, instance)\
type instance;\
memcpy(&instance, & type ## __prototype, sizeof(type));
#define C_OO_DELETE(instance)\
instance->dispose(instance);\
free(instance);
#define C_OO_INIT(type) void type##_init (struct type##_struct *my){return;}
#define C_OO_DISPOSE(type) void type##_dispose (struct type##_struct *my){return;}
#define C_OO_EQUAL(type) char type##_equal (struct type##_struct *my, struct type##_struct *yours){return 0;}
#define C_OO_COPY(type) struct type##_struct * type##_copy (struct type##_struct *my, struct type##_struct *from){return 0;}
A: I like the typeof() operator. It works like sizeof() in that it is resolved at compile time. Instead of returning the number of bytes, it returns the type. This is useful when you need to declare a variable to be the same type as some other variable, whatever type it may be.
typeof(foo) copy_of_foo; //declare bar to be a variable of the same type as foo
copy_of_foo = foo; //now copy_of_foo has a backup of foo, for any type
This might be just a gcc extension, I'm not sure.
A: Use NaN for chained calculations / error return :
//#include <stdint.h>
static uint64_t iNaN = 0xFFF8000000000000;
const double NaN = *(double *)&iNaN; // quiet NaN
An inner function can return NaN as an error flag : it can safely be used in any calculation, and the result will always be NaN.
note : testing for NaN is tricksy, since NaN != NaN... use isnan(x), or roll your own.
x!=x is mathematically correct if x is NaN, but tends to get optimised out by some compilers
A: The often forgotten %n specifier in printf format string can be quite practical sometimes. %n returns the current position of the imaginary cursor used when printf formats its output.
int pos1, pos2;
char *string_of_unknown_length = "we don't care about the length of this";
printf("Write text of unknown %n(%s)%n text\n", &pos1, string_of_unknown_length, &pos2);
printf("%*s\\%*s/\n", pos1, " ", pos2-pos1-2, " ");
printf("%*s", pos1+1, " ");
for(int i=pos1+1; i<pos2-1; i++)
putc('-', stdout);
putc('\n', stdout);
will have following output
Write text of unknown (we don't care about the length of this) text
\ /
--------------------------------------
Granted a little bit contrived but can have some uses when making pretty reports.
A: How about using while(0) inside a switch so you can use continue statements like break :-)
void sw(int s)
{
switch (s) while (0) {
case 0:
printf("zero\n");
continue;
case 1:
printf("one\n");
continue;
default:
printf("something else\n");
continue;
}
}
A: In Visual Studio, it is possible for you to highlight your own defined types.
To do that, create a file called "usertype.dat" in the folder "Commom7/IDE". The contents of that file shall be the types you want to highlight. For example:
//content of usertype.dat
int8_t
int16_t
int32_t
int64_t
uint8_t
uint16_t
uint32_t
uint64_t
float32_t
float64_t
char_t
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "141"
}
|
Q: Does a memory leak at unload of a DLL cause a leak in the host process? Consider this case:
dll = LoadDLL()
dll->do()
...
void do() {
char *a = malloc(1024);
}
...
UnloadDLL(dll);
At this point, will the 1k allocated in the call to malloc() be available to the host process again?
The DLL is statically linking to the CRT.
A: *
*Memory used by a process as tracked by the OS is applicable to the full process and not specific to a DLL.
*Memory is given to the program in chunks by the OS, called heaps
*The heap managers (malloc / new etc) further divide up the chunks and hands it out to requesting code.
*Only when a new heap is allocated does the OS detect an increase in memory.
*When a DLL is statically linked to the C Run time library (CRT), a private copy of CRT with the CRT functions that the DLL's code invokes is compiled and put into the DLL's binary. Malloc is also inclued in this.
*This private copy of malloc will be invoked whenever the code present inside the statically linked DLL tries to allocate memory.
*Consequently, a private heap visible only to this copy of malloc, is acquired from the OS by this malloc and it allocates the memory requested by the code within this private heap.
*When the DLL unloads, it unloads its private heap, and this leak goes unnoticed as the entire heap is returned back to the OS.
*However If the DLL is dynamically linked, the memory is allocated by a single shared version of malloc, global to all code that is linked in the shared mode.
*Memory allocated by this global malloc, comes out of a heap which is also the heap used for all other code that is linked in the dynamic aka shared mode and hence is common. Any leaks from this heap therefore becomes a leak which affects the whole process.
Edit - Added descriptions of the linking scenario.
A: You can't tell. This depends on the implementation of your static and dynamic CRT. It may even depend on the size of the allocation, as there are CRTs that forward large allocations to the OS, but implement their own heap for small allocations.
The problem with a CRT that leaks is of course that it leaks. The problem with a CRT that does not leak is that the executable might reasonable expect to use the memory, as malloc'ed memory should remain usable until free is called.
A: From MSDN Potential Errors Passing CRT Objects Across DLL Boundaries
Each copy of the CRT library has a
separate and distinct state. As such,
CRT objects such as file handles,
environment variables, and locales are
only valid for the copy of the CRT
where these objects are allocated or
set. When a DLL and its users use
different copies of the CRT library,
you cannot pass these CRT objects
across the DLL boundary and expect
them to be picked up correctly on the
other side.
Also, because each copy of the CRT
library has its own heap manager,
allocating memory in one CRT library
and passing the pointer across a DLL
boundary to be freed by a different
copy of the CRT library is a potential
cause for heap corruption.
Hope this helps.
A: Actually, the marked answer is incorrect. That right there is a leak. While it is technically feasible for each dll to implement its own heap, and free it on shutdown, most "runtime" heaps - static or dynamic - are wrappers around the Win32 process heap API.
Unless one has taken specific care to guarantee that this is not the case, the dll will leak the allocation per load,do,unload cycle.
A: One could do a test and see if there are memory leaks. You run a simple test 30 times allocating 1 MB each time. You should figure that out quite quickly.
One thing is for sure. If you allocated memory in the DLL you should also free that memory there (in the DLL).
For example you should have something like this (simple but intuitive pseudocode):
dll = DllLoad();
ptr = dll->alloc();
dll->free(ptr);
DllUnload(dll);
This must be done because the DLL has a different heap than the original process (that loads the dll).
A: No, you do not leak.
If you mix dll models (static, dynamic) then you can end up with a memory error if you allocate memory in a dll, that you free in a different one (or freed in the exe)
This means that the heap created by the statically-linked CRT is not the same heap as a different dll's CRT.
If you'd linked with the dynamic version of the CRT, then you'd have a leak as the heap is shared amongst all dynamically-linked CRTs. It means you should always design your apps to use the dynamic CRTs, or ensure you never manage memory across a dll boundary (ie if you allocate memory in a dll, always provide a routine to free it in the same dll)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Is there any way to use an extension method in an object initializer block in C# The simple demo below captures what I am trying to do. In the real program, I have to use the object initialiser block since it is reading a list in a LINQ to SQL select expression, and there is a value that that I want to read off the database and store on the object, but the object doesn't have a simple property that I can set for that value. Instead it has an XML data store.
It looks like I can't call an extension method in the object initialiser block, and that I can't attach a property using extension methods.
So am I out of luck with this approach? The only alternative seems to be to persuade the owner of the base class to modify it for this scenario.
I have an existing solution where I subclass BaseDataObject, but this has problems too that don't show up in this simple example. The objects are persisted and restored as BaseDataObject - the casts and tests would get complex.
public class BaseDataObject
{
// internal data store
private Dictionary<string, object> attachedData = new Dictionary<string, object>();
public void SetData(string key, object value)
{
attachedData[key] = value;
}
public object GetData(string key)
{
return attachedData[key];
}
public int SomeValue { get; set; }
public int SomeOtherValue { get; set; }
}
public static class Extensions
{
public static void SetBarValue(this BaseDataObject dataObject,
int barValue)
{
/// Cannot attach a property to BaseDataObject?
dataObject.SetData("bar", barValue);
}
}
public class TestDemo
{
public void CreateTest()
{
// this works
BaseDataObject test1 = new BaseDataObject
{ SomeValue = 3, SomeOtherValue = 4 };
// this does not work - it does not compile
// cannot use extension method in the initialiser block
// cannot make an exension property
BaseDataObject test2 = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4, SetBarValue(5) };
}
}
One of the answers (from mattlant) suggests using a fluent interface style extension method. e.g.:
// fluent interface style
public static BaseDataObject SetBarValueWithReturn(this BaseDataObject dataObject, int barValue)
{
dataObject.SetData("bar", barValue);
return dataObject;
}
// this works
BaseDataObject test3 = (new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 }).SetBarValueWithReturn(5);
But will this work in a LINQ query?
A: Object Initializers are just syntactic sugar that requires a clever compiler, and as of the current implementation you can't call methods in the initializer.
var x = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 };
Will get compiler to something like this:
BaseDataObject tempObject = new BaseDataObject();
tempObject.SomeValue = 3;
tempObject.SomeOtherValue = 4;
BaseDataObject x = tempObject;
The difference is that there can't be any synchronization issues. The variable x get's assigned the fully assigned BaseDataObject at once, you can't mess with the object during it's initialization.
You could just call the extension method after the object creation:
var x = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 };
x.SetBarValue()
You could change SetBarValue to be a property with get/set that can be assigned during initialization:
public int BarValue
{
set
{
//Value should be ignored
}
}
Or, you could subclass / use the facade pattern to add the method onto your object:
public class DataObjectWithBarValue : BaseDataObject
{
public void BarValue
{
set
{
SetData("bar", value);
}
get
{
(int) GetData("bar");
}
}
}
A: No but you could do this....:
BaseDataObject test2 = (new BaseDataObject { SomeValue = 3, SomeOtherValue = 4}).SetBarValue(5);
ANd have your extension return the object like Linq Does.
EDIT: This was a good thought untill i reread and saw that the base class was developed by a third person: aka you dont have the code. Others here have posted a correct solution.
A: Even better:
public static T SetBarValue<T>(this T dataObject, int barValue)
where T : BaseDataObject
{
dataObject.SetData("bar", barValue);
return dataObject;
}
and you can use this extension method for derived types of BaseDataObject to chain methods without casts and preserve the real type when inferred into a var field or anonymous type.
A: static T WithBarValue<T>(this T dataObject, int barValue)
where T : BaseDataObject
{ dataObject.SetData("bar", barValue);
return dataObject;
}
var x = new BaseDataObject{SomeValue=3, OtherValue=4}.WithBarValue(5);
A: Is extending the class a possibility? Then you could easily add the property you need.
Failing that, you can create a new class that has similar properties that simply call back to a private instance of the class you are interested in.
A: Right, having learned from the answerers, the short answer to "Is there any way to use an extension method in an object initializer block in C#?" is "No."
The way that I eventually solved the problem that I faced (similar, but more complex that the toy problem that I posed here) was a hybrid approach, as follows:
I created a subclass, e.g.
public class SubClassedDataObject : BaseDataObject
{
public int Bar
{
get { return (int)GetData("bar"); }
set { SetData("bar", value); }
}
}
Which works fine in LINQ, the initialisation block looking like
SubClassedDataObject testSub = new SubClassedDataObject
{ SomeValue = 3, SomeOtherValue = 4, Bar = 5 };
But the reason that I didn't like this approach in the first place is that these objects are put into XML and come back out as BaseDataObject, and casting back was going to be an annoyance, an unnecessary data copy, and would put two copies of the same object in play.
In the rest of the code, I ignored the subclasses and used extension methods:
public static void SetBar(this BaseDataObject dataObject, int barValue)
{
dataObject.SetData("bar", barValue);
}
public static int GetBar(this BaseDataObject dataObject)
{
return (int)dataObject.GetData("bar");
}
And it works nicely.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: WPF animation of items between layouts? I have two different ways of displaying items in a WPF application. The first uses a WrapPanel and the second a vertical StackPanel. I can switch between the two ways of displaying my items by switching the host panel between the two types. This does work but you get an instance change in layout.
Instead I want the child items to animate between the two layouts to give a nice smooth effect to the user. Any ideas how I could go about achieving that? Do I need to a Canvas instead and work out the positioning of children manually? That would be a real pain!
A: Have a look at the SwitchPanel from IdentityMine's Blendables Layout and also read Dr WPF's article on CodeProject about Conceptual Children
A: I have posted another solution on codeproject that is free and ready to use WPF Layout to Layout transitions
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: When exactly plugin.xml files from dependencies of my plugin are loaded? I vahe eclipse rcp app. In my plugin A I use 3rd party plugin B.
In plugin B there is plugin.xml with some extensions. In my plugin A I have added some extensions to extensions defined in plugin B, and it works.
Now I tried to overwrite some values in some extensions from B in plugin A.
Now, when I run app sometimes it uses old values (from plugin.xml in plugin B), sometimes it uses my new values (from plugin A plugin.xml). It's consistent in one execution of app, but changes from execution to execution.
Code that gets these values is in plugin B and I wouldn't like to change it. And looks like that:
IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint("org.jbpm.gd.common.xmlMappings");
IExtension[] extensions = extensionPoint.getExtensions();
How can I ensure my values will be used?
I think it's matter of setting right order of loading of plugin.xml files, so my plugin.xml will be last, and my values will overwrite theirs, but I'm not sure how to do it.
A: Eclipse makes no guarantees about the order that extensions are seen. Further, there is no guaranteed lifecycle for when specific plugins are loaded. If you want a guarantee, you need to implement it manually, and that will probably require a change of plugin B.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: A better Eclipse browser? Does anybody know of a free web browser plugin for eclipse that is better than the built-in browser? I searched but couldn't find anything. I know Tasktop has one, but it's not free...
A: It was (in 2010):
https://marketplace.eclipse.org/content/eclipse-advanced-browser
now is integrated with http://marketplace.eclipse.org/content/j-office-java-fx-office#.U0-y8HB5B74 (http://www.joffice.eu)
Now you can only do something like that: https://stackoverflow.com/a/9056165/2288169
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: fatal error C1900: Il mismatch between 'P1' version '20060201' and 'P2' version '20050411' I compile my project with VIsual Studio 2005 Express Edition, and get this linking error. Can anyone suggest how to solve that?
A: I downloaded VS2005 Service Pack 1 from Microsoft, installed it and it fixed the problem.
A: MSDN: Fatal Error C1900 says:
"Tools run in various passes of the compiler do not match. number1 and number2 refer to the dates on the files. For example, in pass 1, the compiler front end runs (c1.dll) and in pass 2, the compiler back end runs (c2.dll). The dates on the files must match and if they do not, reinstall and use the current version of each tool."
Go to Add/Remove Programs, select Visual Studio 2005 Express Edition, click Change/Remove, then perform a repair.
A: That exact question is asked and answered at http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1512436&SiteID=1.
Try re-installing. It appears to be an install of the wrong service pack.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Active Directory: Retrieve User information I've got a web application that is running against Windows Authentication using our Active Directory. I've got a new requirement to pull some personal information through from the Active Directory entry. What would be the easiest way to get access to this information?
A: You might find the following snippet useful as a starter.
public static bool IsUserInGroup(string lanid, string group)
{
DirectoryEntry entry = new DirectoryEntry("LDAP://" + LDAPPATH);
if(entry != null)
{
entry.Username=@"LDAPUSER";
entry.Password="LDAPPASSWORD";
DirectorySearcher srch = new DirectorySearcher(entry);
srch.Filter = String.Format("(&(objectClass=person)(sAMAccountName={0}))", lanid);
srch.PropertiesToLoad.Add("memberOf");
SearchResult result = srch.FindOne();
if(result != null)
{
if(result.Properties.Contains("memberOf"))
{
string lookfor = String.Format("cn={0},", group.ToLower());
foreach(string memberOf in result.Properties["memberOf"])
{
if(memberOf.ToLower().StartsWith(lookfor))
return true;
}
}
}
return false;
}
throw new Exception(String.Format("Could not get Directory lanid:{0}, group{1}", lanid, group));
}
A: A very good reference: Howto: (Almost) Everything In Active Directory via C#
A: Accessing the user directly through a DirectoryEntry seems like the most straightforward approach. Here are some AD-related tidbits I learned from my first AD-related project:
*
*In a URI, write LDAP in lowercase. Otherwise you'll get a mystery error. I spent more than a day on this depressing issue...
*To clear a single-valued property, set it to an empty string, not null. Null causes an exception.
*To clear a multi-valued property, use the DirectoryEntry.Property.Clear() method.
*The Active Directory schema reference will say which data type a value will be and whether it is multi-value or single-value.
*You do not need to manually RefreshCache() on a Directoryentry but if you ever use it and specify which properties to cache, know that it will not auto-retrieve any other properties in the future.
*A COMException can be thrown at absolutely any time you use the classes in System.DirectoryServices. Keep an eye on those try blocks. Do not assume anything is safe.
You'll probably need to use DirectorySearcher to get your user's directory entry if you don't know its path (which you wouldn't, just by having him logged in). Using it was fairly easy but beware of the quirks in LDAP syntax; namely, having to encode non-ASCII (and other?) characters. The search string you'd use would probably be something like: (&(sAMAccountName=whatever)(class=user)). This is off the top of my head and may be slightly incorrect.
The Active Directory schema reference will be useful. Do understand that the schema can be modified and extended (e.g. installing Exchange will add mailbox information to users).
AD Explorer is a useful tool which you can use for debugging and low-level AD data management. I've found it useful when I know which property I want to set but cannot find the right dialog box in the AD management tool.
A: Have a look at the System.DirectoryServices namespace:
System.DirectoryServices Namespace
A: I've used a standard LDAP library to retrieve information from an Active Directory server, but you'd have to verify that the data you need is available via the LDAP server's schema. In general, you can get any information stored in InetOrganizationalPerson and most of the information related to the group(s) they belong to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Are there any tips/tricks about using Subsonic with Asp.Net MVC Framework? Is there anyone using Subsonic with asp.net mvc framework? If so, can you tell us something about your experience. Are there tips and tricks that can be shared?
A: If you're planning on doing database first design, and you don't need any mapping (i.e. you're in control of your db naming) then SubSonic is a decent option.
It's straight-forward, doesn't hide a lot from you. On the same token, for advanced scenarios I have to side-step it a lot and execute raw sql (or a sproc).
If you're looking for a better object abstraction over the database, something that more closely matches your problem domain, then I'd look at NHibernate or Castle ActiveRecord. This gives you a lot more flexibility in how you want your object model to look, and you have a powerful query API at your disposal.
None of this really has to do with ASP.NET MVC, other than you just use your objects in your web project. I'd suggest putting the entities inside of a separate class library project anyway.
A: I totally agree with Ben SubSonic is an ORM and works well with the MVC concept but doesn't have anything that ties it with MVC.
For small projects or for projects that you already have a Database and don't really care to much about the domain then SubSonic is great and will get you up and running very fast.
But if your project is a bit bigger or more specificity your DB is an after thought then you should go with a tool like NHibernate.
FYI Summer of NHibernate is a great Screencast Series on getting started with NHibernate
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Is there a standard way to authenticate applications to your web API? I'm looking at building a simple web app that will expose an API that lets third-party (well, written by me, but that's not the point) apps query for and modify user-specific data stored on the site.
Obviously I don't want to allow apps to be able to get user-specific information without that users consent. I would want some kind of application authentication where users allow an application they run to use the web API to access their information.
Is there a standard way to achieve this or does every app (i.e. rememberthemilk) just hack up a bespoke solution specifically for them?
A: Will OAuth work for you? That's the problem it was designed to solve.
A: Also be careful to access your web service via HTTPS if the data is traversing the Internet. People take great pains to authenticate their web services, but then leave them vulnerable to network sniffing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: SVNkit cannot create SVNRepoitory I am trying to run a diff on two svn urls using SVNkit. The problem is that I get the error when diff.doDiff is called.
org.tmatesoft.svn.core.SVNException: svn: Unable to create
SVNRepository object for
'http://svn.codehaus.org/jruby/trunk/jruby/src/org/jruby/Finalizable.java'
at
org.tmatesoft.svn.core.internal.wc.SVNErrorManager.error(SVNErrorManager.java:55)
at
org.tmatesoft.svn.core.internal.wc.SVNErrorManager.error(SVNErrorManager.java:40)
at
org.tmatesoft.svn.core.io.SVNRepositoryFactory.create(SVNRepositoryFactory.java:199)
at
org.tmatesoft.svn.core.wc.DefaultSVNRepositoryPool.createRepository(DefaultSVNRepositoryPool.java:213)
at
org.tmatesoft.svn.core.wc.SVNClientManager.createRepository(SVNClientManager.java:242)
at
org.tmatesoft.svn.core.wc.SVNBasicClient.createRepository(SVNBasicClient.java:231)
at
org.tmatesoft.svn.core.wc.SVNDiffClient.doDiffURLURL(SVNDiffClient.java:769)
at
org.tmatesoft.svn.core.wc.SVNDiffClient.doDiff(SVNDiffClient.java:310)
at SVNTest.main(SVNTest.java:30)
I have double checked the URLs (I can open them in TortoiseSVN client). Can anybody help me know what is going on? I have posted the code I am running below.
SVNClientManager manager = SVNClientManager.newInstance(SVNWCUtil.createDefaultOptions(false), user, pass);
SVNDiffClient diff = manager.getDiffClient();
//ISVNDiffStatusHandler diffStatus = new ISVNDiffStatusHandler();
try {
SVNURL oldURL = SVNURL.parseURIDecoded(url);
diff.doDiff(SVNURL.parseURIDecoded(url), SVNRevision.create(oldVersion), SVNURL.parseURIDecoded(url), SVNRevision.HEAD, false, false, System.out);
} catch (SVNException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
A: have you called the following static method?
DAVRepositoryFactory.setup();
This needs to be called before accessing any http:// repositories and the similar
SVNRepositoryFactoryImpl.setup();
should be used for svn:// repositories.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Last Resource Optimization I'm writing a Resource Adaptor which does not support two phase commit.
I know there is an optimization technique called: "Last Resource Optimization".
On JBoss your XAResource class should implement LastResource in order to have the optimization.
My question is: how this can be done in WebLogic, WebSpehre, Glassfish, etc...
A: Weblogic: AFAIK (may be very wrong) only JDBC drivers can be used with LRO, and it's a purely administrative task. When a driver doesn't support XA, it can be configured to be used with LRO: "Select this option if you want to enable non-XA JDBC connections from the data source to emulate participation in global transactions using JTA".
Essentially, LRO tolerates a resource that has no prepare phase, and can only be committed or rolled back. Thus, if only one such resource exist in XA-transaction, we may first attempt to prepare all others, then commit that LRO one, then, if succeed, commit others, otherwise rollback others.
You see, there is no special need in declaring any interface. It's an algorithm that can work with any non-XA resource. I'm not sure why JBoss has it, but I don't expect other servers have something similar.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there an easy way, to Port a Win32 App in Delphi 2009 to .NET? We want migrate from Delphi 7.0 to Delphi 2009, to stay up with a modern IDE and current technology. Our target platform is .NET. What is best way, to achieve this goal?
A: Remember that D2009 is a win32 version, and not .net. I suppose you want to make a two steps path, first move to D2009 and then to .net ?
Luckily, delphi is a very stable platform and it is much easier to convert old applications to latest version, but you have different thing to consider.
If your application is using BDE to access a Db then convert it to use some other technology, like ADO or DBX.
If you use 3rd party components, be sure there exist versions for D2009 and/or .NET
A very delicate aspect is string handling. If you use strings "normally" you should have no big problems, but if you use strings as "byte buffers" like you do in C then you have to be careful and try to rewrite that parts. A rule of thumb is "try to get rid of all PChar's in your code".
A: I'd take onboard the Unicode situation with string handling that came in from D2007 to D2009 - the changes involved in this step might affect your application a lot (only you can tell this). Also, you will need to consider what third party tools/libraries/components you are using. Not everything has made the jump to D2009 yet, and it's likely that some less-popular components might never make the jump at all.
One smarter path might be to migrate D7 to D2007 (which is a well-trodden path, largely painless with lots of wins and worthwhile improvements). Then you're in a modern, stable, pretty-up-to-date, supported Delphi platform from which you can better evaluate a jump to .Net.
My own opinion on this last stage would echo some of the other comments, mind you - unless there's some big win you get from .Net, I don't see why you would move away from Delphi. With the modern requirements of various runtimes and service packs, I think Delphi is becoming an increasingly viable relevant tool for Win32 development.
Either evolve the code from D7 to D2007/D2009, or just jump from D7 to .Net; to do one and then the other seems a little odd!
A: Migrating from Delphi 7 to Delphi 2009 is probably straight forward, there were only minor changes (such as the recently discussed move from ANSI to Unicode strings).
The move to .NET is not so straight forward, though. Although there's a VCL.NET which makes migrating GUIs possible, severeal other things will not work. So you might think of having Win32 code AND .NET code, bringing them together through COM.
(I hope you already know COM, otherwise this is probably not an option;-))
A: Delphi 2009 targets Win32 only.
For .NET you could use RAD Studio 2007 which comes with Delphi personality for .NET and it should be fairly easy to port a simple VCL application to VCL.NET which targets the .NET 2.0 framework. However, if you use any third-party components and libraries you have to check for their .NET alternatives, too.
If you find this would be too much work or if you want to target the latest .NET framework you might be better off rewriting your project from scratch using Microsoft's Visual Studio and C#.
Disclaimer: I have no experience in porting Delphi Win32 projects to .NET so this is just my humble opinion.
A: Porting is never easy. However the semantics between Delphi and .NET are very close, since both had Anders Hejlsberg as their lead architect. You'll most likely need to replace the Win32 VCL calls to their equivalent VCL.NET stuff.
You might want to upgrade to the CodeGear RAD Studio, as that will let you have one IDE for both Delphi and .NET languages (mainly C#).
A lot of times I was able to drop in control replacements when moving from one technology to another. For example, I was able to replace BDE database controls with their ADO.NET replacements, without really having to change code. Ultimately, you own the code and know better than any of us.
Why do you want to target the .NET framework, when you have some very good support for Win32 executables? Delphi is already a small section of the industry, and Delphi with .NET even smaller. Delphi is always going to be a second-class citizen in the .NET world. Delphi is already a first class Win32 citizen.
A: Following on Giacomo's answer above, If you are using BDE, then I can suggest MicroOlap's DAC http://www.microolap.com/ - This will save you a lot of time in not having to convert you code to something else. I am using PostgresDAC, this product is very stable and fast.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Linked Server Performance and options At work we have two servers, one is running an application a lot of people use which has an SQL Server 2000 back end. I have been free to query this for a long time but can't add anything to it such as stored procedures or extra tables.
This has lead to us having a second SQL Server linked to the first one and me building up a library of stored procedures that query data from both sides using linked server. Some of these queries are taking longer than what I would like.
Can someone point me to some good articles about using linked servers? I am particularly interested in finding out what data is being transferred between the two as usually the majority of the sql statement could be performed remotely but I have the feeling it may be transferring the full tables, it is usually just a join to a small final table locally.
Also what do the linked server options do I currently have:
*
*Collation Compatible True
*Data Access True
*Rpc True
*Rpc Out True
*Use Remote Collation False
*Collation Name (Blank)
*Connection Timeout 0
*Query Timeout 0
EDIT:
Just thought I would update this post I used openqueries with dynamic parameters for a while to boost performance, thanks for the tip. However doing this can make queries more messy as you end up dealing with strings. finally this summer we upgraded SQL Server to 2008 and implemented live data mirroring. To be honest the open queries were approaching the speed of local queries for my tasks but the mirroring has certainly made the sql easier to deal with.
A: Avoid joins to linked server tables.
Using a four part naming for your join can be used but is more expensive. Your join could contain criteria that can be used to limit the data set from the linked server and use the indexed columns.
Example:
SELECT loc.field1, lnk.field1
FROM MyTable loc
INNER JOIN RemoteServer.Database.Schema.SomeTable lnk
ON loc.id = lnk.id
AND lnk.RecordDate = GETDATE()
WHERE loc.SalesDate = GETDATE()
This query is also applying a criteria in the join that can be used by the linked server before the join is calculated.
The recommended method is the use of OPENQUERY.
By avoiding the join with the use of OPENQUERY the local server only sends the query to be executed remotely instead sending a set of IDs for the join.
Use the link to retrieve a set of data and perform the calculations locally. Either use a temporary table (for ad hoc queries) or insert the row in a permanent table in a nightly job.
Begining transactions may fail depending if the remote transaction coordinator is set in the liked server. Using it will consume more resources.
Also consider that you are hitting a production server running an application, while you do not specify it, I think is safe to assume that is using heavy transactions and doing inserts and updates. You are taking away resources away from the application.
Your purpose appears to be the use of the data for reporting purposes. Your server can be set to have a simple log instead of full making it more efficient.
You will also avoid your queries to be canceled due to data movement on the linked server. Always be mindful of setting the proper isolation level for your queries and table hints like NOLOCK.
And PLEASE! Never place an OPENQUERY (or any linked server) inside a loop!
A: Royal pain
We used to have several linked servers at our shop and it turned out to be such a PITA.
First of all, there were severe performance problems similar to what you describe. I was shocked when i saw network I/O stats. Despite all efforts, we failed to hint SQL Server into reasonable behavior.
Another problem was that stored procs had these linked server names hardcoded everywhere, with no way to override them. So developers couldn't easily test on their development sandboxes any functionality that touched linked servers. This was a major obstacle for creating a universally usable unit-test suite.
In the end we ditched linked servers completely and moved data synchronization to web-services.
A: When you use linked servers for joins like this, it is important to have the server you are immediately connected to ("local") be the one with the most of the data, where the linked server is only providing a small part of the data, otherwise, yes, it will pull as much data as it needs to perform the join.
Alternatives include copying a subset of the data across to a temporary table with as much work done to slim down the results and any pre-processing that the linked server can perform, and then do the join on the "local" side.
You may find you can easily boost performance by reversing the way you do it, connecting to the server you have no control over (they'll need to make a linked server for you) and then connecting to your server over the link. If you need to do major work with the data where you would have to create sprocs - then push the data onto your server and use your sprocs there.
In some cases, I simply had the linked server perform a nightly creation of this kind of summary which it pushed to the local server, and then the local server performed its work with the join.
A: Queries involving semi-joins across a linked server tend not to be very efficient. You might be better off using OPENQUERY to populate data into a local temporary table and then work on it from there.
A: I wrote a remote Linked Server application in SQL 2000 a couple of years ago and came across the same performance issues you describe. I ended up rewriting my stored procedures several times in order to obtain the best performance.
I used temporary tables extensively. I found that it was less expensive to retrieve large amounts of remote data into a temp table, then join to it, manipulate it, etc. Joining local to remote tables was very slow as you desribe.
Display Execution Plan and Display Estimated Execution Plan tended to help although I did not understand a lot of what I was looking at.
I don't know if there really is a efficient way to do these queries with a remote server because it seems like SQL Server cannot take advantage of its normal optimizations when going against a Linked Server. It may feel like you are transferring the entire table because in fact that is what is happening.
I am wondering if a replication scenario might work for you. By having the data on your local server, you should be able to write normal queries that will perform as desired.
I do not know of any good articles to point you towards. As I write more complicated SQL Server applications, I started to think that I needed a better understanding of how SQL Server worked underneath. To that end we bought the MS Press Inside Microsoft SQL Server 2005 series edited by Kalen Delaney here at work. Volume 1: The Storage Engine is definitely the place to start but I have not gotten that far into it. Since my last few projects have not involved SQL Server, my study of it has gotten lax.
A: Is there a possibility that you could set up a separate database on the server rather than using a linked server?
A: I would advise dynamic openqueries in a cursor loop instead of linked joins.
This is the only way i've been able to replicate MS Access' linked join performance (at least for single remote tables)
Regular linked joins in ms sql are too inefficient by pulling everything specially in humongous tables..
-- I would like to know what is so bad about openqueries inside cursor loops? if done correctly, there are no locking issues.
A: Its a very generous problem, which may have many solutions. But as we have witnessed so many user saying that they have tried everything.
What solved my problem is..
I upgraded sql server 2000 from sp2 to SP4 and if you already have sp4 on sql server 2000 then run Instcat.sql. As per my experience I can assure you this will work for sure, if you are exhausted with all the other workarounds.
Thanks,
Mithalesh
mithalesh.gupta@gmail.com
A: Dynamic SQL and a function can be used to get around the hard-coded name question. For instance, I'm trying an implementation where function ufn_linkedDatabase(@purpose nvarchar(255)) with input 'cpi.cpi' (purpose CPI, sub-purpose default) returns
'[SERVER-NAME.DOMAIN.LCL,2000].[CPI]' in the production environment (where we use alternate port number for SQL Server, I don't know why, including in linked server name). Then a SQL command is assembled in @template varchar(max) with the expression @{cpi.cpi} representing the linked server and database, and then
@workstring = REPLACE(@template, N'@{cpi.cpi}', ...) . How the function actually gets the database name is separate from the procedures - a lookup table is nice.
Issues - to do OPENQUERY(), which is probably still better at least unless the linked server option "collation compatible" is set "true" so that more of the task can be executed on the linked server - important even on a fast network, and our server room internal network is respectably fast - to do OPENQUERY() I probably need to handle 'cpi.cpi.server' and 'cpi.cpi.database' and 'cpi.cpi.server.database' separately. And, I may end up writing exactly one application using this design, in which case it's over-designed. Still, that means that the function itself doesn't have to be any kind of fancy work.
Throwing fast network hardware at the problem may be the cheaper answer, anyway.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: How do I correct the character encoding of a file? I have an ANSI encoded text file that should not have been encoded as ANSI as there were accented
characters that ANSI does not support. I would rather work with UTF-8.
Can the data be decoded correctly or is it lost in transcoding?
What tools could I use?
Here is a sample of what I have:
ç é
I can tell from context (café should be café) that these should be these two characters:
ç é
A: When you see character sequences like ç and é, it's usually an indication that a UTF-8 file has been opened by a program that reads it in as ANSI (or similar). Unicode characters such as these:
U+00C2 Latin capital letter A with circumflex
U+00C3 Latin capital letter A with tilde
U+0082 Break permitted here
U+0083 No break here
tend to show up in ANSI text because of the variable-byte strategy that UTF-8 uses. This strategy is explained very well here.
The advantage for you is that the appearance of these odd characters makes it relatively easy to find, and thus replace, instances of incorrect conversion.
I believe that, since ANSI always uses 1 byte per character, you can handle this situation with a simple search-and-replace operation. Or more conveniently, with a program that includes a table mapping between the offending sequences and the desired characters, like these:
“ -> “ # should be an opening double curly quote
â€? -> ” # should be a closing double curly quote
Any given text, assuming it's in English, will have a relatively small number of different types of substitutions.
Hope that helps.
A: Use iconv - see Best way to convert text files between character sets?
A: Follow these steps with Notepad++
1- Copy the original text
2- In Notepad++, open new file, change Encoding -> pick an encoding you think the original text follows. Try as well the encoding "ANSI" as sometimes Unicode files are read as ANSI by certain programs
3- Paste
4- Then to convert to Unicode by going again over the same menu: Encoding -> "Encode in UTF-8" (Not "Convert to UTF-8") and hopefully it will become readable
The above steps apply for most languages. You just need to guess the original encoding before pasting in notepad++, then convert through the same menu to an alternate Unicode-based encoding to see if things become readable.
Most languages exist in 2 forms of encoding: 1- The old legacy ANSI (ASCII) form, only 8 bits, was used initially by most computers. 8 bits only allowed 256 possibilities, 128 of them where the regular latin and control characters, the final 128 bits were read differently depending on the PC language settings 2- The new Unicode standard (up to 32 bit) give a unique code for each character in all currently known languages and plenty more to come. if a file is unicode it should be understood on any PC with the language's font installed. Note that even UTF-8 goes up to 32 bit and is just as broad as UTF-16 and UTF-32 only it tries to stay 8 bits with latin characters just to save up disk space
A: EDIT: A simple possibility to eliminate before getting into more complicated solutions: have you tried setting the character set to utf8 in the text editor in which you're reading the file? This could just be a case of somebody sending you a utf8 file that you're reading in an editor set to say cp1252.
Just taking the two examples, this is a case of utf8 being read through the lens of a single-byte encoding, likely one of iso-8859-1, iso-8859-15, or cp1252. If you can post examples of other problem characters, it should be possible to narrow that down more.
As visual inspection of the characters can be misleading, you'll also need to look at the underlying bytes: the § you see on screen might be either 0xa7 or 0xc2a7, and that will determine the kind of character set conversion you have to do.
Can you assume that all of your data has been distorted in exactly the same way - that it's come from the same source and gone through the same sequence of transformations, so that for example there isn't a single é in your text, it's always ç? If so, the problem can be solved with a sequence of character set conversions. If you can be more specific about the environment you're in and the database you're using, somebody here can probably tell you how to perform the appropriate conversion.
Otherwise, if the problem characters are only occurring in some places in your data, you'll have to take it instance by instance, based on assumptions along the lines of "no author intended to put ç in their text, so whenever you see it, replace by ç". The latter option is more risky, firstly because those assumptions about the intentions of the authors might be wrong, secondly because you'll have to spot every problem character yourself, which might be impossible if there's too much text to visually inspect or if it's written in a language or writing system that's foreign to you.
A: In sublime text editor, file -> reopen with encoding -> choose the correct encoding.
Generally, the encoding is auto-detected, but if not, you can use the above method.
A: With vim from command line:
vim -c "set encoding=utf8" -c "set fileencoding=utf8" -c "wq" filename
A: If you see question marks in the file or if the accents are already lost, going back to utf8 will not help your cause. e.g. if café became cafe - changing encoding alone will not help (and you'll need original data).
Can you paste some text here, that'll help us answer for sure.
A: I found a simple way to auto-detect file encodings - change the file to a text file (on a mac rename the file extension to .txt) and drag it to a Mozilla Firefox window (or File -> Open). Firefox will detect the encoding - you can see what it came up with under View -> Character Encoding.
I changed my file's encoding using TextMate once I knew the correct encoding. File -> Reopen using encoding and choose your encoding. Then File -> Save As and change the encoding to UTF-8 and line endings to LF (or whatever you want)
A: I found this question when searching for a solution to a code page issue i had with Chinese characters, but in the end my problem was just an issue with Windows not displaying them correctly in the UI.
In case anyone else has that same issue, you can fix it simply by changing the local in windows to China and then back again.
I found the solution here:
http://answers.microsoft.com/en-us/windows/forum/windows_7-desktop/how-can-i-get-chinesejapanese-characters-to/fdb1f1da-b868-40d1-a4a4-7acadff4aafa?page=2&auth=1
Also upvoted Gabriel's answer as looking at the data in notepad++ was what tipped me off about windows.
A: And then there is the somewhat older recode program.
A: There are programs that try to detect the encoding of an file like chardet. Then you could convert it to a different encoding using iconv. But that requires that the original text is still intact and no information is lost (for example by removing accents or whole accented letters).
A: On OS X Synalyze It! lets you display parts of your file in different encodings (all which are supported by the ICU library). Once you know what's the source encoding you can copy the whole file (bytes) via clipboard and insert into a new document where the target encoding (UTF-8 or whatever you like) is selected.
Very helpful when working with UTF-8 or other Unicode representations is UnicodeChecker
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "61"
}
|
Q: Storing objects for locating by x,y coordinates I'm trying to determine a fast way of storing a set of objects, each of which have an x and y coordinate value, such that I can quickly retrieve all objects within a certain rectangle or circle.
For small sets of objects (~100) the naive approach of simply storing them in a list, and iterating through it, is relatively quick. However, for much larger groups, that is expectedly slow.
I've tried storing them in a pair of TreeMaps as well, one sorted on the x coordinate, and one sorted on the y coordinate, using this code:
xSubset = objectsByX.subSet( minX, maxX );
ySubset = objectsByY.subSet( minY, maxY );
result.addAll( xSubset );
result.retainAll( ySubset );
This also works, and is faster for larger sets of objects, but is still slower than I would like.
Part of the problem is also that these objects move around, and need to be inserted back into this storage, which means removing them from and re-adding them to the trees/lists.
I can't help but think there must be better solutions out there.
I'm implementing this in Java, if it makes any difference, though I expect any solution will be more in the form of a useful pattern/algorithm.
A: The general term is a Spatial Index. I guess you should choose according to the existing implementations.
A: A quadtree is the structure which is usually used for that.
A: Quadtrees seem to solve the specific problem I asked. Kd-Trees are a more general form, for any number of dimensions, rather than just two.
R-Trees may also be useful if the objects being stored have a bounding rectangle, rather than being just a simple point.
The general term for these type of structures is Spatial Index.
There is a Java implementation of Quadtree and R-Tree.
A: Have a look at Kd-Trees.
A: Simple QuadTree implementation in C# (easy to translate into java)
http://www.codeproject.com/KB/recipes/QuadTree.aspx
A: You could put all the x cords in a map, and the y cords in another map, and have the map values point to the object.
TreeMap<Integer, TreeMap<Integer, Point>> xMap = new TreeMap<Integer, TreeMap<Integer, Point>>();
for (int x = 1; x < 100; x += 2)
for (int y = 0; y < 100; y += 2)
{
Point p = new Point(x, y);
TreeMap<Integer, Point> tempx = xMap.get(x);
if (tempx == null)
{
tempx = new TreeMap<Integer, Point>();
xMap.put(x, tempx);
}
tempx.put(y, p);
}
SortedMap<Integer, TreeMap<Integer, Point>> tempq = xMap.subMap(5, 8);
Collection<Point> result = new HashSet<Point>();
for (TreeMap<Integer, Point> smaller : tempq.values())
{
SortedMap<Integer, Point> smallerYet = smaller.subMap(6, 12);
result.addAll(smallerYet.values());
}
for (Point q : result)
{
System.out.println(q);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Obtain an index into a vector using Iterators When iterating over elements of a vector it is preferred to use iterators instead of an index (see Why use iterators instead of array indices?).
std::vector<T> vec;
std::vector<T>::iterator it;
for ( it = vec.begin(); it != vec.end(); ++it )
{
// do work
}
However, it can be necessary to use the index in the body of the loop. Which of the following would be preferable in that case, considering performance and flexibility/extensibility?
*
*Revert to the indexed loop
std::vector vec;
size_t i;
for ( i = 0; i < vec.size(); ++i )
{
// use i
}
*Calculate offset
std::vector vec;
std::vector::iterator it;
for ( it = vec.begin(); it != vec.end(); ++it )
{
size_t i = it - vec.begin();
// use i
}
*Use std::distance
std::vector vec;
std::vector::iterator it;
for ( it = vec.begin(); it != vec.end(); ++it )
{
size_t i = std::distance( vec.begin(), it );
// use i
}
A: Using std::distance is a bit more generic since it works for all iterators, not just random access iterators. And it should be just as fast as It - vec.begin() in case of random access iterators.
It - vec.begin() is basically pointer arithmetic.
A: std::distance(vec.begin(), it) will give you the index it is pointing at, assuming it points into vec.
Carl
A: Revert to the indexed loop.
Basically in 90% of the cases, iterators are superior, this is one of those 10%. By using a iterator you are making the code more complex and therefore harder to understand, when the entire reason for using the iterator in the first place was to simplify your code.
A: If you're planning on using exclusively a vector, you may want to switch back to the indexed loop, since it conveys your intent more clearly than iterator-loop. However, if evolution of your program in the future may lead to a change of container, you should stick to the iterators and use std::distance, which is guaranteed to work with all standard iterators.
A: You're missing one solution: keep an index in case you need it, but don't use it as a loop condition. Works on lists too, and the costs (per loop) are O(n) and an extra register.
A: I would always tend towards keeping with iterators for future development reasons.
In the above example, if you perhaps decided to swap out std::vector for std::set (maybe you needed a unique collection of elements), using iterators and distance() would continue to work.
I pretty sure that any performance issues would be optimized to the point of it being negligible.
A: For vectors, I always use the integer method. Each index into the vector is the same speed as an array lookup. If I'm going to be using the value a lot, I create a reference to it, for convenience.
vector iterators can be slightly faster than an index in theory, since they're using pointer arithmetic to iterate through the list. However, usually I find that the readability is worth the minimal runtime difference.
I use iterators for other container types, and sometimes when you don't need the loop variable. But if you need the loop variable, you're not doing anything except making your loop harder to type. (I cannot wait for c++0x's auto..)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: With Apache HttpClient, why isn't my connection timeout working? My implementation of httpclient occasionally throws an exception when calling doGetConnection(). However, I have the following timeout set
_moHttpClient.setHttpConnectionFactoryTimeout(30000);
it looks almost like my timeout is not being picked up. Is there anywhere else I need to set a timeout to ensure this behaviour does not re-occur
A: HttpConnectionManagerParams cmparams = new HttpConnectionManagerParams();
cmparams.setSoTimeout(10000);
cmparams.setTcpNoDelay(true);
HttpConnectionManager manager = new SimpleHttpConnectionManager();
manager.setParams(cmparams);
params = new HttpClientParams();
params.setSoTimeout(5000);
client = new HttpClient(params, manager);
I wonder why I have two different SoTimeouts set. Maybe I was trying to find out which one was actually active, as I had the same problems as you when I used it.
The above is in live code at our place right now, but I cannot say whether it works because it's correct, or because providence is smiling down on me (and the other end is usually always available).
A:
cmparams.setSoTimeout(10000);
This one is for all HttpClient by default.
params.setSoTimeout(5000);
And this one is for a particular httpclient.
A: What exception are you getting thrown ?
Don't forget you have two timeouts to change/check. From HttpConnectionParams
setConnectionTimeout()
setSoTimeout()
so you can control how long you wait for a connection to the server, and how long operations on the socket can take before timing out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Full text search engine example in F#? Are there any good examples (websites or books) around of how to build a full text search engine in F#?
A: Do you want to write this yourself? Or do you simply need the functionality?
If you need the functionality, an embedded/in-memory database with Full Text Search support may do the trick. Since it's .Net, I'd recommend SQLite ADO.Net Provider as the open-source contender. It's really good ( Support LINQ before any other provider out there, design-time support, etc.), and the FTS support is under very active development. I think Google is working on that. There is also VistaDB Database. I'm using that mainly now. It should have FTS support. Entirely .Net, which gives it some integration advantages.
If you have to do it yourself check-out books on Information Retrieval. I've read a few, but know nothing that stands out from the crowd. Amazon might help there.
A: I have written a search engine in F# using just a few lines
of code. You can read about that in my poster
and access the full implementation in
Stefan Savev's home page
The basic idea is shown in the code below, but more explanations are actually needed than the code itself. Those are available at my website as well.
This code creates the index on disk of a collection of documents.
Indexing is done in external memory.
1. let create_postings in_name tmp_dir out_name =
2. let process_doc (doc_id, doc_text) =
3. doc_text |> tokenize |> stopword |> stem
4a. |> List.count
4b. |> ListExt.map(fun (word, tf) -> (word, (doc_id, tf))
5. in_name
6. |> as_lines
7. |> Seq.map_concat extract_docs
8. |> Seq.map_concat process_doc
9a. |> External.group_by (fun (w, _) -> w)
9b. (fun (_, docid_and_tf) -> docid_and_tf)
9c. (fun lst -> (List.length lst, lst))
9d. tmp_dir
9e. (External.ElemDesc())
10. |> output out_name
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: maximum size for xml files whats your rule of thumb for maximum size for xml files.
What if I ask maximum no of records, and one record have 10 values for instance? Another condition is we are loading it from web.
A: This may be not the thing you want to hear, but... If you're thinking about the size of your XML files, chances are you should use a database instead of files (even if they are not flat files but structured like XML). Databases are highly optimized for efficient storage of huge masses of data. The best algorithms for retrieving data are in the code base of databases.
A: There isn't any. There are maximum sizes for files that depend on the file system you are using, though.
A: My rule is that if it's too slow to do what I want, then it's too big, and your data probably needs to be moved to some other format... database or such.
Traversing XML nodes or using XPath can be a dog.
A: There is no limit of XML file size but it takes memory (RAM) as file size of XML file, so long XML file parsing size is performance hit.
It is advised to long XML size using SAX for .NET to parse long XML documents.
A: I don't think you should have a rule of thumb for maximum size for data, be it XML or anything else. If you need to store multiple gigabytes of data, then you store that data. What makes a difference is what API you use to process that data. However, XML may not be your best bet if your data set is very large. In those cases a relational or XML database will probably work better than a single XML file.
A: I think it depends on the context, where the file comes from/is generated from, what you are going to do with it, the bandwidth of any connection it has to pass through, system RAM size etc?
what is your context?
A: Even though not all parsers read the whole file into memory, if you really need a rule of thumb I would say not bigger than half of your available ram. Anything bigger will likely be way too slow :)
A: I worked on a project in 2010 where by i had to move a newspaper website from Typo 3 to Drupal 7 and the fastest way around at the time was to export all the content as xml and then parse them into drupal(Xpath). We tried doing it in one go but we had problems at 4Gigs .. So we divided the xmls per year and had each file have less time to parse and the file size in MBs and that went fine. Other reads suggest that the max file may depend on your ram.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Testing form inputs in PHPUnit What's the best way to test $_GET and $_POST inputs in PHPUnit?
I have a class that sanitises input and want to check that it works correctly when processing bogus data. Is there an easy way to set up the form variables in PHPUnit or should I just pass off the validation to a secondary class/functions that are fed the form variables so test them indirectly?
A: Take a look at the idea of Dependency injection. In a nutshell you should feed your code what it needs as opposed to it getting the data it needs... Here's an example:
example without Dependency Injection
function sanitize1() {
foreach($_POST as $k => $v) {
// code to sanitize $v
}
}
sanitize1();
example with Dependency Injection
function sanitize2(array &$formData) {
foreach($formData as $k => $v) {
// code to sanitize $v
}
}
sanitize2($_POST);
See the difference? In your PHPUnit test you can pass sanitize2() an associative array of your choice; you've injected the dependency. Whereas sanitize1() is coupled with $_POST. $_POST and $_GET are assoc arrays anyways so in your production code you can pass $_GET or $_POST to your function but in your unit tests you'd hard code some expected data.
Unit test example:
function testSanitize() {
$fakeFormData = array ('bio' => 'hi i\'m arin', 'location' => 'San Francisco');
sanitize($fakeFormData);
// assert something
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Double generic constraint on class in Java: extends ConcreteClass & I Is there a way to define a generic constraint in Java which would be analogous to the following C# generic constratint ?
class Class1<I,T> where I : Interface1, Class2 : I
I'm trying to do it like this:
class Class1<I extends Interface1, T extends I & Class2>
But the compiler complains about the "Class2" part: Type parameter cannot be followed by other bounds.
A: This code compiles here fine:
interface Interface1 {}
class Class2 {}
class Class1<I extends Interface1, T extends Class2 & Interface1> {}
Why do you need the I type there when you assume only Interface1 anyway? (you won't know anything more in your class about I than it extends Interface1)
A: The simplest way I can see of resolving the Java code is to make Class2 an interface.
You cannot constrain a type parameter to extends more than one class or type parameter. Further, you can't use super here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: How to read file content into istringstream? In order to improve performance reading from a file, I'm trying to read the entire content of a big (several MB) file into memory and then use a istringstream to access the information.
My question is, which is the best way to read this information and "import it" into the string stream? A problem with this approach (see bellow) is that when creating the string stream the buffers gets copied, and memory usage doubles.
#include <fstream>
#include <sstream>
using namespace std;
int main() {
ifstream is;
is.open (sFilename.c_str(), ios::binary );
// get length of file:
is.seekg (0, std::ios::end);
long length = is.tellg();
is.seekg (0, std::ios::beg);
// allocate memory:
char *buffer = new char [length];
// read data as a block:
is.read (buffer,length);
// create string stream of memory contents
// NOTE: this ends up copying the buffer!!!
istringstream iss( string( buffer ) );
// delete temporary buffer
delete [] buffer;
// close filestream
is.close();
/* ==================================
* Use iss to access data
*/
}
A: std::ifstream has a method rdbuf(), that returns a pointer to a filebuf. You can then "push" this filebuf into your stringstream:
#include <fstream>
#include <sstream>
int main()
{
std::ifstream file( "myFile" );
if ( file )
{
std::stringstream buffer;
buffer << file.rdbuf();
file.close();
// operations on the buffer...
}
}
EDIT: As Martin York remarks in the comments, this might not be the fastest solution since the stringstream's operator<< will read the filebuf character by character. You might want to check his answer, where he uses the ifstream's read method as you used to do, and then set the stringstream buffer to point to the previously allocated memory.
A: OK. I am not saying this will be quicker than reading from the file
But this is a method where you create the buffer once and after the data is read into the buffer use it directly as the source for stringstream.
N.B.It is worth mentioning that the std::ifstream is buffered. It reads data from the file in (relatively large) chunks. Stream operations are performed against the buffer only returning to the file for another read when more data is needed. So before sucking all data into memory please verify that this is a bottle neck.
#include <fstream>
#include <sstream>
#include <vector>
int main()
{
std::ifstream file("Plop");
if (file)
{
/*
* Get the size of the file
*/
file.seekg(0,std::ios::end);
std::streampos length = file.tellg();
file.seekg(0,std::ios::beg);
/*
* Use a vector as the buffer.
* It is exception safe and will be tidied up correctly.
* This constructor creates a buffer of the correct length.
*
* Then read the whole file into the buffer.
*/
std::vector<char> buffer(length);
file.read(&buffer[0],length);
/*
* Create your string stream.
* Get the stringbuffer from the stream and set the vector as it source.
*/
std::stringstream localStream;
localStream.rdbuf()->pubsetbuf(&buffer[0],length);
/*
* Note the buffer is NOT copied, if it goes out of scope
* the stream will be reading from released memory.
*/
}
}
A: This seems like premature optimization to me. How much work is being done in the processing. Assuming a modernish desktop/server, and not an embedded system, copying a few MB of data during intialization is fairly cheap, especially compared to reading the file off of disk in the first place. I would stick with what you have, measure the system when it is complete, and the decide if the potential performance gains would be worth it. Of course if memory is tight, this is in an inner loop, or a program that gets called often (like once a second), that changes the balance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "43"
}
|
Q: How can Google be so fast? What are the technologies and programming decisions that make Google able to serve a query so fast?
Every time I search something (one of the several times per day) it always amazes me how they serve the results in near or less than 1 second time. What sort of configuration and algorithms could they have in place that accomplishes this?
Side note: It is kind of overwhelming thinking that even if I was to put a desktop application and use it on my machine probably would not be half as fast as Google. Keep on learning I say.
Here are some of the great answers and pointers provided:
*
*Google Platform
*Map Reduce
*Algorithms carefully crafted
*Hardware - cluster farms and massive number of cheap computers
*Caching and Load Balancing
*Google File System
A: Here are some of the great answers and pointers provided:
*
*Google Platform
*Map Reduce
*Algorithms carefully crafted
*Hardware - cluster farms and massive number of cheap computers
*Caching and Load Balancing
*Google File System
A: Latency is killed by disk accesses. Hence it's reasonable to believe that all data used to answer queries is kept in memory. This implies thousands of servers, each replicating one of many shards. Therefore the critical path for search is unlikely to hit any of their flagship distributed systems technologies GFS, MapReduce or BigTable. These will be used to process crawler results, crudely.
The handy thing about search is that there's no need to have either strongly consistent results or completely up-to-date data, so Google are not prevented from responding to a query because a more up-to-date search result has become available.
So a possible architecture is quite simple: front end servers process the query, normalising it (possibly by stripping out stop words etc.) then distributing it to whatever subset of replicas owns that part of the query space (an alternative architecture is to split the data up by web pages, so that one of every replica set needs to be contacted for every query). Many, many replicas are probably queried, and the quickest responses win. Each replica has an index mapping queries (or individual query terms) to documents which they can use to look up results in memory very quickly. If different results come back from different sources, the front-end server can rank them as it spits out the html.
Note that this is probably a long way different from what Google actually do - they will have engineered the life out of this system so there may be more caches in strange areas, weird indexes and some kind of funky load-balancing scheme amongst other possible differences.
A: They have implemented good, distributed, algorithms running on a vast amount of hardware.
A: One of the most important delays is webservers is getting your query to the webserver, and the response back. THis latency is bound by the speed of light, which even Google has to obey. However, they have datacenters all over the world. As a result, the average distance to any one of them is lower. This keeps the latency down. Sure, the difference is measured in milliseconds, but it matters if the response has to arrive within 1000 milliseconds.
A: Everyone knows it's because they use pigeons, of course!
Oh yeah, that and Mapreduce.
A: They pretty much have a local copy of the internet cached on thousands of PC's on custom filesystems.
A: Google hires the best of the best. Some of the smartest people in IT work at google. They have virtually infinite money to throw at hardware and engineers.
They use highly optimized storage mechanisms for the tasks that they are performing.
They have geographically located server farms.
A: An attempt at a generalized list (that does not depend on you having access to Google's internal tools):
*
*Parellelize requests (e.g. break up a single request in to smaller sets)
*Async (make as much asynchronious as possible, e.g. won't block the user's request)
*Memory/cache (Disk I/O is slow, keep as much as possible in memory)
*Pre-compute (Do as much work as possible before hand, don't wait for a user to ask for data/processing)
*Care about your front-end HTML (see Yslow and friends)
A: It's a bit too much to put it in one answer.
http://en.wikipedia.org/wiki/Google_platform
A: One fact that I've aways found funny is that Google is in fact run by bioinformatics (’kay, I find that funny because I'm a bioinf…thingy). Let me explain.
Bioinformatics early on had the challenge to search small texts in gigantic strings very fast. For us, the “gigantic string” is of course DNA. Often not a single DNA but a database of several DNAs from different species/individuals. The small texts are proteins or their genetic counterpart, a gene. Most of the first work of computational biologists was restricted to find homologies between genes. This is done to establish the function of newly found genes by noting similarities to genes that are already known.
Now, these DNA strings get very big indeed and (lossy!) search has to be done extremely efficiently. Most of the modern theory of string lookup was thus developed in the context of computational biology.
However, quite some time ago, conventional text search was exhausted. A new approach was needed that allowed searching large strings in sublinear time, that is, without looking at each single character. It was discovered that this can be solved by pre-processing the large string and building a special index data structure over it. Many different such data structures have been proposed. Each have their strengths and weaknesses but there's one that is especially remarkable because it allows a lookup in constant time. Now, in the orders of magnitude in which Google operates this isn't strictly true anymore because load balancing across servers, preprocessing and some other sophisticated stuff has to be taken into account.
But in the essence, the so-called q-gram index allows a lookup in constant time. The only disadvantage: The data structure gets ridiculously big. Essentially, to allow for a lookup of strings with up to q characters (hence the name), it requires a table that has one field for each possible combination of q letters (that is, qS, where S is the size of the alphabet, say 36 (= 26 + 10)). Additionally, there has to be one field for each letter position in the string that was indexed (or in the case of google, for each web site).
To mitigate the sheer size, Google will probably use multiple indices (in fact, they do, to offer services like spelling correction). The topmost ones won't work on character level but on word level instead. This reduces q but it makes S infinitely bigger so they will have to use hashing and collision tables to cope with the infinite number of different words.
On the next level, these hashed words will point to other index data structures which, in turn, will hash characters pointing to websites.
Long story short, these q-gram index data structures are arguably the most central part of Google's search algorithm. Unfortunately, there are no good non-technical papers explaining how q-gram indices work. The only publication that I know that contains a description of how such an index works is … alas, my bachelor thesis.
A: You can find in the google research homepage some pointers about the research papers written by some of the google guys. You should start with the explanatio of the google file system and the map/reduce algorithm to try and understand what's going on behind the google pages.
A: This link it also very informative
Behind the scenes of a google query
A: Hardware.
Lots and lots of hardware. They use massive clusters of commodity PCs as their server farm.
A: TraumaPony is right. Tons of servers and smart architecture for load balancing/caching and voila you can run query in under 1 second. There was a lot of articles on the net describing google services architecture. I'm sure you can find them via Google :)
A: HenryR is probably correct.
Map Reduce does not play a role for the search itself, but is only used for indexing.
Check this video interview with the Map Reduce inventors.
A: An additional reason appears to be that they cheat on the TCP slow start algorithm.
http://blog.benstrong.com/2010/11/google-and-microsoft-cheat-on-slow.html
A: And algorithms that can harness that hardware power. Like mapreduce for instance.
A: If you are interested in more details about how the google cluster works, I'll suggest this open source implementation of their HDFS.
It's based on Mapreduce by google.
A: *
*Multi staged data storage, processing and retrieval
*EFFICIENT Distribution (100's of 1000's of machines) of the above tasks
*Good framework to store the raw data and the processed results
*Good framework to retrieve the results
How exactly all these are done is summarized by all the links that you have in the question summary
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "89"
}
|
Q: Invert Regex Matches How would I invert .NET regex matches? I want to extract only the matched text, e.g. I want to extract all IMG tags from an HTML file, but only the image tags.
A: That has nothing to do with inverting the Regexp. Just search for the relevant Text and put it in a group.
A: I'm with David H.: Inversion would imply you don't want the matches, but rather the text surrounding the matches, in which case the Regex method Split() would work. Here's what I mean:
static void Main(string[] args)
{
Regex re = new Regex(@"\sthe\s", RegexOptions.IgnoreCase);
string text = "this is the text that the regex will use to process the answer";
MatchCollection matches = re.Matches(text);
foreach(Match m in matches)
{
Console.Write(m);
Console.Write("\t");
}
Console.WriteLine();
string[] split = re.Split(text);
foreach (string s in split)
{
Console.Write(s);
Console.Write("\t");
}
}
A: Not sure what you mean. Are you talking about capturing groups?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to gain SSL load balancing? I have to deploy my ASP.NET application into two seperated IIS servers. My application works over HTTPS/TLS. My ASP code has to handle client SSL certificate and it means I can't use simple forward load balancers, because I will never get such certificate from nginx or Apache Load Balancer.
As I understand there is no common (open-source or free) solution for load balancing in Microsoft world and especially for SSL.
I heard about simple DNS balancing, where my domain name would be bound to several ISS servers, and every new client (session) would get IP of one server,and such way I would get simple balancing and SSL support.
Now, I am just at the begging of deployment and it is really interesting to know your opinion of such balancing, or may be to get some recommendations.
Thanks!
As for me, I can't find another solutions for HTTPS beside DNS balancing. I just have no choice.
???
A: Windows NLB is definitely your solution - it sits in the network stack on each of your IIS servers and distributes TCP requests among the member servers. NLB works with SSL traffic, since it distributes via TCP Ports, not the contents of the traffic.
You will need to install the same SSL certs on each server, but other then that, the configuration is trivial.
A: I've successfully been using keepalived on Linux. It's a simple tool that administers http://linuxvirtualserver.org load balancer in a way that you could have fail over load balancing machines and multiple servers.
A: Zen Load Balance is a free, very simple solution. http://sourceforge.net/projects/zenloadbalancer/
A: DNS based load balancing should take you a long way. Click here for an article on the subject. For an overview of load balancing in the IIS/ASP world, go here.
Windows Network Load balancing may be a solution for you, here you'll find lots of information about it.
A: We use Cisco Local Directors, and they seem to handle it fine.
I haven't played with pure software solutions for load balancing, but balance might work fine. I've only used it for purely 1:1 port forwarding.
The advantage of using a balance/LD approach over DNS balancing is that you can easily then use it to take servers out of the pool (for upgrades, deployments, debugging, etc).
A: Depending on how much money is in your budget there are plenty of solutions out there.
You can use Windows Network Load Balancing on Windows Server for no extra cost. It is reasonably simple to setup and won't get in the way of the client certificate.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: php - proc_open (or other function that works) I need to do some command lines through a browser.
What I need to do in a command-line would be:
$login
<login name>
<password>
$passwd
<old password>
<new password>
<retype new password>
So, how can I do this using the proc_open function?
Or should I use another function to do this?
Adam Wright, I've tried your example, but I just can't change users password.
do I need to do any other things in the script (besides defining $user, $userPassword and $newPassword)?
Thanks
A: You don't need to issue login to change the password for a user, just give their name to passwd. Using popen (as we don't need to read in this tiny example), something like
$pp = popen("passwd ${user}", "w");
fwrite($pp, $oldPassword . '\n');
fwrite($pp, $newPassword . '\n');
fwrite($pp, $newPassword . '\n');
pclose($pp);
If you want to read the responses, use proc_open, and just read from the stdout handle you're given.
I hope this is all well secured, and that you have a lot of sanitisation on the username.
A: http://pecl.php.net/package/PAM might be something you can use.
It has a function bool pam_chpass(string $username, string $oldpassword, string $newpassword [, string &$error ]).
But I've never used it.
A: Found this Change Linux or UNIX system password using PHP script in the internet.
A very detailed description on how to create a website where a user can change his own system password.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Passing timestamp parameters in SQLAnalyzer to debug stored procedures Hi I'm trying to debug a stored procedure through SQL Analyzer and one of the parameters is a timestamp datatype. If I wanted to pass 0x00000001410039E2 through as a parameter how would i do this? When I pass 0x00000001410039E2 I get a string truncation error and when I pass just 1410039E2 I get 0x1410039E20000000?
Edit: @Frans Yes this works but my issue is that in SQLAnalyzer when i right-click and debug when I enter the value in the value textbox I get the error message:
[Microsoft][ODBC SQL Server Driver]String data, right truncation
A: The debug input screen expects you to enter a hexadecimal value. You don't have to enter the 0x in front of this value.
Just enter 00000001410039E2 and it will work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get back the output of os.execute in Lua When I do an "os.execute" in Lua, a console quickly pops up, executes the command, then closes down. But is there some way of getting back the console output only using the standard Lua libraries?
A: If you have io.popen, then this is what I use:
function os.capture(cmd, raw)
local f = assert(io.popen(cmd, 'r'))
local s = assert(f:read('*a'))
f:close()
if raw then return s end
s = string.gsub(s, '^%s+', '')
s = string.gsub(s, '%s+$', '')
s = string.gsub(s, '[\n\r]+', ' ')
return s
end
If you don't have io.popen, then presumably popen(3) is not available on your system, and you're in deep yoghurt. But all unix/mac/windows Lua ports will have io.popen.
(The gsub business strips off leading and trailing spaces and turns newlines into spaces, which is roughly what the shell does with its $(...) syntax.)
A: I think you want this http://pgl.yoyo.org/luai/i/io.popen io.popen. But it's not always compiled in.
A: I don't know about Lua specifically but you can generally run a command as:
comd >comd.txt 2>&1
to capture the output and error to the file comd.txt, then use the languages file I/O functions to read it in.
That's how I'd do it if the language itself didn't provide for capturing stanard output and error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "52"
}
|
Q: Free alternative to RegexBuddy Are there any good alternatives that support writing regexps in different flavors and allow you to test them?
A: Here's a list of the Regex tools mentioned across the threads:
Regulator
Expresso
.NET Regular Expression Designer
Regex-Coach
larsolavtorvik online tool
Regex Pal
Regular Expression Workbench
Rubular
Reggy
RegExr
A: Expresso is way up there on my list.
A: The excellent and free Rad Software Regular Expression Designer doesn't appear in the list above but it's certainly worth a look at.
Support for different "flavours" is limited but as far as writing and testing actual regular expressions is concerned it's good and the in-built help is very useful too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
}
|
Q: JAXB 2 in an Oracle 10g Webapp I have a web application that uses JAXB 2. When deployed on an Oracle 10g Application Server, I get errors as soon as I try to marshal an XML file. It turns out that Oracle includes JAXB 1 in a jar sneakily renamed "xml.jar".
How I can force my webapp to use the version of the jaxb jars that I deployed in WEB-INF/lib over that which Oracle has forced into the classpath, ideally through configuration rather than having to mess about with classloaders in my code?
A: I assume you use the former BEA Weblogic Server?
You can add a weblogic.xml file to your WEB-INF, looking like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE weblogic-web-app PUBLIC "-//BEA Systems, Inc.//DTD Web Application 8.1//EN" "http://www.bea.com/servers/wls810/dtd/weblogic810-web-jar.dtd">
<weblogic-web-app>
<container-descriptor>
<prefer-web-inf-classes>true</prefer-web-inf-classes>
</container-descriptor>
</weblogic-web-app>
(in reply to the comment, I don't have enough reputation yet :-))
Indeed, DLL hell because it is "all or nothing". There seems to be another, more conditional way, described here. Haven't tried that one myself though...
A: If you are still using Oracle's OC4J then include their orion-application.xml in your EAR's META-INF. It should look something like...
<?xml version="1.0" encoding="UTF-8"?>
<orion-application>
<imported-shared-libraries>
<remove-inherited name="skip.this.package"/>
</imported-shared-libraries>
</orion-application>
...with the package you want skipped.
A: Use a different JVM than your Oracle instance and make sure that their libraries are not in your classpath.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Translate algorithmic C to Python I would like to translate some C code to Python code or bytecode. The C code in question is what i'd call purely algorithmic: platform independent, no I/O, just algorithms and in-memory data structures.
An example would be a regular expression library. Translation tool would process library source code and produce a functionally equivalent Python module that can be run in a sandboxed environment.
What specific approaches, tools and techniques can you recommend?
Note: Python C extension or ctypes is not an option because the environment is sandboxed.
Another note: looks like there is a C-to-Java-bytecode compiler, they even compiled libjpeg to Java. Is Java bytecode+VM too different from CPython bytecode+VM?
A: use indent(1) and ctopy(1)... for extra credit test speeds on pypy... for bonus credit use pyastra to generate assembly code.
Regardless of language you will always have to sacrifice storing outputs of various constructs and functions between run-time space (CPU) or memory-space (RAM).
Check the great language shootout if you want to see what I'm talking about either way this is too much comp sci snobbery...
Here is an example, want to use floating point math without using floating point numbers?
x * 1,000,000 = a
y * 1,000,000 = b
a {function} b = result
result / 1,000,000 = z
Don't get bogged down, get primal, use caveman math if you have to.
A: The fastest way (in terms of programmer effort, not efficiency) would probably involve using an existing compiler to compile C to something simple (for example LLVM) and either:
*
*interpret that in Python (exorbitant performance penalty)
*translate that to Python (huge performance penalty)
*translate that to Python bytecode (big performance penalty)
Translating C to Python directly is possible (and probably yields faster code than the above approaches), but you'd be essentially writing a C compiler backend, which is a huge task.
Edit, afterthought: A perhaps even more quick-and-dirty way of doing that is to take the parse tree for the C code, transform that to a Python data structure and interpret that in Python.
A: There is frankly no way to mechanically and meaningfully translate C to Python without suffering an insane performance penalty. As we all know Python isn't anywhere near C speed (with current compilers and interpreters) but worse than that is that what C is good at (bit-fiddling, integer math, tricks with blocks of memory) Python is very slow at, and what Python is good at you can't express in C directly. A direct translation would therefore be extra inefficient, to the point of absurdity.
The much, much better approach in general is indeed to keep the C the C, and wrap it in a Python extension module (using SWIG, Pyrex, Cython or writing a wrapper manually) or call the C library directly using ctypes. All the benefits (and downsides) of C for what's already C or you add later, and all the convenience (and downsides) of Python for any code in Python.
That won't satisfy your 'sandboxing' needs, but you should realize that you cannot sandbox Python particularly well anyway; it takes a lot of effort and modification of CPython, and if you forget one little hole somewhere your jail is broken. If you want to sandbox Python you should start by sandboxing the entire process, and then C extensions can get sandboxed too.
A: Write a C interpreter in pure Python? ;-)
A: Why not keeping the C code and creating a Python C module which can be imported into a running Python environment?
A: First, i'd consider wrapping the existing C library with Pythonic goodness to provide an API in the form of a python module. I'd look at swig, ctypes, pyrex, and whatever else is out there these days. The C library itself would stay there unchanged. Saves work.
But if i really had to write original Python code based on the C, there's no tool i'd use, just my brain. C allows too many funny tricks with pointers, clever things with macros, etc that i'd never trust an automated tool even if someone pointed one out to me.
I mentioned Pyrex - this is a language similar to C but also Python oriented. I haven't done much with it, but it could be easier than writing pure python, given that you're starting with C as a guide.
Converting from more constrained, tamer languages such as IDL (the data languages scientists like to use, not the other IDL) is hard, requiring manual and mental effort. C? Forget it, not until the UFO people give us their fancy software tools that are a thousand years ahead of our state of the art!
A: Any automatic translation is going to suffer for not using the power of Python. C-type procedural code would run very slowly if translated directly into Python, you would need to profile and replace whole sections with more Python-optimized code.
A: I'd personnaly use a tool to extract an uml sheme from the C code, then use it to generate python code.
From this squeleton, I's start to get rid of the uncessary C-style structures and then I'd fill the methods with python code.
I think it would be the safer and yet most efficient way.
A: You can always compile the C code, and load in the libraries using ctypes in python.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Java utility to validate string against NMTOKEN I have some application code which generates XML documents, which are then validated against an XML Schema. The schema makes use of NMTOKEN types, and occasionally, the generated XML contains string values which are illegal NMTOKENs (e.g. they contain spaces or weird punctuation). The Xerces schema validation catches it OK, of course, but I'd like to catch it earlier, in my own code, and handle it more gracefully.
I was going to write my own isValidNMTOKEN method, and check that each charcter is valid according to the schema spec, but I was hoping there was an existing utility out there that would do this for me.
Sort of like a commons-lang for XML. Nothing useful in xml.apache.org/commons, sadly.
A: org.apache.axis.types.NMToken from Apachie Axis (the webservice framework) has a static isValid(String) method and may be what you need (or may be more than you need).
NMToken in the Axis API
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I get user informations from a session id in ASP.NET? In an asp.net application, i would like to use a webservice to return the username associated with the session id passed as a parameter. We're currently using InProc session store.
Is it possible to do this ?
Edit: what i'm trying to do is get information about another session than the current one. I'm not trying to get the SessionID, i've already got it. I'm trying to get the user information associated with a given SessionID.
Thanks,
Mathieu G.
A: You could possibly create a "fake"cookie with the session ID and make a request to your web service using it, so that the web service was fooled into thinking you were part of the session, enabling you to read any info from it. Sounds like quite the hack, though :)
A: Something like:
HttpSessionState ss = HttpContext.Current.Session;
HttpContext.Current.Response.Write(ss.SessionID);
That will get the current sessionID.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is Java the best language for Mobile App Devlopment? I was wondering what are the benefits of using anything else but Java for Mobile Application Development.
A: I do think that yes, Java is the most common language for devices, with two exceptions:
*
*Windows mobile applications, that are frequently built in C++ but that will be built more on the .NET framework in the future.
*iPhone applications, that use Cocoa and Objective-C.
A: Java is the most ubiquitous and for that alone it is your best choice.
A: You have to use whatever the phone vendor(s) that you intend to support will provide. As most provide Java, but only some provide other things, if you want to support a range of handsets, you probably need to use Java for at least some of them.
Your client (be they internal or external) will need to decide what handsets to support, and you then need to base your decision on supported handsets.
It's not entirely impossible that you'll have to ship versions in different programming languages, which may make code reuse more "challenging". It all depends on your requirements. Nobody on this site can tell you what they are :)
A: It really depends on what you're trying to do.
Java, whilst ubiqutious does have speed disadvantages. Also it's not "write once, run anywhere" as it is on the desktop space, as different manufactureres, even different devices have different sub-sets of java installed each with differening inclusions of APIs.
Using native code is going to be more efficient, whilst more difficult to port. It provides a more direct representation of the devices capabilities without the sandboxing of a VMs Apis.
Alternatively, you could use a language like C which whilst isn't strictly portable, will have implemenations on many devices with minor tweaks to make, whilst retaining a lot of the speed beenifts of such a language. (OpenC on S60/Symbian), C on Palm etc.
A: It depends on what you see as the future of the the mobile space. If the iPhone turns out to be as popular as the iPod, then no, Java probably wouldn't be the best choice.
One thing to consider is that at some point there may no longer be such thing as an iPod Nano, perhaps the Touch will be the only iPod available. In that case, every single iPod out would support Apple's iPhone OS and the number of iPhone OS mobile devices would far exceed those of Java.
Five years from now perhaps "Cocoa vs. Android" will be the new Mac vs. PC. In that case, Java could be just as good as Cocoa.
A: The only reason I can think of is that you wouldn't need a Java runtime on the target device.
Palm, for instance, allows you to code in C and talk directly to the OS routines in ROM. The C code compiles directly to the machine language without needing a runtime.
A: before one can provide a speculative answer to such a trivial question there are other variables that need be answered. What kind of phone application does one want to develop.
e.g. you can use xhtml for something that does not need to connect to the phones' core features.
and when you need to connect to the phone software or hardware you have can use java,python,c++,windows mobile or the new kid on the block android.
A: Java is the best if you want to support multiple phones, however J2ME is a limited environment. If you are doing homebrew development then develop for whatever your own phone uses, for commercial development then Java is the most widespread (and there are companies that can port Java to other platforms).
A: One of the advantages of using native code is your are closer to the hardware, on a mobile phone this means you might be able to take advantage of features which are not exposed to the virtual machine upon which your Java application is running, the promise of Android is that everything is a lot more exposed that it is with a typical Java Mobile implementation
A: Best is to go to nokia, apple microsoft or google web sites or whaterver and see what developer tools and resources are available and choose the one you want to develop for all of them are very good as good mobile app developers can help increase their market share.
A: Depends on what Application you are trying to write.
If its a simple service / data provider I would use HTML and CSS via a framework like
jqTouch, jQuery Mobile, or http://www.sencha.com/ as these will run on mostsmart phones and you can package them into a binary app using something like http://www.phonegap.com/ this will allow for sliding, GPS, local file storage using HTML5
If you need to a database, motion sensing, bluetooth, game type application then you could look at
http://monotouch.net/
http://monodroid.net/
That lets you write c# .net code and deploy onto any platform do you should be covered for windows mobile, android and iPhone.
There is also http://rhomobile.com/ that lets you write applications for all mobile platforms using Ruby.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Workaround for Spring/Hibernate due to non-standard behaviour of UNIQUE constraint in MS SQL There is a UNIQUE database constraint on an index which doesn't allow more than one record having identical columns.
There is a piece of code, managed by Hibernate (v2.1.8), doing two DAO
getHibernateTemplate().save( theObject )
calls which results two records entered into the table mentioned above.
If this code is executed without transactions, it results INSERT, UPDATE, then another INSERT and another UPDATE SQL statements and works fine. Apparently, the sequence is to insert the record containing DB NULL first, and then update it with the proper data.
If this code is executed under Spring (v2.0.5) wrapped in a single Spring transaction, it results two INSERTS, followed by immediate exception due to UNIQUE constraint mentioned above.
This problem only manifests itself on MS SQL due to its incompatibility with ANSI SQL. It works fine on MySQL and Oracle. Unfortunately, our solution is cross-platform and must support all databases.
Having this stack of technologies, what would be your preferred workaround for given problem?
A: You could try flushing the hibernate session in between the two saves. This may force Hibernate to perform the first update before the second insert.
Also, when you say that hibernate is inserting NULL with the insert, do you mean every column is NULL, or just the ID column?
A: I have no experience in Hibernate, so I don't know if you are free to change the DB at your will or if Hibernate requires a specific DB structure you cannot change.
If you can make changes then you can use this workaround in MSSQL tu emulate the ANSI behaviour :
drop the unique index/constraint
define a calc field like this:
alter table MyTable Add MyCalcField as
case when MyUniqueField is NULL
then cast(Myprimarykey as MyUniqueFieldType)
else MyUniqueField end
add the unique constraint on this new field you created.
Naturally this applies if MyUniqueField is not the primary key! :)
You can find more details in this article at databasejournal.com
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Direct casting vs 'as' operator? Consider the following code:
void Handler(object o, EventArgs e)
{
// I swear o is a string
string s = (string)o; // 1
//-OR-
string s = o as string; // 2
// -OR-
string s = o.ToString(); // 3
}
What is the difference between the three types of casting (okay, the 3rd one is not a casting, but you get the intent). Which one should be preferred?
A: string s = (string)o; // 1
Throws InvalidCastException if o is not a string. Otherwise, assigns o to s, even if o is null.
string s = o as string; // 2
Assigns null to s if o is not a string or if o is null. For this reason, you cannot use it with value types (the operator could never return null in that case). Otherwise, assigns o to s.
string s = o.ToString(); // 3
Causes a NullReferenceException if o is null. Assigns whatever o.ToString() returns to s, no matter what type o is.
Use 1 for most conversions - it's simple and straightforward. I tend to almost never use 2 since if something is not the right type, I usually expect an exception to occur. I have only seen a need for this return-null type of functionality with badly designed libraries which use error codes (e.g. return null = error, instead of using exceptions).
3 is not a cast and is just a method invocation. Use it for when you need the string representation of a non-string object.
A: The as keyword is good in asp.net when you use the FindControl method.
Hyperlink link = this.FindControl("linkid") as Hyperlink;
if (link != null)
{
...
}
This means you can operate on the typed variable rather then having to then cast it from object like you would with a direct cast:
object linkObj = this.FindControl("linkid");
if (link != null)
{
Hyperlink link = (Hyperlink)linkObj;
}
It's not a huge thing, but it saves lines of code and variable assignment, plus it's more readable
A: According to experiments run on this page: http://www.dotnetguru2.org/sebastienros/index.php/2006/02/24/cast_vs_as
(this page is having some "illegal referrer" errors show up sometimes, so just refresh if it does)
Conclusion is, the "as" operator is normally faster than a cast. Sometimes by many times faster, sometimes just barely faster.
I peronsonally thing "as" is also more readable.
So, since it is both faster and "safer" (wont throw exception), and possibly easier to read, I recommend using "as" all the time.
A: 2 is useful for casting to a derived type.
Suppose a is an Animal:
b = a as Badger;
c = a as Cow;
if (b != null)
b.EatSnails();
else if (c != null)
c.EatGrass();
will get a fed with a minimum of casts.
A: "(string)o" will result in an InvalidCastException as there's no direct cast.
"o as string" will result in s being a null reference, rather than an exception being thrown.
"o.ToString()" isn't a cast of any sort per-se, it's a method that's implemented by object, and thus in one way or another, by every class in .net that "does something" with the instance of the class it's called on and returns a string.
Don't forget that for converting to string, there's also Convert.ToString(someType instanceOfThatType) where someType is one of a set of types, essentially the frameworks base types.
A: It seems the two of them are conceptually different.
Direct Casting
Types don't have to be strictly related. It comes in all types of flavors.
*
*Custom implicit/explicit casting: Usually a new object is created.
*Value Type Implicit: Copy without losing information.
*Value Type Explicit: Copy and information might be lost.
*IS-A relationship: Change reference type, otherwise throws exception.
*Same type: 'Casting is redundant'.
It feels like the object is going to be converted into something else.
AS operator
Types have a direct relationship. As in:
*
*Reference Types: IS-A relationship Objects are always the same, just the reference changes.
*Value Types: Copy boxing and nullable types.
It feels like the you are going to handle the object in a different way.
Samples and IL
class TypeA
{
public int value;
}
class TypeB
{
public int number;
public static explicit operator TypeB(TypeA v)
{
return new TypeB() { number = v.value };
}
}
class TypeC : TypeB { }
interface IFoo { }
class TypeD : TypeA, IFoo { }
void Run()
{
TypeA customTypeA = new TypeD() { value = 10 };
long longValue = long.MaxValue;
int intValue = int.MaxValue;
// Casting
TypeB typeB = (TypeB)customTypeA; // custom explicit casting -- IL: call class ConsoleApp1.Program/TypeB ConsoleApp1.Program/TypeB::op_Explicit(class ConsoleApp1.Program/TypeA)
IFoo foo = (IFoo)customTypeA; // is-a reference -- IL: castclass ConsoleApp1.Program/IFoo
int loseValue = (int)longValue; // explicit -- IL: conv.i4
long dontLose = intValue; // implict -- IL: conv.i8
// AS
int? wraps = intValue as int?; // nullable wrapper -- IL: call instance void valuetype [System.Runtime]System.Nullable`1<int32>::.ctor(!0)
object o1 = intValue as object; // box -- IL: box [System.Runtime]System.Int32
TypeD d1 = customTypeA as TypeD; // reference conversion -- IL: isinst ConsoleApp1.Program/TypeD
IFoo f1 = customTypeA as IFoo; // reference conversion -- IL: isinst ConsoleApp1.Program/IFoo
//TypeC d = customTypeA as TypeC; // wouldn't compile
}
A: *
*string s = (string)o; Use when something should
definitely be the other thing.
*string s = o as string; Use when something might be the other
thing.
*string s = o.ToString(); Use when you don't care what
it is but you just want to use the
available string representation.
A: string s = o as string; // 2
Is prefered, as it avoids the performance penalty of double casting.
A: All given answers are good, if i might add something:
To directly use string's methods and properties (e.g. ToLower) you can't write:
(string)o.ToLower(); // won't compile
you can only write:
((string)o).ToLower();
but you could write instead:
(o as string).ToLower();
The as option is more readable (at least to my opinion).
A: It really depends on whether you know if o is a string and what you want to do with it. If your comment means that o really really is a string, I'd prefer the straight (string)o cast - it's unlikely to fail.
The biggest advantage of using the straight cast is that when it fails, you get an InvalidCastException, which tells you pretty much what went wrong.
With the as operator, if o isn't a string, s is set to null, which is handy if you're unsure and want to test s:
string s = o as string;
if ( s == null )
{
// well that's not good!
gotoPlanB();
}
However, if you don't perform that test, you'll use s later and have a NullReferenceException thrown. These tend to be more common and a lot harder to track down once they happens out in the wild, as nearly every line dereferences a variable and may throw one. On the other hand, if you're trying to cast to a value type (any primitive, or structs such as DateTime), you have to use the straight cast - the as won't work.
In the special case of converting to a string, every object has a ToString, so your third method may be okay if o isn't null and you think the ToString method might do what you want.
A: I would like to attract attention to the following specifics of the as operator:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/as
Note that the as operator performs only reference conversions,
nullable conversions, and boxing conversions. The as operator can't
perform other conversions, such as user-defined conversions, which
should instead be performed by using cast expressions.
A: Use direct cast string s = (string) o; if in the logical context of your app string is the only valid type. With this approach, you will get InvalidCastException and implement the principle of Fail-fast. Your logic will be protected from passing the invalid type further or get NullReferenceException if used as operator.
If the logic expects several different types cast string s = o as string; and check it on null or use is operator.
New cool feature have appeared in C# 7.0 to simplify cast and check is a Pattern matching:
if(o is string s)
{
// Use string variable s
}
or
switch (o)
{
case int i:
// Use int variable i
break;
case string s:
// Use string variable s
break;
}
A: 'as' is based on 'is', which is a keyword that checks at runtime if the object is polimorphycally compatible (basically if a cast can be made) and returns null if the check fails.
These two are equivalent:
Using 'as':
string s = o as string;
Using 'is':
if(o is string)
s = o;
else
s = null;
On the contrary, the c-style cast is made also at runtime, but throws an exception if the cast cannot be made.
Just to add an important fact:
The 'as' keyword only works with reference types. You cannot do:
// I swear i is an int
int number = i as int;
In those cases you have to use casting.
A: If you already know what type it can cast to, use a C-style cast:
var o = (string) iKnowThisIsAString;
Note that only with a C-style cast can you perform explicit type coercion.
If you don't know whether it's the desired type and you're going to use it if it is, use as keyword:
var s = o as string;
if (s != null) return s.Replace("_","-");
//or for early return:
if (s==null) return;
Note that as will not call any type conversion operators. It will only be non-null if the object is not null and natively of the specified type.
Use ToString() to get a human-readable string representation of any object, even if it can't cast to string.
A: When trying to get the string representation of anything (of any type) that could potentially be null, I prefer the below line of code. It's compact, it invokes ToString(), and it correctly handles nulls. If o is null, s will contain String.Empty.
String s = String.Concat(o);
A: Since nobody mentioned it, the closest to instanceOf to Java by keyword is this:
obj.GetType().IsInstanceOfType(otherObj)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "839"
}
|
Q: Wrong number of arguments error with TestMailer I'm running a strange problem sending emails. I'm getting this exception:
ArgumentError (wrong number of arguments (1 for 0)):
/usr/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:642:in `initialize'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:642:in `new'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:642:in `create'
/usr/lib/ruby/gems/1.8/gems/ar_mailer-1.3.1/lib/action_mailer/ar_mailer.rb:92:in `perform_delivery_activerecord'
/usr/lib/ruby/gems/1.8/gems/ar_mailer-1.3.1/lib/action_mailer/ar_mailer.rb:91:in `each'
/usr/lib/ruby/gems/1.8/gems/ar_mailer-1.3.1/lib/action_mailer/ar_mailer.rb:91:in `perform_delivery_activerecord'
/usr/lib/ruby/gems/1.8/gems/actionmailer-2.1.1/lib/action_mailer/base.rb:508:in `__send__'
/usr/lib/ruby/gems/1.8/gems/actionmailer-2.1.1/lib/action_mailer/base.rb:508:in `deliver!'
/usr/lib/ruby/gems/1.8/gems/actionmailer-2.1.1/lib/action_mailer/base.rb:383:in `method_missing'
/app/controllers/web_reservations_controller.rb:29:in `test_email'
In my web_reservations_controller I have a simply method calling
TestMailer.deliver_send_email
And my TesMailer is something like:
class TestMailer < ActionMailer::ARMailer
def send_email
@recipients = "xxx@example.com"
@from = "xxx@example.com"
@subject = "TEST MAIL SUBJECT"
@body = "<br>TEST MAIL MESSAGE"
@content_type = "text/html"
end
end
Do you have any idea?
Thanks!
Roberto
A: The problem is with the model that ar_mailer is using to store the message. You can see in the backtrace that the exception is coming from ActiveRecord::Base.create when it calls initialize. Normally an ActiveRecord constructor takes an argument, but in this case it looks like your model doesn't. ar_mailer should be using a model called Email. Do you have this class in your app/models directory? If so, is anything overridden with initialize? If you are overriding initialize, be sure to give it arguments and call super.
class Email < ActiveRecord::Base
def initialize(attributes)
super
# whatever you want to do
end
end
A: Check that email_class is set correctly: http://seattlerb.rubyforge.org/ar_mailer/classes/ActionMailer/ARMailer.html#M000002
Also don't use instance variables. Try:
class TestMailer < ActionMailer::ARMailer
def send_email
recipients "roberto.druetto@gmail.com"
from "roberto.druetto@gmail.com"
subject "TEST MAIL SUBJECT"
content_type "text/html"
end
end
From the docs: the body method has special behavior. It takes a hash which generates an instance variable named after each key in the hash containing the value that that key points to.
So something like this added to the method above:
body :user => User.find(1)
Will allow you to use @user in the template.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Keyword highlighting on selection in Visual Studio 2008 A little while ago I managed to get Visual Studio 2008 (C++) into a state where, if I would select a keyword (or any symbol for that matter), by either double clicking on it or highlighting it, all other instances of that symbol within the current file would become highlighted too.
This was a really useful feature.
Since then it's gone away, and I don't know how to get it back.
Please help.
@Sander - that'll be it. Thanks!
A: I think you've installed RockScroll. It also lights them up in the graphical scrollbar (its main feature)
A: I use MetalScroll, it's like RockScroll only better; it doesn't interfere with Resharper (a VS must-have) and you can set it up to only highlight if you hold down 'alt' when you double-click.
A: There is something called "WordLight" by Mikhail Nasyrov.
An add-in for Visual Studio 2008 that highlights all occurrences of a selected text.
It searches and highlights substrings that are currently selected in a text editor.
Can be found at below link
WordLight
https://marketplace.visualstudio.com/items?itemName=MikhailNasyrov.WordLight
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is it possible to upload entire folders in ASP.NET? The file upload control in asp.net does not allow me to select a folder and enables me to select only the files. Is there any way in which I can select a folder (obviously without using the file upload control).
Why I want to select the folder is basically to store its entire path in a database table.
A: The HTML <input type=file> element only supports single file uploads. If you to have multiple file upload, you would have to use a 3rd party component - usually written in Flash.
Here an example: http://www.codeproject.com/KB/aspnet/FlashUpload.aspx
A: No, browsing for files are the client-side feature, and the only information about file path is their name. It's cause security.
A: I dont think HTML supports what you are trying to do. Perhaps as a workaround you can have them select a file in the folder and then chop off the file name when processing it but thats a mess to be honest.
Ask them to Paste or type the path into a textbox perhaps. The issue here is you cant check for typos.
Id say you should rethink what you are trying to do.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to perform string Diffs in Java? I need to perform Diffs between Java strings. I would like to be able to rebuild a string using the original string and diff versions. Has anyone done this in Java? What library do you use?
String a1; // This can be a long text
String a2; // ej. above text with spelling corrections
String a3; // ej. above text with spelling corrections and an additional sentence
Diff diff = new Diff();
String differences_a1_a2 = Diff.getDifferences(a,changed_a);
String differences_a2_a3 = Diff.getDifferences(a,changed_a);
String[] diffs = new String[]{a,differences_a1_a2,differences_a2_a3};
String new_a3 = Diff.build(diffs);
a3.equals(new_a3); // this is true
A: This library seems to do the trick: google-diff-match-patch. It can create a patch string from differences and allow to reapply the patch.
edit: Another solution might be to https://code.google.com/p/java-diff-utils/
A: The java diff utills library might be useful.
A: As Torsten Says you can use
org.apache.commons.lang.StringUtils;
System.err.println(StringUtils.getLevenshteinDistance("foobar", "bar"));
A: Apache Commons has String diff
org.apache.commons.lang.StringUtils
StringUtils.difference("foobar", "foo");
A: If you need to deal with differences between big amounts of data and have the differences efficiently compressed, you could try a Java implementation of xdelta, which in turn implements RFC 3284 (VCDIFF) for binary diffs (should work with strings too).
A: Use the Levenshtein distance and extract the edit logs from the matrix the algorithm builds up. The Wikipedia article links to a couple of implementations, I'm sure there's a Java implementation among in.
Levenshtein is a special case of the Longest Common Subsequence algorithm, you might also want to have a look at that.
A: Apache Commons Text now has StringsComparator:
StringsComparator c = new StringsComparator(s1, s2);
c.getScript().visit(new CommandVisitor<Character>() {
@Override
public void visitKeepCommand(Character object) {
System.out.println("k: " + object);
}
@Override
public void visitInsertCommand(Character object) {
System.out.println("i: " + object);
}
@Override
public void visitDeleteCommand(Character object) {
System.out.println("d: " + object);
}
});
A: I found it useful to discover, (for a regression test, where I didn't need diffing support in production) that assertj provides built-in access for java-diff-utils. See its DiffUtils, InputStream, or Diff classes, for example.
A: public class Stringdiff {
public static void main(String args[]){
System.out.println(strcheck("sum","sumsum"));
}
public static String strcheck(String str1,String str2){
if(Math.abs((str1.length()-str2.length()))==-1){
return "Invalid";
}
int num=diffcheck1(str1, str2);
if(num==-1){
return "Empty";
}
if(str1.length()>str2.length()){
return str1.substring(num);
}
else{
return str2.substring(num);
}
}
public static int diffcheck1(String str1,String str2)
{
int i;
String str;
String strn;
if(str1.length()>str2.length()){
str=str1;
strn=str2;
}
else{
str=str2;
strn=str1;
}
for(i=0;i<str.length() && i<strn.length();i++){
if(str1.charAt(i)!=str2.charAt(i)){
return i;
}
}
if(i<str1.length()||i<str2.length()){
return i;
}
return -1;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "57"
}
|
Q: Regex to remove conditional comments I want a regex which can match conditional comments in a HTML source page so I can remove only those. I want to preserve the regular comments.
I would also like to avoid using the .*? notation if possible.
The text is
foo
<!--[if IE]>
<style type="text/css">
ul.menu ul li{
font-size: 10px;
font-weight:normal;
padding-top:0px;
}
</style>
<![endif]-->
bar
and I want to remove everything in <!--[if IE]> and <![endif]-->
EDIT: It is because of BeautifulSoup I want to remove these tags. BeautifulSoup fails to parse and gives an incomplete source
EDIT2: [if IE] isn't the only condition. There are lots more and I don't have any list of all possible combinations.
EDIT3: Vinko Vrsalovic's solution works, but the actual problem why beautifulsoup failed was because of a rogue comment within the conditional comment. Like
<!--[if lt IE 7.]>
<script defer type="text/javascript" src="pngfix_253168.js"></script><!--png fix for IE-->
<![endif]-->
Notice the <!--png fix for IE--> comment?
Though my problem was solve, I would love to get a regex solution for this.
A: >>> from BeautifulSoup import BeautifulSoup, Comment
>>> html = '<html><!--[if IE]> bloo blee<![endif]--></html>'
>>> soup = BeautifulSoup(html)
>>> comments = soup.findAll(text=lambda text:isinstance(text, Comment)
and text.find('if') != -1) #This is one line, of course
>>> [comment.extract() for comment in comments]
[u'[if IE]> bloo blee<![endif]']
>>> print soup.prettify()
<html>
</html>
>>>
python 3 with bf4:
from bs4 import BeautifulSoup, Comment
html = '<html><!--[if IE]> bloo blee<![endif]--></html>'
soup = BeautifulSoup(html, "html.parser")
comments = soup.findAll(text=lambda text:isinstance(text, Comment)
and text.find('if') != -1) #This is one line, of course
[comment.extract() for comment in comments]
[u'[if IE]> bloo blee<![endif]']
print (soup.prettify())
If your data gets BeautifulSoup confused, you can fix it before hand or customize the parser, among other solutions.
EDIT: Per your comment, you just modify the lambda passed to findAll as you need (I modified it)
A: Here's what you'll need:
<!(|--)\[[^\]]+\]>.+?<!\[endif\](|--)>
It will filter out all sorts of conditional comments including:
<!--[if anything]>
...
<[endif]-->
and
<![if ! IE 6]>
...
<![endif]>
EDIT3: Vinko Vrsalovic's solution works, but the actual problem why beautifulsoup failed was because of a rogue comment within the conditional comment. Like
Notice the comment?
Though my problem was solve, I would love to get a regex solution for this.
How about this:
(<!(|--)\[[^\]]+\]>.*?)(<!--.+?-->)(.*?<!\[endif\](|--)>)
Do a replace on that regular expression leaving \1\4 (or $1$4) as the replacement.
I know it has .*? and .+? in it, see my comment on this post.
A: I'd simply go with :
import re
html = """fjlk<wb>dsqfjqdsmlkf fdsijfmldsqjfl fjdslmfkqsjf<---- fdjslmjkqfs---><!--[if lt IE 7.]>\
<script defer type="text/javascript" src="pngfix_253168.js"></script><!--png fix for IE-->\
<![endif]-->fjlk<wb>dsqfjqdsmlkf fdsijfmldsqjfl fjdslmfkqsjf<---- fdjslmjkqfs--->"""
# here the black magic occurs (whithout '.')
clean_html = ''.join(re.split(r'<!--\[[^¤]+?endif]-->', html))
print clean_html
'fjlk<wb>dsqfjqdsmlkf fdsijfmldsqjfl fjdslmfkqsjf<---- fdjslmjkqfs--->fjlk<wb>dsqfjqdsmlkf fdsijfmldsqjfl fjdslmfkqsjf<---- fdjslmjkqfs--->'
N.B : [^¤] will match any char that is not '¤'. This is really useful since it's lightning fast and this char can be found on any keyboard. But the trick is it's really hard to type (no one will type it by mistake) and nobody uses it : it's a generical money devise char.
If you don't feel like using ¤, however, you can use chr(7) to generate the "system bell" char, wich is unprintable and can't be found in a web page ;-)
A: As I see it, you only need to worry about downlevel-hidden comments (the ones that start with <!--), and you don't need to match anything beyond the word if and the space following it. This should do what you want:
"<!--\[if\s(?:[^<]+|<(?!!\[endif\]-->))*<!\[endif\]-->"
That mess in the middle is to satisfy your desire not to use .*?, but I don't really think it's worth the effort. The .*? approach should work fine if you compile the regex with the Re.S flag set or wrap it in (?s:...). For example:
"(?s:<!--\[if\s.*?<!\[endif\]-->)"
A: @Benoit
Small Correction (with multiline turned on):
"<!--\[if IE\]>.*?<!\[endif\]-->"
A: Don't use a regular expression for this. You will get confused about comments containing opening tags and what not, and do the wrong thing. HTML isn't regular, and trying to modify it with a single regular expression will fail.
Use a HTML parser for this. BeautifulSoup is a good, easy, flexible and sturdy one that is able to handle real-world (meaning hopelessly broken) HTML. With it you can just look up all comment nodes, examine their content (you can use a regular expression for that, if you wish) and remove them if they need to be removed.
A: This works in Visual Studio 2005, where there is no line span option:
\<!--\[if IE\]\>{.|\n}*\<!\[endif\]--\>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Designing for change I'm pretty sure most of us are familiar with the concept of a project's requirements changing after it starts, this becomes more and more of an issue the less the client knows about how things work and the closer you work with them.
How then can I design a system (specifically a website but general advice will probably be best here) so that smallish changes can be made, are there any programming strategies that deal with this issue?
A: I think the biggest thing is to make sure you have a comprehensive test suite. That way you can make changes confidently when needed and know when it breaks.
A: Having no experience with PHP, take this with a pinch of salt.
But it's all about knowing change will come. So when you are coding and start wanting to hack things to get them done, stop and think "what if I need to change this again?".
Now, I know php is a scripting language, but you must be able to library off code right? Thats the best thing to do, keep the UI (the web page) as LIGHT as possible, for the most part 1 or two method calls.
If you have fancy rendering logic, library it. Create a nice look that may be common? Look at what might change (colour scheme etc.), library it. You're already putting all your core code into libraries though right? ;)
If you always work on building your library, all you need to then do when the change request comes in is "find the right book for it".. Whats cool about what we do is that if the book is well written, you can easily add annotations to it ;)
This is basically what I am doing at work at the moment, my "project" is to build the platform that future apps will be working on, so this is really my main focus. :)
Update
Mendelt made a good point on applying YAGNI, with all of the above, don't just write stuff to library it but if you think for a second that the sexy little table you just created (because a client wanted it) might be used again, then it's time to think about making it more usable. Some obscure function for a one-off client should be done ad-hoc.
A: Well, I'd try to tackle this problem from the other side:
More communication with the customer/user.
I have been there myself, programming things that were not wanted or not properly communicated and having to redo lots of code. It would have been prevented with more communication or rather: with more of the right communication.
Aside from that:
Allow Users to change the color and ask them now and then, where to place a button and the probability, they will be satisfied with this "great level of control" is quite good. And then they won't want you to redo real features. Yes, I am sarcastic about this.
A: All the normal oo principles apply here, reduce coupling, increase cohesion, don't repeat yourself etc. This will make sure you have a flexible and extendible code base.
Apart from that don't try to preempt change. Apply YAGNI (You aint gonna need it) everywhere. Only build stuff you know your users need. Dont build stuff you think you're going to need. You're more likely to guess wrong and then you've got a bunch of code that's probably only in the way.
A: I suggest using a tried and tested framework for your language of choice. Most good frameworks will have been designed to accommodate a multitude of scenarios.
A: First, you should identify the aspects that will have a high change probability. These aspects should be 'abstracted out'. A classic example is the style of your website (i.e. through css). But you could even so define a 'presenter' class that lays out the specific elements of a web page.
The hard thing is making a correct estimate of the change probability. But that's up to you :)
A: This is where frameworks come into play.
If all the baseline, background, business-as-usual is in the framework, then your application is the extensions, special-cases and add-ons.
The framework is already designed and built for change. Your stuff is the change that the frame was designed to accept.
When change occurs, you will respond to change with some combination of modifying the framework configuration and rewriting your stuff that plugs into the framework. You cope with change by not focusing on the default, background stuff. Delegate that to someone else -- the framework authors.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Best Practice: Potentially huge Winform grid? I am writing an application in VB.NET 2008 that manages software deployment and I want to display a "deployment overview" grid.
The grid will be populated with the names of each application (top row) and the name of each workstation (1st column). The remaining cells will be populated according to whether the corresponding software title has been installed correctly, install failed OR not deployed.
What would be the best way to present this information to the end-user? Could the application 'cope' with maybe a thousand check boxes or would it be better to 'owner-draw' a grid in some way?
I may also require the ability to click on any of these cells to view and/or set other properties.
Many thanks for your help.
John
A: I have used the .NET's GridDataView without any problems using the Virtual Mode while trying to show over 10000 rows but there are good products out there that are also very good in loading tons of data like Developer express XtraGrid and Telerik's RadGridView.
The only challenge was keep the UAT people happy with all the noise from several thousands of rows.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Webservices client and ssl I have a Java client that calls a web service at the moment using the Http protocol.
When i try to use the Https protocol i keep getting this error
java.io.IOException: DerInputStream.getLength(): lengthTag=127, too big.
Any ideas what could be up?
Thanks
Damien
A: Due to american export regulations in encryption technologies, you can't use strong encryption out of the box. Your error looks like you (or your framework) is trying to use strong encryption, and other parts of the framework is not allowing it.
A discussion of a case that looks similar to yours can be found here.
A good crypto provider is BouncyCastle. Takes some reading, but it's not that hard to make it work.
Good luck,
A: Are you sure you are connecting your HTTPS client to the server port that talks over HTTPS (TLS/SSL) rather than HTTP?
A: YOu have to pass the keystore type from the client. This error should go then.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I sort a list of integers using only one additional integer variable? How to sort list of values using only one variable?
A: A solution in C:
#include <stdio.h>
int main()
{
int list[]={4,7,2,4,1,10,3};
int n; // the one int variable
startsort:
for (n=0; n< sizeof(list)/sizeof(int)-1; ++n)
if (list[n] > list[n+1]) {
list[n] ^= list[n+1];
list[n+1] ^= list[n];
list[n] ^= list[n+1];
goto startsort;
}
for (n=0; n< sizeof(list)/sizeof(int); ++n)
printf("%d\n",list[n]);
return 0;
}
Output is of course the same as for the Icon program.
A: I suspect I'm doing your homework for you, but hey it's an interesting challenge. Here's a solution in Icon:
procedure mysort(thelist)
local n # the one integer variable
every n := (1 to *thelist & 1 to *thelist-1) do
if thelist[n] > thelist[n+1] then thelist[n] :=: thelist[n+1]
return thelist
end
procedure main(args)
every write(!mysort([4,7,2,4,1,10,3]))
end
The output:
1
2
3
4
4
7
10
A: You could generate/write a lot of sorting-networks for each possible list size. Inside the sorting network you use a single variable for the swap operation.
I wouldn't recommend that you do this in software, but it is possible nevertheless.
Here's a sorting-routine for all n up to 4 in C
// define a compare and swap macro
#define order(a,b) if ((a)<(b)) { temp=(a); (a) = (b); (b) = temp; }
static void sort2 (int *data)
// sort-network for two numbers
{
int temp;
order (data[0], data[1]);
}
static void sort3 (int *data)
// sort-network for three numbers
{
int temp;
order (data[0], data[1]);
order (data[0], data[2]);
order (data[1], data[2]);
}
static void sort4 (int *data)
// sort-network for four numbers
{
int temp;
order (data[0], data[2]);
order (data[1], data[3]);
order (data[0], data[1]);
order (data[2], data[3]);
order (data[1], data[2]);
}
void sort (int *data, int n)
{
switch (n)
{
case 0:
case 1:
break;
case 2:
sort2 (data);
break;
case 3:
sort3 (data);
break;
case 4:
sort4 (data);
break;
default:
// Sorts for n>4 are left as an exercise for the reader
abort();
}
}
Obviously you need a sorting-network code for each possible N.
More info here:
http://en.wikipedia.org/wiki/Sorting_network
A: In java:
import java.util.Arrays;
/**
* Does a bubble sort without allocating extra memory
*
*/
public class Sort {
// Implements bubble sort very inefficiently for CPU but with minimal variable declarations
public static void sort(int[] array) {
int index=0;
while(true) {
next:
{
// Scan for correct sorting. Wasteful, but avoids using a boolean parameter
for (index=0;index<array.length-1;index++) {
if (array[index]>array[index+1]) break next;
}
// Array is now correctly sorted
return;
}
// Now swap. We don't need to rescan from the start
for (;index<array.length-1;index++) {
if (array[index]>array[index+1]) {
// use xor trick to avoid using an extra integer
array[index]^=array[index+1];
array[index+1]^=array[index];
array[index]^=array[index+1];
}
}
}
}
public static void main(final String argv[]) {
int[] array=new int[] {4,7,2,4,1,10,3};
sort(array);
System.out.println(Arrays.toString(array));
}
}
Actually, by using the trick proposed by Nils, you can eliminate even the one remaining int allocation - though of course that would add to the stack instead...
A: In ruby:
[1, 5, 3, 7, 4, 2].sort
A: You dont, it is already sorted. (as the question is vague, I shall assume variable is a synonym for an object)
A: If you have a list (1 5 3 7 4 2) and a variable v, you can exchange two values of the list, for example the 3 and the 7, by first assigning 3 to v, then assigning 7 to the place of 3, finally assigning the value of v to the original place of 7. After that, you can reuse v for the next exchange. In order to sort, you just need an algorithm that tells which values to exchange. You can look for a suitable algorithm for example at http://en.wikipedia.org/wiki/Sorting_algorithm .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to reformat multi-line comments in Eclipse PDT? In Eclipse PDT, Ctrl-Shift-F reformats code. However, it doesn't modify comments at all. Is there some way to reformat ragged multi-line comments to 80 characters per line (or whatever)?
i.e. convert
// We took a breezy excursion and
// gathered Jonquils from the river slopes. Sweet Marjoram grew
// in luxuriant
// profusion by the window that overlooked the Aztec city.
to
// We took a breezy excursion and gathered Jonquils
// from the river slopes. Sweet Marjoram grew in
// luxuriant profusion by the window that overlooked
// the Aztec city.
(I think this applies to regular Eclipse as well.)
Update Turns out that Eclipse in Java mode will reformat the lines above, but only if they're /* */-style comments. It will shorten // lines that are too long, but it won't join lines that are too short together.
A: You probably need to configure the Java formatter to include comments.
Preferences -> Java -> Code Style -> Formatter -> Edit... -> Comments
Make sure that "Enable XXX comment formatting" is enabled.
A: I've never really been able to get the Eclipse formatter to format my code exactly how I want, and this is just one of several shortcomings I've encountered. I've heard the Jalopy formatter is much better. There's both a commercial and free version available with Eclipse plugins for both. I've heard the commercial version is more sophisticated (development on the free version appears to have stalled), but I haven't actually used either personally.
A: My solution involves using the vrapper plugin (free): http://vrapper.sourceforge.net/home/ which gives you vim support within your text editor.
Once the vrapper plugin is installed you can press v to go into visual mode, highlight your multi-line comment and then press G+Q to auto format the comment so that lines are 80 columns in width (default). You can change the default column width, but you'll need to read the documentation for the vrapper plugin. Cheers!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Given a date range (start and end dates), how can I count the days, excluding specified days of the week in .Net? I'm creating a UI that allows the user the select a date range, and tick or un-tick the days of the week that apply within the date range.
The date range controls are DateTimePickers, and the Days of the Week are CheckBoxes
Here's a mock-up of the UI:
From Date: (dtpDateFrom)
To Date: (dtpDateTo)
[y] Monday, [n] Tuesday, [y] Wednesday, (etc)
What's the best way to show a total count the number of days, based not only on the date range, but the ticked (or selected) days of the week?
Is looping through the date range my only option?
A: Here's how I would approach it:
*
*Find day of week (dow) of first and last date
*Move first day forward to same dow as last. Store number of days moved that are to be included
*Calculate number of weeks between first and last
*Calculate number of included days in a week * number of weeks + included days moved
As pseudo code:
moved = start + end_dow - start_dow
extras = count included days between start and moved
weeks = ( end - moved ) / 7
days = days_of_week_included * weeks + extras
This will take constant time, no matter how far apart the start and end days.
The details of implementing this algorithm depend on what language and libraries you are using. Where possible, I use C++ plus boost::date_time for this sort of thing.
A: Looping through wouldn't be your only option - you could perform subtraction to figure out the total number of days, and subtract one for each of your "skipped" dates every week range in between that contains one of those days. By the time you figure out whether a day lands on one of the partial weeks at the beginning or end of the range and add #weeks * skipped days in a week, your code will be more complicated than it would be if just counted, but if you're expecting to have huge date ranges, it might perform better.
If I were you, I'd write the simple looping option and rewrite it if it turned out that profiling revealed it to be a bottleneck.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: .NET Configuration (app.config/web.config/settings.settings) I have a .NET application which has different configuration files for Debug and Release builds. E.g. the debug app.config file points to a development SQL Server which has debugging enabled and the release target points to the live SQL Server. There are also other settings, some of which are different in debug/release.
I currently use two separate configuration files (debug.app.config and release.app.config). I have a build event on the project which says if this is a release build then copy release.app.config to app.config, else copy debug.app.config to app.config.
The problem is that the application seems to get its settings from the settings.settings file, so I have to open settings.settings in Visual Studio which then prompts me that the settings have changed so I accept the changes, save settings.settings and have to rebuild to make it use the correct settings.
Is there a better/recommended/preferred method for achieving a similar effect? Or equally, have I approached this completely wrong and is there a better approach?
A: We used to use Web Deployment projects but have since migrated to NAnt. Instead of branching and copying different setting files we currently embed the configuration values directly in the build script and inject them into our config files via xmlpoke tasks:
<xmlpoke
file="${stagingTarget}/web.config"
xpath="/configuration/system.web/compilation/@debug"
value="true"
/>
In either case, your config files can have whatever developer values you want and they'll work fine from within your dev environment without breaking your production systems. We've found that developers are less likely to arbitrarily change the build script variables when testing things out, so accidental misconfigurations have been rarer than with other techniques we've tried, though it's still necessary to add each var early in the process so that the dev value doesn't get pushed to prod by default.
A: My current employer solved this issue by first putting the dev level (debug, stage, live, etc) in the machine.config file. Then they wrote code to pick that up and use the right config file. That solved the issue with the wrong connection string after the app gets deployed.
They just recently wrote a central webservice that sends back the correct connection string from the value in the machine.config value.
Is this the best solution? Probably not, but it works for them.
A: Any configuration that might differ across environments should be stored at the machine level, not the application level. (More info on configuration levels.)
These are the kinds of configuration elements that I typically store at the machine level:
*
*Application settings
*Connection strings
*retail=true
*Smtp settings
*Health monitoring
*Hosting environment
*Machine key
When each environment (developer, integration, test, stage, live) has its own unique settings in the c:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG directory, then you can promote your application code between environments without any post-build modifications.
And obviously, the contents of the machine-level CONFIG directory get version-controlled in a different repository or a different folder structure from your app. You can make your .config files more source-control friendly through intelligent use of configSource.
I've been doing this for 7 years, on over 200 ASP.NET applications at 25+ different companies. (Not trying to brag, just want to let you know that I've never seen a situation where this approach doesn't work.)
A: This might help some people dealing with Settings.settings and App.config: Watch out for GenerateDefaultValueInCode attribute in the Properties pane while editing any of the values in the Settings.settings grid in Visual Studio (Visual Studio 2008 in my case).
If you set GenerateDefaultValueInCode to True (True is the default here!), the default value is compiled into the EXE (or DLL), you can find it embedded in the file when you open it in a plain text editor.
I was working on a console application and if I had defaulted in the EXE, the application always ignored the configuration file placed in the same directory! Quite a nightmare and no information about this on the whole Internet.
A: One of the solutions that worked me fine was using a WebDeploymentProject.
I had 2/3 different web.config files in my site, and on publish, depending on the selected configuration mode (release/staging/etc...) I would copy over the Web.Release.config and rename it to web.config in the AfterBuild event, and delete the ones I don't need (Web.Staging.config for example).
<Target Name="AfterBuild">
<!--Web.config -->
<Copy Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' " SourceFiles="$(SourceWebPhysicalPath)\Web.Release.config" DestinationFiles="$(OutputPath)\Web.config" />
<Copy Condition=" '$(Configuration)|$(Platform)' == 'Staging|AnyCPU' " SourceFiles="$(SourceWebPhysicalPath)\Web.Staging.config" DestinationFiles="$(OutputPath)\Web.config" />
<!--Delete extra files -->
<Delete Files="$(OutputPath)\Web.Release.config" />
<Delete Files="$(OutputPath)\Web.Staging.config" />
<Delete Files="@(ProjFiles)" />
</Target>
A: There is a related question here:
Improving Your Build Process
Config files come with a way to override the settings:
<appSettings file="Local.config">
Instead of checking in two files (or more), you only check in the default config file, and then on each target machine, you put a Local.config, with just the appSettings section that has the overrides for that particular machine.
If you are using config sections, the equivalent is:
configSource="Local.config"
Of course, it's a good idea to make backup copies of all the Local.config files from other machines and check them in somewhere, but not as a part of the actual solutions. Each developer puts an "ignore" on the Local.config file so it doesn't get checked in, which would overwrite everyone else's file.
(You don't actually have to call it "Local.config", that's just what I use)
A: You'll find another solution here: Best way to switch configuration between Development/UAT/Prod environments in ASP.NET? which uses XSLT to transfor the web.config.
There are also some good examples on using NAnt.
A: Our project has the same issue where we had to maintain configs for dev, qa, uat and prod. Here is what we followed (only applies if you are familiar with MSBuild):
Use MSBuild with the MSBuild Community tasks extension. It includes the 'XmlMassUpdate' task that can 'mass-update' entries in any XML file once you give it the correct node to start with.
To Implement:
1) You need to have one config file which will have your dev env entries; this is the config file in your solution.
2) You need to have a 'Substitutions.xml' file, that contains only the entries that are DIFFERENT (appSettings and ConnectionStrings mostly) for each environment. Entries that do not change across the environment need not be put in this file. They can live in the web.config file of the solution and will not be touched by the task
3) In your build file, just call the XML mass update task and provide the right environment as a parameter.
See example below:
<!-- Actual Config File -->
<appSettings>
<add key="ApplicationName" value="NameInDev"/>
<add key="ThisDoesNotChange" value="Do not put in substitution file" />
</appSettings>
<!-- Substitutions.xml -->
<configuration xmlns:xmu="urn:msbuildcommunitytasks-xmlmassupdate">
<substitutions>
<QA>
<appSettings>
<add xmu:key="key" key="ApplicationName" value="NameInQA"/>
</appSettings>
</QA>
<Prod>
<appSettings>
<add xmu:key="key" key="ApplicationName" value="NameInProd"/>
</appSettings>
</Prod>
</substitutions>
</configuration>
<!-- Build.xml file-->
<Target Name="UpdateConfigSections">
<XmlMassUpdate ContentFile="Path\of\copy\of\latest web.config" SubstitutionsFile="path\of\substitutionFile" ContentRoot="/configuration" SubstitutionsRoot="/configuration/substitutions/$(Environment)" />
</Target>
replace '$Environment' with 'QA' or 'Prod' based on what env. you are building for. Note that you should work on a copy of a config file and not the actual config file itself to avoid any possible non-recoverable mistakes.
Just run the build file and then move the updated config file to your deployment environment and you are done!
For a better overview, read this:
http://blogs.microsoft.co.il/blogs/dorony/archive/2008/01/18/easy-configuration-deployment-with-msbuild-and-the-xmlmassupdate-task.aspx
A: Like you I've also set up 'multi' app.config - eg app.configDEV, app.configTEST, app.config.LOCAL. I see some of the excellent alternatives suggested, but if you like the way it works for you, I'd add the following:
I have a
<appSettings>
<add key = "Env" value = "[Local] "/>
for each app I add this to the UI in the titlebar:
from ConfigurationManager.AppSettings.Get("Env");
I just rename the config to the one I'm targetting (I have a project with 8 apps with lots of database/wcf config against 4 evenioments). To deploy with clickonce into each I change 4 seetings in the project and go. (this I'd love to automate)
My only gotcha is to remember to 'clean all' after a change, as the old config is 'stuck' after a manual rename. (Which I think WILL fix you setting.setting issue).
I find this works really well (one day I'll get time to look at MSBuild/NAnt)
A: From what I am reading, it sounds like you are using Visual Studio for your build process. Have you thought about using MSBuild and Nant instead?
Nant's xml syntax is a little weird but once you understand it, doing what you mentioned becomes pretty trivial.
<target name="build">
<property name="config.type" value="Release" />
<msbuild project="${filename}" target="Build" verbose="true" failonerror="true">
<property name="Configuration" value="${config.type}" />
</msbuild>
<if test="${config.type == 'Debug'}">
<copy file=${debug.app.config}" tofile="${app.config}" />
</if>
<if test="${config.type == 'Release'}">
<copy file=${release.app.config}" tofile="${app.config}" />
</if>
</target>
A: To me it seems that you can benefit from the Visual Studio 2005 Web Deployment Projects.
With that, you can tell it to update/modify sections of your web.config file depending on the build configuration.
Take a look at this blog entry from Scott Gu for a quick overview/sample.
A: It says asp.net above, so why not save your settings in the database and use a custom-cache to retrieve them?
The reason we did it because it's easier (for us) to update the continuously database than it is to get permission to continuously update production files.
Example of a Custom Cache:
public enum ConfigurationSection
{
AppSettings
}
public static class Utility
{
#region "Common.Configuration.Configurations"
private static Cache cache = System.Web.HttpRuntime.Cache;
public static String GetAppSetting(String key)
{
return GetConfigurationValue(ConfigurationSection.AppSettings, key);
}
public static String GetConfigurationValue(ConfigurationSection section, String key)
{
Configurations config = null;
if (!cache.TryGetItemFromCache<Configurations>(out config))
{
config = new Configurations();
config.List(SNCLavalin.US.Common.Enumerations.ConfigurationSection.AppSettings);
cache.AddToCache<Configurations>(config, DateTime.Now.AddMinutes(15));
}
var result = (from record in config
where record.Key == key
select record).FirstOrDefault();
return (result == null) ? null : result.Value;
}
#endregion
}
namespace Common.Configuration
{
public class Configurations : List<Configuration>
{
#region CONSTRUCTORS
public Configurations() : base()
{
initialize();
}
public Configurations(int capacity) : base(capacity)
{
initialize();
}
public Configurations(IEnumerable<Configuration> collection) : base(collection)
{
initialize();
}
#endregion
#region PROPERTIES & FIELDS
private Crud _crud; // Db-Access layer
#endregion
#region EVENTS
#endregion
#region METHODS
private void initialize()
{
_crud = new Crud(Utility.ConnectionName);
}
/// <summary>
/// Lists one-to-many records.
/// </summary>
public Configurations List(ConfigurationSection section)
{
using (DbCommand dbCommand = _crud.Db.GetStoredProcCommand("spa_LIST_MyConfiguration"))
{
_crud.Db.AddInParameter(dbCommand, "@Section", DbType.String, section.ToString());
_crud.List(dbCommand, PopulateFrom);
}
return this;
}
public void PopulateFrom(DataTable table)
{
this.Clear();
foreach (DataRow row in table.Rows)
{
Configuration instance = new Configuration();
instance.PopulateFrom(row);
this.Add(instance);
}
}
#endregion
}
public class Configuration
{
#region CONSTRUCTORS
public Configuration()
{
initialize();
}
#endregion
#region PROPERTIES & FIELDS
private Crud _crud;
public string Section { get; set; }
public string Key { get; set; }
public string Value { get; set; }
#endregion
#region EVENTS
#endregion
#region METHODS
private void initialize()
{
_crud = new Crud(Utility.ConnectionName);
Clear();
}
public void Clear()
{
this.Section = "";
this.Key = "";
this.Value = "";
}
public void PopulateFrom(DataRow row)
{
Clear();
this.Section = row["Section"].ToString();
this.Key = row["Key"].ToString();
this.Value = row["Value"].ToString();
}
#endregion
}
}
A: Web.config:
Web.config is needed when you want to host your application on IIS. Web.config is a mandatory config file for IIS to configure how it will behave as a reverse proxy in front of Kestrel. You have to maintain a web.config if you want to host it on IIS.
AppSetting.json:
For everything else that does not concern IIS, you use AppSetting.json.
AppSetting.json is used for Asp.Net Core hosting. ASP.NET Core uses the "ASPNETCORE_ENVIRONMENT" environment variable to determine the current environment. By default, if you run your application without setting this value, it will automatically default to the Production environment and uses "AppSetting.production.json" file. When you debug via Visual Studio it sets the environment to Development so it uses "AppSetting.json". See this website to understand how to set the hosting environment variable on Windows.
App.config:
App.config is another configuration file used by .NET which is mainly used for Windows Forms, Windows Services, Console Apps and WPF applications. When you start your Asp.Net Core hosting via console application app.config is also used.
TL;DR
The choice of the configuration file is determined by the hosting environment you choose for the service. If you are using IIS to host your service, use a Web.config file. If you are using any other hosting environment, use an App.config file.
See Configuring Services Using Configuration Files documentation
and also check out Configuration in ASP.NET Core.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "164"
}
|
Q: How to debug multithreaded midlet app in EclipseMe? When debugging multithreaded midlet in the EclipseMe, the breakpoints work for me only in the main thread but not I other threads. Any ideas?
A: A wild guess, have you tried putting Thread.sleep() in the main thread and see whether the debugger enters the other thread!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What's the difference between an element and a node in XML? I'm working in Java with XML and I'm wondering; what's the difference between an element and a node?
A: A node is the base class for both elements and attributes (and basically all other XML representations too).
A: Element is the only kind of node that can have child nodes and attributes.
Document also has child nodes, BUT
no attributes, no text, exactly one child element.
A: Different W3C specifications define different sets of "Node" types.
Thus, the DOM spec defines the following types of nodes:
Document -- Element (maximum of
one), ProcessingInstruction,
Comment, DocumentType
DocumentFragment
-- Element, ProcessingInstruction,
Comment, Text, CDATASection, EntityReference
DocumentType --
no children
EntityReference
-- Element, ProcessingInstruction,
Comment, Text, CDATASection, EntityReference
Element -- Element, Text, Comment, ProcessingInstruction,
CDATASection, EntityReference
Attr -- Text, EntityReference
ProcessingInstruction
-- no children
Comment -- no
children
Text -- no
children
CDATASection --
no children
Entity -- Element, ProcessingInstruction,
Comment, Text, CDATASection, EntityReference
Notation -- no
children
The XML Infoset (used by XPath) has a smaller set of nodes:
*The Document Information Item
*Element Information Items
*Attribute Information Items
*Processing Instruction Information Items
*Unexpanded Entity Reference Information Items
*Character Information Items
*Comment Information Items
*The Document Type Declaration Information Item
*Unparsed Entity Information Items
*Notation Information Items
*Namespace Information Items
XPath has the following Node types:
*
*root nodes
*element nodes
*text nodes
*attribute nodes
*namespace nodes
*processing instruction nodes
*comment nodes
The answer to your question "What is the difference between an element and a node" is:
An element is a type of node. Many other types of nodes exist and serve different purposes.
A: A Node is a part of the DOM tree, an Element is a particular type of Node
e.g.
<foo> This is Text </foo>
You have a foo Element, (which is also a Node, as Element inherits from Node) and a Text Node 'This is Text', that is a child of the foo Element/Node
A: The Node object is the primary data type for the entire DOM.
A node can be an element node, an attribute node, a text node, or any other of the node types explained in the "Node types" chapter.
An XML element is everything from (including) the element's start tag to (including) the element's end tag.
A: A node can be a number of different kinds of things: some text, a comment, an element, an entity, etc. An element is a particular kind of node.
A: A node is defined as:
the smallest unit of a valid, complete structure in a document.
or as:
An object in the tree view that serves as a container to hold related objects.
Now their are many different kinds of nodes as an elements node, an attribute node etc.
A: As described in the various XML specifications, an element is that which consists of a start tag, and end tag, and the content in between, or alternately an empty element tag (which has no content or end tag). In other words, these are all elements:
<foo> stuff </foo>
<foo bar="baz"></foo>
<foo baz="qux" />
Though you hear "node" used with roughly the same meaning, it has no precise definition per XML specs. It's usually used to refer to nodes of things like DOMs, which may be closely related to XML or use XML for their representation.
A: An xml document is made of nested elements. An element begins at its opening tag and ends at its closing tag. You're probably seen <body> and </body> in html. Everything between the opening and closing tags is the element's content. If an element is defined by a self-closing tag (eg. <br/>) then its content is empty.
Opening tags can also specify attributes, eg. <p class="rant">. In this example the attribute name is 'class' and its value 'rant'.
The XML language has no such thing as a 'node'. Read the spec, the word doesn't occur.
Some people use the word 'node' informally to mean element, which is confusing because some parsers also give the word a technical meaning (identifying 'text nodes' and 'element nodes'). The exact meaning depends on the parser, so the word is ill-defined unless you state what parser you are using. If you mean element, say 'element'.
A: Now i know ,the element is one of node
All node types in here"http://www.w3schools.com/dom/dom_nodetype.asp"
Element is between the start tag and end in the end tag
So text node is a node , but not a element.
A: An element is a type of node as are attributes, text etc.
A: node & element are same. Every element is a node , but it's not that every node must be an element.
A: XML Element is a XML Node but with additional elements like attributes.
<a>Lorem Ipsum</a> //This is a node
<a id="sample">Lorem Ipsum</a> //This is an element
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "400"
}
|
Q: "Son of Suckerfish" CSS Menu - sub menus not closing in IE7 Despite my most convincing cries to the contrary, I was recently forced to implement a horizontal drop-down navigation system, so I opted for the friendliest one I could find - Son of Suckerfish.
I tested in various browsers on my machine and all appeared to be fine. However, some (but not all!) IE7 users are experiencing an issue where sub menus do not close after they have been hovered over. The most annoying thing is that the affected users are using the exact version of IE7 that I am (7.0.5730.13), with the same privacy and security settings (I even had them send screenshots of the tabs in Internet Options) on the same OS (XP). I cannot verify if Vista is affected or not.
Obviously trying to debug this issue is a nightmare since I cannot replicate it, so I am wondering if anyone here can and might know how to solve it. I have set up an example page here:
http://x01.co.uk/menu_test/
Additionally, there's an annoying flicker on rollover of the sub items which I have also tried to solve with no success, so any help with that would also be appreciated.
A: This is a problem that occurs in IE7 when another part of the page has focus (ie, you clicked somewhere and then mouse-over the menu). It seems to be an issue with the :hover pseudo-class.
Adding a hasLayout trigger to the :hover style should fix the problem.
#nav li:hover {
position: static;
}
There are other solutions too. There's a great write-up about the problem here:
Sticky Sons of Suckerfish
A: For testing why not download the Vista IE7 VPC image from MS themselves?
http://www.microsoft.com/downloads/details.aspx?FamilyId=21EABB90-958F-4B64-B5F1-73D0A413C8EF
Not sure about the bug though. Remember having similar issues I think its because you need a JS. Will try and find out
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Installing mysql problem Running OS X Leopard an MacBook Pro from Jan. 2008.
I used to run mysql server from a package but then rails started putting a warning that I should install mysql from gem: gem install mysql
It did not work, I got the following error message:
Building native extensions. This could take a while...
ERROR: Error installing mysql:
ERROR: Failed to build gem native extension.
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby extconf.rb install mysql
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lm... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lz... yes
... snip ...
Gem files will remain installed in /Library/Ruby/Gems/1.8/gems/mysql-2.7 for inspection.
Results logged to /Library/Ruby/Gems/1.8/gems/mysql-2.7/gem_make.out
Then I tried a different way, upon a friend's advice and tried to follow the excellent instructions at http://hivelogic.com/articles/2007/11/installing-mysql-on-mac-os-x
but now ran into a new problem when trying to run 'mysql -u root'
The message I get is:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
I have googled my heart out trying to fix either problem and feel stuck. Thanks for reading and helping
A: To the first problem - I would imagine that Ruby gem is installing the ruby MySQL interface/drivers, not the MySQL server itself. It may be not present, or in a place the standard scripts can't find.
The second message indicates that the MySQL server is not running. Try starting it again, or examine any logs/messages for some indication as to why it might not be starting
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: IE6 + IE7 on a clean XP install We need to test a website in both IE6 and IE7. We've had bugs appear running on actual windows machines that aren't visible under vmware (?!), so we have an actual windows laptop to do this - but only one. Is it possible to install IE6 and IE7 side-by-side in such a way that they absolutely, positively, behave exactly like they would if there was only one of them? How?
A: The officially sanctioned way is to use the microsoft-provided Virtual PC installation and VPC images. You don't need additional windows licenses to run these.
http://blogs.msdn.com/ie/archive/2006/11/30/ie6-and-ie7-running-on-a-single-machine.aspx
http://www.microsoft.com/downloads/details.aspx?FamilyId=6D58729D-DFA8-40BF-AFAF-20BCB7F01CD1&displaylang=en
http://www.microsoft.com/downloads/details.aspx?FamilyId=21EABB90-958F-4B64-B5F1-73D0A413C8EF&displaylang=en
A: Take a look at http://tredosoft.com/Multiple_IE. Bear in mind that running both side by side is not supported by Microsoft (http://blogs.msdn.com/cwilso/archive/2006/02/01/522281.aspx) and there's no guarantee that they will work absolutely fine side by side - a Windows Update could easily break something and sometimes people find conditional comments don't work properly amongst other things. All I can suggest is you give it a go and see how you get on.
A: The only really reliable way I've found is to use Virtual PC and have an image with IE6 on it, Multiple IE or IETester don't always work exactly the same as the original versions
A: If you can publish your pages on the web, you can try http://browsershots.org/
I always use it when I have to test a new layout with almost any browser on the planet.
A: Virtual PC 2007 is the latest version of VPC. You should use the newer version if you're running Windows Vista. VPC 2004 isn't supported for Vista.
Download page for Virtual PC 2007 SP1
Microsoft Virtual VPC Homepage where you can find the latest version of VPC
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/132588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.