text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Java code to import CSV into Access I posted the code below to the Sun developers forum since I thought it was erroring (the true error was before this code was even hit). One of the responses I got said it would not work and to throw it away. But it is actually working. It might not be the best code (I am new to Java) but is there something inherently "wrong" with it?
=============
CODE:
private static void ImportFromCsvToAccessTable(String mdbFilePath, String accessTableName
, String csvDirPath , String csvFileName ) throws ClassNotFoundException, SQLException {
Connection msConn = getDestinationConnection(mdbFilePath);
try{
String strSQL = "SELECT * INTO " + accessTableName + " FROM [Text;HDR=YES;DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";
PreparedStatement selectPrepSt = msConn.prepareStatement(strSQL );
boolean result = selectPrepSt.execute();
System.out.println( "result = " + result );
} catch(Exception e) {
System.out.println(e);
} finally {
msConn.close();
}
}
A: The literal answer is no - there is never anything "inherently wrong" with code, it's a matter of whether it meets the requirements - which may or may not include being maintainable, secure, robust or fast.
The code you are running is actually a JET query purely within Access - the Java code is doing nothing except telling Access to run the query.
On the one hand, if it ain't broke don't fix it. On the other hand, there's a good chance it will break in the near future so you could try fixing it in advance.
The two likely reasons it might break are:
*
*SQL injection risk. Depending on where csvDirPath and csvFileName come from (e.g. csvFileName might come from the name of the file uploaded by a user?), and on how clever the Access JDBC driver is, you could be open to someone breaking or deleting your data by inserting a semicolon (or some brackets to make a subquery) and some additional SQL commands into the query.
*You are relying on the columns of the CSV file being compatible with the columns of the Access table. If you have unchecked CSV being uploaded, or if the CSV generator has a particular way of handling nulls, or if you one day get an unusual date or number format, you may get an error on inserting into the Access table.
Having said all that, we are all about pragmatism here. If the above code is from a utility class which you are going to use by hand a few times a week/month/year/ever, then it isn't really a problem.
If it is a class which forms part of a web application, then the 'official' Java way to do it would be to read records out of the CSV file (either using a CSV parser or a CSV/text JDBC driver), get the columns out of the recordset, do some validation or sanity checking on them, and then use a new PreparedStatement to insert them into the Access database. Much more trouble but much more robust.
You can probably find a combination of tools (e.g. object-relational layers or other data access tools) which will do a lot of that for you, but setting up the tools is going to be as much hassle as writing the code. Then again, you'll learn a lot from either one.
A: One word of warning - jdbc -> Access queries (which bridge using odbc) do not work on 64 bit systems, as there exist no 64 bit Access database drivers (The driver is included into 32 bit copies of Windows and can only be accessed by 32 bit processes. You can run "odbcad32" or look at the ODBC control panel to see that the driver is present)
While I don't see the code with the connection string in your code snippet, I am not aware of any noncommercial Access JDBC drivers for Java, only jdbc->odbc bridging and relying on Windows to have the Access (*.mdb) driver. Microsoft no longer supports this driver and has no plans to port it to 64bit, so infrastructure wise it is something to think about.
A: @david.w.fenton.myopenid.com: "Can you provide a citation about MS's plans to never introduce 64-bit ODBC drivers for Jet?"
David, I found a post on Microsoft's Connect Feedback about that.
http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=125117
"At the moment there are no plans to ship a 64-bit version of JET driver by Office team. We may considere alternate options and will update you when we have a concrete plan."
Thanks,
SSIS team.
Posted by Microsoft on 10/3/2007 at 9:47 PM
There's been no update from Microsoft in that feedback thread.
A: Question to Joshua McKinnon:
Can you provide a citation about MS's plans to never introduce 64-bit ODBC drivers for Jet? This sounds reasonable, so I'm not doubting you at all, I would just like to know if you have a source for it that you can point to.
Surely MS is providing access to Jet on 64-bit systems through OLEDB, though, right? That doesn't help with JDBC, but certainly provides a method to use Jet data (they have to provide something, since Jet 4 is part of the OS, as it is used as the data store for Active Directory, and has been used thus since Windows 2000).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I create a draggable and resizable JavaScript popup window? I want to create a draggable and resizable window in JavaScript for cross browser use, but I want to try and avoid using a framework if I can.
Has anyone got a link or some code that I can use?
A: JQuery would be a good way to go. And with the Jquery UI plugins (such as draggable), it's a breeze.. (there's a demo here).
Not using a framework, to keep it 'pure', seems just a waste of time to me. There's good stuff, that will save you tremendous amounts of time, time better spent in making your application even better.
But you can always check out the source to get some 'inspiration', and adapt it without the overhead of the stuff you won't use. It's well done and easy to read, and you often discover some cross-browser hacks you didn't even think about..
edit: oh, if you REALLY don't wan't no framework EVER, just check out their source then.. sure you can use some of it for your application.
A: JQuery is more focused on a lot of nice utility functions, and makes DOM manipulation a whole lot easier. Basically, I consider it to be Javascript as it should have been. It's a supremely helpful addition to the Javascript language itself.
ExtJS is a suite of GUI components with specific APIs... Use it if you want to easily create components that look like that, otherwise, go with a more flexible framework.
A: Sometimes you can't choose your environment or architecture, so you're stuck working within constraints like not being able to use frameworks...
A: Avoiding a framework altogether will leave you with lots of code and a bunch of tedious browser-testing.
If you would consider a framework I'd suggest jQuery with the jqDnR plugin. I think it will solve your problem or perhaps you could combine the functionality of the jQuery draggables with the jQuery resizables
A: Just trying to avoid large framework downloads to the client for one very small thing, perhaps I am being daft.
I had looked at jQuery but also ExtJS, the documentation and UI 'look' seem far superior and professional in ExtJS ... are there particular reasons for you guys recommending jQuery?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to unit test an object with database queries I've heard that unit testing is "totally awesome", "really cool" and "all manner of good things" but 70% or more of my files involve database access (some read and some write) and I'm not sure how to write a unit test for these files.
I'm using PHP and Python but I think it's a question that applies to most/all languages that use database access.
A: I would suggest mocking out your calls to the database. Mocks are basically objects that look like the object you are trying to call a method on, in the sense that they have the same properties, methods, etc. available to caller. But instead of performing whatever action they are programmed to do when a particular method is called, it skips that altogether, and just returns a result. That result is typically defined by you ahead of time.
In order to set up your objects for mocking, you probably need to use some sort of inversion of control/ dependency injection pattern, as in the following pseudo-code:
class Bar
{
private FooDataProvider _dataProvider;
public instantiate(FooDataProvider dataProvider) {
_dataProvider = dataProvider;
}
public getAllFoos() {
// instead of calling Foo.GetAll() here, we are introducing an extra layer of abstraction
return _dataProvider.GetAllFoos();
}
}
class FooDataProvider
{
public Foo[] GetAllFoos() {
return Foo.GetAll();
}
}
Now in your unit test, you create a mock of FooDataProvider, which allows you to call the method GetAllFoos without having to actually hit the database.
class BarTests
{
public TestGetAllFoos() {
// here we set up our mock FooDataProvider
mockRepository = MockingFramework.new()
mockFooDataProvider = mockRepository.CreateMockOfType(FooDataProvider);
// create a new array of Foo objects
testFooArray = new Foo[] {Foo.new(), Foo.new(), Foo.new()}
// the next statement will cause testFooArray to be returned every time we call FooDAtaProvider.GetAllFoos,
// instead of calling to the database and returning whatever is in there
// ExpectCallTo and Returns are methods provided by our imaginary mocking framework
ExpectCallTo(mockFooDataProvider.GetAllFoos).Returns(testFooArray)
// now begins our actual unit test
testBar = new Bar(mockFooDataProvider)
baz = testBar.GetAllFoos()
// baz should now equal the testFooArray object we created earlier
Assert.AreEqual(3, baz.length)
}
}
A common mocking scenario, in a nutshell. Of course you will still probably want to unit test your actual database calls too, for which you will need to hit the database.
A: The book xUnit Test Patterns describes some ways to handle unit-testing code that hits a database. I agree with the other people who are saying that you don't want to do this because it's slow, but you gotta do it sometime, IMO. Mocking out the db connection to test higher-level stuff is a good idea, but check out this book for suggestions about things you can do to interact with the actual database.
A: I usually try to break up my tests between testing the objects (and ORM, if any) and testing the db. I test the object-side of things by mocking the data access calls whereas I test the db side of things by testing the object interactions with the db which is, in my experience, usually fairly limited.
I used to get frustrated with writing unit tests until I start mocking the data access portion so I didn't have to create a test db or generate test data on the fly. By mocking the data you can generate it all at run time and be sure that your objects work properly with known inputs.
A: Options you have:
*
*Write a script that will wipe out database before you start unit tests, then populate db with predefined set of data and run the tests. You can also do that before every test – it'll be slow, but less error prone.
*Inject the database. (Example in pseudo-Java, but applies to all OO-languages)
class Database {
public Result query(String query) {... real db here ...}
}
class MockDatabase extends Database {
public Result query(String query) {
return "mock result";
}
}
class ObjectThatUsesDB {
public ObjectThatUsesDB(Database db) {
this.database = db;
}
}
now in production you use normal database and for all tests you just inject the mock database that you can create ad hoc.
*Do not use DB at all throughout most of code (that's a bad practice anyway). Create a "database" object that instead of returning with results will return normal objects (i.e. will return User instead of a tuple {name: "marcin", password: "blah"}) write all your tests with ad hoc constructed real objects and write one big test that depends on a database that makes sure this conversion works OK.
Of course these approaches are not mutually exclusive and you can mix and match them as you need.
A: Unit testing your database access is easy enough if your project has high cohesion and loose coupling throughout. This way you can test only the things that each particular class does without having to test everything at once.
For example, if you unit test your user interface class the tests you write should only try to verify the logic inside the UI worked as expected, not the business logic or database action behind that function.
If you want to unit test the actual database access you will actually end up with more of an integration test, because you will be dependent on the network stack and your database server, but you can verify that your SQL code does what you asked it to do.
The hidden power of unit testing for me personally has been that it forces me to design my applications in a much better way than I might without them. This is because it really helped me break away from the "this function should do everything" mentality.
Sorry I don't have any specific code examples for PHP/Python, but if you want to see a .NET example I have a post that describes a technique I used to do this very same testing.
A: You could use mocking frameworks to abstract out the database engine. I don't know if PHP/Python got some but for typed languages (C#, Java etc.) there are plenty of choices
It also depends on how you designed those database access code, because some design are easier to unit test than other like the earlier posts have mentioned.
A: I agree with the first post - database access should be stripped away into a DAO layer that implements an interface. Then, you can test your logic against a stub implementation of the DAO layer.
A: Ideally, your objects should be persistent ignorant. For instance, you should have a "data access layer", that you would make requests to, that would return objects. This way, you can leave that part out of your unit tests, or test them in isolation.
If your objects are tightly coupled to your data layer, it is difficult to do proper unit testing. The first part of unit test, is "unit". All units should be able to be tested in isolation.
In my C# projects, I use NHibernate with a completely separate Data layer. My objects live in the core domain model and are accessed from my application layer. The application layer talks to both the data layer and the domain model layer.
The application layer is also sometimes called the "Business Layer".
If you are using PHP, create a specific set of classes ONLY for data access. Make sure your objects have no idea how they are persisted and wire up the two in your application classes.
Another option would be to use mocking/stubs.
A: I've never done this in PHP and I've never used Python, but what you want to do is mock out the calls to the database. To do that you can implement some IoC whether 3rd party tool or you manage it yourself, then you can implement some mock version of the database caller which is where you will control the outcome of that fake call.
A simple form of IoC can be performed just by coding to Interfaces. This requires some kind of object orientation going on in your code so it may not apply to what your doing (I say that since all I have to go on is your mention of PHP and Python)
Hope that's helpful, if nothing else you've got some terms to search on now.
A: Setting up test data for unit tests can be a challenge.
When it comes to Java, if you use Spring APIs for unit testing, you can control the transactions on a unit level. In other words, you can execute unit tests which involves database updates/inserts/deletes and rollback the changes. At the end of the execution you leave everything in the database as it was before you started the execution. To me, it is as good as it can get.
A: The easiest way to unit test an object with database access is using transaction scopes.
For example:
[Test]
[ExpectedException(typeof(NotFoundException))]
public void DeleteAttendee() {
using(TransactionScope scope = new TransactionScope()) {
Attendee anAttendee = Attendee.Get(3);
anAttendee.Delete();
anAttendee.Save();
//Try reloading. Instance should have been deleted.
Attendee deletedAttendee = Attendee.Get(3);
}
}
This will revert back the state of the database, basically like a transaction rollback so you can run the test as many times as you want without any sideeffects. We've used this approach successfully in large projects. Our build does take a little long to run (15 minutes), but it is not horrible for having 1800 unit tests. Also, if build time is a concern, you can change the build process to have multiple builds, one for building src, another that fires up afterwards that handles unit tests, code analysis, packaging, etc...
A: I can perhaps give you a taste of our experience when we began looking at unit testing our middle-tier process that included a ton of "business logic" sql operations.
We first created an abstraction layer that allowed us to "slot in" any reasonable database connection (in our case, we simply supported a single ODBC-type connection).
Once this was in place, we were then able to do something like this in our code (we work in C++, but I'm sure you get the idea):
GetDatabase().ExecuteSQL( "INSERT INTO foo ( blah, blah )" )
At normal run time, GetDatabase() would return an object that fed all our sql (including queries), via ODBC directly to the database.
We then started looking at in-memory databases - the best by a long way seems to be SQLite. (http://www.sqlite.org/index.html). It's remarkably simple to set up and use, and allowed us subclass and override GetDatabase() to forward sql to an in-memory database that was created and destroyed for every test performed.
We're still in the early stages of this, but it's looking good so far, however we do have to make sure we create any tables that are required and populate them with test data - however we've reduced the workload somewhat here by creating a generic set of helper functions that can do a lot of all this for us.
Overall, it has helped immensely with our TDD process, since making what seems like quite innocuous changes to fix certain bugs can have quite strange affects on other (difficult to detect) areas of your system - due to the very nature of sql/databases.
Obviously, our experiences have centred around a C++ development environment, however I'm sure you could perhaps get something similar working under PHP/Python.
Hope this helps.
A: You should mock the database access if you want to unit test your classes. After all, you don't want to test the database in a unit test. That would be an integration test.
Abstract the calls away and then insert a mock that just returns the expected data. If your classes don't do more than executing queries, it may not even be worth testing them, though...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "170"
} |
Q: What is the proper virtual directory access permission level required for a SOAP web service? When setting up a new virtual directory for hosting a SOAP web service in IIS 6.0 on a Server 2003 box I am required to set the access permissions for the virtual directory. The various permissions are to allow/disallow the following:
*
*Read
*Run scripts (such as ASP)
*Execute (such as ISAPI or CGI)
*Write
*Browse
The SOAP web service is being published through the SOAP3.0 ISAPI server with the extensions set to "Allowed" in the Web Service Extensions pane of the IIS Manager.
Since I don't want to expose the contents of this directory to the web I know Browse is not desirable. But, I don't know if I need to have the Run scripts, Execute, and Write permissions enabled to properly publish this web service. The web service is being used to send and receive XML data sets between the server and remote clients. What is the correct level of access permission for my SOAP web service's virtual directory?
A: Upon further examination, I've come to the conclusion that one assumption I had about needing Read permissions was incorrect.
SOAP web services only need the "Run scripts" permission enabled because the .wsdl apparently comes from the web service in the form of a script execution response. So the minimum required for a SOAP3.0 web service's directory is Run scripts.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: C# Performance For Proxy Server (vs C++) I want to create a simple http proxy server that does some very basic processing on the http headers (i.e. if header x == y, do z). The server may need to support hundreds of users. I can write the server in C# (pretty easy) or c++ (much harder). However, would a C# version have as good of performance as a C++ version? If not, would the difference in performance be big enough that it would not make sense to write it in C#?
A: You can use unsafe C# code and pointers in critical bottleneck points to make it run faster. Those behave much like C++ code and I believe it executes as fast.
But most of the time, C# is JIT-ted to uber-fast already, I don't believe there will be much differences as with what everyone has said.
But one thing you might want to consider is: Managed code (C#) string operations are rather slow compared to using pointers effectively in C++. There are more optimization tricks with C++ pointers than with CLR strings.
I think I have done some benchmarks before, but can't remember where I've put them.
A: Why do you expect a much higher performance from the C++ application?
There is no inherent slowdown added by a C# application when you are doing it right. (not too many dropped references, frequent object creation/dropping per call, etc.)
The only time a C++ application really outperforms an equivalent C# application is when you can do (very) low level operations. E.g. casting raw memory pointers, inline assembler, etc.
The C++ compiler may be better at creating fast code, but mostly this is wasted in most applications. If you do really have a part of your application that must be blindingly fast, try writing a C call for that hot spot.
Only if most of the system behaves too slowly you should consider writing it in C/C++. But there are many pitfalls that may kill your performance in your C++ code.
(TLDR: A C++ expert may create 'faster' code as an C# expert, but a mediocre C++ programmer may create slower code than mediocre C# one)
A: I would expect the C# version to be nearly as fast as the C++ one but with smaller memory footprint.
In some cases managed code is actually a LOT faster and uses less memory compared to non optimized C++. C++ code can be faster if written by expert, but it rarely justifies the effort.
As a side note I can recall a performance "competition" in the blogosphere between Michael Kaplan (c#) and Raymond Chan (C++) to write a program, that does exactly the same thing. Raymond Chan, who is considered one of the best programmers in the world (Joel) succeeded to write faster C++ after a long struggle rewriting most of the code.
A: The proxy server you describe would deal mostly with string data and I think its reasonable to implement in C#. In your example,
if header x == y, do z
the slowest part might actually be doing whatever 'z' is and you'll have to do that work regardless of the language.
A: In my experience, the design and implementation has much more to do with performance than do the choice of language/framework (however, the usual caveats apply: eg, don't write a device driver in C# or java).
I wouldn't think twice about writing the type of program you describe in a managed language (be it Java, C#, etc). These days, the performance gains you get from using a lower level language (in terms of closeness to hardware) is often easily offset by the runtime abilities of a managed environment. Of course this is coming from a C#/python developer so I'm not exactly unbiased...
A: If you need a fast and reliable proxy server, it might make sense to try some of those that already exist. But if you have custom features that are required, then you may have to build your own. You may want to collect some more information on the expected load: hundreds of users might be a few requests a minute or a hundred requests a second.
Assuming you need to serve under or around 200 qps on a single machine, C# should easily meet your needs -- even languages known for being slow (e.g. Ruby) can easily pump out a few hundred requests a second.
Aside from performance, there are other reasons to choose C#, e.g. it's much easier to write buffer overflows in C++ than C#.
A: Is your http server going to run on a dedicated machine? If yes, I would say go with C# if it is easier for you. If you need to run other applications on the same machine, you'll need to take into account the memory footprint of your application and the fact that GC will run at "random" times.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I configure an ASP.NET MVC project to work with Boo I want to build an ASP.NET MVC application with Boo instead of C#. If you know the steps to configure this type of project setup, I'd be interested to know what I need to do.
The MVC project setup is no problem. What I'm trying to figure out how to configure the pages and project to switch to use the Boo language and compiler.
A: So there are two levels of "work with Boo". One would be all the code (namely, the Controllers), and the other would be the views.
For the code, I assume Boo compiles to standard .NET assemblies, so simply properly following the naming conventions using by ASP.NET MVC should allow you to write Controllers. You will probably need to start with a C# or VB version of the MVC web application project template and port some of the boilerplate code over into Boo to get the solution entirely in Boo (I presume Boo supports Web Application projects?).
The other half is views. Someone will need to port the Brail view engine over to the ASP.NET MVC view engine system. This may already be done, but I don't know for sure. If it's not, then this is probably a significant amount of work to be done.
Probably the best place to get answers to these kinds of questions is the MvcContrib community on CodePlex.
A: The Brail view engine has been implemented to be used in ASP.NET MVC. The MvcContrib project implemented the code. The source code is located on Google Code.
As far as the controllers, I really am not sure. I am not that familiar with Boo. I know a lot of developers use it for configuration instead of using xml for instance. My tips would be, if Boo can inherit off the Controller base class and you stick to the naming conventions, you should be alright. If you vary off the naming conventions, well you would need to implement your own IControllerFactory to instantiate the boo controllers as the requests come in.
I have been following the ASP.NET MVC bits since the first CTP and through that whole time, I have not seen somebody use Boo to code with. I think you will be the first to try to accomplish this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Performance vs Readability Reading this question I found this as (note the quotation marks) "code" to solve the problem (that's perl by the way).
100,{)..3%!'Fizz'*\5%!'Buzz'*+\or}%n*
Obviously this is an intellectual example without real (I hope to never see that in real code in my life) implications but, when you have to make the choice, when do you sacrifice code readability for performance? Do you apply just common sense, do you do it always as a last resort? What are your strategies?
Edit: I'm sorry, seeing the answers I might have expressed the question badly (English is not my native language). I don't mean performance vs readability only after you've written the code, I ask about before you write it as well. Sometimes you can foresee a performance improvement in the future by making some darker design or providing with some properties that will make your class darker. You may decide you will use multiple threads or just a single one because you expect the scalability that such threads may give you, even when that will make the code much more difficult to understand.
A: I always start with the most readable version I can think of. If performance is a problem, I refactor. If the readable version makes it hard to generalize, I refactor.
The key is to have good tests so that refactoring is easy.
I view readability as the #1 most important issue in code, though working correctly is a close second.
A: Readability is most important. With modern computers, only the most intensive routines of the most demanding applications need to worry too much about performance.
A: My favorite answer to this question is:
*
*Make it work
*Make it right
*Make it fast
In the scope of things no one gives a crap about readability except the next unlucky fool that has to take care of your code. However, that being said... if you're serious about your art, and this is an art form, you will always strive to make your code the most per formant it can be while still being readable by others. My friend and mentor (who is a BADASS in every way) once graciously told me on a code-review that "the fool writes code only they can understand, the genius writes code that anyone can understand." I'm not sure where he got that from but it has stuck with me.
Reference
A:
Programs must be written for people to read, and only incidentally for
machines to execute. — Abelson & Sussman, SICP
Well written programs are probably easier to profile and hence improve performance.
A: You should always go for readability first. The shape of a system will typically evolve as you develop it, and the real performance bottlenecks will be unexpected. Only when you have the system running and can see real evidence - as provided by a profiler or other such tool - will the best way to optimise be revealed.
"If you're in a hurry, take the long way round."
A: agree with all the above, but also:
when you decide that you want to optimize:
*
*Fix algorithmic aspects before syntax (for example don't do lookups in large arrays)
*Make sure that you prove that your change really did improve things, measure everything
*Comment your optimization so the next guy seeing that function doesn't simplify it back to where you started from
*Can you precompute results or move the computation to where it can be done more effectively (like a db)
in effect, keep readability as long as you can - finding the obscure bug in optimized code is much harder and annoying than in the simple obvious code
A: My process for situations where I think performance may be an issue:
*
*Make it work.
*Make it clear.
*Test the performance.
*If there are meaningful performance issues: refactor for speed.
Note that this does not apply to higher-level design decisions that are more difficult to change at a later stage.
A: I apply common sense - this sort of thing is just one of the zillion trade-offs that engineering entails, and has few special characteristics that I can see.
But to be more specific, the overwhelming majority of people doing weird unreadable things in the name of performance are doing them prematurely and without measurement.
A: Choose readability over performance unless you can prove that you need the performance.
A: I would say that you should only sacrifice readability for performance if there's a proven performance problem that's significant. Of course "significant" is the catch there, and what's significant and what isn't should be specific to the code you're working on.
A: "Premature optimization is the root of all evil." - Donald Knuth
A: Readability always wins. Always. Except when it doesn't. And that should be very rarely.
A: at times when optimization is necessary, i'd rather sacrifice compactness and keep the performance enhancement. perl obviously has some deep waters to plumb in search of the conciseness/performance ratio, but as cute as it is to write one-liners, the person who comes along to maintain your code (who in my experience, is usually myself 6 months later) might prefer something more in the expanded style, as documented here:
http://www.perl.com/pub/a/2004/01/16/regexps.html
A: There are exceptions to the premature optimization rule. For example, when accessing an image in memory, reading a pixel should not be an out-of-line function. And when providing for custom operations on the image, never do it like this:
typedef Pixel PixelModifierFunction(Pixel);
void ModifyAllPixels(PixelModifierFunction);
Instead, let external functions access the pixels in memory, though it's uglier. Otherwise, you are sure to write slow code that you'll have to refactor later anyway, so you're doing extra work.
At least, that's true if you know you're going to deal with large images.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Understanding Interfaces I have class method that returns a list of employees that I can iterate through. What's the best way to return the list? Typically I just return an ArrayList. However, as I understand, interfaces are better suited for this type of action. Which would be the best interface to use? Also, why is it better to return an interface, rather than the implementation (say ArrayList object)? It just seems like a lot more work to me.
A: Personally, I would use a List<Employee> for creating the list on the backend, and then use IList when you return. When you use interfaces, it gives you the flexability to change the implementation without having to alter who's using your code. If you wanted to stick with an ArrayList, that'd be a non-generic IList.
A: @ Jason
You may as well return IList<> because an array actually implements this interface.
A: The best way to do something like this would be to return, as you say, a List, preferably using generics, so it would be List<Employee>.
Returning a List rather than an ArrayList means that if later you decide to use, say, a LinkedList, you don't have to change any of the code other than where you create the object to begin with (i.e, the call to "new ArrayList())".
A: If all you are doing is iterating through the list, you can define a method that returns the list as IEnumerable (for .NET).
By returning the interface that provides just the functionality you need, if some new collection type comes along in the future that is better/faster/a better match for your application, as long as it still implements IEnumerable you can completely rewrite your method, using the new type inside it, without changing any of the code that calls it.
A: Is there any reason the collection needs to be ordered? Why not simply return an IEnumerable<Employee>? This gives the bare minimum that is required - if you later wanted some other form of storage, like a Bag or Set or Tree or whatnot, your contract would remain intact.
A: I disagree with the premise that it's better to return an interface. My reason is that you want to maximize the usefulness a given block of code exposes.
With that in mind, an interface works for accepting an item as an argument. If a function parameter calls for an array or an ArrayList, that's the only thing you can pass to it. If a function parameter calls for an IEnumerable it will accept either, as well as a number of other objects. It's more useful
The return value, however, works opposite. When you return an IEnumerable, the only thing you can do is enumerate it. If you have a List handy and return that then code that calls your function can also easily do a number of other things, like get a count.
I stand united with those advising you to get away from the ArrayList, though. Generics are so much better.
A: Return type for your method should be IList<Employee>.
That means that the caller of your method can use anything that IList offers but cannot use things specific to ArrayList. Then if you feel at some point that LinkedList or YourCustomSuperDuperList offers better performance or other advantages you can safely use it within your method and not screw callers of it.
That's roughly interfaces 101. ;-)
A: An interface is a contract between the implementation and the user of the implementation.
By using an interface, you allow the implementation to change as much as it wants as long as it maintains the contract for the users.
It also allows multiple implementations to use the same interface so that users can reuse code that interacts with the interface.
A: You don't say what language you're talking about, but in something .NETish, then it's no more work to return an IList than a List or even an ArrayList, though the mere mention of that obsolete class makes me think you're not talking about .NET.
A: An interface is essentially a contract that a class has certain methods or attributes; programming to an interface rather then a direct implementation allows for more dynamic and manageable code, as you can completely swap out implementations as long as the "contract" is still held.
In the case you describe, passing an interface does not give you a particular advantage, if it were me, I would pass the ArrayList with the generic type, or pass the Array itself: list.toArray()
A: Actually you shouldn't return a List if thats a framework, at least not without thinking it, the recommended class to use is a Collection. The List class has some performance improvements at the cost of server extendability issues. It's in fact an FXCop rule.
You have the reasoning for that in this article
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Update Panel inside of a UserControl inside of a Repeater inside of another UpdatePanel Yes, it sounds crazy....It might be.
The final updatepanel does not appear to trigger anything, it just refreshes the update panels and does not call back to the usercontrol hosting it.
Any ideas?
EDIT: I got it posting back, however the controls inside the final usercontrol have lost their data...I'm thinking its because the main repeater is rebinding on each postback...Not sure where to take this one now.
A: I would suggest you start by removing the UpdatePanels at first, and make sure your control orgy is working correctly with postbacks. Once you have that working, try adding the UpdatePanels back in from the bottom up.
A: If you set the UpdateMode property to Conditional (default is Always) on both UpdatePanels it should stop the outer UpdatePanel triggering when only the usercontrols updatepanel should have refreshed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NHibernate and Oracle connect through Windows Authenication How do I use Windows Authentication to connect to an Oracle database?
Currently, I just use an Oracle Username and password, however, a requirement is to give the user on install the option of selecting Windows Authentication since we offer the same as SQL.
A: You need to modify the AUTHENTICATION_SERVICES entry in SQLNET.ORA to this:
SQLNET.AUTHENTICATION_SERVICES= (NTS)
As well, you will need to setup the accounts in Oracle to match the Windows accounts. Have a look at http://www.dba-oracle.com/bk_sqlnet_authentication_services.htm for more details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I retrieve data sent to the web server in ASP.NET? What are the ways to retrieve data submitted to the web server from a form in the client HTML in ASP.NET?
A: You can also search through both the Form and QueryString collections at the same time so that the data will be found regardless of the the request method.
value = Request("formElementID")
A: In VB.NET
For POST requests:
value = Request.Form("formElementID")
For GET requests:
value = Request.QueryString("formElementID")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In Exchange (2003) how do I list the forms used in the public folder tree? Does anyone have a script or can anyone point me in the right direction to query an Exchange (2003) public folder tree to determine all the forms being used ?
I need an output of form object/display name and count for each form type in each folder.
A: You can give Redemption a try. It should be suitable for what you need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a Way to use Linq to Oracle I can connect with the DataContext to the Oracle database however I get errors in running the query against the oracle database. I looked at the SQL generated and it is for MSSQL and not Oracle PSQL.
Does anybody know of a decent easy to use wrapper to use LINQ against an Oracle Database?
A: One thing you might look into is that there is now LINQ to Entities, which leverages the MS Entity Framework, which I believe is DB agnostic. I'm still looking into how it works myself, but if you could create an ADO.NET Data Entity that interfaces with Oracle, you could then use LINQ against that Entity.
A: There's also Lightspeed which has a per-organization (not per-developer) license scheme and seems to have a pretty solid documentation library and a free trial version (up to 8 entities). I'm checking this out presently.
A: After a long search I found DbLinq and should do the trick. I am going to try it myself. I came across your question because I was searching for the same solution. Hope it helps.
A: Do look at Linq to entities though. I have a datareader populate a collection of objects that are mapped to the oracle table. I can use linq to query that collection in very powerful, simple, and easy ways. I love it. Highly recommend.
A: Try Devart LinqConnect. This product allows you to work with Oracle, etc.
A: Why not try ALinq ? http://www.alinq.org
A: No, LINQ to SQL is very much MS SQL only - think of it as a client driver.
Microsoft is/was helping Oracle and DataDirect develop providers for Oracle and other non-MS database servers.
A: We use the OraDirect driver from Devart. It includes ADO.NET Entity framework support. You can download a trial version here. You may then use LINQ to entities or entity SQL on top of this.
The pricing of this is quite developer friendly, you pay per developer seat and you may use it however you like.
Another big advantage of this driver is that you can use it without installing an Oracle client, this is a big plus and worth the price alone.
@Greg: We evaluated the datadirect drivers as well, but the performance was poor and cost astronomical.
Edit: It seems DevArt announced a beta with LINQ support recently
A: Look in codeplex:
Linq To Oracle project
A: Not an easy way, at least until a good provider is produced.
Really MS should provide at least an OLEDB Linq provider. After all, Linq to Sql is basically an implementation of IQueryable with designer support.
A: Another cross-database solution that works fairly well across Oracle, SQLite, MySQL and SQL Server is eXpress Persistent Objects
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: How can I authenticate using client credentials in WCF just once? What is the best approach to make sure you only need to authenticate once when using an API built on WCF?
My current bindings and behaviors are listed below
<bindings>
<wsHttpBinding>
<binding name="wsHttp">
<security mode="TransportWithMessageCredential">
<transport/>
<message clientCredentialType="UserName" negotiateServiceCredential="false" establishSecurityContext="true"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="NorthwindBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceAuthorization principalPermissionMode="UseAspNetRoles"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="MembershipProvider"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
Next is what I am using in my client app to authenticate (currently I must do this everytime I want to make a call into WCF)
Dim client As ProductServiceClient = New ProductServiceClient("wsHttpProductService")
client.ClientCredentials.UserName.UserName = "foo"
client.ClientCredentials.UserName.Password = "bar"
Dim ProductList As List(Of Product) = client.GetProducts()
What I would like to do is auth w/ the API once using these credentials, then get some type of token for the period of time my client application is using the web service project. I thought establishsecuritycontext=true did this for me?
A: If you're on an intranet, Windows authentication can be handled for "free" by configuration alone.
If this isn't appropriate, token services work just fine, but for some situations they may be just too much.
The application I'm working on needed bare-bones authentication. Our server and client run inside a (very secure) intranet, so we didn't care too much for the requirement to use an X.509 certificate to encrypt the communication, which is required if you're using username authentication.
So we added a custom behavior to the client that adds the username and (encrypted) password to the message headers, and another custom behavior on the server that verifies them.
All very simple, required no changes to the client side service access layer or the service contract implementation. And as it's all done by configuration, if and when we need to move to something a little stronger it'll be easy to migrate.
A: While I hate to give an answer I'm not 100% certain of, the lack of responses so far makes me think a potentially correct answer might be okay in this case.
As far as I'm aware there isn't the kind of session token mechanism you're looking for out-of-the-box with WCF which means you're going to have to do some heavy lifting to get things working in the way you want. I should make it clear there is a session mechanism in WCF but it's focused on guaranteeing message orders and is not the ideal tool for creating an authentication session.
I just finished working on a project where we implemented our own session mechanism to handle all manner of legacy SOAP stacks, but I believe the recommended way to implement authenticated sessions is to use a Secure Token Service (STS) like Pablo Cibraro's.
If you want more details please shout, but I suspect Pablo's blog will have more than enough info for you to steam ahead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Should I use Google Web Toolkit for my new webapp? I would like to create a database backed interactive AJAX webapp which has a custom (specific kind of events, editing) calendaring system. This would involve quite a lot of JavaScript and AJAX, and I thought about Google Web Toolkit for the interface and Ruby on Rails for server side.
Is Google Web Toolkit reliable and good? What hidden risks might be if I choose Google Web Toolkit? Can one easily combine it with Ruby on Rails on server side? Or should I try to use directly a JavaScript library like jQuery?
I have no experience in web development except some HTML, but I am an experienced programmer (c++, java, c#), and I would like to use only free tools for this project.
A: If you are looking to integrate GWT with non-Java backends such as ROR, PHP etc., you should bear in mind that GWT 1.5 now supports JavaScript Overlay types. This feature lets you write classes that can be mapped over the top of native JavaScript objects to easily provide accessor methods for properties of those objects and other extended functionality.
See this link for more details:
JavaScript Overlay Types
So you could return JSON encoded data from your backend via AJAX calls, parse it into a JavaScript Object and then access the data through your GWT Java code using the overlay classes you've created. Or when you render your page you can render static config data as JavaScript Objects and read it in via this mechanism, rather than having to do an AJAX call to grab the data.
A: If you know JAVA, and have somewhere you can host it (like a tomcat or glassfish container) I would recommend that much more than using Ruby for the back end. The main reason is that then you can share all of your objects, and use the built in RPC mechanism. I've done this for quite a lot of our projects and it's a huge timesaver, not to mention that the code is less error prone, because you don't convert your java objects to anything and then back again.
I have linked my GWT with Rails before, using the to_json function in Rails and then reading the JSON in GWT. It's all supported, but it is far more annoying than just doing the back end in JAVA.
Of course if you have cheap hosting, then Java containers are pretty much out of the question, in which case I would think Rails would be the next best thing.
A: GWT is very high quality with a great community. However you do need to know CSS if you want to adjust the look of things (you will) - CSS can do a lot of the layout, just like regular web if you want it to. Libraries like GWT-ext or ExtGWT can help a bit as they have stunning "out of the box" looks but for a price (extra size to your app).
A: RoR is actually one of the things the GWT is made to work well with, as long as you're using REST properly. It's in the Google Web Toolkit Applications book, and you can see a demo from the book using this kind of idea here. That's not to say that you won't have any problems, but I think the support is definitely out there for it.
There's a neat project for making RoR/GWT easy that you can find here (MIT license). I haven't had a chance to try it out yet, but it looks like a good amount of thought has been put into it. One catch is that it looks like it hasn't been fully tested with 2.1 Rails yet, just 2.0, so you may run into a few (probably minor and fixable) errors.
A: You can code everything in Java using GWT, and you can integrate existing 3rd party javascript libraries with it. It's very good. I've never used RoR much though, so can't say anything about that.
A: If you're experienced in Java but not in Javascript/CSS, then GWT is going to be a lifesaver (unless you want to learn them, of course). CSS has so many little fiddly details. It is not uncommon to spend half a day fixing a 2 pixel misalignment that only occurs in IE6.
I am not sure about how easy it would be to use ROR for the back end... It is possible, I am sure, since GWT ajax communication is just servlets. But they provide some really nice functionality for passing Java objects back and forth which you won't be able to utilize if your server isn't also using Java.
A: I wrote about some of the disadvantages of GWT recently. Mainly, the disadvantages are: long deployment cycle for changes to some parts of the application and a rather steep learning curve. As a seasoned Java programmer, the second should be less of a problem and if you use a seperate backend, the first is also mitigated (as a complete redeploy is primarily required when you change the 'server' part of the application).
A: GWT is a wonderful framework with lots of potential. Keep in mind that it's still quite new, though. There are some unresolved bugs that can really annoy you, and they usually require ugly workarounds to get past. The community is great but you'll probably end up with a few problems sooner or later that Google can't answer yet.
But hey, I say go for it. The potential for GWT is awesome, and I bet it's future will be bright.
A: You should definitely use GWT for a new project (it's pretty easy to use in an old project too).
I my experience it's very fast to learn and use. The compiled javascript code is much better than anything you could ever write by hand and it works fast too.
Another benefit is the ability to debug you're code (which is hell with javascript alone)
A: This blog has inputs from many experienced users of GWT and have some great discussion points. I personally have huge experience with varied UI Frameworks. I will add my two cents. Lets look at fundamental advantages and disadvantages of GWT
Fundamental Advantage
GWT takes the web layer programming to JAVA. So, the obvious advantages of Java start getting into play. It will provide Object Oriented programming. It will also provide great debugging and compile time checks. Since it generates HTML and Javascript, it will also have ability to hide some complexity within its generator.
Fundamental Disadvantage
The disadvantage starts from the same statement. GWT takes the web layer programming to JAVA. If you know JAVA, probably you will never look out for an alternative language to write your business logic. It's self sufficient and great. But when it comes to writing configurations for a JAVA application. We use property files, database, XML etc. We never store configurations in a JAVA class file. Think hard, why is that?
This is because configuration is a static data. It often require hierarchy. It is supposed to be readable. It never requires compilation. It doesn't require knowledge of JAVA programming language. In short, it is a different ball game. Now the question is, how it relates to our discussion?
Now, lets think about a web page. Do you think when we write a web page we write a business logic? Absolutely not. Web page is just a configuration. It is a configuration of hierarchical containers and fields. We need to write business logic for the data that will be captured from and displayed on the web page and not to create the web page itself.
Previous paragraph makes a very very strong statement. This will explain why HTML and XML based web pages are still the most popular ones. XML is the best in business to write configurations. A framework must allow a clear separation of web page from business logic (the goal of MVC framework). By doing this a web designer will be able to apply his skills of visualization and artistry to create brilliant looking web pages just by configuring XMLs and without being bothered about the intricacies of a programming language. Developers will be able to use their best in business JAVA for writing business logic.
Finally, lets talk about the repercussions in direct terms. GWT breaks this principal so it is bound to fail. The cost for developing GWT application will be very high because you will need multiskill programmers to write web pages. The required look and feel will be very hard to achieve. The turn around time of modifying the web page will be very high because of unnecessary compilation. And lastly, since you are writing web pages in JAVA it is very easy to corrupt it with business logic. Unknowingly you will introduce complexities that must be avoided.
A: You could also consider Grails ("Groovy on Rails") which gives you the benefits of a Rails framework and the use of the Java VM.
A: Our team recently asked the same question, and we chose to go with GWT, especially since the designer plugin made working with GWT more accessible to non-java experts on the team. Whoever makes this choice, just beware you DON'T use the GWT Designer plugin !! It has not been updated (in at least a year, apparently) to create a GWT application that is compatible with IE8.
Our team had almost completed our application layouts, which were working perfectly in Chrome, FF and Safari. Then they blew up in IE. IE 7 would load partial pages (but not composite includes), and IE8 was not even able to load up the application. It just hung.
The designer plugin has buttons that allow the user to add CellTable widgets that are not IE compatible (CellTable, DeckPanel, Horizontal Panel, Vertical Panel, among others). These will cause intense pain when the layouts have to be re-done in java without assistance from the designer.
Experienced GWT users love it, but the designer plugin will kill you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Compile a referenced dll Using VS2005 and VB.NET.
I have a project that is an API for a data-store that I created. When compiled creates api.dll.
I have a second project in the same solution that has a project reference to the API project which when compiled will create wrapper.dll. This is basically a wrapper for the API that is specific to an application.
When I use wrapper.dll in that other application, I have to copy wrapper.dll and api.dll to my new application. How can I get the wrapper project to compile the api.dll into itself so that I only have one dll to move around?
A: You'll probably have to use a tool, such as ILMerge, to merge the two assemblies.
A: There's an easier way. Just create shortcuts (called linked files in Visual Studio-ese) in your wrapper.dll project that point to the source files in api.dll. That will compile your source directly into wrapper.dll.
A: @Jas, it's a special feature in Visual Studio. The procedure is outlined in this blog entry, called "Sharing a Strong Name Key File Across Projects". The example is for sharing strong name key files, but will work for any kind of file.
Briefly, you right-click on your project and select "Add Existing Item". Browse to the directory of the file(s) you want to link and highlight the file or files. Insted of just hitting "Add" or "Open" (depending on your version of Visual Studio), click on the little down arrow on the right-hand side of that button. You'll see options to "Open" or "Link File" if you're using Visual Studio 2003, or "Add" or "Add as Link" with 2005 (I'm not sure about 2008). In any case, choose the one that involves the word "Link". Then your project will essentially reference the file - it will be accessible both from the original project its was in and the project you "linked" it to.
This is a convenient way to create an assembly that contains all the functionality of wrapper.dll and api.dll, but you'll have to remember to repeat this procedure every time you add a new file to api.dll (but not wrapper.dll).
A: I think you could compile api.dll as a resource into wrapper.dll. Then manually access that Resource out of api.dll and manually load it. I have manually loaded assemblies from disk, so loading one from a Stream should not be any different.
I would try including the dll in your project as a file, similar to including a text or xml file (in addition to its project reference for compilation). Then I would set the build action to "Embedded Resource." Within wrapper.dll, I would use the Assembly object to access api.dll just like any other embedded resource. You will then also want to load the assembly using Assembly.Load http://msdn.microsoft.com/en-us/library/system.reflection.assembly.load.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Source Versioning for Visual Studio Express Is there any Visual Studio Express plug ins for source versioning? I am starting a project on my own and only have the Express version of Visual Studio 2008.
A: You don't really need an integration/plugin. First is not supported but there are very good alternatives to make it work.
Whatever SCM you decide to use (SVN, GIT, PlasticSCM, Mercurial) just use the "find changes" workflow:
*
*Do your changes
*Find your modifications within the tool you've chosen to use
*Commit
http://codicesoftware.blogspot.com/2009/12/how-to-find-changes-on-plastic-scm.html
Edit: PlasticSCM is free for up to 15 users since Nov 1st 2010.
A: Visual studio 2012 Express offers an express version of Team Foundation Server.
A: Way I do this is I have TortosieHG installed and then in visual studios express i went to Tools>External Tools.
I created the following enteries:
Title: HG New Repositry
Command: C:\Program Files\TortoiseHg\hgtk.exe
Arguments: --nofork init Initial
directory: $(SolutionDir)
Title: HG Commit
Command: C:\Program Files\TortoiseHg\hgtk.exe
Arguments: --nofork init Initial directory: $(SolutionDir)
I then added the two external tools to the toolbar. Now I don't get as nice intergration as I would with the full version of visual studios but I can commit source code and create a source repository without leaving Visual Studios.
A: Source control integration is not supported in the Express editions of Visual Studio. Check out the feature comparison chart at http://msdn.microsoft.com/en-us/vstudio/products/cc149003.aspx
A: Short answer: No.
The Express editions support neither the Add-Ins nor Source Control providers (SCC plug-ins). While there are ways to make this work, they are undocumented, violate the license and have caused legal trouble before…
A: I don't think there are any plugins for Express versions of VS. Googling 'Jamie Cansdale' is the canonical reference for this issue.
A: The VisualSVN manual says it works with all editions of Visual Studio - though I have not personally tried it. I know that none of Microsoft's Team Foundation Server stuff will work with Express.
A: VisualSVN doesn't support Visual Studio Express editions. Visit here for more info http://www.visualsvn.com/visualsvn/download/
A: Interesting, does the Express edition auto-check for file updates? If so, just use TortoiseSVN and save yourself the money of upgrading.
A: You can get cloud based Team Foundation Service for free as long as your project has 5 or fewer members. I've been using it for a few months now and it works great. There are a some features of Team Foundation Server that are not available yet, but, hey, it's free.
http://tfs.visualstudio.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: How to write a regular expression pattern that is capable of validating URIs? How does one go about authoring a Regular Expression that matches against all strings that are valid URIs, while failing to match against all strings that are invalid URIs?
To be specific about what I am referencing when I say URI, I have added a link below for the most current URI RFC standard. It defines the entity that I want to validate using a regular expression.
I don't need it to be able to parse the URI. I just need a regular expression for validating.
The .Net Regular Expression Format is preferred. (.Net V1.1)
My Current Solution:
^([a-zA-Z0-9+.-]+):(//([a-zA-Z0-9-._~!$&'()*+,;=:]*)@)?([a-zA-Z0-9-._~!$&'()*+,;=]+)(:(\\d*))?(/?[a-zA-Z0-9-._~!$&'()*+,;=:/]+)?(\\?[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?(#[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?$(:(\\d*))?(/?[a-zA-Z0-9-._~!$&'()*+,;=:/]+)?(\?[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?(\#[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?$
A: The best regex I came up with according to RFC 3986 (https://www.rfc-editor.org/rfc/rfc3986) was the following:
// named groups
/^(?<scheme>[a-z][a-z0-9+.-]+):(?<authority>\/\/(?<user>[^@]+@)?(?<host>[a-z0-9.\-_~]+)(?<port>:\d+)?)?(?<path>(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@])+(?:\/(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@])*)*|(?:\/(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@])+)*)?(?<query>\?(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@]|[/?])+)?(?<fragment>\#(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@]|[/?])+)?$/i
// unnamed groups
/^([a-z][a-z0-9+.-]+):(\/\/([^@]+@)?([a-z0-9.\-_~]+)(:\d+)?)?((?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@])+(?:\/(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@])*)*|(?:\/(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@])+)*)?(\?(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@]|[/?])+)?(\#(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@]|[/?])+)?$/i
capture groups
*
*scheme
*authority
*userinfo
*host
*port
*path
*query
*fragment
A: The best and most definitive guide to this I have found is here: http://jmrware.com/articles/2009/uri_regexp/URI_regex.html (In answer to your question, see the URI table entry)
All of these rules from RFC3986 are reproduced in Table 2 along with a regular expression implementation for each rule.
A javascript implementation of this is available here: https://github.com/jhermsmeier/uri.regex
For reference, the URI regex is repeated below:
# RFC-3986 URI component: URI
[A-Za-z][A-Za-z0-9+\-.]* : # scheme ":"
(?: // # hier-part
(?: (?:[A-Za-z0-9\-._~!$&'()*+,;=:]|%[0-9A-Fa-f]{2})* @)?
(?:
\[
(?:
(?:
(?: (?:[0-9A-Fa-f]{1,4}:) {6}
| :: (?:[0-9A-Fa-f]{1,4}:) {5}
| (?: [0-9A-Fa-f]{1,4})? :: (?:[0-9A-Fa-f]{1,4}:) {4}
| (?: (?:[0-9A-Fa-f]{1,4}:){0,1} [0-9A-Fa-f]{1,4})? :: (?:[0-9A-Fa-f]{1,4}:) {3}
| (?: (?:[0-9A-Fa-f]{1,4}:){0,2} [0-9A-Fa-f]{1,4})? :: (?:[0-9A-Fa-f]{1,4}:) {2}
| (?: (?:[0-9A-Fa-f]{1,4}:){0,3} [0-9A-Fa-f]{1,4})? :: [0-9A-Fa-f]{1,4}:
| (?: (?:[0-9A-Fa-f]{1,4}:){0,4} [0-9A-Fa-f]{1,4})? ::
) (?:
[0-9A-Fa-f]{1,4} : [0-9A-Fa-f]{1,4}
| (?: (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) \.){3}
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
)
| (?: (?:[0-9A-Fa-f]{1,4}:){0,5} [0-9A-Fa-f]{1,4})? :: [0-9A-Fa-f]{1,4}
| (?: (?:[0-9A-Fa-f]{1,4}:){0,6} [0-9A-Fa-f]{1,4})? ::
)
| [Vv][0-9A-Fa-f]+\.[A-Za-z0-9\-._~!$&'()*+,;=:]+
)
\]
| (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
| (?:[A-Za-z0-9\-._~!$&'()*+,;=]|%[0-9A-Fa-f]{2})*
)
(?: : [0-9]* )?
(?:/ (?:[A-Za-z0-9\-._~!$&'()*+,;=:@]|%[0-9A-Fa-f]{2})* )*
| /
(?: (?:[A-Za-z0-9\-._~!$&'()*+,;=:@]|%[0-9A-Fa-f]{2})+
(?:/ (?:[A-Za-z0-9\-._~!$&'()*+,;=:@]|%[0-9A-Fa-f]{2})* )*
)?
| (?:[A-Za-z0-9\-._~!$&'()*+,;=:@]|%[0-9A-Fa-f]{2})+
(?:/ (?:[A-Za-z0-9\-._~!$&'()*+,;=:@]|%[0-9A-Fa-f]{2})* )*
|
)
(?:\? (?:[A-Za-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # [ "?" query ]
(?:\# (?:[A-Za-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # [ "#" fragment ]
A: Does Uri.IsWellFormedUriString work for you?
A: The URI specification says:
The following line is the regular expression for breaking-down a well-formed URI reference into its components.
^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
(I guess that's the same regex as in the STD66 link given in another answer.)
But breaking-down is not validating. To correctly validate a URI, one would have to translate the BNF for URIs to a regex. While some BNFs cannot be expressed as regular expressions, I think with this one it could be done. But it shouldn't be done - it would be a huge mess. It's better to use a library function.
A: This site looks promising: http://snipplr.com/view/6889/regular-expressions-for-uri-validationparsing/
They propose following regex:
/^([a-z0-9+.-]+):(?://(?:((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*)@)?((?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*)(?::(\d*))?(/(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?|(/?(?:[a-z0-9-._~!$&'()*+,;=:@]|%[0-9A-F]{2})+(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?)(?:\?((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*))?(?:#((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*))?$/i
A: Are there some specific URIs you care about or are you trying to find a single regex that validates STD66?
I was going to point you to this regex for parsing a URI. You could then, in theory, check to see if all of the elements you care about are there.
But I think bdukes answer is better.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: MySQL Results to a File How do I write the results from a mysql query to file? I just need something quick. Output can be CSV, XML, HTML, etc.
A: SELECT a,b,a+b
FROM test_table
INTO OUTFILE '/tmp/result.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(the docs show INTO OUTFILE up in the SELECT .. portion which may work as well, but I've never tried it that way)
http://dev.mysql.com/doc/refman/5.0/en/select.html
INTO OUTFILE creates a file on the server; if you are on a client and want it there, do:
mysql -u you -p -e "SELECT ..." > file_name
A: if you have phpMyAdmin installed, it is a nobrainer: Run the query (haven't got a copy loaded, so I can't tell you the details, but it really is easy) and check neer bottom for export options. CSV will be listed, but I think you can also have SQL if you like :)
phpMyAdmin will give CSV in Excels dialect, which is probably what you want...
A: You can use MySQL Query Browser to run the query and then just go to File -> Export Resultset and choose the output format. The options are CSV, HTML, XML, Excel and PLIST.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Authenticating Domain Users with System.DirectoryServices Given a username and a password for a domain user, what would be the best way to authenticate that user programatically?
A: You can use some hacks to authenticate only.
Try
Dim directoryEntry as New DirectoryEntry("LDAP://DomainController:389/dc=domain,dc=suffix", "username", "password")
Dim temp as Object = directoryEntry.NativeObject
return true
Catch
return false
End Try
If the user is not valid, the directory entry NativeObject cannot be accessed and throws an exception. While this isn't the most efficient way (exceptions are evil, blah blah blah), it's quick and painless. This also has the super-cool advantage of working with all LDAP servers, not just AD.
A: It appears that .NET 3.5 added a new namespace to deal with this issue - System.DirectoryServices.AccountManagement. Code sample is below:
Private Function ValidateExternalUser(ByVal username As String, ByVal password As String) As Boolean
Using context As PrincipalContext = New PrincipalContext(ContextType.Domain, _defaultDomain)
Return context.ValidateCredentials(username, password, ContextOptions.Negotiate)
End Using
End Function
The namespace also seems to provide a lot of methods for manipulating a domain account (changing passwords, expiring passwords, etc).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Fastest way to calculate primes in C#? I actually have an answer to my question but it is not parallelized so I am interested in ways to improve the algorithm. Anyway it might be useful as-is for some people.
int Until = 20000000;
BitArray PrimeBits = new BitArray(Until, true);
/*
* Sieve of Eratosthenes
* PrimeBits is a simple BitArray where all bit is an integer
* and we mark composite numbers as false
*/
PrimeBits.Set(0, false); // You don't actually need this, just
PrimeBits.Set(1, false); // remindig you that 2 is the smallest prime
for (int P = 2; P < (int)Math.Sqrt(Until) + 1; P++)
if (PrimeBits.Get(P))
// These are going to be the multiples of P if it is a prime
for (int PMultiply = P * 2; PMultiply < Until; PMultiply += P)
PrimeBits.Set(PMultiply, false);
// We use this to store the actual prime numbers
List<int> Primes = new List<int>();
for (int i = 2; i < Until; i++)
if (PrimeBits.Get(i))
Primes.Add(i);
Maybe I could use multiple BitArrays and BitArray.And() them together?
A: You might save some time by cross-referencing your bit array with a doubly-linked list, so you can more quickly advance to the next prime.
Also, in eliminating later composites once you hit a new prime p for the first time - the first composite multiple of p remaining will be p*p, since everything before that has already been eliminated. In fact, you only need to multiply p by all the remaining potential primes that are left after it in the list, stopping as soon as your product is out of range (larger than Until).
There are also some good probabilistic algorithms out there, such as the Miller-Rabin test. The wikipedia page is a good introduction.
A: Parallelisation aside, you don't want to be calculating sqrt(Until) on every iteration. You also can assume multiples of 2, 3 and 5 and only calculate for N%6 in {1,5} or N%30 in {1,7,11,13,17,19,23,29}.
You should be able to parallelize the factoring algorithm quite easily, since the Nth stage only depends on the sqrt(n)th result, so after a while there won't be any conflicts. But that's not a good algorithm, since it requires lots of division.
You should also be able to parallelize the sieve algorithms, if you have writer work packets which are guaranteed to complete before a read. Mostly the writers shouldn't conflict with the reader - at least once you've done a few entries, they should be working at least N above the reader, so you only need a synchronized read fairly occasionally (when N exceeds the last synchronized read value). You shouldn't need to synchronize the bool array across any number of writer threads, since write conflicts don't arise (at worst, more than one thread will write a true to the same place).
The main issue would be to ensure that any worker being waited on to write has completed. In C++ you'd use a compare-and-set to switch to the worker which is being waited for at any point. I'm not a C# wonk so don't know how to do it that language, but the Win32 InterlockedCompareExchange function should be available.
You also might try an actor based approach, since that way you can schedule the actors working with the lowest values, which may be easier to guarantee that you're reading valid parts of the the sieve without having to lock the bus on each increment of N.
Either way, you have to ensure that all workers have got above entry N before you read it, and the cost of doing that is where the trade-off between parallel and serial is made.
A:
Without profiling we cannot tell which bit of the program needs optimizing.
If you were in a large system, then one would use a profiler to find that the prime number generator is the part that needs optimizing.
Profiling a loop with a dozen or so instructions in it is not usually worth while - the overhead of the profiler is significant compared to the loop body, and about the only ways to improve a loop that small is to change the algorithm to do fewer iterations. So IME, once you've eliminated any expensive functions and have a known target of a few lines of simple code, you're better off changing the algorithm and timing an end-to-end run than trying to improve the code by instruction level profiling.
A: @DrPizza Profiling only really helps improve an implementation, it doesn't reveal opportunities for parallel execution, or suggest better algorithms (unless you've experience to the otherwise, in which case I'd really like to see your profiler).
I've only single core machines at home, but ran a Java equivalent of your BitArray sieve, and a single threaded version of the inversion of the sieve - holding the marking primes in an array, and using a wheel to reduce the search space by a factor of five, then marking a bit array in increments of the wheel using each marking prime. It also reduces storage to O(sqrt(N)) instead of O(N), which helps both in terms of the largest N, paging, and bandwidth.
For medium values of N (1e8 to 1e12), the primes up to sqrt(N) can be found quite quickly, and after that you should be able to parallelise the subsequent search on the CPU quite easily. On my single core machine, the wheel approach finds primes up to 1e9 in 28s, whereas your sieve (after moving the sqrt out of the loop) takes 86s - the improvement is due to the wheel; the inversion means you can handle N larger than 2^32 but makes it slower. Code can be found here. You could parallelise the output of the results from the naive sieve after you go past sqrt(N) too, as the bit array is not modified after that point; but once you are dealing with N large enough for it to matter the array size is too big for ints.
A: You also should consider a possible change of algorithms.
Consider that it may be cheaper to simply add the elements to your list, as you find them.
Perhaps preallocating space for your list, will make it cheaper to build/populate.
A: Are you trying to find new primes? This may sound stupid, but you might be able to load up some sort of a data structure with known primes. I am sure someone out there has a list. It might be a much easier problem to find existing numbers that calculate new ones.
You might also look at Microsofts Parallel FX Library for making your existing code multi-threaded to take advantage of multi-core systems. With minimal code changes you can make you for loops multi-threaded.
A: There's a very good article about the Sieve of Eratosthenes: The Genuine Sieve of Eratosthenes
It's in a functional setting, but most of the opimization do also apply to a procedural implementation in C#.
The two most important optimizations are to start crossing out at P^2 instead of 2*P and to use a wheel for the next prime numbers.
For concurrency, you can process all numbers till P^2 in parallel to P without doing any unnecessary work.
A: void PrimeNumber(long number)
{
bool IsprimeNumber = true;
long value = Convert.ToInt32(Math.Sqrt(number));
if (number % 2 == 0)
{
IsprimeNumber = false;
MessageBox.Show("No It is not a Prime NUmber");
return;
}
for (long i = 3; i <= value; i=i+2)
{
if (number % i == 0)
{
MessageBox.Show("It is divisible by" + i);
IsprimeNumber = false;
break;
}
}
if (IsprimeNumber)
{
MessageBox.Show("Yes Prime NUmber");
}
else
{
MessageBox.Show("No It is not a Prime NUmber");
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Is there a pattern using Linq to dynamically create a filter? Is there a pattern using Linq to dynamically create a filter?
I have the need to create custom filtering on a list, in the past I would just dynamically create the SQL...it doesn't seem like this is possible with Linq.
A: Dynamically Composing Expression Predicates
A: something like this?
var myList = new List<string> { "a","b","c" };
var items = from item in db.Items
where myList.Contains(item.Name)
select item;
that would create a sql statement like
SELECT * FROM Items [t0] where Name IN ('a','b','c')
A: Check out the Dynamic Linq Library from ScottGu's blog:
For example, below is a standard type-safe LINQ to SQL VB query that retrieves data from a Northwind database and displays it in a ASP.NET GridView control:
Dim Northwind As New NorthwindDataContext
Dim query = From q In Northwind.Products Where p.CategoryID = 2 And p.UnitPrice > 3 Order By p.SupplierID Select p
Gridview1.DataSource = query
GridView1.DataBind()
Using the LINQ DynamicQuery library I could re-write the above query expression instead like so
Dim Northwind As New NorthwindDataContext
Dim query = Northwind.Products .where("CategoryID=2 And UnitPrice>3") . OrderBy("SupplierId")
Gridview1.DataSource = query
GridView1.DataBind()
Notice how the conditional-where clause and sort-orderby clause now take string expressions instead of code expressions. Because they are late-bound strings I can dynamically construct them. For example: I could provide UI to an end-user business analyst using my application that enables them to construct queries on their own (including arbitrary conditional clauses).
A: Dynamic Linq is one way to go.
It may be overkill for your scenario. Consider:
IQueryable<Customer> query = db.Customers;
if (searchingByName)
{
query = query.Where(c => c.Name.StartsWith(someletters));
}
if (searchingById)
{
query = query.Where(c => c.Id == Id);
}
if (searchingByDonuts)
{
query = query.Where(c => c.Donuts.Any(d => !d.IsEaten));
}
query = query.OrderBy(c => c.Name);
List<Customer> = query.Take(10).ToList();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: What is the best way to share MasterPages across projects Suppose you have two seperate ASP.NET Web Application projects that both need to use a common MasterPage.
What's the best way to share the MasterPage across projects without having to duplicate code? Preferably without having to resort to source control or file system hacks.
A: From K. Scott Allen's ASP.Net Master Pages: Tips, Tricks, and Traps article, on "Sharing Master Pages":
The first alternative is to copy shared master page files into a
single location on an IIS web server. Each application can then create
a virtual directory as a subdirectory and point the virtual directory
to the real directory of master pages. The applications can then set
the MasterPageFile property of a page to the name of the virtual
directory, plus the name of the master page file. When we drop an
updated master page file into the real directory, the new master page
will appear in all the applications immediately.
A second approach is to use a version control system to share a set of
master page files across multiple projects. Most source control /
version control systems support some level of “share” functionality,
where a file or folder can appear in more than one project. When a
developer checks in an updated master page file, the other projects
will see the change immediately (although this behavior is generally
configurable). In production and test, each application would need to
be redeployed for the update master page to appear.
Finally, the VirtualPathProvider in ASP.NET 2.0 can serve files that
do not exist on the file system. With the VirtualPathProvider, a set
of master pages could live in database tables that all applications
use. For an excellent article on the VirutalPathProvider, see “Virtualizing Access to Content: Serving Your Web Site from a ZIP File”.
A: Keep a primary copy in source control, and let your source control system worry about it.
A: I have trying to accomplish the same thing. I look into a couple of solutions but I think using a virtual directory is probably the best way to share master pages.
Here are a couple sources that you can look at.
*
*Sharing Master Pages amongst
Applications by Embedding it in a
Dll
*Sharing Master Pages in Visual Studio
*ASP.Net 2.0 - Master Pages: Tips, Tricks, and Traps
The third bullets near the end the article tells you of possible ways you can share Masterpages also.
A: Use a symbolic link:
A symbolic link is a file-system object that points to another file
system object. The object being pointed to is called the target.
Symbolic links are transparent to users; the links appear as normal
files or directories, and can be acted upon by the user or application
in exactly the same manner.
A: Supposing you can create a common repository for all your projects (a common folder in your source control tree, for example), you could add the master pages as links by using relative paths.
However, IIRC, Visual Studio makes local copies of files added from external paths. You might have to text-edit the solution/project file to add the linked files.
This, of course, is assuming you use "Web Application" format. Older VS "Web Sites" do not have project files and rely on having all files within the site folder.
A: AFAIK there is no elegant way to do what you are looking to.. VS will always end up copying it.
I think to be honest it may not be a great idea.. Obviously you want to share the lowest common code, but a whole MasterPage?.. Sounds like you could be asking for trouble since one minor change could have such an impact on one or more applications..
I would suggest instead seperating out the good bits of functionality into components/controls and deploying them.
A: I cant see why you would want to have the same markup accross different projects, if you do, I dont know an easy way.
However with code, obviously you can write a code file which inherits from
System.Web.UI.MasterPage
Put in whatever logic you want in all your master pages in there. Build it as your awesome dll then just include that in your projects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: Good Mercurial repository viewer for Mac Is there a good, native Mac tool to view Mercurial repositories, similar to gitnub for Git?
A: A few months back, Dustin Sallings wrote a fork of GitNub that uses Mercurial. It's Leopard-only, but lovely.
On Tiger, the "view" exension mentioned in the other comments works okay, as does hgview.
A: Try the newly released MacHg. It uses the native GUI toolkit for Mac and comes with its own bundled version of Mercurial.
There are many more screenshots available.
A: I know it's pretty old question, however just for sake of completeness, I think it is still worth to mention here the newest kid on the block called Murky.
A: I just released a new tool, SourceTree which is native Mac OS X and lets you work with both Mercurial and Git repositories in one application.
A: You can use the one "built in", hg view. You'll need TCL installed though.
From the documentation:
The hgk Tcl script is a direct port of the gitk tool used with git. The hgk.py extension allows hgk to interact with mercurial in a git-like manner.
edit @ Matthew: yeah, that's why I linked to the documentation that explains it. You need to enable it in your .hgrc (like the fetch command), and TCL --as mentioned.
A:
hg: unknown command 'view'
(Maybe I need to install something - but it's not native, nonetheless).
There is one "native" application out there, but it's not especially user-friendly. In fact, I'd go as far as saying that it's harder to use than the command line.
There was some talk a year or so ago about a version of SCPlugin, which puts badges on icons in the Finder that are under SVN control, and gives you a contextual menu (very much like TortoiseSVN on windows), but that seems to have collapsed.
I have been planning to create a mercurial "clone" of Versions (I asked them if they would consider doing a version of it for DVCS, and they said no).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
} |
Q: A WYSIWYG Markdown control for Windows Forms? [We have a Windows Forms database front-end application that, among other things, can be used as a CMS; clients create the structure, fill it, and then use a ASP.NET WebForms-based site to present the results to publicly on the Web. For added flexibility, they are sometimes forced to input actual HTML markup right into a text field, which then ends up as a varchar in the database. This works, but it's far from user-friendly.]
As such… some clients want a WYSIWYG editor for HTML. I'd like to convince them that they'd benefit from using simpler language (namely, Markdown). Ideally, what I'd like to have is a WYSIWYG editor for that. They don't need tables, or anything sophisticated like that.
A cursory search reveals a .NET Markdown to HTML converter, and then we have a Windows Forms-based text editor that outputs HTML, but apparently nothing that brings the two together. As a result, we'd still have our varchars with markup in there, but at least it would be both quite human-readable and still easily parseable.
Would this — a WYSIWYG editor that outputs Markdown, which is then later on parsed into HTML in ASP.NET — be feasible? Any alternative suggestions?
A: I think the best approach for this is to combine
*
*Converting Markdown to HTML &
*Displaying HTML in WinForms
The most up to date Markdown Library seems to be markdig which you can install via nuget
A simple implementation might be to:
*
*Add a SplitContainer to a Form control, set Dock = Fill
*Add a TextBox, set Dock = Fill and set to Multiline = True
*Add a WebBrowser, set Dock = Fill
Then handle the TextChanged event, parse the text into html and set to DocumentText like this:
private void textBox1_TextChanged(object sender, EventArgs e)
{
var md = textBox1.Text;
var html = Markdig.Markdown.ToHtml(md);
webBrowser1.DocumentText = html;
}
Here's a recorded demo:
A: @Soeren,
You can most definitely embed IE with the Javascript Markdown editor inside a Windows Forms application.
A:
the RichTextBox control
So you want to use Markdown but you want the user not to know it? This might not be an achievable goal. I think the point of Markdown is that it is geared toward writers that are willing to learn a little bit of fairly natural syntax and edit everything in plain text (like Wikipedia? are there pure WYSIWYG editors for that? probably... and probably some other Wikipedia editor person has to come and clean up the resulting markup and formatting...). If you want it to be transparent to the user (like MS Word) Markdown may not be what you want or give you the advantages it advertises in that situation.
The input happens in Windows Forms
Oops! Now I understand better your question. I guess it depends on how your Windows Forms app looks whether the embedded IE control sticks out like a sore thumb. If you try it you might find that you can get it to work.[1]
In your position, I would try something like this [2]:
*
*http://wmd-editor.com/examples/splitscreen
If you don't think that sort of arrangement will go over well with your users, (especially all the editing in the text-only window) then once again I don't think Markdown is the answer for your specific application. If you think your users are keen on the idea of editing pure text, then I bet we can find a solution. Please clarify?
Jared.
[1] I had success dropping an IE HTML control into a project strictly to display some generated results as a PDF (using an IE Reader plugin like Adobe Reader or Foxit). The user has no idea that that part of the GUI is an IE control, it just shows the PDF, allows printing and saving, etc.
[2] ...but remove the borders and make the two split controls touch all four edges of the embedded IE control, or get very close... keep it light grey or white, for example, and eliminate any borders of the IE control so it blends into the surrounding controls. Maybe put this on its own tab page and I challenge a non-technical user to tell/care if it's an HTML control or native.
I could totally be wrong about all this (one would have to see this in action to determine if it would work) but it might be easier than writing your own interactive Markdown editor...
...actually to implement your own C# Markdown editor, you could just put a text edit box next to an embedded IE control and run the current Markdown through the .NET Markdown->HTML converter on a separate thread, and replace the HTML in the IE control (assuming the Markdown->HTML converter is very liberal and robust against throwing ANY exceptions).
A: Can't you just use the same control I'm Stack Overflow uses (that we're all typing into)---WMD, and just store the Markdown in the VARCHAR. Then use the .NET Markdown to HTML converter, as you mentioned, to display the HTML as needed. Jeff talks about this in more detail in a StackOverflow podcast (don't know the episode number).
A: "WYSIWYG Markdown" is really an oxymoron since the whole point of Markdown is to allow you to write markup syntax naturally and intuitively which is then post-processed into html, unless you mean actually taking for example **text** and rendering it as **text** for example. That would actually be kind of cool, but it would get very difficult for things like numbered and bulleted lists, since you would have to do all the positioning, yet keep everything based on actual textual characters (e.g. '*' instead of the bullet symbol) and support proper textual input positioning, backspace, etc.
*
*For example,
*in this bullet list,
*the bullets would actually have to be asterisks,
*and the spacing would not really be there.
That would certainly be worth paying attention to, if someone did tackle it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Register file extensions / mime types in Linux I'm developing a Linux application that has its own file format. I want my app to open when you double-click on those files.
How can I register a file extension and associate it with my application on Linux? I'm looking for a way that is standard (works with GNOME and KDE based systems) and can be done automatic when my program is installed or run for the first time.
A: Use xdg-utils from freedesktop.org Portland.
Register the icon for the MIME type:
xdg-icon-resource install --context mimetypes --size 48 myicon-file-type.png x-application-mytype
Create a configuration file (freedesktop Shared MIME documentation):
<?xml version="1.0"?>
<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'>
<mime-type type="application/x-mytype">
<comment>A witty comment</comment>
<comment xml:lang="it">Uno Commento</comment>
<glob pattern="*.myapp"/>
</mime-type>
</mime-info>
Install the configuration file:
xdg-mime install mytype-mime.xml
This gets your files recognized and associated with an icon. xdg-mime default can be used for associating an application with the MIME type after you get a .desktop file installed.
A: 1) in linux this is a function of your desktop environment rather than the os itself.
2) GNOME and KDE have different methods to accomplish this.
3) There's nothing stopping you from doing it both ways.
A: Try this script: needs:
1. your application icon -> $APP = FIREFOX.png
2. your mimetype icon -> application-x-$APP = HTML.png
in the current directory:
#BASH SCRIPT: Register_my_new_app_and_its_extension.sh
APP="FOO"
EXT="BAR"
COMMENT="$APP's data file"
# Create directories if missing
mkdir -p ~/.local/share/mime/packages
mkdir -p ~/.local/share/applications
# Create mime xml
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">
<mime-type type=\"application/x-$APP\">
<comment>$COMMENT</comment>
<icon name=\"application-x-$APP\"/>
<glob pattern=\"*.$EXT\"/>
</mime-type>
</mime-info>" > ~/.local/share/mime/packages/application-x-$APP.xml
# Create application desktop
echo "[Desktop Entry]
Name=$APP
Exec=/usr/bin/$APP %U
MimeType=application/x-$APP
Icon=$APP
Terminal=false
Type=Application
Categories=
Comment=
"> ~/.local/share/applications/$APP.desktop
# update databases for both application and mime
update-desktop-database ~/.local/share/applications
update-mime-database ~/.local/share/mime
# copy associated icons to pixmaps
cp $APP.png ~/.local/share/pixmaps
cp application-x-$APP.png ~/.local/share/pixmaps
make sure:
FOO binary is there in /usr/bin (or in $PATH)
A: There are two parts to this. You need to register a new file type and then create a desktop entry for your application. The desktop entry associates your application with your new mime type.
I thought that both Gnome and KDE (maybe only 4+?) used the freedesktop shared mime info spec, but I may well be wrong.
A: This is all existing answers combined, completed and corrected into a single bash script.
#!/bin/bash
set -e # stop on error
APP=my-app
EXT=my-app
COMMENT=Comment
EXEC=/usr/bin/my-app
LOGO=./logo.png
xdg-icon-resource install --context mimetypes --size 48 $LOGO application-x-$APP
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">
<mime-type type=\"application/x-$APP\">
<comment>$COMMENT</comment>
<icon name=\"application-x-$APP\"/>
<glob pattern=\"*.$EXT\"/>
</mime-type>
</mime-info>" > $APP-mime.xml
xdg-mime install $APP-mime.xml
rm $APP-mime.xml
update-mime-database $HOME/.local/share/mime
echo "[Desktop Entry]
Name=$APP
Exec=$EXEC %U
MimeType=application/x-$APP
Icon=application-x-$APP
Terminal=false
Type=Application
Categories=
Comment=$COMMENT
"> $APP.desktop
desktop-file-install --dir=$HOME/.local/share/applications $APP.desktop
rm $APP.desktop
update-desktop-database $HOME/.local/share/applications
xdg-mime default $APP.desktop application/x-$APP
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "60"
} |
Q: Simple password encryption What is a good, simple encryption scheme for protecting passwords in a database? I don't necessarily need anything that's hyper-secure nor do I need anything that's lightning fast, but those things would be nice. Primarily, I just want something that's easy to implement without being terribly slow or insecure.
A: Use the SHA one way hashing algorithm along with a unique salt. It is the main algorithm I use for storing my passwords in the database.
A: As mk says, SHA1 or MD5 are the standard ones, along with SHA2.
Update: As processors have gotten faster over the years, hashes have gotten more brute-forceable. It's now recommended you use bcrypt.
Another update: bcrypt is still probably good, but if I was writing a new system today I would use scrypt.
What you want is more generally called a cryptographic hash function. Cryptographic hashes are designed to be one-way (given the resulting hash, you shouldn't be able to derive the original input). Also, the likelihood of two arbitrary strings having the same hash (known as a hash collision) should be low (ideally 1/number of hash values).
Unfortunately, just because your passwords are hashed doesn't free you from having to try really hard to keep the hashed versions safe. Far too many people will use weak passwords that would be vulnerable to an off-line brute-force attack.
Edit - several people have also already pointed out the importance of using a salt. A salt is a constant value that you mix in with the input before using the hash function. Having a unique salt prevents off-line attackers from using pre-computed tables of common passwords (rainbow tables) to brute-force your passwords even faster.
A: MD5 or SHA1 + salt.
A: If you use MD5 or SHA1 use a salt to avoid rainbow table hacks.
In C# this is easy:
MD5CryptoServiceProvider hasher = new MD5CryptoServiceProvider();
string addSalt = string.Concat( "ummm salty ", password );
byte[] hash = hasher.ComputeHash( Encoding.Unicode.GetBytes( addSalt ) );
A: Easy: BCrypt.
A: If you're using SQL Server, there's the HashBytes function:
http://msdn.microsoft.com/en-us/library/ms174415.aspx
A: I second the vote for MD5 or SHA with a salt. Any of the major web development languages have functions built-in for computing the hash (in PHP, for example, the mcrypt package contains the necessary functions).
A: You need to be using an uni-directional hash algorithm like SHA-1 suggested above with a salt. I would suggest this site for more information. It includes some sample code / implementation.
http://www.obviex.com/samples/hash.aspx
A: The key to better security, I think, is to use dynamic salts. This means that you generate a random string for each new user and use that string to salt the hash. Of course, you need to store this salt in the database to be able to verify the password later (I don't encrypt it in any way).
A: For a non-reversible encryption I would most definitely go with SHA256 or SHA1. MD5 has quite a lot of collisions now and a lot of effort has been put into breaking it, so not a good one to use.
A: If you want to future-proof your solution, I'd recommend SHA256 or SHA512. Cryptographic geekworld is getting the jitters about MD5 and, to a slightly lesser extent, SHA1.
Or, if you can, wait for SHA-3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Visual Studio 08 Spell Check Addin? If possible one that supports at least spell checking:
*
*C# string literals
*HTML content
*Comments
A: If you're using ReSharper, there's a free addon for it called Agent Smith Plugin. One of its many features is a built in spell checker, that allows fixing the spelling mistakes using the ReSharper shortcut key, Alt-Enter.
A: Well, 3 weeks later, I've stumbled across CodeSpell. [Note: this link no longer works and the product does not appear to be listed by that company).
Its $30 but has a trial period. Does everything I asked for. Check link to see features.
This blog entry, though dated, helped me out.
Edit: The original link is now invalid but this appears to be the new home of CodeSpell at SubMain. Here is acquisition announcement from them.
A: Visual Assist X. Spell checks your comments and a whole lot more.
http://www.wholetomato.com/
A: The plugin from Microsoft's Mikhail Arkhipov does HTML and Comments, I don't believe it does C# strings, though. I use the Agent Smith plugin for ReSharper for that.
A: FxCop ships with a spell check now - have you tried that?
Here's a nice add-on for Visual Studio 2005/2008 by Mikhail Arkhipov of MSFT.
A: I use this to check Comments and string spell checker. It's from component one http://www.componentone.com/SuperProducts/IntelliSpell/. It's very fast and there is a free community version.
A: CodeRush also has spell check.
A: The source code for Spelly is available, it would be pretty easy to update it for vs2008.
A: Spelly has been ported to VS 2003. I don't know if it works with VS 2008 (because I'm very happy with Agent Smith for ReSharper), but source is included.
A: I was running an obsolete version on Visual Studio 08, as of April last year this is the apparent update: http://visualstudiogallery.msdn.microsoft.com/2f3d691d-8838-4d84-ad64-44a02db37e30/
Unfortunately for me, it only works on commented code and not strings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: Finding City and Zip Code for a Location Given a latitude and longitude, what is the easiest way to find the name of the city and the US zip code of that location.
(This is similar to https://stackoverflow.com/questions/23572/latitude-longitude-database, except I want to convert in the opposite direction.)
Related question: Get street address at lat/long pair
A: Any of the online services mentioned and their competitors offer "reverse geocoding" which does what you ask--convert lon/lat coordinates into a street address of some-sort.
If you only need the zip codes and/or cities, then I would obtain the Zip Code database and urban area database from the US Census Bureau which is FREE (paid for by your tax dollars). http://www.census.gov/geo/www/cob/zt_metadata.html.
From there, you can either come up with your own search algorithm for the spatial data or make use of one of a spatial databases such as Microsoft SQL Server, PostGIS, Oracle Spatial, ArcSDE, etc.
Update: The 2010 Census data can be found at:
http://www2.census.gov/census_2010/
A: This is the web service to call.
http://developer.yahoo.com/search/local/V2/localSearch.html
This site has ok web services, but not exactly what you're asking for here.
http://www.usps.com/webtools/
A: You have two main options:
Use a Reverse Geocoding Service
*
*Google's can only be used in conjunction with an embedded Google Map on the same page, so I don't recommend it unless that is what you are doing.
*Yahoo has a good one, see http://developer.yahoo.com/search/local/V3/localSearch.html
*I've not used OpenStreetMap's. Their maps look very detailed and thorough, and are always getting better, but I'd be worried about latency and reliability, and whether their address data is complete (address data is not directly visible on a map, and OpenStreetMap is primarily an interactive map).
Use a Map of the ZIP Codes
The US Census publishes a map of US ZIP codes here. They build this from their smallest statistical unit, a Census Block, which corresponds to a city block in most cases. For each block, they find what ZIP code is most common on that block (most blocks have only one ZIP code, but blocks near the border between ZIP codes might have more than one). They then aggregate all the blocks with a given ZIP code into a single area called a Zip Code Tabulation Area. They publish a map of those areas in ESRI shapefile format.
I know about this because I wrote a Java Library and web service that (among other things) uses this map to return the ZIP code for a given latitude and longitude. It is a commercial product, so it won't be for everyone, but it is fast, easy to use, and solves this specific problem without an API. You can read about this product here:
http://askgeo.com/database/UsZcta2010
And about all of your geographic offerings here:
http://askgeo.com
Unlike reverse geocoding solutions, which are only available as Web APIs because running your own service would be extremely difficult, you can run this library on your own server and not depend on an external resource.
A: If you call volume to the service gets up too high, you should definitely consider getting your own set of postal data. In most cases, that will provide all of the information that you need, and there are plenty of db tools for indexing location data (i.e. PostGIS for PostgreSQL).
A: You can buy a fairly inexpensive subscription to zipcodes with lat and long info here: http://www.zipcodedownload.com/
A: Or google's reverse geocoding
link
http://maps.google.com/maps/geo?output=xml&q={0},{1}&key={2}&sensor=true&oe=utf8
where 0 is latitude 1 is longitude
A: geonames has an extensive set of ws that can handle this (among others):
http://www.geonames.org/export/web-services.html#findNearbyPostalCodes
http://www.geonames.org/export/web-services.html#findNearbyPlaceName
A: Another reverse geocoding provider that hasn't been listed here yet is OpenStreetMap: you can use their Nominatim search service.
OSM has the (potentially?) added bonus of being entirely user editable (wiki-like) and thus having a very liberal licencing scheme of all this data. Think of this of open source map data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Limiting traffic to SSL version of page only We have an external service that is currently accessible via the http (port 80, non-SSL) and https (port 443, SSL) addresses.
What is the best way to limit connections to only the https address? Is it something we can do via IIS or does it have to be done via code.
Additional info: Regular ASP.NET web service (.asmx) running on IIS on Windows 2003 server. Service is built with C# on .NET 3.5.
A: *
*Require SSL on the application
*In a custom error page for the 403 redirect the browser to the incoming URL, changing http to https along the way.
Note: Keep port 80 open for this - or there won't be a server to listen for requests to redirect.
A: Just to clarify Greg's point 1. IIS Manager > Site properties > Directory Security > Secure Communications > Require Secure Channel (SSL)
A: Is just not accepting any connections on port 80 an option? I'm a complete web server noob so I don't know if the server can operate without an unsecured listen port but if the server can operate only listen on port 443 that would seem to be simplest option.
Another option would be a redirect from the unsecure port to the secure one
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: InputManager on OS X I was wondering if InputManagers are still part of Leopard and if there is a good example that would show me what are the use of it?
A: InputManagers are still available on Leopard, except:
*
*they need to be in the Local domain (/Library/InputManagers); you cannot install them per-user any more,
*they need to have appropriate privileges,
*in 64-bit, they won't get loaded at all.
The Leopard AppKit Release Notes have more specific details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is there anything similar to the OS X InputManager on Windows? Is there anything similar on Windows what would achieve the same as the InputManager on OS X?
A: I'm pretty sure Windows has an API that developers can use to create new kinds of text input systems. I gather there are a wide variety of text input systems in use in non-Roman-derived markets, many of which are provided by third parties.
It's unclear if that's what you were really asking about, though, because you just assumed everyone knows what you would want to use an Input Manager for on Mac OS X.
*
*If you want to create a new type of input method, ask how to do that.
*If you want to get your own code running inside other applications, ask how to do that.
Don't just assume people can read your mind when asking questions, and don't assume that they have the same experience that you do and will recognize all the same platform-specific terminology.
A: If you are looking to inject code into processes (which is what Input Managers are most commonly used for), the Windows equivalents are:
*
*AppInit_DLLs to automatically load your DLL into new processes,
*CreateRemoteThread to start a new thread in a particular existing process, and
*SetWindowsHookEx to allow the capture of window events (keyboard, mouse, window creating, drawing, etc).
All of these methods require a DLL which will be injected into the remote process. C would be the best language to write such a DLL in as such a DLL needs to be quite light weight as to not bog the system down. RPC methods such as named pipes can be used to communicate to a master process should this be required.
Googling for these three APIs will turn up general sample code for these methods.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: querying 2 tables with the same spec for the differences I recently had to solve this problem and find I've needed this info many times in the past so I thought I would post it. Assuming the following table def, how would you write a query to find all differences between the two?
table def:
CREATE TABLE feed_tbl
(
code varchar(15),
name varchar(40),
status char(1),
update char(1)
CONSTRAINT feed_tbl_PK PRIMARY KEY (code)
CREATE TABLE data_tbl
(
code varchar(15),
name varchar(40),
status char(1),
update char(1)
CONSTRAINT data_tbl_PK PRIMARY KEY (code)
Here is my solution, as a view using three queries joined by unions. The diff_type specified is how the record needs updated: deleted from _data(2), updated in _data(1), or added to _data(0)
CREATE VIEW delta_vw AS (
SELECT feed_tbl.code, feed_tbl.name, feed_tbl.status, feed_tbl.update, 0 as diff_type
FROM feed_tbl LEFT OUTER JOIN
data_tbl ON feed_tbl.code = data_tbl.code
WHERE (data_tbl.code IS NULL)
UNION
SELECT feed_tbl.code, feed_tbl.name, feed_tbl.status, feed_tbl.update, 1 as diff_type
FROM data_tbl RIGHT OUTER JOIN
feed_tbl ON data_tbl.code = feed_tbl.code
where (feed_tbl.name <> data_tbl.name) OR
(data_tbl.status <> feed_tbl.status) OR
(data_tbl.update <> feed_tbl.update)
UNION
SELECT data_tbl.code, data_tbl.name, data_tbl.status, data_tbl.update, 2 as diff_type
FROM feed_tbl LEFT OUTER JOIN
data_tbl ON data_tbl.code = feed_tbl.code
WHERE (feed_tbl.code IS NULL)
)
A: UNION will remove duplicates, so just UNION the two together, then search for anything with more than one entry. Given "code" as a primary key, you can say:
edit 0: modified to include differences in the PK field itself
edit 1: if you use this in real life, be sure to list the actual column names. Dont use dot-star, since the UNION operation requires result sets to have exactly matching columns. This example would break if you added / removed a column from one of the tables.
select dt.*
from
data_tbl dt
,(
select code
from
(
select * from feed_tbl
union
select * from data_tbl
)
group by code
having count(*) > 1
) diffs --"diffs" will return all differences *except* those in the primary key itself
where diffs.code = dt.code
union --plus the ones that are only in feed, but not in data
select * from feed_tbl ft where not exists(select code from data_tbl dt where dt.code = ft.code)
union --plus the ones that are only in data, but not in feed
select * from data_tbl dt where not exists(select code from feed_tbl ft where ft.code = dt.code)
A: I would use a minor variation in the second union:
where (ISNULL(feed_tbl.name, 'NONAME') <> ISNULL(data_tbl.name, 'NONAME')) OR
(ISNULL(data_tbl.status, 'NOSTATUS') <> ISNULL(feed_tbl.status, 'NOSTATUS')) OR
(ISNULL(data_tbl.update, '12/31/2039') <> ISNULL(feed_tbl.update, '12/31/2039'))
For reasons I have never understood, NULL does not equal NULL (at least in SQL Server).
A: You could also use a FULL OUTER JOIN and a CASE ... END statement on the diff_type column along with the aforementioned where clause in querying 2 tables with the same spec for the differences
That would probably achieve the same results, but in one query.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: "File Save Failed" error when working with Crystal Reports in VS2008 Occasionally while attempting to save a Crystal Report that I'm working on in VS2008, a dialog titled "File Save Failed" pops up saying "The document could not be saved in C:\Users\Phillip\AppData\Local\Temp{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}.rpt. It has been saved in C:\Users\Phillip\AppData\Local\Temp\~zzz{YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY}.tmp."
If I OK the dialog, I get a "Save File As" dialog. If I specify the correct location of the report file, I'm asked if I want to replace the existing file. If I say "Yes", I get an error message saying "The operation could not be completed. The system cannot find the file specified." Even if I specify a completely different filename, in a different folder (e.g. C:/test.rpt) I get the same "operation could not be completed" error.
Sometimes if I wait a moment, then try to save again, it works fine. More frequently, however, I keep getting the "Save File As" dialog. My only option then is to close the report and discard my changes.
This is an intermittent problem - much of the time, saving the report works just fine. Any ideas?
A: Copernic Desktop Search sometimes locks files so that they can't be written. Closing the program resolves the problem. Perhaps the same problem occurs with other search engines too.
A: I had a problem VS2010 and Crystal which may be related
Suddenly saving was not working (asterisk never went away) - then VS would crash on trying to exit the report form (presumably trying to save).
I found that by changing the tab to preview the report (at the bottom) which I rarely do due to the fact that it is rarely accurate enough - I could save from there.
Saving during the preview removed the (dirty) astersisk in the top tab and allowed me to exit the form cleanly.
Too early to tell if the report is still ok - I too have had to recreate reports in the past.
Though once I did download the demo for the full Crystal which allowed me to mend a report so that is sometimes worth it too.
A: sounds like a job for process moniter. you should be able use process moniter to see what's really hapening and why.
http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx
Or you could install VS2008 sp1 and cross your fingers. (I'd do both)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is using too much static bad or good? I like to use static functions in C++ as a way to categorize them, like C# does.
Console::WriteLine("hello")
Is this good or bad? If the functions are used often I guess it doesn't matter, but if not do they put pressure on memory?
What about static const?
A: Those who say static functions can be replaced by namespaces are wrong, here is a simple example:
class X
{
public:
static void f1 ()
{
...
f2 ();
}
private:
static void f2 () {}
};
As you can see, public static function f1 calls another static, but private function f2.
This is not just a collection of functions, but a smart collection with its own encapsulated methods. Namespaces would not give us this functionality.
Many people use the "singleton" pattern, just because it is a common practice, but in many cases you need a class with several static methods and just one static data member. In this case there is no need for a singleton at all. Also calling the method instance() is slower than just accessing the static functions/members directly.
A:
but is it good or bad
The first adjective that comes to mind is "unnecessary". C++ has free functions and namespaces, so why would you need to make them static functions in a class?
The use of static methods in uninstantiable classes in C# and Java is a workaround because those languages don't have free functions (that is, functions that reside directly in the namespace, rather than as part of a class). C++ doesn't have that flaw. Just use a namespace.
A: Use namespaces to make a collection of functions:
namespace Console {
void WriteLine(...) // ...
}
As for memory, functions use the same amount outside a function, as a static member function or in a namespace. That is: no memory other that the code itself.
A: I'm all for using static functions. These just make sense especially when organized into modules (static class in C#).
However, the moment those functions need some kind of external (non compile-time const) data, then that function should be made an instance method and encapsulated along with its data into a class.
In a nutshell: static functions ok, static data bad.
A: Agree with Frank here, there's not a problem with static (global) functions (of course providing they are organised).. The problems only start to really creep in when people think "oh I will just make the scope on this bit of data a little wider".. Slippery slope :)
To put it really into perspective.. Functional Programming ;)
A: One specific reason static data is bad, is that C++ makes no guarantees about initialization order of static objects in different translation units. In practice this can cause problems when one object depends on another in a different translation unit. Scott Meyers discusses this in Item 26 of his book More Effective C++.
A: I tend to make classes that consist of static functions, but some say the "right way" to do this is usually to use namespaces instead. (I developed my habits before C++ had namespaces.)
BTW, if you have a class that consists only of static data and functions, you should declare the constructor to be private, so nobody tries to instantiate it. (This is one of the reasons some argue to use namespaces rather than classes.)
A: The problem with static functions is that they can lead to a design that breaks encapsulation. For example, if you find yourself writing something like:
public class TotalManager
{
public double getTotal(Hamburger burger)
{
return burger.getPrice() + burget.getTax();
}
}
...then you might need to rethink your design. Static functions often require you to use setters and getters which clutter a Class's API and makes things more complicated in general. In my example, it might be better to remove Hamburger's getters and just move the getTotal() class into Hamburger itself.
A: For organization, use namespaces as already stated.
For global data I like to use the singleton pattern because it helps with the problem of the unknown initialization order of static objects. In other words, if you use the object as a singleton it is guaranteed to be initialized when its used.
Also be sure that your static functions are stateless so that they are thread safe.
A: I usually only use statics in conjunction with the friend system.
For example, I have a class which uses a lot of (inlined) internal helper functions to calculate stuff, including operations on private data.
This, of course, increases the number of functions the class interface has.
To get rid of that, I declare a helper class in the original classes .cpp file (and thus unseen to the outside world), make it a friend of the original class, and then move the old helper functions into static (inline) member functions of the helper class, passing the old class per reference in addition to the old parameters.
This keeps the interface slim and doesn't require a big listing of free friend functions.
Inlining also works nicely, so I'm not completely against static.
(I avoid it as much as I can, but using it like this, I like to do.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Pass reference to element in C# Array I build up an array of strings with
string[] parts = string.spilt(" ");
And get an array with X parts in it, I would like to get a copy of the array of strings starting at element
parts[x-2]
Other than the obvious brute force approach (make a new array and insert strings), is there a more elegant way to do this in C#?
A: I remembered answering this question and just learned about a new object that may provide a high performance method of doing what you want.
Take a look at ArraySegment<T>. It will let you do something like.
string[] parts = myString.spilt(" ");
int idx = parts.Length - 2;
var stringView = new ArraySegment<string>(parts, idx, parts.Length - idx);
A: How about Array.Copy?
http://msdn.microsoft.com/en-us/library/aa310864(VS.71).aspx
Array.Copy Method (Array, Int32, Array, Int32, Int32)
Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 32-bit integers.
A: List<string> parts = new List<string>(s.Split(" "));
parts.RemoveRange(0, x - 2);
Assuming that List<string>(string[]) is optimized to use the existing array as a backing store instead of doing a copy operation this could be faster than doing an array copy.
A: Use Array.Copy. It has an overload that does what you need:
Array.Copy (Array, Int32, Array,
Int32, Int32)
Copies a range of elements from an Array starting at the specified source
index and pastes them to another Array
starting at the specified destination
index.
A: Array.Copy Method
I guess something like:
string[] less = new string[parts.Length - (x - 2)];
Array.Copy(parts, x - 2, less, 0, less.Length);
(sans the off by 1 bug that I'm sure is in there.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: What's the best way to allow a user to browse for a file in C#? What's the best way to allow a user to browse for a file in C#?
A: using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Select a file";
if (dlg.ShowDialog()== DialogResult.OK)
{
//do something with dlg.FileName
}
}
A: I would say use the standard "Open File" dialog box (OpenFileDialog), this makes it less intimidating for new users and helps with a consistant UI.
A: Close, Ryan, but you never showed the dialog. it should be:
if (dlg.ShowDialog() == DialogResult.OK)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Is there an "exists" function for jQuery? How can I check the existence of an element in jQuery?
The current code that I have is this:
if ($(selector).length > 0) {
// Do something
}
Is there a more elegant way to approach this? Perhaps a plugin or a function?
A: You can save a few bytes by writing:
if ($(selector)[0]) { ... }
This works because each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get the first item from the array. It returns undefined if there is no item at the specified index.
A: You can use:
if ($(selector).is('*')) {
// Do something
}
A little more elegant, perhaps.
A: This plugin can be used in an if statement like if ($(ele).exist()) { /* DO WORK */ } or using a callback.
Plugin
;;(function($) {
if (!$.exist) {
$.extend({
exist: function() {
var ele, cbmExist, cbmNotExist;
if (arguments.length) {
for (x in arguments) {
switch (typeof arguments[x]) {
case 'function':
if (typeof cbmExist == "undefined") cbmExist = arguments[x];
else cbmNotExist = arguments[x];
break;
case 'object':
if (arguments[x] instanceof jQuery) ele = arguments[x];
else {
var obj = arguments[x];
for (y in obj) {
if (typeof obj[y] == 'function') {
if (typeof cbmExist == "undefined") cbmExist = obj[y];
else cbmNotExist = obj[y];
}
if (typeof obj[y] == 'object' && obj[y] instanceof jQuery) ele = obj[y];
if (typeof obj[y] == 'string') ele = $(obj[y]);
}
}
break;
case 'string':
ele = $(arguments[x]);
break;
}
}
}
if (typeof cbmExist == 'function') {
var exist = ele.length > 0 ? true : false;
if (exist) {
return ele.each(function(i) { cbmExist.apply(this, [exist, ele, i]); });
}
else if (typeof cbmNotExist == 'function') {
cbmNotExist.apply(ele, [exist, ele]);
return ele;
}
else {
if (ele.length <= 1) return ele.length > 0 ? true : false;
else return ele.length;
}
}
else {
if (ele.length <= 1) return ele.length > 0 ? true : false;
else return ele.length;
}
return false;
}
});
$.fn.extend({
exist: function() {
var args = [$(this)];
if (arguments.length) for (x in arguments) args.push(arguments[x]);
return $.exist.apply($, args);
}
});
}
})(jQuery);
jsFiddle
You may specify one or two callbacks. The first one will fire if the element exists, the second one will fire if the element does not exist. However, if you choose to pass only one function, it will only fire when the element exists. Thus, the chain will die if the selected element does not exist. Of course, if it does exist, the first function will fire and the chain will continue.
Keep in mind that using the callback variant helps maintain chainability – the element is returned and you can continue chaining commands as with any other jQuery method!
Example Uses
if ($.exist('#eleID')) { /* DO WORK */ } // param as STRING
if ($.exist($('#eleID'))) { /* DO WORK */ } // param as jQuery OBJECT
if ($('#eleID').exist()) { /* DO WORK */ } // enduced on jQuery OBJECT
$.exist('#eleID', function() { // param is STRING && CALLBACK METHOD
/* DO WORK */
/* This will ONLY fire if the element EXIST */
}, function() { // param is STRING && CALLBACK METHOD
/* DO WORK */
/* This will ONLY fire if the element DOES NOT EXIST */
})
$('#eleID').exist(function() { // enduced on jQuery OBJECT with CALLBACK METHOD
/* DO WORK */
/* This will ONLY fire if the element EXIST */
})
$.exist({ // param is OBJECT containing 2 key|value pairs: element = STRING, callback = METHOD
element: '#eleID',
callback: function() {
/* DO WORK */
/* This will ONLY fire if the element EXIST */
}
})
A: I see most of the answers here are not accurate as they should be, they check element length, it can be OK in many cases, but not 100%, imagine if number pass to the function instead, so I prototype a function which check all conditions and return the answer as it should be:
$.fn.exists = $.fn.exists || function() {
return !!(this.length && (this[0] instanceof HTMLDocument || this[0] instanceof HTMLElement));
}
This will check both length and type, Now you can check it this way:
$(1980).exists(); //return false
$([1,2,3]).exists(); //return false
$({name: 'stackoverflow', url: 'http://www.stackoverflow.com'}).exists(); //return false
$([{nodeName: 'foo'}]).exists() // returns false
$('div').exists(); //return true
$('.header').exists(); //return true
$(document).exists(); //return true
$('body').exists(); //return true
A: A simple utility function for both id and class selector.
function exist(IdOrClassName, IsId) {
var elementExit = false;
if (IsId) {
elementExit = $("#" + "" + IdOrClassName + "").length ? true : false;
} else {
elementExit = $("." + "" + IdOrClassName + "").length ? true : false;
}
return elementExit;
}
calling this function like bellow
$(document).ready(function() {
$("#btnCheck").click(function() {
//address is the id so IsId is true. if address is class then need to set IsId false
if (exist("address", true)) {
alert("exist");
} else {
alert("not exist");
}
});
});
A: Just check the length of the selector, if it more than 0 then it's return true otherwise false.
For ID:
if( $('#selector').length ) // use this if you are using id to check
{
// it exists
}
For Class:
if( $('.selector').length ) // use this if you are using class to check
{
// it exists
}
For Dropdown:
if( $('#selector option').size() ) { // use this if you are using dropdown size to check
// it exists
}
A: In Javascript
if (typeof selector != "undefined") {
console.log("selector exists");
} else {
console.log("selector does not exists");
}
In jQuery
if($('selector').length){
alert("selector exists");
} else{
alert("selector does not exists");
}
A: There's no need for jQuery really. With plain JavaScript it's easier and semantically correct to check for:
if(document.getElementById("myElement")) {
//Do something...
}
If for any reason you don't want to put an id to the element, you can still use any other JavaScript method designed to access the DOM.
jQuery is really cool, but don't let pure JavaScript fall into oblivion...
A: You could use this:
jQuery.fn.extend({
exists: function() { return this.length }
});
if($(selector).exists()){/*do something*/}
A: All answers is not working bullet proof to check existence of an element in jQuery. After many years of coding, only this solution does not throw any warnings about existance or not:
if($(selector).get(0)) { // Do stuff }
Or to bail instead in the beginning of your function:
if(!$(selector).get(0)) return;
Explained
In this case, you dont have to deal with zero | null lengths issues. This forces to fetch an element, not count them.
A: I am using this:
if($("#element").length > 0){
//the element exists in the page, you can do the rest....
}
Its very simple and easy to find an element.
A: By default - No.
There's the length property that is commonly used for the same result in the following way:
if ($(selector).length)
Here, 'selector' is to be replaced by the actual selector you are interested to find if it exists or not. If it does exist, the length property will output an integer more than 0 and hence the if statement will become true and hence execute the if block. If it doesn't, it will output the integer '0' and hence the if block won't get executed.
A: The reason all of the previous answers require the .length parameter is that they are mostly using jquery's $() selector which has querySelectorAll behind the curtains (or they are using it directly). This method is rather slow because it needs to parse the entire DOM tree looking for all matches to that selector and populating an array with them.
The ['length'] parameter is not needed or useful and the code will be a lot faster if you directly use document.querySelector(selector) instead, because it returns the first element it matches or null if not found.
function elementIfExists(selector){ //named this way on purpose, see below
return document.querySelector(selector);
}
/* usage: */
var myelement = elementIfExists("#myid") || myfallbackelement;
However this method leaves us with the actual object being returned; which is fine if it isn't going to be saved as variable and used repeatedly (thus keeping the reference around if we forget).
var myel=elementIfExists("#myid");
// now we are using a reference to the element which will linger after removal
myel.getParentNode.removeChild(myel);
console.log(elementIfExists("#myid")); /* null */
console.log(myel); /* giant table lingering around detached from document */
myel=null; /* now it can be garbage collected */
In some cases this may be desired. It can be used in a for loop like this:
/* locally scoped myel gets garbage collected even with the break; */
for (var myel; myel = elementIfExist(sel); myel.getParentNode.removeChild(myel))
if (myel == myblacklistedel) break;
If you don't actually need the element and want to get/store just a true/false, just double not it !! It works for shoes that come untied, so why knot here?
function elementExists(selector){
return !!document.querySelector(selector);
}
/* usage: */
var hastables = elementExists("table"); /* will be true or false */
if (hastables){
/* insert css style sheet for our pretty tables */
}
setTimeOut(function (){if (hastables && !elementExists("#mytablecss"))
alert("bad table layouts");},3000);
A: Is $.contains() what you want?
jQuery.contains( container, contained )
The $.contains() method returns true if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply. Otherwise, it returns false. Only element nodes are supported; if the second argument is a text or comment node, $.contains() will return false.
Note: The first argument must be a DOM element, not a jQuery object or plain JavaScript object.
A: You can check element is present or not using length in java script.
If length is greater than zero then element is present if length is zero then
element is not present
// These by Id
if ($("#elementid").length > 0) {
// Element is Present
} else {
// Element is not Present
}
// These by Class
if ($(".elementClass").length > 0) {
// Element is Present
} else {
// Element is not Present
}
A: I have found if ($(selector).length) {} to be insufficient. It will silently break your app when selector is an empty object {}.
var $target = $({});
console.log($target, $target.length);
// Console output:
// -------------------------------------
// [▼ Object ] 1
// ► __proto__: Object
My only suggestion is to perform an additional check for {}.
if ($.isEmptyObject(selector) || !$(selector).length) {
throw new Error('Unable to work with the given selector.');
}
I'm still looking for a better solution though as this one is a bit heavy.
Edit: WARNING! This doesn't work in IE when selector is a string.
$.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE
A: If you used
jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }
you would imply that chaining was possible when it is not.
This would be better:
jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }
Alternatively, from the FAQ:
if ( $('#myDiv').length ) { /* Do something */ }
You could also use the following. If there are no values in the jQuery object array then getting the first item in the array would return undefined.
if ( $('#myDiv')[0] ) { /* Do something */ }
A: Checking for existence of an element is documented neatly in the official jQuery website itself!
Use the .length property of the jQuery collection returned by your
selector:
if ($("#myDiv").length) {
$("#myDiv").show();
}
Note that it isn't always necessary to test whether an element exists.
The following code will show the element if it exists, and do nothing
(with no errors) if it does not:
$("#myDiv").show();
A: this is very similar to all of the answers, but why not use the ! operator twice so you can get a boolean:
jQuery.fn.exists = function(){return !!this.length};
if ($(selector).exists()) {
// the element exists, now what?...
}
A: No need for jQuery (basic solution)
if(document.querySelector('.a-class')) {
// do something
}
Much more performant option below (notice the lack of a dot before a-class).
if(document.getElementsByClassName('a-class')[0]) {
// do something
}
querySelector uses a proper matching engine like $() (sizzle) in jQuery and uses more computing power but in 99% of cases will do just fine. The second option is more explicit and tells the code exactly what to do. It's much faster according to JSBench https://jsbench.me/65l2up3t8i
A: I found that this is the most jQuery way, IMHO.
Extending the default function is easy and can be done in a global extension file.
$.fn.exist = function(){
return !!this.length;
};
console.log($("#yes").exist())
console.log($("#no").exist())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="yes">id = yes</div>
A: $(selector).length && //Do something
A: Try testing for DOM element
if (!!$(selector)[0]) // do stuff
A: Inspired by hiway's answer I came up with the following:
$.fn.exists = function() {
return $.contains( document.documentElement, this[0] );
}
jQuery.contains takes two DOM elements and checks whether the first one contains the second one.
Using document.documentElement as the first argument fulfills the semantics of the exists method when we want to apply it solely to check the existence of an element in the current document.
Below, I've put together a snippet that compares jQuery.exists() against the $(sel)[0] and $(sel).length approaches which both return truthy values for $(4) while $(4).exists() returns false. In the context of checking for existence of an element in the DOM this seems to be the desired result.
$.fn.exists = function() {
return $.contains(document.documentElement, this[0]);
}
var testFuncs = [
function(jq) { return !!jq[0]; },
function(jq) { return !!jq.length; },
function(jq) { return jq.exists(); },
];
var inputs = [
["$()",$()],
["$(4)",$(4)],
["$('#idoexist')",$('#idoexist')],
["$('#idontexist')",$('#idontexist')]
];
for( var i = 0, l = inputs.length, tr, input; i < l; i++ ) {
input = inputs[i][1];
tr = "<tr><td>" + inputs[i][0] + "</td><td>"
+ testFuncs[0](input) + "</td><td>"
+ testFuncs[1](input) + "</td><td>"
+ testFuncs[2](input) + "</td></tr>";
$("table").append(tr);
}
td { border: 1px solid black }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="idoexist">#idoexist</div>
<table style>
<tr>
<td>Input</td><td>!!$(sel)[0]</td><td>!!$(sel).length</td><td>$(sel).exists()</td>
</tr>
</table>
<script>
$.fn.exists = function() {
return $.contains(document.documentElement, this[0]);
}
</script>
A: In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0 means false, everything else true. So you could write:
if ($(selector).length)
You don't need that >0 part.
A: I just like to use plain vanilla javascript to do this.
function isExists(selector){
return document.querySelectorAll(selector).length>0;
}
A: I stumbled upon this question and i'd like to share a snippet of code i currently use:
$.fn.exists = function(callback) {
var self = this;
var wrapper = (function(){
function notExists () {}
notExists.prototype.otherwise = function(fallback){
if (!self.length) {
fallback.call();
}
};
return new notExists;
})();
if(self.length) {
callback.call();
}
return wrapper;
}
And now i can write code like this -
$("#elem").exists(function(){
alert ("it exists");
}).otherwise(function(){
alert ("it doesn't exist");
});
It might seem a lot of code, but when written in CoffeeScript it is quite small:
$.fn.exists = (callback) ->
exists = @length
callback.call() if exists
new class
otherwise: (fallback) ->
fallback.call() if not exists
A: I had a case where I wanted to see if an object exists inside of another so I added something to the first answer to check for a selector inside the selector..
// Checks if an object exists.
// Usage:
//
// $(selector).exists()
//
// Or:
//
// $(selector).exists(anotherSelector);
jQuery.fn.exists = function(selector) {
return selector ? this.find(selector).length : this.length;
};
A: With jQuery you do not need >0, this is all you need:
if ($(selector).length)
With vanilla JS, you can do the same with:
if(document.querySelector(selector))
If you want to turn it into a function that returns bool:
const exists = selector => !!document.querySelector(selector);
if(exists(selector)){
// some code
}
A: How about:
function exists(selector) {
return $(selector).length;
}
if (exists(selector)) {
// do something
}
It's very minimal and saves you having to enclose the selector with $() every time.
A: I'm using this:
$.fn.ifExists = function(fn) {
if (this.length) {
$(fn(this));
}
};
$("#element").ifExists(
function($this){
$this.addClass('someClass').animate({marginTop:20},function(){alert('ok')});
}
);
Execute the chain only if a jQuery element exist - http://jsfiddle.net/andres_314/vbNM3/2/
A: $("selector") returns an object which has the length property. If the selector finds any elements, they will be included in the object. So if you check its length you can see if any elements exist. In JavaScript 0 == false, so if you don't get 0 your code will run.
if($("selector").length){
//code in the case
}
A: Here is my favorite exist method in jQuery
$.fn.exist = function(callback) {
return $(this).each(function () {
var target = $(this);
if (this.length > 0 && typeof callback === 'function') {
callback.call(target);
}
});
};
and other version which supports callback when selector does not exist
$.fn.exist = function(onExist, onNotExist) {
return $(this).each(function() {
var target = $(this);
if (this.length > 0) {
if (typeof onExist === 'function') {
onExist.call(target);
}
} else {
if (typeof onNotExist === 'function') {
onNotExist.call(target);
}
}
});
};
Example:
$('#foo .bar').exist(
function () {
// Stuff when '#foo .bar' exists
},
function () {
// Stuff when '#foo .bar' does not exist
}
);
A: You don't have to check if it's greater than 0 like $(selector).length > 0, $(selector).length it's enough and an elegant way to check the existence of elements. I don't think that it is worth to write a function only for this, if you want to do more extra things, then yes.
if($(selector).length){
// true if length is not 0
} else {
// false if length is 0
}
A: You can use this:
// if element exists
if($('selector').length){ /* do something */ }
// if element does not exist
if(!$('selector').length){ /* do something */ }
A: Yes!
jQuery.fn.exists = function(){ return this.length > 0; }
if ($(selector).exists()) {
// Do something
}
This is in response to: Herding Code podcast with Jeff Atwood
A: Here is the complete example of different situations and way to check if element exists using direct if on jQuery selector may or may not work because it returns array or elements.
var a = null;
var b = []
var c = undefined ;
if(a) { console.log(" a exist")} else { console.log("a doesn't exit")}
// output: a doesn't exit
if(b) { console.log(" b exist")} else { console.log("b doesn't exit")}
// output: b exist
if(c) { console.log(" c exist")} else { console.log("c doesn't exit")}
// output: c doesn't exit
FINAL SOLUTION
if($("#xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
//output : xusyxxs doesnn't exist
if($(".xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
//output : xusyxxs doesnn't exist
Demo
console.log("existing id", $('#id-1').length)
console.log("non existing id", $('#id-2').length)
console.log("existing class single instance", $('.cls-1').length)
console.log("existing class multiple instance", $('.cls-2').length)
console.log("non existing class", $('.cls-3').length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="id-1">
<div class="cls-1 cls-2"></div>
<div class="cls-2"></div>
</div>
A: Try this.
simple and short and usable in the whole project:
jQuery.fn.exists=function(){return !!this[0];}; //jQuery Plugin
Usage:
console.log($("element-selector").exists());
_________________________________
OR EVEN SHORTER:
(for when you don't want to define a jQuery plugin):
if(!!$("elem-selector")[0]) ...;
or even
if($("elem-selector")[0]) ...;
A: The fastest and most semantically self explaining way to check for existence is actually by using plain JavaScript:
if (document.getElementById('element_id')) {
// Do something
}
It is a bit longer to write than the jQuery length alternative, but executes faster since it is a native JS method.
And it is better than the alternative of writing your own jQuery function. That alternative is slower, for the reasons @snover stated. But it would also give other programmers the impression that the exists() function is something inherent to jQuery. JavaScript would/should be understood by others editing your code, without increased knowledge debt.
NB: Notice the lack of an '#' before the element_id (since this is plain JS, not jQuery).
A: if ( $('#myDiv').size() > 0 ) { //do something }
size() counts the number of elements returned by the selector
A: Yes The best method of doing this :
By JQuery :
if($("selector").length){
//code in the case
}
selector can be Element ID OR Element Class
OR
If you don't want to use jQuery Library then you can achieve this by using Core JavaScript :
By JavaScript :
if(document.getElementById("ElementID")) {
//Do something...
}
A: There is an oddity known as short circuit conditioning. Not many are making this feature known so allow me to explain! <3
//you can check if it isnt defined or if its falsy by using OR
console.log( $(selector) || 'this value doesnt exist' )
//or run the selector if its true, and ONLY true
console.log( $(selector) && 'this selector is defined, now lemme do somethin!' )
//sometimes I do the following, and see how similar it is to SWITCH
console.log(
({ //return something only if its in the method name
'string':'THIS is a string',
'function':'THIS is a function',
'number':'THIS is a number',
'boolean':'THIS is a boolean'
})[typeof $(selector)]||
//skips to this value if object above is undefined
'typeof THIS is not defined in your search')
The last bit allows me to see what kind of input my typeof has, and runs in that list. If there is a value outside of my list, I use the OR (||) operator to skip and nullify. This has the same performance as a Switch Case and is considered somewhat concise. Test Performance of the conditionals and uses of logical operators.
Side note: The Object-Function kinda has to be rewritten >.<' But this test I built was made to look into concise and expressive conditioning.
Resources:
Logical AND (with short circuit evaluation)
A: Thanks for sharing this question. First of all, there are multiple ways to check it.
If you want to check whether an HTML element exists in DOM. To do so you can try the following ways.
*
*Using Id selector: In DOM to select element by id, you should provide the name of the id starting with the prefix (#). You have to make sure that each Html element in the DOM must have unique id.
*Using class selector: You can select all elements with belonging to a specific class by using the prefix (.).
Now if you want to check if the element exist or not in DOM you can check it using the following code.
if($("#myId").length){
//id selector
}
if($(".myClass").length){
//class selector
}
If you want to check any variable is undefined or not. You can check it using the following code.
let x
if(x)
console.log("X");
else
console.log("X is not defined");
A: The input won't have a value if it doesn't exist. Try this...
if($(selector).val())
A: No, there is no such a method. But you can extend jQuery for your own one. Current way (2022) to do that is:
jQuery.fn.extend({
exists() { return !!this.length }
});
A: Use querySelectorAll with forEach, no need for if and extra assignment:
document.querySelectorAll('.my-element').forEach((element) => {
element.classList.add('new-class');
});
as the opposite to:
const myElement = document.querySelector('.my-element');
if (myElement) {
element.classList.add('new-class');
}
A: Use the following syntax to check if the element actually exists using jQuery.
let oElement = $(".myElementClass");
if(oElement[0]) {
// Do some jQuery operation here using oElement
}
else {
// Unable to fetch the object
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3104"
} |
Q: Setting up replicated repositories in Plastic SCM So we're trying to set up replicated repositories using PlasticSCM, one in the US, and one in Australia and running into a bit of a snag.
The US configuration is Active Directory, the AU configuration is User/Password. This in itself is not a big deal, I've already set up the SID translation table.
The problem is with plasticscm's replicate command itself. This is the command which should replicate from the US to AU, run ON the AU server.
cm replicate br:/main@rep:default@repserver:US:8084 rep:myrep@repserver:AU:9090 --trmode=name --trtable=trans.txt --authdata=ActiveDirectory:192.168.1.3:389:[email protected]:fPBea2rPsQaagEW3pKNveA==:dc=factory,dc=com
The part I'm stuck at is the authdata part (the above is an EXAMPLE only). How can I generate the obscured password? I think it's the only thing preventing these two repositories from talking to each other.
A: Ok, I've solved my own problem.
To get that "authdata" string, you need to configure your client to how you need to authenticate.
Then navigate to c:[users directory][username]\Local Settings\Application Data\plastic.
Pick up the client.conf and extract the string from the SecurityConfig element in the XML.
A: Check the new GUI here. It's a little bit easier.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Regex (C#): Replace \n with \r\n How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?
I know to do it using plan String.Replace, like:
myStr.Replace("\n", "\r\n");
myStr.Replace("\r\r\n", "\r\n");
However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist).
A: It might be faster if you use this.
(?<!\r)\n
It basically looks for any \n that is not preceded by a \r. This would most likely be faster, because in the other case, almost every letter matches [^\r], so it would capture that, and then look for the \n after that. In the example I gave, it would only stop when it found a \n, and them look before that to see if it found \r
A: Will this do?
[^\r]\n
Basically it matches a '\n' that is preceded with a character that is not '\r'.
If you want it to detect lines that start with just a single '\n' as well, then try
([^\r]|$)\n
Which says that it should match a '\n' but only those that is the first character of a line or those that are not preceded with '\r'
There might be special cases to check since you're messing with the definition of lines itself the '$' might not work too well. But I think you should get the idea.
EDIT: credit @Kibbee Using look-ahead s is clearly better since it won't capture the matched preceding character and should help with any edge cases as well. So here's a better regex + the code becomes:
myStr = Regex.Replace(myStr, "(?<!\r)\n", "\r\n");
A: I guess that "myStr" is an object of type String, in that case, this is not regex.
\r and \n are the equivalents for CR and LF.
My best guess is that if you know that you have an \n for EACH line, no matter what, then you first should strip out every \r. Then replace all \n with \r\n.
The answer chakrit gives would also go, but then you need to use regex, but since you don't say what "myStr" is...
Edit:looking at the other examples tells me one thing.. why do the difficult things, when you can do it easy?, Because there is regex, is not the same as "must use" :D
Edit2: A tool is very valuable when fiddling with regex, xpath, and whatnot that gives you strange results, may I point you to: http://www.regexbuddy.com/
A: I was trying to do the code below to a string and it was not working.
myStr.Replace("(?<!\r)\n", "\r\n")
I used Regex.Replace and it worked
Regex.Replace( oldValue, "(?<!\r)\n", "\r\n")
A: myStr.Replace("([^\r])\n", "$1\r\n");
$ may need to be a \
A: Try this: Replace(Char.ConvertFromUtf32(13), Char.ConvertFromUtf32(10) + Char.ConvertFromUtf32(13))
A: If I know the line endings must be one of CRLF or LF, something that works for me is
myStr.Replace("\r?\n", "\r\n");
This essentially does the same neslekkiM's answer except it performs only one replace operation on the string rather than two. This is also compatible with Regex engines that don't support negative lookbehinds or backreferences.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
} |
Q: How to insert a line break in a SQL Server VARCHAR/NVARCHAR string I didn't see any similar questions asked on this topic, and I had to research this for something I'm working on right now. Thought I would post the answer for it in case anyone else had the same question.
A: I'd say
concat('This is line 1.', 0xd0a, 'This is line 2.')
or
concat(N'This is line 1.', 0xd000a, N'This is line 2.')
A: char(13) is CR. For DOS-/Windows-style CRLF linebreaks, you want char(13)+char(10), like:
'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'
A: Here's a C# function that prepends a text line to an existing text blob, delimited by CRLFs, and returns a T-SQL expression suitable for INSERT or UPDATE operations. It's got some of our proprietary error handling in it, but once you rip that out, it may be helpful -- I hope so.
/// <summary>
/// Generate a SQL string value expression suitable for INSERT/UPDATE operations that prepends
/// the specified line to an existing block of text, assumed to have \r\n delimiters, and
/// truncate at a maximum length.
/// </summary>
/// <param name="sNewLine">Single text line to be prepended to existing text</param>
/// <param name="sOrigLines">Current text value; assumed to be CRLF-delimited</param>
/// <param name="iMaxLen">Integer field length</param>
/// <returns>String: SQL string expression suitable for INSERT/UPDATE operations. Empty on error.</returns>
private string PrependCommentLine(string sNewLine, String sOrigLines, int iMaxLen)
{
String fn = MethodBase.GetCurrentMethod().Name;
try
{
String [] line_array = sOrigLines.Split("\r\n".ToCharArray());
List<string> orig_lines = new List<string>();
foreach(String orig_line in line_array)
{
if (!String.IsNullOrEmpty(orig_line))
{
orig_lines.Add(orig_line);
}
} // end foreach(original line)
String final_comments = "'" + sNewLine + "' + CHAR(13) + CHAR(10) ";
int cum_length = sNewLine.Length + 2;
foreach(String orig_line in orig_lines)
{
String curline = orig_line;
if (cum_length >= iMaxLen) break; // stop appending if we're already over
if ((cum_length+orig_line.Length+2)>=iMaxLen) // If this one will push us over, truncate and warn:
{
Util.HandleAppErr(this, fn, "Truncating comments: " + orig_line);
curline = orig_line.Substring(0, iMaxLen - (cum_length + 3));
}
final_comments += " + '" + curline + "' + CHAR(13) + CHAR(10) \r\n";
cum_length += orig_line.Length + 2;
} // end foreach(second pass on original lines)
return(final_comments);
} // end main try()
catch(Exception exc)
{
Util.HandleExc(this,fn,exc);
return("");
}
}
A: All of these options work depending on your situation, but you may not see any of them work if you're using SSMS (as mentioned in some comments SSMS hides CR/LFs)
So rather than driving yourself round the bend, Check this setting in
Tools | Options
A: Run this in SSMS, it shows how line breaks in the SQL itself become part of string values that span lines :
PRINT 'Line 1
Line 2
Line 3'
PRINT ''
PRINT 'How long is a blank line feed?'
PRINT LEN('
')
PRINT ''
PRINT 'What are the ASCII values?'
PRINT ASCII(SUBSTRING('
',1,1))
PRINT ASCII(SUBSTRING('
',2,1))
Result :
Line 1
Line 2
Line 3
How long is a blank line feed?
2
What are the ASCII values?
13
10
Or if you'd rather specify your string on one line (almost!) you could employ REPLACE() like this (optionally use CHAR(13)+CHAR(10) as the replacement) :
PRINT REPLACE('Line 1`Line 2`Line 3','`','
')
A: I found the answer here: http://blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carriage-return-and-new-line-feed-in-code/
You just concatenate the string and insert a CHAR(13) where you want your line break.
Example:
DECLARE @text NVARCHAR(100)
SET @text = 'This is line 1.' + CHAR(13) + 'This is line 2.'
SELECT @text
This prints out the following:
This is line 1.
This is line 2.
A: This is always cool, because when you get exported lists from, say Oracle, then you get records spanning several lines, which in turn can be interesting for, say, cvs files, so beware.
Anyhow, Rob's answer is good, but I would advise using something else than @, try a few more, like §§@@§§ or something, so it will have a chance for some uniqueness. (But still, remember the length of the varchar/nvarchar field you are inserting into..)
A: Following a Google...
Taking the code from the website:
CREATE TABLE CRLF
(
col1 VARCHAR(1000)
)
INSERT CRLF SELECT 'The quick brown@'
INSERT CRLF SELECT 'fox @jumped'
INSERT CRLF SELECT '@over the '
INSERT CRLF SELECT 'log@'
SELECT col1 FROM CRLF
Returns:
col1
-----------------
The quick brown@
fox @jumped
@over the
log@
(4 row(s) affected)
UPDATE CRLF
SET col1 = REPLACE(col1, '@', CHAR(13))
Looks like it can be done by replacing a placeholder with CHAR(13)
Good question, never done it myself :)
A: I got here because I was concerned that cr-lfs that I specified in C# strings were not being shown in SQl Server Management Studio query responses.
It turns out, they are there, but are not being displayed.
To "see" the cr-lfs, use the print statement like:
declare @tmp varchar(500)
select @tmp = msgbody from emailssentlog where id=6769;
print @tmp
A: Another way to do this is as such:
INSERT CRLF SELECT 'fox
jumped'
That is, simply inserting a line break in your query while writing it will add the like break to the database. This works in SQL server Management studio and Query Analyzer. I believe this will also work in C# if you use the @ sign on strings.
string str = @"INSERT CRLF SELECT 'fox
jumped'"
A: In some special cases you may find this useful (e.g. rendering cell-content in MS Report )
example:
select * from
(
values
('use STAGING'),
('go'),
('EXEC sp_MSforeachtable
@command1=''select ''''?'''' as tablename,count(1) as anzahl from ? having count(1) = 0''')
) as t([Copy_and_execute_this_statement])
go
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "670"
} |
Q: How do you configure an OpenFileDialog to select folders? In VS .NET, when you are selecting a folder for a project, a dialog that looks like an OpenFileDialog or SaveFileDialog is displayed, but is set up to accept only folders. Ever since I've seen this I've wanted to know how it's done. I am aware of the FolderBrowserDialog, but I've never really liked that dialog. It starts too small and doesn't let me take advantage of being able to type a path.
I'm almost certain by now there's not a way to do this from .NET, but I'm just as curious how you do it from unmanaged code as well. Short of completely reimplementing the dialog from scratch, how do you modify the dialog to have this behavior?
I'd also like to restate that I am aware of the FolderBrowserDialog but sometimes I don't like to use it, in addition to being genuinely curious how to configure a dialog in this manner. Telling me to just use the FolderBrowserDialog helps me maintain a consistent UI experience but doesn't satisfy my curiosity so it won't count as an answer.
It's not a Vista-specific thing either; I've been seeing this dialog since VS .NET 2003, so it is doable in Win2k and WinXP. This is less of a "I want to know the proper way to do this" question and more of a "I have been curious about this since I first wanted to do it in VS 2003" question. I understand that Vista's file dialog has an option to do this, but it's been working in XP so I know they did something to get it to work. Vista-specific answers are not answers, because Vista doesn't exist in the question context.
Update: I'm accepting Scott Wisniewski's answer because it comes with a working sample, but I think Serge deserves credit for pointing to the dialog customization (which is admittedly nasty from .NET but it does work) and Mark Ransom for figuring out that MS probably rolled a custom dialog for this task.
A: I have a dialog that I wrote called an OpenFileOrFolder dialog that allows you to open either a folder or a file.
If you set its AcceptFiles value to false, then it operates in only accept folder mode.
You can download the source from GitHub here
A: There is the Windows API Code Pack. It's got a lot of shell related stuff, including the CommonOpenFileDialog class (in the Microsoft.WindowsAPICodePack.Dialogs namespace). This is the perfect solution - the usual open dialog with only folders displayed.
Here is an example of how to use it:
CommonOpenFileDialog cofd = new CommonOpenFileDialog();
cofd.IsFolderPicker = true;
cofd.ShowDialog();
Unfortunately Microsoft no longer ships this package, but several people have unofficially uploaded binaries to NuGet. One example can be found here. This package is just the shell-specific stuff. Should you need it, the same user has several other packages which offer more functionality present in the original package.
A: I assume you're on Vista using VS2008? In that case I think that the FOS_PICKFOLDERS option is being used when calling the Vista file dialog IFileDialog. I'm afraid that in .NET code this would involve plenty of gnarly P/Invoke interop code to get working.
A: You can use FolderBrowserDialogEx -
a re-usable derivative of the built-in FolderBrowserDialog. This one allows you to type in a path, even a UNC path. You can also browse for computers or printers with it. Works just like the built-in FBD, but ... better.
(EDIT: I should have pointed out that this dialog can be set to select files or folders. )
Full Source code (one short C# module). Free. MS-Public license.
Code to use it:
var dlg1 = new Ionic.Utils.FolderBrowserDialogEx();
dlg1.Description = "Select a folder to extract to:";
dlg1.ShowNewFolderButton = true;
dlg1.ShowEditBox = true;
//dlg1.NewStyle = false;
dlg1.SelectedPath = txtExtractDirectory.Text;
dlg1.ShowFullPathInEditBox = true;
dlg1.RootFolder = System.Environment.SpecialFolder.MyComputer;
// Show the FolderBrowserDialog.
DialogResult result = dlg1.ShowDialog();
if (result == DialogResult.OK)
{
txtExtractDirectory.Text = dlg1.SelectedPath;
}
A: The Ookii.Dialogs package contains a managed wrapper around the new (Vista-style) folder browser dialog. It also degrades gracefully on older operating systems.
*
*Ookii Dialogs for WPF targetting .NET 4.5 and available on NuGet
*Ookii Dialogs for Windows Forms targetting .NET 4.5 and available on NuGet
A: First Solution
I developed this as a cleaned up version of .NET Win 7-style folder select dialog by Bill Seddon of lyquidity.com (I have no affiliation). (I learned of his code from another answer on this page). I wrote my own because his solution requires an additional Reflection class that isn't needed for this focused purpose, uses exception-based flow control, doesn't cache the results of its reflection calls. Note that the nested static VistaDialog class is so that its static reflection variables don't try to get populated if the Show method is never called. It falls back to the pre-Vista dialog if not in a high enough Windows version. Should work in Windows 7, 8, 9, 10 and higher (theoretically).
using System;
using System.Reflection;
using System.Windows.Forms;
namespace ErikE.Shuriken {
/// <summary>
/// Present the Windows Vista-style open file dialog to select a folder. Fall back for older Windows Versions
/// </summary>
public class FolderSelectDialog {
private string _initialDirectory;
private string _title;
private string _fileName = "";
public string InitialDirectory {
get { return string.IsNullOrEmpty(_initialDirectory) ? Environment.CurrentDirectory : _initialDirectory; }
set { _initialDirectory = value; }
}
public string Title {
get { return _title ?? "Select a folder"; }
set { _title = value; }
}
public string FileName { get { return _fileName; } }
public bool Show() { return Show(IntPtr.Zero); }
/// <param name="hWndOwner">Handle of the control or window to be the parent of the file dialog</param>
/// <returns>true if the user clicks OK</returns>
public bool Show(IntPtr hWndOwner) {
var result = Environment.OSVersion.Version.Major >= 6
? VistaDialog.Show(hWndOwner, InitialDirectory, Title)
: ShowXpDialog(hWndOwner, InitialDirectory, Title);
_fileName = result.FileName;
return result.Result;
}
private struct ShowDialogResult {
public bool Result { get; set; }
public string FileName { get; set; }
}
private static ShowDialogResult ShowXpDialog(IntPtr ownerHandle, string initialDirectory, string title) {
var folderBrowserDialog = new FolderBrowserDialog {
Description = title,
SelectedPath = initialDirectory,
ShowNewFolderButton = false
};
var dialogResult = new ShowDialogResult();
if (folderBrowserDialog.ShowDialog(new WindowWrapper(ownerHandle)) == DialogResult.OK) {
dialogResult.Result = true;
dialogResult.FileName = folderBrowserDialog.SelectedPath;
}
return dialogResult;
}
private static class VistaDialog {
private const string c_foldersFilter = "Folders|\n";
private const BindingFlags c_flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
private readonly static Assembly s_windowsFormsAssembly = typeof(FileDialog).Assembly;
private readonly static Type s_iFileDialogType = s_windowsFormsAssembly.GetType("System.Windows.Forms.FileDialogNative+IFileDialog");
private readonly static MethodInfo s_createVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("CreateVistaDialog", c_flags);
private readonly static MethodInfo s_onBeforeVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("OnBeforeVistaDialog", c_flags);
private readonly static MethodInfo s_getOptionsMethodInfo = typeof(FileDialog).GetMethod("GetOptions", c_flags);
private readonly static MethodInfo s_setOptionsMethodInfo = s_iFileDialogType.GetMethod("SetOptions", c_flags);
private readonly static uint s_fosPickFoldersBitFlag = (uint) s_windowsFormsAssembly
.GetType("System.Windows.Forms.FileDialogNative+FOS")
.GetField("FOS_PICKFOLDERS")
.GetValue(null);
private readonly static ConstructorInfo s_vistaDialogEventsConstructorInfo = s_windowsFormsAssembly
.GetType("System.Windows.Forms.FileDialog+VistaDialogEvents")
.GetConstructor(c_flags, null, new[] { typeof(FileDialog) }, null);
private readonly static MethodInfo s_adviseMethodInfo = s_iFileDialogType.GetMethod("Advise");
private readonly static MethodInfo s_unAdviseMethodInfo = s_iFileDialogType.GetMethod("Unadvise");
private readonly static MethodInfo s_showMethodInfo = s_iFileDialogType.GetMethod("Show");
public static ShowDialogResult Show(IntPtr ownerHandle, string initialDirectory, string title) {
var openFileDialog = new OpenFileDialog {
AddExtension = false,
CheckFileExists = false,
DereferenceLinks = true,
Filter = c_foldersFilter,
InitialDirectory = initialDirectory,
Multiselect = false,
Title = title
};
var iFileDialog = s_createVistaDialogMethodInfo.Invoke(openFileDialog, new object[] { });
s_onBeforeVistaDialogMethodInfo.Invoke(openFileDialog, new[] { iFileDialog });
s_setOptionsMethodInfo.Invoke(iFileDialog, new object[] { (uint) s_getOptionsMethodInfo.Invoke(openFileDialog, new object[] { }) | s_fosPickFoldersBitFlag });
var adviseParametersWithOutputConnectionToken = new[] { s_vistaDialogEventsConstructorInfo.Invoke(new object[] { openFileDialog }), 0U };
s_adviseMethodInfo.Invoke(iFileDialog, adviseParametersWithOutputConnectionToken);
try {
int retVal = (int) s_showMethodInfo.Invoke(iFileDialog, new object[] { ownerHandle });
return new ShowDialogResult {
Result = retVal == 0,
FileName = openFileDialog.FileName
};
}
finally {
s_unAdviseMethodInfo.Invoke(iFileDialog, new[] { adviseParametersWithOutputConnectionToken[1] });
}
}
}
// Wrap an IWin32Window around an IntPtr
private class WindowWrapper : IWin32Window {
private readonly IntPtr _handle;
public WindowWrapper(IntPtr handle) { _handle = handle; }
public IntPtr Handle { get { return _handle; } }
}
}
}
It is used like so in a Windows Form:
var dialog = new FolderSelectDialog {
InitialDirectory = musicFolderTextBox.Text,
Title = "Select a folder to import music from"
};
if (dialog.Show(Handle)) {
musicFolderTextBox.Text = dialog.FileName;
}
You can of course play around with its options and what properties it exposes. For example, it allows multiselect in the Vista-style dialog.
Second Solution
Simon Mourier gave an answer that shows how to do the exact same job using interop against the Windows API directly, though his version would have to be supplemented to use the older style dialog if in an older version of Windows. Unfortunately, I hadn't found his post yet when I worked up my solution. Name your poison!
A: Better to use the FolderBrowserDialog for that.
using (FolderBrowserDialog dlg = new FolderBrowserDialog())
{
dlg.Description = "Select a folder";
if (dlg.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("You selected: " + dlg.SelectedPath);
}
}
A: After hours of searching I found this answer by leetNightShade to a working solution.
There are three things I believe make this solution much better than all the others.
*
*It is simple to use.
It only requires you include two files (which can be combined to one anyway) in your project.
*It falls back to the standard FolderBrowserDialog when used on XP or older systems.
*The author grants permission to use the code for any purpose you deem fit.
There’s no license as such as you are free to take and do with the code what you will.
Download the code here.
A: OK, let me try to connect the first dot ;-)
Playing a little bit with Spy++ or Winspector shows that the Folder textbox in the VS Project Location is a customization of the standard dialog. It's not the same field as the filename textbox in a standard file dialog such as the one in Notepad.
From there on, I figure, VS hides the filename and filetype textboxes/comboboxes and uses a custom dialog template to add its own part in the bottom of the dialog.
EDIT: Here's an example of such customization and how to do it (in Win32. not .NET):
m_ofn is the OPENFILENAME struct that underlies the file dialog. Add these 2 lines:
m_ofn.lpTemplateName = MAKEINTRESOURCE(IDD_FILEDIALOG_IMPORTXLIFF);
m_ofn.Flags |= OFN_ENABLETEMPLATE;
where IDD_FILEDIALOG_IMPORTXLIFF is a custom dialog template that will be added in the bottom of the dialog. See the part in red below.
(source: apptranslator.com)
In this case, the customized part is only a label + an hyperlink but it could be any dialog. It could contain an OK button that would let us validate folder only selection.
But how we would get rid of some of the controls in the standard part of the dialog, I don't know.
More detail in this MSDN article.
A: Exact Audio Copy works this way on Windows XP. The standard file open dialog is shown, but the filename field contains the text "Filename will be ignored".
Just guessing here, but I suspect the string is injected into the combo box edit control every time a significant change is made to the dialog. As long as the field isn't blank, and the dialog flags are set to not check the existence of the file, the dialog can be closed normally.
Edit: this is much easier than I thought. Here's the code in C++/MFC, you can translate it to the environment of your choice.
CFileDialog dlg(true, NULL, "Filename will be ignored", OFN_HIDEREADONLY | OFN_NOVALIDATE | OFN_PATHMUSTEXIST | OFN_READONLY, NULL, this);
dlg.DoModal();
Edit 2: This should be the translation to C#, but I'm not fluent in C# so don't shoot me if it doesn't work.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.FileName = "Filename will be ignored";
openFileDialog1.CheckPathExists = true;
openFileDialog1.ShowReadOnly = false;
openFileDialog1.ReadOnlyChecked = true;
openFileDialog1.CheckFileExists = false;
openFileDialog1.ValidateNames = false;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
// openFileDialog1.FileName should contain the folder and a dummy filename
}
Edit 3: Finally looked at the actual dialog in question, in Visual Studio 2005 (I didn't have access to it earlier). It is not the standard file open dialog! If you inspect the windows in Spy++ and compare them to a standard file open, you'll see that the structure and class names don't match. When you look closely, you can also spot some differences between the contents of the dialogs. My conclusion is that Microsoft completely replaced the standard dialog in Visual Studio to give it this capability. My solution or something similar will be as close as you can get, unless you're willing to code your own from scratch.
A: You can subclass the file dialog and gain access to all its controls. Each has an identifier that can be used to obtain its window handle. You can then show and hide them, get messages from them about selection changes etc. etc. It all depends how much effort you want to take.
We did ours using WTL class support and customized the file dialog to include a custom places bar and plug-in COM views.
MSDN provides information on how to do this using Win32, this CodeProject article includes an example, and this CodeProject article provides a .NET example.
A: You can use code like this
*
*The filter is hide files
*The filename is hide first text
To advanced hide of textbox for filename you need to look at
OpenFileDialogEx
The code:
{
openFileDialog2.FileName = "\r";
openFileDialog1.Filter = "folders|*.neverseenthisfile";
openFileDialog1.CheckFileExists = false;
openFileDialog1.CheckPathExists = false;
}
A: Try this one from Codeproject (credit to Nitron):
I think it's the same dialog you're talking about - maybe it would help if you add a screenshot?
bool GetFolder(std::string& folderpath, const char* szCaption=NULL, HWND hOwner=NULL)
{
bool retVal = false;
// The BROWSEINFO struct tells the shell how it should display the dialog.
BROWSEINFO bi;
memset(&bi, 0, sizeof(bi));
bi.ulFlags = BIF_USENEWUI;
bi.hwndOwner = hOwner;
bi.lpszTitle = szCaption;
// must call this if using BIF_USENEWUI
::OleInitialize(NULL);
// Show the dialog and get the itemIDList for the selected folder.
LPITEMIDLIST pIDL = ::SHBrowseForFolder(&bi);
if(pIDL != NULL)
{
// Create a buffer to store the path, then get the path.
char buffer[_MAX_PATH] = {'\0'};
if(::SHGetPathFromIDList(pIDL, buffer) != 0)
{
// Set the string value.
folderpath = buffer;
retVal = true;
}
// free the item id list
CoTaskMemFree(pIDL);
}
::OleUninitialize();
return retVal;
}
A: On Vista you can use IFileDialog with FOS_PICKFOLDERS option set. That will cause display of OpenFileDialog-like window where you can select folders:
var frm = (IFileDialog)(new FileOpenDialogRCW());
uint options;
frm.GetOptions(out options);
options |= FOS_PICKFOLDERS;
frm.SetOptions(options);
if (frm.Show(owner.Handle) == S_OK) {
IShellItem shellItem;
frm.GetResult(out shellItem);
IntPtr pszString;
shellItem.GetDisplayName(SIGDN_FILESYSPATH, out pszString);
this.Folder = Marshal.PtrToStringAuto(pszString);
}
For older Windows you can always resort to trick with selecting any file in folder.
Working example that works on .NET Framework 2.0 and later can be found here.
A: You can use code like this
The filter is empty string.
The filename is AnyName but not blank
openFileDialog.FileName = "AnyFile";
openFileDialog.Filter = string.Empty;
openFileDialog.CheckFileExists = false;
openFileDialog.CheckPathExists = false;
A: The Ookii Dialogs for WPF library has a class that provides an implementation of a folder browser dialog for WPF.
https://github.com/augustoproiete/ookii-dialogs-wpf
There's also a version that works with Windows Forms.
A: I know the question was on configuration of OpenFileDialog but seeing that Google brought me here i may as well point out that if you are ONLY looking for folders you should be using a FolderBrowserDialog Instead as answered by another SO question below
How to specify path using open file dialog in vb.net?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "260"
} |
Q: How do I find the 'temp' directory in Linux? How do I find the 'temp' directory in Linux? I am writing a platform neutral C++ function that returns the temp directory. In Mac and Windows, there is an API that returns these results. In Linux, I'm stumped.
A: Check following variables:
*
*The environment variable TMPDIR
*The value of the P_tmpdir macro
If all fails try to use the directory /tmp.
You can also use tempnam function to generate a unique temporary file name.
A: Edit: Fair point from the commenter. tmpnam isn't a good choice these days; use mktemp/mkstemp instead.
Historical answer: Be POSIX compliant, and use tmpnam (which will give you a full filename in a temporary location).
A: Use the value of the $TMPDIR environment variable, and if that doesn't exist, use /tmp.
A: The accepted sequence, specifically from a GNU standpoint, is:
*
*Check the environmental variable TMPDIR (getenv("TMPDIR")) only if
the program is not running as SUID/SGID (issetugid() == 0)
*Otherwise use P_tmpdir if it is defined and is valid
*and finally, should those fail, use _PATH_TMP available from paths.h
If you are adding an extension or module, check to see if the core provides a function for this purpose. For example, PHP exports php_get_temporary_directory() from main/php_open_temporary_file.h.
A: In standard c, you could try: P_tmpdir
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
} |
Q: Attaching to a foreign executable in Visual C++ 2003 I have an executable (compiled by someone else) that is hitting an assertion near my code. I work on the code in Visual C++ 2003, but I don't have a project file for this particular executable (the code is used to build many different tools). Is it possible to launch the binary in Visual C++'s debugger and just tell it where the sources are? I've done this before in GDB, so I know it ought to be possible.
A: Without the PDB symbols for that application you're going to have a tough time making heads or tails of what is going on and where. I think any source code information is going to be only in that PDB file that was created when whoever built that application.
This is assuming that the PDB file was EVER created for this application - which is not the default configuration for release mode VC++ projects I think. Since you're asserting, I guessing this is a debug configuration?
A: Short of any other answers, I would try attaching to the executable process in Visual Studio, setting a break point in your code and when you step into the process you don't have source to, it should ask for a source file.
A: Yes, it's possible. Just set up an empty project and specify the desired .exe file as debug target. I don't remember exactly how, but I know it's doable, because I used to set winamp.exe as debug target when I developed plug-ins for Winamp.
Since you don't have the source file it will only show the assembly code, but that might still be useful as you can also inspect memory, registers, etc.
Update
If you are debugging an assertion in your own program you should be able to see the source just fine, since the path to the source file is stored in the executable when you compile it with debug information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I display a PDF in Adobe Flex? Looking for a way to display a PDF in Flex. I'm sure there are several ways. Looking for the easiest to maintain / integrate / most user friendly. I'm guessing it's possible to display a browser window in the app and render it, but if it goes off of IE / FireFox it's not acceptable for this project.
Thanks...
A: This looks like a nice PDF viewer for flex http://www.devaldi.com/?p=212
A: We just did a large AIR app that used PDF quite a bit - make sure you save yourself some heartache and write some code to check the acrobat version or that it's even installed - if they don't have it you won't get an error, just a blank HTML control.
I know, it sounds obvious, but still...
A: Sorry to say so, but convertion PDF to kind of swf of flash things... doesn't that kill the PDF thoughts ?
I mean, PDF should be electronic paper right ? When creating a SWF file out of it, you just destroy that. No more editing, no more filling out a form.
The strange thing is, that PDF is an Adobe product... and Flex (Flash Builder) is a Adobe product.
Two products that Adobe wants to be world dominator off. But combining PDF into Flex... is not standard.
A: Check out: http://www.swftools.org/ for tools to convert your PDF to SWF, speifically pdf2swf- http://www.swftools.org/pdf2swf.html
A: Check out Share on Acrobat.com, there you can upload PDFs and make them embedable Flash files (sort of like YouTube for documents). Should be possible to load those into Flex. Not an ideal solution, but unfortunately you need to convert the PDF to an SWF somehow to be able to load it into a Flex application. I don't know of any good tools that do this. If someone else knows please share.
If you target AIR you can load a PDF into a HTML view, but that doesn't work when running in the browser (the HTML component is only available in AIR).
A: in Adobe Digital Edition, Adobe Load PDFs into flash (if you check the main file .exe you can see it), without any convert. therefore i think it is possible to do.
i decompiled it and found lot of classes related to pdf but i can't run it after recompiled it :(
if you solve this problem you should focus the Adobe Digital Edition product.
A: Oh sweet, this is an air app. I'll go with the HTML view. I can't convert them to SWF because the client will be uploading the files.
A: if AIR Application,
use HTMLLoader().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: What is the best way to inherit an array that needs to store subclass specific data? I'm trying to set up an inheritance hierarchy similar to the following:
abstract class Vehicle
{
public string Name;
public List<Axle> Axles;
}
class Motorcycle : Vehicle
{
}
class Car : Vehicle
{
}
abstract class Axle
{
public int Length;
public void Turn(int numTurns) { ... }
}
class MotorcycleAxle : Axle
{
public bool WheelAttached;
}
class CarAxle : Axle
{
public bool LeftWheelAttached;
public bool RightWheelAttached;
}
I would like to only store MotorcycleAxle objects in a Motorcycle object's Axles array, and CarAxle objects in a Car object's Axles array. The problem is there is no way to override the array in the subclass to force one or the other. Ideally something like the following would be valid for the Motorcycle class:
class Motorcycle : Vehicle
{
public override List<MotorcycleAxle> Axles;
}
but the types have to match when overriding. How can I support this architecture? Will I just have to do a lot of run-time type checking and casting wherever the Axles member is accessed? I don't like adding run-time type checks because you start to lose the benefits of strong typing and polymorphism. There have to be at least some run-time checks in this scenario since the WheelAttached and Left/RightWheelAttached properties depend on the type, but I would like to minimize them.
A: Use more generics
abstract class Vehicle<T> where T : Axle
{
public string Name;
public List<T> Axles;
}
class Motorcycle : Vehicle<MotorcycleAxle>
{
}
class Car : Vehicle<CarAxle>
{
}
abstract class Axle
{
public int Length;
public void Turn(int numTurns) { ... }
}
class MotorcycleAxle : Axle
{
public bool WheelAttached;
}
class CarAxle : Axle
{
public bool LeftWheelAttached;
public bool RightWheelAttached;
}
A: 2 options spring to mind. 1 is using generics:
abstract class Vehicle<TAxle> where TAxle : Axle {
public List<TAxle> Axles;
}
The second uses shadowing - and this assumes you have properties:
abstract class Vehicle {
public IList<Axle> Axles { get; set; }
}
class Motorcyle : Vehicle {
public new IList<MotorcycleAxle> Axles { get; set; }
}
class Car : Vehicle {
public new IList<CarAxle> Axles { get; set; }
}
void Main() {
Vehicle v = new Car();
// v.Axles is IList<Axle>
Car c = (Car) v;
// c.Axles is IList<CarAxle>
// ((Vehicle)c).Axles is IList<Axle>
The problem with shadowing is that you have a generic List. Unfortunately, you can't constrain the list to only contain CarAxle. Also, you can't cast a List<Axle> into List<CarAxle> - even though there's an inheritance chain there. You have to cast each object into a new List (though that becomes much easier with LINQ).
I'd go for generics myself.
A: I asked a similar question and got a better answer, the problem is related to C#'s support for covariance and contravariance. See that discussion for a little more information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What control is this? ("Open" Button with Drop Down) The Open button on the open file dialog used in certain windows applications includes a dropdown arrow with a list of additional options — namely Open With...
I haven't seen this in every Windows application, so you may have to try a few to get it, but SQL Server Management Studio and Visual Studio 2017 will both show the button that way if you go to the menu and choose File->Open->File...
I want to use a button like this with a built-in list in one of my applications, but I can't find the control they're using anywhere in Visual Studio. I should clarify that I'm looking for that specific button, not the entire dialog. Any thoughts?
A: I used the draggable search in Spy++ (installed with VS) to look at the split open button on the file-open dialog of VS.
This revealed that it's an ordinary windows button with a style which includes BS_DEFSPLITBUTTON. That's a magic keyword which gets you to some interesting places, including
http://www.codeplex.com/windowsformsaero/SourceControl/FileView.aspx?itemId=212902&changeSetId=9930
and here
http://msdn.microsoft.com/en-us/library/bb775949.aspx#using_splits
Hope this helps you.
EDIT:
I've actually just tried that code from CodePlex and it does create a split button - but you do have to make sure you've set the button's FlatStyle to 'System' rather than 'Standard' which is the default. I've not bothered to hook-up the event handling stuff for the drop-down, but that's covered in the MSDN link, I think.
Of course, this is Vista-only (but doesn't need Aero enabled, despite the name on codeplex) - if you need earlier OS support, you'll be back to drawing it yourself.
A: I remembered that Ketarin has a button like that.
Using Reflector I found great open source control called wyDay.SplitButton.
A: I think what you are looking for is called a toolStripSplitButton. It is only available in a toolStrip. But you can add a toolStripContainer anywhere on your form and then put the toolStrip and toolStripSplitButton inside your container.
You won't want to show the grips so you'll want to set your gripMargin = 0. You can also set your autosize=true so that the toolstrip conforms to your button. The button will just look like a normal button (except for the split part) on your form.
A: I've not familiar with using either of these, but try searching msdn for splitbutton or dropdownbutton. I think those are similar to what you're looking for.
A: Here's my split button implementation. It does not draw the arrow, and the focus/unfocus behavior is a little different.
Both mine and the originals handle visual styles and look great with Aero.
Based on http://wyday.com/splitbutton/
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using System.Drawing;
using System.ComponentModel;
using System.Diagnostics;
// Original: http://blogs.msdn.com/jfoscoding/articles/491523.aspx
// Wyatt's fixes: http://wyday.com/splitbutton/
// Trimmed down and redone significantly from that version (Nick 5/6/08)
namespace DF
{
public class SplitButton : Button
{
private ContextMenuStrip m_SplitMenu = null;
private const int SplitSectionWidth = 14;
private static int BorderSize = SystemInformation.Border3DSize.Width * 2;
private bool mBlockClicks = false;
private Timer mTimer;
public SplitButton()
{
this.AutoSize = true;
mTimer = new Timer();
mTimer.Interval = 100;
mTimer.Tick += new EventHandler(mTimer_Tick);
}
private void mTimer_Tick(object sender, EventArgs e)
{
mBlockClicks = false;
mTimer.Stop();
}
#region Properties
[DefaultValue(null)]
public ContextMenuStrip SplitMenu
{
get
{
return m_SplitMenu;
}
set
{
if (m_SplitMenu != null)
m_SplitMenu.Closing -=
new ToolStripDropDownClosingEventHandler(m_SplitMenu_Closing);
m_SplitMenu = value;
if (m_SplitMenu != null)
m_SplitMenu.Closing +=
new ToolStripDropDownClosingEventHandler(m_SplitMenu_Closing);
}
}
private void m_SplitMenu_Closing(object sender, ToolStripDropDownClosingEventArgs e)
{
HideContextMenuStrip();
// block click events for 0.5 sec to prevent re-showing the menu
}
private PushButtonState _state;
private PushButtonState State
{
get
{
return _state;
}
set
{
if (!_state.Equals(value))
{
_state = value;
Invalidate();
}
}
}
#endregion Properties
protected override void OnEnabledChanged(EventArgs e)
{
if (Enabled)
State = PushButtonState.Normal;
else
State = PushButtonState.Disabled;
base.OnEnabledChanged(e);
}
protected override void OnMouseClick(MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;
if (State.Equals(PushButtonState.Disabled))
return;
if (mBlockClicks)
return;
if (!State.Equals(PushButtonState.Pressed))
ShowContextMenuStrip();
else
HideContextMenuStrip();
}
protected override void OnMouseEnter(EventArgs e)
{
if (!State.Equals(PushButtonState.Pressed) && !State.Equals(PushButtonState.Disabled))
{
State = PushButtonState.Hot;
}
}
protected override void OnMouseLeave(EventArgs e)
{
if (!State.Equals(PushButtonState.Pressed) && !State.Equals(PushButtonState.Disabled))
{
if (Focused)
{
State = PushButtonState.Default;
}
else
{
State = PushButtonState.Normal;
}
}
}
protected override void OnPaint(PaintEventArgs pevent)
{
base.OnPaint(pevent);
Graphics g = pevent.Graphics;
Rectangle bounds = this.ClientRectangle;
// draw the button background as according to the current state.
if (State != PushButtonState.Pressed && IsDefault && !Application.RenderWithVisualStyles)
{
Rectangle backgroundBounds = bounds;
backgroundBounds.Inflate(-1, -1);
ButtonRenderer.DrawButton(g, backgroundBounds, State);
// button renderer doesnt draw the black frame when themes are off =(
g.DrawRectangle(SystemPens.WindowFrame, 0, 0, bounds.Width - 1, bounds.Height - 1);
}
else
{
ButtonRenderer.DrawButton(g, bounds, State);
}
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
g.DrawString(Text, Font, SystemBrushes.ControlText, bounds, format);
}
private void ShowContextMenuStrip()
{
State = PushButtonState.Pressed;
if (m_SplitMenu != null)
{
m_SplitMenu.Show(this, new Point(0, Height), ToolStripDropDownDirection.BelowRight);
}
}
private void HideContextMenuStrip()
{
State = PushButtonState.Normal;
m_SplitMenu.Hide();
mBlockClicks = true;
mTimer.Start();
}
}
}
A: I don't think there's a built-in control that can do it in .NET. I'm poking around in the MSDN documentation for the standard Windows Button control, but it doesn't look like it's there.
I did find a Code Project article with a custom implementation; this might help a little.
A: Since I found the control in Windows itself, I was hoping to find it built-in somewhere already so I didn't have to add anything to my code-base to use it. But the split button at this link (found via the msdn suggestion) looks pretty promising.
I'll try it later myself, but I don't know how well it will handle visual styles.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Process Memory Size - Different Counters I'm trying to find out how much memory my own .Net server process is using (for monitoring and logging purposes).
I'm using:
Process.GetCurrentProcess().PrivateMemorySize64
However, the Process object has several different properties that let me read the memory space used:
Paged, NonPaged, PagedSystem, NonPagedSystem, Private, Virtual, WorkingSet
and then the "peaks": which i'm guessing just store the maximum values these last ones ever took.
Reading through the MSDN definition of each property hasn't proved too helpful for me. I have to admit my knowledge regarding how memory is managed (as far as paging and virtual goes) is very limited.
So my question is obviously "which one should I use?", and I know the answer is "it depends".
This process will basically hold a bunch of lists in memory of things that are going on, while other processes communicate with it and query it for stuff. I'm expecting the server where this will run on to require lots of RAM, and so i'm querying this data over time to be able to estimate RAM requirements when compared to the sizes of the lists it keeps inside.
So... Which one should I use and why?
A: OK, I found through Google the same page that Lars mentioned, and I believe it's a great explanation for people that don't quite know how memory works (like me).
http://shsc.info/WindowsMemoryManagement
My short conclusion was:
*
*Private Bytes = The Memory my process has requested to store data. Some of it may be paged to disk or not. This is the information I was looking for.
*Virtual Bytes = The Private Bytes, plus the space shared with other processes for loaded DLLs, etc.
*Working Set = The portion of ALL the memory of my process that has not been paged to disk. So the amount paged to disk should be (Virtual - Working Set).
Thanks all for your help!
A: If you want to use the "Memory (Private Working Set)" as shown in Windows Vista task manager, which is the equivalent of Process Explorer "WS Private Bytes", here is the code. Probably best to throw this infinite loop in a thread/background task for real-time stats.
using System.Threading;
using System.Diagnostics;
//namespace...class...method
Process thisProc = Process.GetCurrentProcess();
PerformanceCounter PC = new PerformanceCounter();
PC.CategoryName = "Process";
PC.CounterName = "Working Set - Private";
PC.InstanceName = thisProc.ProcessName;
while (true)
{
String privMemory = (PC.NextValue()/1000).ToString()+"KB (Private Bytes)";
//Do something with string privMemory
Thread.Sleep(1000);
}
A: To get the value that Task Manager gives, my hat's off to Mike Regan's solution above. However, one change: it is not: perfCounter.NextValue()/1000; but perfCounter.NextValue()/1024; (i.e. a real kilobyte). This gives the exact value you see in Task Manager.
Following is a full solution for displaying the 'memory usage' (Task manager's, as given) in a simple way in your WPF or WinForms app (in this case, simply in the title). Just call this method within the new Window constructor:
private void DisplayMemoryUsageInTitleAsync()
{
origWindowTitle = this.Title; // set WinForms or WPF Window Title to field
BackgroundWorker wrkr = new BackgroundWorker();
wrkr.WorkerReportsProgress = true;
wrkr.DoWork += (object sender, DoWorkEventArgs e) => {
Process currProcess = Process.GetCurrentProcess();
PerformanceCounter perfCntr = new PerformanceCounter();
perfCntr.CategoryName = "Process";
perfCntr.CounterName = "Working Set - Private";
perfCntr.InstanceName = currProcess.ProcessName;
while (true)
{
int value = (int)perfCntr.NextValue() / 1024;
string privateMemoryStr = value.ToString("n0") + "KB [Private Bytes]";
wrkr.ReportProgress(0, privateMemoryStr);
Thread.Sleep(1000);
}
};
wrkr.ProgressChanged += (object sender, ProgressChangedEventArgs e) => {
string val = e.UserState as string;
if (!string.IsNullOrEmpty(val))
this.Title = string.Format(@"{0} ({1})", origWindowTitle, val);
};
wrkr.RunWorkerAsync();
}`
A: Is this a fair description? I'd like to share this with my team so please let me know if it is incorrect (or incomplete):
There are several ways in C# to ask how much memory my process is using.
*
*Allocated memory can be managed (by the CLR) or unmanaged.
*Allocated memory can be virtual (stored on disk) or loaded (into RAM pages)
*Allocated memory can be private (used only by the process) or shared (e.g. belonging to a DLL that other processes are referencing).
Given the above, here are some ways to measure memory usage in C#:
1) Process.VirtualMemorySize64(): returns all the memory used by a process - managed or unmanaged, virtual or loaded, private or shared.
2) Process.PrivateMemorySize64(): returns all the private memory used by a process - managed or unmanaged, virtual or loaded.
3) Process.WorkingSet64(): returns all the private, loaded memory used by a process - managed or unmanaged
4) GC.GetTotalMemory(): returns the amount of managed memory being watched by the garbage collector.
A: If you want to know how much the GC uses try:
GC.GetTotalMemory(true)
If you want to know what your process uses from Windows (VM Size column in TaskManager) try:
Process.GetCurrentProcess().PrivateMemorySize64
If you want to know what your process has in RAM (as opposed to in the pagefile) (Mem Usage column in TaskManager) try:
Process.GetCurrentProcess().WorkingSet64
See here for more explanation on the different sorts of memory.
A: Working set isn't a good property to use. From what I gather, it includes everything the process can touch, even libraries shared by several processes, so you're seeing double-counted bytes in that counter. Private memory is a much better counter to look at.
A: I'd suggest to also monitor how often pagefaults happen. A pagefault happens when you try to access some data that have been moved from physical memory to swap file and system has to read page from disk before you can access this data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Is there a lang-vb or lang-basic option for prettify.js from Google? Visual Basic code does not render correctly with prettify.js from Google.
on Stack Overflow:
Partial Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'set page title
Page.Title = "Something"
End Sub
End Class
in Visual Studio...
I found this in the README document:
How do I specify which language my
code is in?
You don't need to specify the language
since prettyprint() will guess. You
can specify a language by specifying
the language extension along with the
prettyprint class like so:
<pre class="prettyprint lang-html">
The lang-* class specifies the language file extensions.
Supported file extensions include
"c", "cc", "cpp", "cs", "cyc", "java", "bsh", "csh", "sh",
"cv", "py", "perl", "pl", "pm", "rb", "js",
"html", "html", "xhtml", "xml", "xsl".
</pre>
I see no lang-vb or lang-basic option. Does anyone know if one exists as an add-in?
Note: This is related to the VB.NET code blocks suggestion for Stack Overflow.
A: /EDIT: I've rewritten the whole posting.
Below is a pretty complete solution to the VB highlighting problem. If SO has got nothing better, please use it. VB syntax highlighting is definitely wanted.
I've also added a code example with some complex code literals that gets highlighted correctly. However, I haven't even tried to get XLinq right. Might still work, though. The keywords list is taken from the MSDN. Contextual keywords are not included. Did you know the GetXmlNamespace operator?
The algorithm knows literal type characters. It should also be able to handle identifier type characters but I haven't tested these. Note that the code works on HTML. As a consequence, &, < and > are required to be read as named (!) entities, not single characters.
Sorry for the long regex.
var highlightVB = function(code) {
var regex = /("(?:""|[^"])+"c?)|('.*$)|#.+?#|(&[HO])?\d+(\.\d*)?(e[+-]?\d+)?U?([SILDFR%@!#]|&)?|\.\d+[FR!#]?|\s+|\w+|&|<|>|([-+*/\\^$@!#%&<>()\[\]{}.,:=]+)/gi;
var lines = code.split("\n");
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
var tokens;
var result = "";
while (tokens = regex.exec(line)) {
var tok = getToken(tokens);
switch (tok.charAt(0)) {
case '"':
if (tok.charAt(tok.length - 1) == "c")
result += span("char", tok);
else
result += span("string", tok);
break;
case "'":
result += span("comment", tok);
break;
case '#':
result += span("date", tok);
break;
default:
var c1 = tok.charAt(0);
if (isDigit(c1) ||
tok.length > 1 && c1 == '.' && isDigit(tok.charAt(1)) ||
tok.length > 5 && (tok.indexOf("&") == 0 &&
tok.charAt(5) == 'H' || tok.charAt(5) == 'O')
)
result += span("number", tok);
else if (isKeyword(tok))
result += span("keyword", tok);
else
result += tok;
break;
}
}
lines[i] = result;
}
return lines.join("\n");
}
var keywords = [
"addhandler", "addressof", "alias", "and", "andalso", "as", "boolean", "byref",
"byte", "byval", "call", "case", "catch", "cbool", "cbyte", "cchar", "cdate",
"cdec", "cdbl", "char", "cint", "class", "clng", "cobj", "const", "continue",
"csbyte", "cshort", "csng", "cstr", "ctype", "cuint", "culng", "cushort", "date",
"decimal", "declare", "default", "delegate", "dim", "directcast", "do", "double",
"each", "else", "elseif", "end", "endif", "enum", "erase", "error", "event",
"exit", "false", "finally", "for", "friend", "function", "get", "gettype",
"getxmlnamespace", "global", "gosub", "goto", "handles", "if", "if",
"implements", "imports", "in", "inherits", "integer", "interface", "is", "isnot",
"let", "lib", "like", "long", "loop", "me", "mod", "module", "mustinherit",
"mustoverride", "mybase", "myclass", "namespace", "narrowing", "new", "next",
"not", "nothing", "notinheritable", "notoverridable", "object", "of", "on",
"operator", "option", "optional", "or", "orelse", "overloads", "overridable",
"overrides", "paramarray", "partial", "private", "property", "protected",
"public", "raiseevent", "readonly", "redim", "rem", "removehandler", "resume",
"return", "sbyte", "select", "set", "shadows", "shared", "short", "single",
"static", "step", "stop", "string", "structure", "sub", "synclock", "then",
"throw", "to", "true", "try", "trycast", "typeof", "variant", "wend", "uinteger",
"ulong", "ushort", "using", "when", "while", "widening", "with", "withevents",
"writeonly", "xor", "#const", "#else", "#elseif", "#end", "#if"
]
var isKeyword = function(token) {
return keywords.indexOf(token.toLowerCase()) != -1;
}
var isDigit = function(c) {
return c >= '0' && c <= '9';
}
var getToken = function(tokens) {
for (var i = 0; i < tokens.length; i++)
if (tokens[i] != undefined)
return tokens[i];
return null;
}
var span = function(class, text) {
return "<span class=\"" + class + "\">" + text + "</span>";
}
Code for testing:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
'set page title
Page.Title = "Something"
Dim r As String = "Say ""Hello"""
Dim i As Integer = 1234
Dim d As Double = 1.23
Dim s As Single = .123F
Dim l As Long = 123L
Dim ul As ULong = 123UL
Dim c As Char = "x"c
Dim h As Integer = &H0
Dim t As Date = #5/31/1993 1:15:30 PM#
Dim f As Single = 1.32e-5F
End Sub
A: Prettify does support VB comments as of the 8th of January 2009.
To get vb syntax highlighting working correctly you need three things;
<script type="text/javascript" src="/External/css/prettify/prettify.js"></script>
<script type="text/javascript" src="/External/css/prettify/lang-vb.js"></script>
and a PRE block around your code eg:
<PRE class="prettyprint lang-vb">
Function SomeVB() as string
' do stuff
i = i + 1
End Function
</PRE>
Stackoverflow is missing the lang-vb.js inclusion, and the ability to specify which language via Markdown, ie: class="prettyprint lang-vb" which is why it doesn't work here.
for details on the issue: see the Prettify issues log
A: In the meantime, you can put an extra comment character at the end of your comments to get it to look okay. For example:
Sub TestMethod()
'Method body goes here'
End Sub
You also need to escape internal comment characters in the normal vb-fashion:
Sub TestMethod2()
'Here''s another comment'
End Sub
Prettify still treats it as a string literal rather than a comment, but at least it looks okay.
Another method I've seen is to start comments with an extra '//, like this:
Sub TestMethod3()
''// one final comment
End Sub
Then it's handled like a comment, but you have to deal with C-style comment markers
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Java Swing: Displaying images from within a Jar When running a Java app from eclipse my ImageIcon shows up just fine.
But after creating a jar the path to the image obviously gets screwed up.
Is there a way to extract an image from the jar at runtime so I can then open it up? Or, is there a better way to do this?
I'd like to distribute a single jar file if possible.
A: In netbeans 8.1 what I've done is to include the folder of icons and other images called Resources inside the src folder in the project file. So whenever i build Jar file the folder is included there.The file tree should be like this:
*
*src (Java files in source packges are here)
*
*** PACKAGE YOU NAMED IN PROJECT**
*
*file.java
*Resources
*
*image.jpg
The code should be like:
jToggleButton1.setIcon(new javax.swing.ImageIcon(this.getClass().getResource("/resources/image.jpg")));
A: To create an ImageIcon from an image file within the same jars your code is loaded:
new javax.swing.ImageIcon(getClass().getResource("myimage.jpeg"))
Class.getResource returns a URL of a resource (or null!). ImageIcon has a constructors that load from a URL.
To construct a URL for a resource in a jar not on your "classpath", see the documentation for java.net.JarURLConnection.
A: You can try something like:
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("/images/image.jpg");
In your JAR file, you might have a directory structure of:
MyJAR.jar
- com (class files in here)
- images
----image.jpg
A: This is working for me to load and set the content pane background image:
jar (or build path) contains:
- com
- img
---- bg.png
java contains:
JFrame f = new JFrame("Testing load resource from jar");
try {
BufferedImage bg = ImageIO.read(getClass().getResource("/img/bg.png"));
f.setContentPane(new ImagePanel(bg));
} catch (IOException e) {
e.printStackTrace();
}
Tested and working in both jar and unjarred (is that the technical term) execution.
BTW getClass().getClassLoader().getResourceAsStream("/img/bg.png") - which I tried first - returned me a null InputStream.
A: Load image in from Jar file during run time is the same as loading image when executed from IDE e.g netbeans the difference is that when loading image from JAR file the path must be correct and its case sensitive (very important).
This works for me
image1 = new javax.swing.ImageIcon(getClass().getResource("/Pictures/firstgame/habitat1.jpg"));
img = image1.getImage().getScaledInstance(lblhabitat1.getWidth(), lblhabitat1.getHeight(), Image.SCALE_SMOOTH);
lblhabitat1.setIcon(new ImageIcon(img));
if p in "/Pictures/firstgame/habitat1.jpg" is in lower case it wont work. check spaces, cases and spelling
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "48"
} |
Q: Enforcing web coding standards The HTML standard defines a clear separation of concerns between CSS (presentation) and HTML (semantics or structure).
Does anyone use a coding standards document for CSS and XHTML that has clauses which help to maintain this separation? What would be good clauses to include in such a coding standards document?
A: We don't have a physical document we all adhere to where I work. There are a number of guidelines we try and keep in mind but there isn't really enough information to require a physcial document. This article sums them up these guidelines pretty well. You may also consider formatting your CSS to make it easier to read. Smashing Magazine has a great article on this subject.
A: The article referred to by @Lee Theobald is a good start.
Some basic ideas I try to keep in mind when marking up:
Regarding html:
Try to write for the next person - that is, think about how easy or difficult it might be for someone else to come and pick up your work and carry on.
To support this principle, you should try and make sure your markup is as legible as possible - class and id tags in particular should relate as much as possible to their intended content. In other words, try to use your tags to describe the kind of content they will have.
For example, "Sub-navigation", "content" etc.
The aim is to provide markup that someone can pickup having not looked at before and get a sense of the logical structure of the document.
Also, try to avoid the addition of markup that is purely to achieve a visual effect. But bear in mind that any website that requires even slightly sophisticated styling is unlikely to be able avoid non-semantic markup, due to weaknesses in current implementations of CSS and browser-compatibility issues.
Regarding CSS files:
Many people divide their css up into sections using comments, separating them into functional or structural areas. So you might have a section for your header, your footer, or typography and so on. Others take this further and split css across files, having one for typography, one for layout etc. However, this can according to Yslow! can have a negative impact on page loading, due to increased http requests.
I could write more, but as you can see I struggle to be concise. I hope this is of some use to you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How can I return a variable from a $.getJSON function I want to return StudentId to use elsewhere outside of the scope of the $.getJSON()
j.getJSON(url, data, function(result)
{
var studentId = result.Something;
});
//use studentId here
I would imagine this has to do with scoping, but it doesn't seem to work the same way c# does
A:
it doesn't seem to work the same way
c# does
To accomplish scoping similar to C#, disable async operations and set dataType to json:
var mydata = [];
$.ajax({
url: 'data.php',
async: false,
dataType: 'json',
success: function (json) {
mydata = json.whatever;
}
});
alert(mydata); // has value of json.whatever
A: Yeah, my previous answer does not work because I didn't pay any attention to your code. :)
The problem is that the anonymous function is a callback function - i.e. getJSON is an async operation that will return at some indeterminate point in time, so even if the scope of the variable were outside of that anonymous function (i.e. a closure), it would not have the value you would think it should:
var studentId = null;
j.getJSON(url, data, function(result)
{
studentId = result.Something;
});
// studentId is still null right here, because this line
// executes before the line that sets its value to result.Something
Any code that you want to execute with the value of studentId set by the getJSON call needs to happen either within that callback function or after the callback executes.
A: Even simpler than all the above. As explained earlier $.getJSON executes async which causes the problem. Instead of refactoring all your code to the $.ajax method just insert the following in the top of your main .js file to disable the async behaviour:
$.ajaxSetup({
async: false
});
good luck!
A: If you wish delegate to other functions you can also extend jquery with the $.fn. notation like so:
var this.studentId = null;
$.getJSON(url, data,
function(result){
$.fn.delegateJSONResult(result.Something);
}
);
$.fn.delegateJSONResult = function(something){
this.studentId = something;
}
A: hmm, if you've serialized an object with the StudentId property then I think that it will be:
var studentId;
function(json) {
if (json.length > 0)
studentId = json[0].StudentId;
}
But if you're just returning the StudentId itself maybe it's:
var studentId;
function(json) {
if (json.length > 0)
studentId = json[0];
}
Edit: Or maybe .length isn't even required (I've only returned generic collections in JSON).
Edit #2, this works, I just tested:
var studentId;
jQuery.getJSON(url, data, function(json) {
if (json)
studentId = json;
});
Edit #3, here's the actual JS I used:
$.ajax({
type: "POST",
url: pageName + "/GetStudentTest",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{id: '" + someId + "'}",
success: function(json) {
alert(json);
}
});
And in the aspx.vb:
<System.Web.Services.WebMethod()> _
<System.Web.Script.Services.ScriptMethod()> _
Public Shared Function GetStudentTest(ByVal id As String) As Integer
Return 42
End Function
A: var context;
$.ajax({
url: 'file.json',
async: false,
dataType: 'json',
success: function (json) {
assignVariable(json);
}
});
function assignVariable(data) {
context = data;
}
alert(context);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "54"
} |
Q: Accessing a Component on an inherited form from the base form A number of forms in my project inherit from a base form. It is easy to get at the Controls collection of the derived forms, but I have not found a simple way to access the Components collection, since VS marks this as private.
I assume this could be done with reflection, but I'm not really sure how best to go about it, not having worked with reflection before.
Right now, I'm using a sort of clunky workaround, in which I override a function GetComponents and return an array of the components I'm interested in. This is obviously prone to errors, since it's easy to forget to implement the overridden function or update it when components are added.
If anyone has any tips or can suggest a better way, I'd be glad to hear.
A: If you set the Modifiers property of your components to strict protected makes them accessible without the use of a components collection.
Edit:
Discoverability could be done using reflection to walk over each field. Although that might be suboptimal in your case.
A: If you're worried about forgetting to override the function, then make it abstract.
A: Set the 'components' modifier to protected in your base form class. Remove the 'components' declaration in all the derived forms.
Call this below method in base form load event,
public void SetComponentsStyle()
{
if (null != this.components)
{
foreach (Component comp in this.components.Components)
{
if (comp is ToolTip)
{
}
else if (comp is ContextMenuStrip)
{
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ASP.NET - How do you Unit Test WebControls? Alright.
So I figure it's about time I get into unit testing, since everyone's been banging on about it for long enough. I've installed NUnit and gone through a few "intro to unit testing" type tutorials.
I'm currently putting together a small framework to help with the rebuild of one of our web apps, so I've created a VS2008 project for my framework and I want to unit test it as I go.
How on earth do I go about unit testing the WebControls? The methods are all protected or private, and since it's a framework, there isn't much else but WebControls.
Any pointers?
Burns
A: You can do model-view-controller or model-view-presenter type architectures without using a full blown framework. You already found out that unit-testing ui-components is difficult. There are ways around that but you probably don't want to go that route. Usually this will make your tests very hard to maintain, more maintenance nightmare's is something programmers can do without :-)
Try to separate out the functionality you want to test in a "controller" or "presenter" class. Then test that class. To make it more testable you can hide the usercontrol class (the view) behind an interface and make the controller or presenter talk to the view through the interface. That way you can mock up the view in your tests.
I know this sounds like a lot of work and it seems like a workaround but if you get used to this it's a realy nice architecture that makes it far easier to change ui behaviour. You can always start using a "real" mvc framework when you realy need it :-)
A: Ues the assembly:InternalsVisibleTo attribute and you'll be able to access those private members.
Put it in your webcontrol project's AssemblyInfo.cs (under Properties node)
[assembly:InternalsVisibleTo("YourTestProjectName")]
A: You have found the biggest pain point of ASP.NET. As far as sealed, private classes that hinder unit testing.
This is the main reason that TDD people will use a MVC framework (ASP.NET MVC, Castle MonoRail) as it provides a clear seperation from your view templates and your controller logic. The controllers are fully testable.
A: This is an old article by now, but I was using NUnitASP to write nunit tests for asp.net WebControls in 2004. That article gives a detailed example of testing a simple control using their concept of creating a corresponding "Tester" class that encapsulates the details of your control from you tests. The Tester can (should) also be in the same assembly as your control so can share some things between them (e.g. utility functions, constants, etc.).
I used the technique (and others use variants of the technique) still today to test very sophisticated controls.
I hope that is helpful.
A: You could also look at testing components through the browser as a user would see them using a testing framework such as WebAii. I've seen it work and its pretty cool. I've also been told you can plug it into automated builds but I've not seen that as of yet.
Hope it helps ...
A: The MVC framework mentioned above is the best way to test what the control does. However testing how it works is a bit different.
This is totally off the cuff but you could make the user control expose some protected methods and properties to return validation information and then have a testing user control inherit it. That control could populate fields, press buttons and what not. Kind of messy but it could work.
A: You can also take a look at this Rhino Igloo framework. It is a compromised MVC framework for WebForms.
A: Ivonna
can test WebControls in isolation, within the Asp.Net context
Just call session.GetControl("Path.ascx") and verify that it has all necessary properties.
A: You test them like this:
[Test]
public void ConditionQueryBuilderTest_RendersProperHtml()
{
var sw = new StringWriter();
var queryBuilder = new ConditionQueryBuilderStub
{
ID = "UnitTestbuilder",
QueryBuilderURL = @"\SomeAspxPage\SomeWebMethod",
ResetQueryBuilderURL = @"\SomeAspxPage\OnQueryBuilderReset",
FilterValuesCollection = new Dictionary<int, string> { {15, "Some Condition"}}
};
queryBuilder.RenderAllContents(new HtmlTextWriter(sw));
AppendLog(sw.ToString());
Assert.AreEqual(ExpectedHtml, sw.ToString()); // ExpectedHTML is the raw expected HTML
}
Here is my stub:
internal class ConditionQueryBuilderStub : ConditionQueryBuilder // ConditionQueryBuilder is a WebControl
{
internal void RenderAllContents(HtmlTextWriter writer)
{
RenderContents(writer);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Resources of techniques use for collision detection in 2D? What are in your opinion the best resources (books or web pages) describing algorithms or techniques to use for collision detection in a 2D environment?
I'm just eager to learn different techniques to make more sophisticated and efficient games.
A: Personally, I love the work of Paul Bourke.
Also, Paul Nettle used to write on the topic. He has a full 3D collision detection library, but you may be more interested in the ideas behind such libraries (which are very applicable to 2D). For that, see General Collision Detection for Games Using Ellipsoids.
A: Metanet Software has published some relevant tutorials. Metanet develops N (Flash-based, for Windows, Mac, Linux) and N+ (for the X360, DS, and PSP).
A: Collision detection is often a two phase process. Some sort of "broad phase" algorithm for determinining if two objects even have a chance of overlapping (to try to avoid n^2 compares) followed by a "narrow phase" collision detection algorithm, which is based on the geometry requirements of your application.
Sweep and Prune is a well established efficient broad phase algorithm (with a handful of variants that may or may not suit your application) for objects undergoing relatively physical movement (things that move crazy fast or have vastly different sizes and bounding regions might make this unsuitable). The Bullet library has a 3d implementation for reference.
Narrow phase collision can often be as simple as "CircleIntersectCircle." Again the Bullet libraries have good reference implementations. In 3d land when more precise detection is required for arbitrary objects, GJK is among the current cream of the crop - nothing in my knowledge would prevent it from being adapted to 2d (but it might end up slower than just brute forcing all your edges ;)
Finally, after you have collision detection, you are often in need of some sort of collision response. Box 2d is a good starting point for a physical response solution.
A: The book 'Real-Time Collision Detection' by Christer Ericson (ISBN: 1-55860-732-3) is a recent (2005) and widely praised book which should give you some good answers.
It starts with a basic primer of some of the maths you will need to know, and then goes into various types of bounding volumes (spheres, axis-aligned bounding boxes, oriented bounding boxes) commonly used in collision detection.
Next up for discussion are numerous algorithms for detecting collisions between various combinations of primitives, such as lines, triangles, spheres, polygons, planes, bounding volumes etc.
Also of importance is the coverage of some of the major methods of spatial division and organisation of your objects (volume hierarchies, BSP trees, Octrees, etc.). This essentially speeds up collision detection, as it allows you to subdivide your objects so you can avoid unnecessary comparisons between objects (e.g. I know from my data structures that object A is too far away to hit object B, so I won't even do a distance check).
It also includes some coverage of how to actually check for collisions between moving objects (intervals, etc) but be aware that even though this is a fairly hefty book and covers the material well, it is for collision detection, not resolution or response. So it will help you determine whether two objects have collided, but not really what to do about it, i.e. how to resolve it. The intersection tests will usually give you the data you need to make such decisions, but in terms of the general problem of writing a solver, which uses collision detection routines to detect collisions and then decide what to do about them, this book does not cover that in depth.
A: If your objects are represented as points in 2D space you can use line intersection to determine if two objects have collided. You can use similar logic to check if an object is inside another object (and thus they have collided even any of their lines are not currently intersecting). The math to do this is quite simple, and should be covered by any textbook on basic geometry. Detecting if an object has passed completely through an object might be a bit more tricky though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Forcing the Solution Explorer to select the file in the editor in visual studio 2005 In Visual Studio 2005, whenever I would view a file in the main editor, the Solution Explorer would find and highlight that file. Some time ago, this stopped working and the Solution Explorer would do nothing.
This has become quite a pain since following a chain of "Go To Definition"s can lead you all over your solution. Where is the setting to turn this back on?
A: Click on the Tools → Options menu. Select the Projects and Solutions → General option page.
Make sure "Track active item in Solution Explorer" is checked. That should do it.
A: I like to keep this option turned off (especially when working with a big project), but it's useful to be able to find the file in the tree now and then. I found a way to do this here.
I hope I'm not being too verbose here, but here's the guide to making this work that I wrote for my work's wiki:
*
*Go to Tools->Macros->Macro Explorer.
*In the Macro Explorer tree that comes up, right-click MyMacros, and then New Module....
*Call the new module SyncItem (if you want).
*Right-click the new module, then Edit.
*Paste this into the code window. (I don't know or care if the Imports lines are necessary; they're just there by default.)
code:
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Public Module SyncItem
Sub SyncSolutionExplorer()
DTE.ExecuteCommand("View.TrackActivityinSolutionExplorer")
DTE.ExecuteCommand("View.TrackActivityinSolutionExplorer")
End Sub
End Module
The macro is most useful if you bind it to a keystroke. Here's how to do that:
*
*Go to Tools->Options, then select Environment->Keyboard.
*Find the new macro in the list (start typing "syncitem" or similar in the search box).
*I choose Alt-Shift-T (which this dialog box likes to call Shift-Alt-T) for, um, "Tree," I guess? If you're a fan of Edit.LineTranspose, whatever that is (I think it swaps the current line with the following one), then you might like to pick a different shortcut.
A: Tools->Options->Project and Solutions->General
Check the box "Track Active Item in Solution Explorer"
A: Tools -> Options -> Environment -> Keyboard
Assign the command
View.TrackActivityinSolutionExplorer
(I use Alt+L)
then to use always hit Alt+L followed by Alt+L
which turns on the feature and locates the file in the source tree and then turns it off again to stop the location bouncing around when you do not want it to.
A: I just discovered that ReSharper can do what Owen suggests. I have disabled the "Track active item in Solution Explorer"-setting, and when I'm working in a source-file I press Shift + Alt + L and the file is selected in the Solution Explorer. I haven't changed the binding, so I guess that is the default. The upside to this is that you don't have to create a macro and then bind it to a keystroke (although not very difficult, it still has to be done). The downside is that ReSharper isn't free, so it's probably not a solution for everybody.
A: *
*Navigate to Tools -> Options
*Select "Projects and Solutions" in the tree view on the left
*Select "Track Active Item in Solution Explorer"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "43"
} |
Q: Ubiquity Hack What's the most useful hack you've discovered for Mozilla's new Ubiquity tool?
A: I wrote this a few days ago: http://www.appidx.com/ubiq/stackoverflow.html
The execute portion refuses to run with POST data. The code is the right code, and I've tried with the native code of the function with the XUL component javascript and it likewise refuses to run. Any help would be appreciated. The preview on the other hand works fine.
CmdUtils.CreateCommand({
name: "stackoverflow",
author: {name: "Aryeh Goldsmith"},
homepage: "http://www.appidx.com/ubiq/",
icon: "http://stackoverflow.com/favicon.ico",
takes: {search: noun_arb_text},
license: "MPL",
description: "Searches the highlighted text on stackoverflow.",
_version: "52",
preview: function ( pblock, inputObject) {
var query = inputObject.text;
pblock.innerHTML = "Search stackoverflow.com for " + query + "<br/>";
var url = "http://stackoverflow.com/search";
params = {"search-text": query, "hiddenstuff": ''};
jQuery.post( url, params, function( html ) {
var $ = jQuery;
pblock.innerHTML += "<div style='display:none;'>" + html + "</div>";
var ques = $(pblock).find('.summary h3');
var details = $(pblock).find('.summary .excerpt');
var out = "<div style='margin-bottom: 6px;'><b>Previewing the first 5 results:</b></div>";
for (var j = 0; j< ques.size() && j < 5; j++) {
out += "<div style='padding: 5px;'><b>" + ques[j].innerHTML + "</b><br />";
out += details[j].innerHTML + "</div>";
}
pblock.innerHTML = out;
});
},
execute: function( inputObject ) {
var query = inputObject.text;
var url = "http://stackoverflow.com/search";
var params = {
"search-text": query,
hiddenstuff: ""
};
// The following refuses to work... why? I just don't know! AFAIK it's correct.
openUrl(url, params);
},
})
A: That it can close Firefox faster then I can with the mouse and that little [x] thing in the corner... :-P
A: "translate this" and "edit-page". I think I'd find the Google Apps features useful if they supported hosted domains.
A: I just wrote this:
makeSearchCommand({
name: "stackoverflow-tagsearch",
author: { name: "Jörg W Mittag", email: "[email protected]"},
license: "MIT X11",
url: "http://Beta.StackOverflow.Com/questions/tagged/{QUERY}",
icon: "http://StackOverflow.Com/favicon.ico",
description: "Searches <a href=\"http://StackOverflow.Com\">StackOverflow.Com</a> for the given tag(s).",
help: "Searches <a href=\"http://StackOverflow.Com\">StackOverflow.Com</a> for the given tag(s).",
preview: function(pBlock, directObj) {
if (directObj.text)
pBlock.innerHtml = "Searches <a href=\"http://StackOverflow.Com\">StackOverflow.Com</a> for " + directObj.text;
else
pBlock.innerHTML = "Searches <a href=\"http://StackOverflow.Com\">StackOverflow.Com</a> for the given tag(s).";
}
});
Nice toy!
Now I need to figure out how to HTTP POST to http://Beta.StackOverflow.Com/search with JQuery and Ubiquity ... If only there was a site where I could ask that question!
A: I use a lot the "email it" and the "twitter" commands
A: My co-worker has had 3 blue-screens on his machine since installing it. Not totally convinced this is what did it, but it's the only thing he's changed today. I'm uninstalling it for now (and so is he).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Migrating from ASP Classic to .NET and pain mitigation We're in the process of redesigning the customer-facing section of our site in .NET 3.5. It's been going well so far, we're using the same workflow and stored procedures, for the most part, the biggest changes are the UI, the ORM (from dictionaries to LINQ), and obviously the language. Most of the pages to this point have been trivial, but now we're working on the heaviest workflow pages.
The main page of our offer acceptance section is 1500 lines, about 90% of that is ASP, with probably another 1000 lines in function calls to includes. I think the 1500 lines is a bit deceiving too since we're working with gems like this
function GetDealText(sUSCurASCII, sUSCurName, sTemplateOptionID, sSellerCompany, sOfferAmount, sSellerPremPercent, sTotalOfferToSeller, sSellerPremium, sMode, sSellerCurASCII, sSellerCurName, sTotalOfferToSeller_SellerCurr, sOfferAmount_SellerCurr, sSellerPremium_SellerCurr, sConditions, sListID, sDescription, sSKU, sInv_tag, sFasc_loc, sSerialNoandModel, sQTY, iLoopCount, iBidCount, sHTMLConditions, sBidStatus, sBidID, byRef bAlreadyAccepted, sFasc_Address1, sFasc_City, sFasc_State_id, sFasc_Country_id, sFasc_Company_name, sListingCustID, sAskPrice_SellerCurr, sMinPrice_SellerCurr, sListingCur, sOrigLocation)
The standard practice I've been using so far is to spend maybe an hour or so reading over the app both to familiarize myself with it, but also to strip out commented-out/deprecated code. Then to work in a depth-first fashion. I'll start at the top and copy a segment of code in the aspx.cs file and start rewriting, making obvious refactorings as I go especially to take advantage of our ORM. If I get a function call that we don't have, I'll write out the definition.
After I have everything coded I'll do a few passes at refactoring/testing. I'm just wondering if anyone has any tips on how to make this process a little easier/more efficient.
A: Believe me, I know exactly where you are coming from.. I am currently migrating a large app from ASP classic to .NET.. And I am still learning ASP.NET! :S (yes, I am terrified!).
The main things I have kept in my mind is this:
*
*I dont stray too far from the current design (i.e. no massive "lets rip ALL of this out and make it ASP.NET magical!) due to the incredibly high amount of coupling that ASP classic tends to have, this would be very dangerous. Of course, if you are confident, fill your boots :) This can always be refactored later.
*Back everything up with tests, tests and more tests! I am really trying hard to get into TDD, but its very difficult to test existing apps, so every time I remove a chunk of classic and replace with .NET, I ensure I have as much green-light tests backing me as possible.
*Research a lot, there are some MAJOR changes between classic and .NET and sometimes what can be many lines of code and includes in classic can be achieved in a few lines of code, think before coding.. I've learnt this the hard way, several times :D
Its very much like playing Jenga with your code :)
Best of luck with the project, any more questions, then please ask :)
A:
After I have everything coded I'll do a few passes at refactoring/testing. I'm just wondering if anyone has any tips on how to make this process a little easier/more efficient.
(source: cartoonstock.com)
Normally I'm not a fan of TDD, but in the case of refactoring it really is the way to go.
Write some tests first which verify what the bit you're looking at is actually doing. Then refactor. This is a LOT more reliable than just 'it looks like it still works.'
The other huge benefit to this is that when you're refactoring something which is further down the page, or in a shared library or something, you can just re-run the tests, as opposed to finding out the hard way that a seemingly unrelated change was actually related
A: You're going from classic ASP to ASP with 3.5 without just re-writing? Skillz. I've had to deal with some legacy ASP @work and I think it's just easier to parse it and re-write it.
A: A 1500-line ASP page? With lots of calls out to include files? Don't tell me -- the functions don't have any naming convention that tells you which include file has their implementation... That brings back memories (shudder)...
It sounds to me like you have a pretty solid approach -- I'm not sure if there is any magical way to mitigate your pain. After your conversion effort, the architecture of your app will still be messy and UI-heavy (i.e. code-behind running workflows), and it will probably still be fairly painful to maintain, but the refactoring you are doing should definitely help.
I hope you have weighed the upgrade you are doing against just rewriting from scratch -- as long as you are not intending to extend the app too much and you are not primarily responsible for maintaining the app, upgrading a complex workflow-based app like you are doing may be cheaper and a better choice than rewriting it from scratch. ASP.NET should give you better opportunities to improve performance and scalability, at least, than Classic ASP. From your question I imagine that it is too late in the process for that discussion anyway.
Good luck!
A: Sounds like you have a pretty good handle on things. I've seen a lot of people try to do a straight-line transliteration, includes and all, and it just doesn't work. You need to have a good understanding of how ASP.Net wants to work, because it's much different from Classic ASP, and it sounds like maybe you have that.
For larger files, I'd try to get a higher level view first. For example, one thing I've noticed is that Classic ASP was horrible about function calls. You'd be reading through some code and find a call to a function with no clue as to where it might be implemented. As a result, Classic ASP code tended to have long functions and scripts to avoid those nasty jumps. I remember seeing a function that printed out to 40 pages! Parsing straight through that much code is no fun.
ASP.Net makes it easier to follow function calls around, so you might start by breaking out your larger code blocks into several smaller functions.
A:
Don't tell me -- the functions don't
have any naming convention that tells
you which include file has their
implementation... That brings back
memories (shudder)...
How did you guess? ;)
I hope you have weighed the upgrade
you are doing against just rewriting
from scratch -- as long as you are not
intending to extend the app too much
and you are not primarily responsible
for maintaining the app, upgrading a
complex workflow-based app like you
are doing may be cheaper and a better
choice than rewriting it from scratch.
ASP.NET should give you better
opportunities to improve performance
and scalability, at least, than
Classic ASP. From your question I
imagine that it is too late in the
process for that discussion anyway.
This was something we talked about. Based on timing (trying to beat a competitor's site to launch) and resources (basically two developers) it made sense to not nuke the site from orbit. Things have actually gone much better than I expected. We were aware even from the planning stages that this code was going to give us the most problems. You should see the revision history of the classic ASP pages involved, it's a bloodbath.
For larger files, I'd try to get a
higher level view first. For example,
one thing I've noticed is that Classic
ASP was horrible about function calls.
You'd be reading through some code and
find a call to a function with no clue
as to where it might be implemented.
As a result, Classic ASP code tended
to have long functions and scripts to
avoid those nasty jumps. I remember
seeing a function that printed out to
40 pages! Parsing straight through
that much code is no fun.
I've actually had this displeasure of working with the legacy code quite a bit so I have a decent high level understanding of the system. You're right about the function length, there are some routines (most I've refactored down into much smaller ones) that are 3-4x as long as any of the aspx pages/helper classes/ORMs on the new site.
A: I once came across a .Net app that was ported from ASP. The .aspx pages were totally blank. To render the UI, the developers used StringBuilders in the code behind and then did a response.write. This would be the wrong way to do it!
A:
I once came across a .Net app that was ported from ASP. The .aspx pages were totally blank. To render the UI, the developers used StringBuilders in the code behind and then did a response.write. This would be the wrong way to do it!
I've seen it done the other way, the code behind page was blank, except for declaration of globals, then the VBScript was left in the ASPX.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How do you get a reference to the enclosing class from an anonymous inner class in Java? I'm currently creating an explicit reference to this in the outer class so that I have a name to refer to in the anonymous inner class. Is there a better way to do this?
A: I just found this recently. Use OuterClassName.this.
class Outer {
void foo() {
new Thread() {
public void run() {
Outer.this.bar();
}
}.start();
}
void bar() {
System.out.println("BAR!");
}
}
Updated If you just want the object itself (instead of invoking members), then Outer.this is the way to go.
A: Use EnclosingClass.this
A: You can still use Outer.class to get the class of the outer class object (which will return the same Class object as Outer.this.getClass() but is more efficient)
If you want to access statics in the enclosing class, you can use Outer.name where name is the static field or method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "51"
} |
Q: Constructors with the same argument type I have a Person object with two constructors - one takes an int (personId), the other a string (logonName). I would like another constructor that takes a string (badgeNumber). I know this can't be done, but seems it might be a common situation. Is there a graceful way of handling this? I suppose this would apply to any overloaded method. Code:
public class Person
{
public Person() {}
public Person(int personId)
{
this.Load(personId);
}
public Person(string logonName)
{
this.Load(logonName);
}
public Person(string badgeNumber)
{
//load logic here...
}
...etc.
A: You might consider using custom types.
For example, create LogonName and BadgeNumber classes.
Then your function declarations look like...
public Person(LogonName ln)
{
this.Load(ln.ToString());
}
public Person(BadgeNumber bn)
{
//load logic here...
}
Such a solution might give you a good place to keep the business logic that governs the format and usage of these strings.
A: You have four options that I can think of, three of which have already been named by others:
*
*Go the factory route, as suggested by several others here. One disadvantage to this is that you can't have consistent naming via overloading (or else you'd have the same problem), so it's superficially less clean. Another, larger, disadvantage is that it precludes the possibility of allocating directly on the stack. Everything will be allocated on the heap if you take this approach.
*Custom object wrappers. This is a good approach, and the one I would recommend if you are starting from scratch. If you have a lot of code using, e.g., badges as strings, then rewriting code may make this a non-viable option.
*Add an enumeration to the method, specifying how to treat the string. This works, but requires that you rewrite all the existing calls to include the new enumeration (though you can provide a default if desired to avoid some of this).
*Add a dummy parameter that is unused to distinguish between the two overloads. e.g. Tack a bool onto the method. This approach is taken by the standard library in a few places, e.g. std::nothrow is a dummy parameter for operator new. The disadvantages of this approach are that it's ugly and that it doesn't scale.
If you already have a large base of existing code, I'd recommend either adding the enumeration (possibly with a default value) or adding the dummy parameter. Neither is beautiful, but both are fairly simple to retrofit.
If you are starting from scratch, or only have a small amount of code, I'd recommend the custom object wrappers.
The factory methods would be an option if you have code which heavily uses the raw badge/logonName strings, but doesn't heavily use the Person class.
A: You could perhaps use factory methods instead?
public static Person fromId(int id) {
Person p = new Person();
p.Load(id);
return p;
}
public static Person fromLogonName(string logonName) {
Person p = new Person();
p.Load(logonName);
return p;
}
public static Person fromBadgeNumber(string badgeNumber) {
Person p = new Person();
// load logic
return p;
}
private Person() {}
A: No.
You might consider a flag field (enum for readability) and then have the constructor use htat to determine what you meant.
A: That won't work. You might consider making a class called BadgeNumber that wraps a string in order to avoid this ambiguity.
A: You cannot have two different constructors/methods with the same signature, otherwise, how can the compiler determine which method to run.
As Zack said, I would consider creating an "options" class where you could actually pass the parameters contained in a custom type. This means you can pretty much pass as many parameters as you like, and do what you like with the options, just be careful you dont create a monolithic method that tries to do everything..
Either that, or vote for the factory pattern..
A: You could use a static factory method:
public static Person fromLogon(String logon) { return new Person(logon, null); }
public static Person fromBadge(String badge) { return new Person(null, badge); }
A: As has been suggested, custom types is the way to go in this case.
A: If you are using C# 3.0, you can use Object Initializers:
public Person()
{
}
public string Logon { get; set; }
public string Badge { get; set; }
You would call the constructor like this:
var p1 = new Person { Logon = "Steve" };
var p2 = new Person { Badge = "123" };
A: Only thing I can think of to handle what you're wanting to do is to have to params, one that describes the param type (an enum with LogonName, BadgeNumer, etc) and the second is the param value.
A: You could switch to a factory style pattern.
public class Person {
private Person() {}
public static PersonFromID(int personId)
{
Person p = new Person().
person.Load(personID);
return p;
this.Load(personId);
}
public static PersonFromID(string name)
{
Person p = new Person().
person.LoadFromName(name);
return p;
}
...
}
Or, as suggested, use custom types. You can also hack something using generics, but I wouldn't recommend it for readability.
A: Depending on your business constraints:
public class Person
{
public string Logon { get; set; } = "";
public string Badge { get; set; } = "";
public Person(string logon="", string badge="") {}
}
// Use as follow
Person p1 = new Person(logon:"MylogonName");
Person p2 = new Person(badge:"MyBadge");
A: How about ...
public Person(int personId)
{
this.Load(personId);
}
public Person(string logonName)
{
this.Load(logonName);
}
public Person(Object badgeNumber)
{
//load logic here...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Response.Redirect using ~ Path I have a method that where I want to redirect the user back to a login page located at the root of my web application.
I'm using the following code:
Response.Redirect("~/Login.aspx?ReturnPath=" + Request.Url.ToString());
This doesn't work though. My assumption was that ASP.NET would automatically resolve the URL into the correct path. Normally, I would just use
Response.Redirect("../Login.aspx?ReturnPath=" + Request.Url.ToString());
but this code is on a master page, and can be executed from any folder level. How do I get around this issue?
A:
I think you need to drop the "~/" and replace it with just "/", I believe / is the root
STOP RIGHT THERE! :-) unless you want to hardcode your web app so that it can only be installed at the root of a web site.
"~/" is the correct thing to use, but the reason that your original code didn't work as expected is that ResolveUrl (which is used internally by Redirect) tries to first work out if the path you are passing it is an absolute URL (e.g. "**http://server/**foo/bar.htm" as opposed to "foo/bar.htm") - but unfortunately it does this by simply looking for a colon character ':' in the URL you give it. But in this case it finds a colon in the URL you give in the ReturnPath query string value, which fools it - therefore your '~/' doesn't get resolved.
The fix is that you should be URL-encoding the ReturnPath value which escapes the problematic ':' along with any other special characters.
Response.Redirect("~/Login.aspx?ReturnPath=" + Server.UrlEncode(Request.Url.ToString()));
Additionally, I recommend that you (or anyone) never use Uri.ToString - because it gives a human-readable, more "friendly" version of the URL - not a necessarily correct one (it unescapes things). Instead use Uri.AbsoluteUri - like so:
Response.Redirect("~/Login.aspx?ReturnPath=" + Server.UrlEncode(Request.Url.AbsoluteUri));
A: you can resolve the URL first
Response.Redirect("~/Login.aspx);
and add the parameters after it got resolved.
A: What about using
Response.Redirect(String.Format("http://{0}/Login.aspx?ReturnPath={1}", Request.ServerVariables["SERVER_NAME"], Request.Url.ToString()));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: Lightweight rich-text XML format? I am writing a basic word processing application and am trying to settle on a native "internal" format, the one that my code parses in order to render to the screen. I'd like this to be XML so that I can, in the future, just write XSLT to convert it to ODF or XHTML or whatever.
When searching for existing standards to use, the only one that looks promising is ODF. But that looks like massive overkill for what I need. All I need is paragraph tags, font selection, font size & decoration...that's pretty much it. It would take me a long time to implement even a minimal ODF renderer, and I'm not sure it's worth the trouble.
Right now I'm thinking of making my own XML format, but that's not really good practice. Better to use a standard, especially since then I can probably find the XSLTs I might need in the future already written.
Or should I just bite the bullet and implement ODF?
EDIT: Regarding the Answer
I knew about XSL-FO before, but due to the weight of the spec hadn't really consdiered it. But you're right, a subset would give me everything I need to work with and room to grow. Thanks so much the reminder.
Plus, by including a rendering library like FOP or RenderX, I get PDF generation for free. Not bad...
A: As you are sure about needing to represent the presentational side of things, it may be worth looking at the XSL-FO W3C Recommendation. This is a full-blown page description language and the (deeply unfashionable) other half of the better-known XSLT.
Clearly the whole thing is anything but "lightwight", but if you just incorporated a
very limited subset - which could even just be (to match your spec of "paragraph tags, font selection, font size & decoration") fo:block and the common font properties, something like:
<yourcontainer xmlns:fo="http://www.w3.org/1999/XSL/Format">
<fo:block font-family="Arial, sans-serif" font-weight="bold"
font-size="16pt">Example Heading</fo:block>
<fo:block font-family="Times, serif"
font-size="12pt">Paragraph text here etc etc...</fo:block>
</yourcontainer>
This would perhaps have a few advantages over just rolling your own. There's an open specification to work from, and all that implies. It reuses CSS properties as XML attributes (in a similar manner to SVG), so many of the formatting details will seem somewhat familiar. You'd have an upgrade path if you later decided that, say, intelligent paging was a must-have feature - including more sections of the spec as they become relevant to your application.
There's one other thing you might get from investigating XSL-FO - seeing how even just-doing-paragraphs-and-fonts can be horrendously complicated. Trying to do text layout and line breaking 'The Right Way' for various different languages and use cases seems very daunting to me.
A: If its only for word processing, then perhaps DocBook might be a little lighter than ODF?
However, the wiki entry states:
DocBook is a semantic markup language for technical documentation. It was originally intended for writing technical documents related to computer hardware and software but it can be used for any other sort of documentation.
So it might not be so suitable for a general-purpose word-processor?
The advantage of using DocBook would be the fact that a number of DocBook -> other format converters should be available? Hope this helps.
A: I like DocBook, but it doesn't really fit. It strives to be presentation-independent, the intention being that you would use XSLT to render it to a presentation format.
In a word processor, the user is editing presentation along with the content. For example, the user doesn't want to mark a "keyword", necessarily, they want to make some text bold.
A DocBook editor would be a very nice thing (I'm not sure a good one exists), but it's not really what I'm doing.
A: Well, right... But since I need to be able to convert to XML anyway, why hold both my document tree and the DOM tree in memory, when there's nothing preventing me from working right off the DOM tree?
Particularly since one unique feature of my program is that everything is always saved as you type, and I don't want to run a whole conversion to XML every time I hit a key. Easier just to tie input and output directly to my in-memory DOM tree.
Edit:
Oh, and the only problem with XHTML is that I do want to support basic pagination. Though I guess there's nothing stopping me with using some additional tags for that...
A: XML is an external format, not internal.
What's wrong with XHTML? It's simple and it's ubiquitous (at least HTML is). Your implementation would be easy to debug, and your users will be eternally greatful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Passing around sets of data A question that has pondered me for the last while. I am primarily a .net developer who dabbles in Objective-C for iPhone and Mac.
How do you go about sending "datasets" between methods in objective-c. For example in C# you can populate a custom class with data and pass it around in a List of type custom class. EG if you had a customer class you would just do something like:
List<Customer> customers = DataLayer.GetAllCustomers();
The only way I can see how this could be done in obj-c would be to populate an NSArray with custom objects? Is this an efficient way to do things? Any other recommendations? I am using sqlite as the database/data I want to return.
A: You're on the right track.
Cocoa's collection classes — which all have mutable an immutable variants — are:
*
*NSArray: ordered, can contain an object multiple times
*NSDictionary: unordered, mapping from keys to values, keys are copied
*NSSet: unordered, can contain an object only once
*NSCountedSet: unordered, can contain an object multiple times
The immutable variants help a lot with efficiency. The standard pattern for accessors of classes that have mutable variants is to copy rather than retain. This is codified in the @property mechanism, by using the copy attribute on the property:
// Department.h
@interface Department : NSObject
@property (readwrite, copy) NSSet *employees;
@end
This means that if you pass a mutable array to something that takes an array, it will be copied, and if you pass that to something else, it will be copied again. The trick is though that "copying" an immutable object really just retains it, so you only take a hit for that first copy. You probably want to make a copy that first time anyway so you don't pass a mutable array to something else, then mutate it behind the back of whatever you passed it to.
For Cocoa on Mac OS X, I'd also strongly encourage you to take a look at Core Data. It's an alternative to the "data set" pattern you might be used to from .NET/ADO/etc. With Core Data, you don't "get all customers" and then pass that collection around. Instead you query for the customers you care about, and as you traverse relationships of the objects you've queried for, other objects will be pulled in for you automatically.
Core Data also gets you features like visual modeling of your entities, automatic generation of property getters & setters, fine-grained control over migration from one schema version to another, and so on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: C#: instantiating classes from XML What I have is a collection of classes that all implement the same interface but can be pretty wildly different under the hood. I want to have a config file control which of the classes go into the collection upon starting the program, taking something that looks like :
<class1 prop1="foo" prop2="bar"/>
and turning that into :
blah = new class1();
blah.prop1="foo";
blah.prop2="bar";
In a very generic way. The thing I don't know how to do is take the string prop1 in the config file and turn that into the actual property accessor in the code. Are there any meta-programming facilities in C# to allow that?
A: It may be easier to serialise the classes to/from xml, you can then simply pass the XmlReader (which is reading your config file) to the deserializer and it will do the rest for you..
This is a pretty good article on serialization
Edit
One thing I would like to add, even though reflection is powerful, it requires you to know some stuff about the type, such as parameters etc.
Serializing to XML doesnt need any of that, and you can still have type safety by ensuring you write the fully qualified type name to the XML file, so the same type is automatically loaded.
A: Reflection allows you to do that. You also may want to look at XML Serialization.
Type type = blah.GetType();
PropertyInfo prop = type.GetProperty("prop1");
prop.SetValue(blah, "foo", null);
A: I would also suggest Xml serialization as others have already mentioned. Here is a sample I threw together to demonstrate. Attributes are used to connect the names from the Xml to the actual property names and types in the data structure. Attributes also list out all the allowed types that can go into the Things collection. Everything in this collection must have a common base class. You said you have a common interface already -- but you may have to change that to an abstract base class because this code sample did not immediately work when Thing was an interface.
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
string xml =
"<?xml version=\"1.0\"?>" +
"<config>" +
"<stuff>" +
" <class1 prop1=\"foo\" prop2=\"bar\"></class1>" +
" <class2 prop1=\"FOO\" prop2=\"BAR\" prop3=\"42\"></class2>" +
"</stuff>" +
"</config>";
StringReader sr = new StringReader(xml);
XmlSerializer xs = new XmlSerializer(typeof(ThingCollection));
ThingCollection tc = (ThingCollection)xs.Deserialize(sr);
foreach (Thing t in tc.Things)
{
Console.WriteLine(t.ToString());
}
}
}
public abstract class Thing
{
}
[XmlType(TypeName="class1")]
public class SomeThing : Thing
{
private string pn1;
private string pn2;
public SomeThing()
{
}
[XmlAttribute("prop1")]
public string PropertyNumber1
{
get { return pn1; }
set { pn1 = value; }
}
[XmlAttribute("prop2")]
public string AnotherProperty
{
get { return pn2; }
set { pn2 = value; }
}
}
[XmlType(TypeName="class2")]
public class SomeThingElse : SomeThing
{
private int answer;
public SomeThingElse()
{
}
[XmlAttribute("prop3")]
public int TheAnswer
{
get { return answer; }
set { answer =value; }
}
}
[XmlType(TypeName = "config")]
public class ThingCollection
{
private List<Thing> things;
public ThingCollection()
{
Things = new List<Thing>();
}
[XmlArray("stuff")]
[XmlArrayItem(typeof(SomeThing))]
[XmlArrayItem(typeof(SomeThingElse))]
public List<Thing> Things
{
get { return things; }
set { things = value; }
}
}
}
A: Reflection or XML-serialization is what you're looking for.
Using reflection you could look up the type using something like this
public IYourInterface GetClass(string className)
{
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (Type type in asm.GetTypes())
{
if (type.Name == className)
return Activator.CreateInstance(type) as IYourInterface;
}
}
return null;
}
Note that this will go through all assemblies. You might want to reduce it to only include the currently executing assembly.
For assigning property values you also use reflection. Something along the lines of
IYourInterface o = GetClass("class1");
o.GetType().GetProperty("prop1").SetValue(o, "foo", null);
While reflection might be the most flexible solution you should also take a look at XML-serialization in order to skip doing the heavy lifting yourself.
A: Plenty of metaprogramming facilities.
Specifically, you can get a reference to the assembly that holds these classes, then easily get the Type of a class from its name. See Assembly.GetType Method (String).
From there, you can instantiate the class using Activator or the constructor of the Type itself. See Activator.CreateInstance Method.
Once you have an instance, you can set properties by again using the Type object. See Type.GetProperty Method and/or Type.GetField Method along PropertyInfo.SetValue Method.
A: I recently did something very similar, I used an abstract factory. In fact, you can see the basic concept here:
Abstract Factory Design Pattern
A: I think you can utilize Dynamics here. Create ExpandoObject, it can be used either as Dictionary for setting properties from xml config.
A: Reflection is what you want. Reflection + TypeConverter. Don't have much more time to explain, but just google those, and you should be well on your way. Or you could just use the xml serializer, but then you have to adhere to a format, but works great.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: .Net Compact Framework scrollbars - horizontal always show when vertical shows I am new to the .Net Compact Framework and have been unable to find an answer via Google. Gasp! Yes, it's true, but that is part of why StackOverflow is here, right?
I have a form that is longer than the screen, so a vertical scroll-bar appears as expected. However, this appears to force a horizontal scroll-bar to appear as well. (If I scroll to the right, there is nothing visible except white space ... about the size of a scroll-bar.)
Is this a "feature" that is unavoidable? Anyone have experience in this area?
A: Place your controls within a panel or equivalent and then reduce the width of the panel by the size of a vertical scrollbar. That means that when the vertical scrollbar appears then it will no longer require the horizontal scrollbar to make up for the lost width that the vertical scrollbar took.
A: You need to use the Anchor attribute on the controls.
Make the control Anchored to the Top, Left and Right.
When the form requires the vertical scrollbar the controls will resize instead of using the horizontal scrollbar.
Also you may find it easier to put all the controls into a Panel. Make the Panel the first control you add to your form.
Make the panel as big as the form, or lower than the bottom of the form is you need more space.
Set the anchor to Top, Left, Right. Set the autoscroll to true. On the Form turn autoscroll off.
Now put the controls into the Panel. You still need to set the anchor points on each of your controls or your Panel control will use the horizontal scrollbar and make the whole exercise pointless.
This is a good technique when you need to use the SIP(Soft Input Panel) as the Panels Height attribute can be altered when the SIP.Enabled attribute changes and prevents some of the controls being hidden by the SIP - it is annoying having to write text in a Textbox that you can't see.
The panel will provide the scrollbar as needed.
I'd say it is a good idea to put all controls in a Panel on the Form as adding it later can be a pain in the arse if the SIP is required later.
A: Yes - I've got experience with that - unfortunately it was no different from your own. I've generally avoided scrolling forms and used paging wherever possible on .Net CF. If this is an option for you, I'd recommend it.
I'd assume the scroll bar issue is to do with the form size being fixed to the width of the available screen (regardless of design-time settings) so the introduction of a vertical scroll bar obscures part of the (not needed) full-width form.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I set ItemTemplate dynamically in WPF? Using WPF, I have a TreeView control that I want to set its ItemTemplate dynamically through procedural code. How do I do this? I assume I need to find the resource somewhere.
myTreeViewControl.ItemTemplate = ??
A: if your treeview control requires different templates for your items, you should implement DataTemplateSelector class and set it's instance to your tree view. as far as i remember there is a property of DataTemplateSelector.
A: If the template is defined in your <Window.Resources> section directly:
myTreeViewControl.ItemTemplate = this.Resources["SomeTemplate"] as DataTemplate;
If it's somewhere deep within your window, like in a <Grid.Resources> section or something, I think this'll work:
myTreeViewControl.ItemTemplate = this.FindResource("SomeTemplate") as DataTemplate;
And if it's elsewhere in your application, I think App.FindResource("SomeTemplate") will work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Content Type for MHT files What is the content type for MHT files?
A: Microsoft, who co-authored the spec for MHT, seem to think that it should be 'message/rfc822' on this support page.
No specific MIME type seems to be given in the spec though:
RFC2557: MIME Encapsulation of Aggregate Documents, such as HTML (MHTML)
A: I know this is old, but I thought it should be clarified and explained in more detail...
@Guy Starbuck wrote:
message/rfc822
RFC 822 - STANDARD FOR THE FORMAT OF ARPA INTERNET TEXT MESSAGES
The problem with this answer is that MHTML files are not defined by RFC822.
The correct content-type for MHTML files (.mht, .mhtml) is multipart/related.
As stated above, RFC822 defines the format for internet text messages. The content-type message/rfc822 is used for text attachments within email messages [1][2].
Most of us have probably received a reply to an email where, instead of being quoted inline, the original message is included as an attachment. That attachment has a content-type of message/rfc822. In such emails, the content-types break down as follows:
*
*multipart/mixed = entire message
*text/plain = text of reply email
*message/rfc822 = original email as attachment
On the other hand, as noted by @feeela, MHTML files are defined in RFC2557. MHTML files are comprised of many different parts, each of which can have a different content-type. However, RFC2557 defines the content-type of the entire file as multipart/related.
[1] RFC1341: MIME (Multipurpose Internet Mail Extensions)
[2] The message Content-Type
A: message/rfc822
RFC 822 - STANDARD FOR THE FORMAT OF ARPA INTERNET TEXT MESSAGES
Here is a hyperlink: message/rfc822
A: "MIME Encapsulation of Aggregate Documents, such as HTML" (MHTML or MHT) is an IETF standard proposed in 1999 in the RFC 2557.
Its MIME type is multipart/related and the extension is .mht.
See also:
*
*https://www.rfc-editor.org/rfc/rfc2557
*http://en.wikipedia.org/wiki/MHTML
A: application/octet-stream
You can stream the contents of a .eml file to a browser with this content type and .mht as the extension, and the email will be rendered similar to the way it is rendered in an email client.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: VMWare Tools for Ubuntu Hardy I am using VMWare tools for Ubuntu Hardy, but for some reason vmware-install.pl finds fault with my LINUX headers. The error message says that the "address space size" doesn't match.
To try and remediate, I have resorted to vmware-any-any-update117, and am now getting the following error instead:
In file included from include/asm/page.h:3,
from /tmp/vmware-config0/vmmon-only/common/hostKernel.h:56,
from /tmp/vmware-config0/vmmon-only/common/task.c:30:
include/asm/page_32.h: In function ‘pte_t native_make_pte(long unsigned int)’:
include/asm/page_32.h:112: error: expected primary-expression before ‘)’ token
include/asm/page_32.h:112: error: expected ‘;’ before ‘{’ token
include/asm/page_32.h:112: error: expected primary-expression before ‘.’ token
include/asm/page_32.h:112: error: expected `;' before ‘}’ token
Can anyone help me make some sense of this, please?
A: This error ofter occurs because incompatibility of VMWare Tools Version and recent Kernels (You can test it using older Kernels). Sometimes you can fix some thing with patches all over the internet, but I prefer to downgrade my kernel or don't using latest distribution's version in VMWare. It can be really annoying. Another problem you may have is with your mouse pointer in X Windows, like if it was a inch to left or below than it really shows.
About vmware-any-any-update117, it's a patch to VMWare running under linux, usually Workstation version. It won't have effect in Tools.
A: You're probably best off using the VMWare Tools .rpm file instead of the install script on Ubuntu. Alien is a program that will let you turn a .rpm into a Ubuntu-friendly .deb package.
A: Check out this link as it helped me install the tools in one of my vms. http://diamondsw.dyndns.org/Home/Et_Cetera/Entries/2008/4/25_Linux_2.6.24_and_VMWare.html
A: I've heard a lot of good things about VirtualBox from Sun. If you get fed up with VMWare, it's worth a look.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Using Virtual PC for Web Development with Oracle Is anyone using Virtual PC to maintain multiple large .NET 1.1 and 2.0 websites? Are there any lessons learned? I used Virtual PC recently with a small WinForms app and it worked great, but then everything works great with WinForms. ASP.NET development hogs way more resources, requires IIS to be running, requires a ridiculously long wait after recompilations, etc., so I'm a little concerned. And I'll also be using Oracle, if that makes any difference.
Also, is there any real reason to use VM Ware instead of Virtual PC?
A: I've used VirtualPCs for a few years for development of some fairly hefty web apps without much problem. Lots of RAM is important. I keep my VPCs on an external USB drive and they perform great from there. This gives me the flexibility to take the drive with me if I need to do work somewhere else... just install VPC on a host plug in the USB drive and start coding.
For servers, we use VMWare and have had little to no trouble with it.
Recently I went back to working on my local machine as you lose the benefit of dual monitors with VPCs, and I don't need to be as mobile as I used to.
A: As long as you have the resources (separate hard disk for the virtual machine, sufficient RAM), I don't see why you would have any problems.
A: Virtual PC 2007 is very fast esp on a CPU that has hardware support for VM's. 3GB RAM a must for anything not small. XP makes a good guest OS, Vista works well as a host.
A: Thanks for all the answers. So RAM is the key.
As far as dual monitor capability, I found that I could use dual monitors, as long as one of those monitors was my actual machine. And that was what I wanted anyway.
Mike
A: If you are going to be using VPCs as a server...perhaps Hyper-V (http://en.wikipedia.org/wiki/Windows_Server_Virtualization) is something to look at.
Its pretty powerful, in how it lets you assign RAM / CPU Cores to a virtualized machine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JavaScript animation with Safari I'm trying to create web applications that use JavaScript. I'd like to be able to use animation in these applications. I've tried to use basic JavaScript, but I've decided that the best thing to do is to use a library (such as YUI or jQuery).
I'm running into a problem. On Safari, when I run animation scripts, the animation is very chunky, very blocky. This happens with YUI as well as basic JavaScript. Why does this happen? Are there any good libraries that don't create this problem in Safari, but are also good for Internet Explorer and Firefox (and, hopefully, Opera)?
A: I have found MooTools to be pretty slick for animations, just a little smoother than jQuery.
I generally prefer jQuery, which I find to be a little more intuitive (in my head anyway), but I would use MooTools if slick animation is the most important requirement.
A: JQuery has animation, but I don't know what it is like on a Mac (I don't have a mac). If things are going slow, then you are probably making the animations too complicated. Remember, JavaScript is a slow language, and DOM is not designed for animation, so try to limit yourself with respect to the number of animations at the same time. Always ask if the animation is really necessary.
A: Well, for starters you could use CSS Transformations if the application is Safari-specific. Otherwise JQuery got some built in animations and a big community behind it (and thus, a large plugin repository).
A: You can download some sample code and check locally to make sure that things are supposed to work. For example, you can get the source code for B&K's jQuery book at http://www.manning.com/bibeault/ (check out the source link) and try out the samples for Chapter 5. If those pages work (locally) for you on Safari, then at least you know your basic environment is sane.
I'm having similar problems, and I suspect there are Safari bugs that jQuery is tripping over. But I haven't yet figured out whether it's me writing sloppy code (with FF perhaps being more forgiving than Safari), or if it's Safari, or if it's jQuery. I'll post more if I get any wiser.
A: Strange, WebKit (the JavaScript engine that Safari uses) is supposed to be pretty fast. Make sure that you have the latest version, there have been great progress for the JavaScript engines in the Safari and Firefox releases in recent time. Also, I think Dojo and MooTools have faster animations than jQuery, at least in my experience.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Fast SQL Server 2005 script generation It seems like the generation of SQL scripts from the SQL Server Management Studio is terribly slow. I think that the old Enterprise Manager could run laps around the newer script generation tool. I've seen a few posts here and there with other folks complaining about the speed, but I haven't seen much offered in the way of alternatives.
Is there a low-cost/free tool for scripting an entire SQL Server 2005 database that will perform better that SSMS? It would be hard to do worse.
A: We are using the tools by RedGate which I personally find very useful in any aspect of work with databases. For scripting I would recommend the SQL Compare (you need a pro version for scripting). The SQL Compare is a must have for deploying schema changes from the deployment DB to the live Server and a real timesaver.
Those tools are not free but I think they could save you money in a long run
A: See the Database Publishing Wizard that is part of the SQL Server Hosting Toolkit. It generates a single SQL file for both schema and data.
A: I don't know what is "terribly slow" for you, but I have a decent performance with SQL 2005 Management Studio. In either case, RedGate products are very cool. Unfortunately they are not free.
A: What kind of scrpt generation are you talking about now?, generating create scripts from the objects in the database is way faster in SSMS compared to EM.
But if you are running an select or something that gives you lots of rows in the grid, it is crazy slow.. like scripts generating inserts statements of all rows in an table, if you got lots of data, it is almost not doable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Cannot access a webservice from mobile device I developed a program in a mobile device (Pocket PC 2003) to access a web service, the web service is installed on a Windows XP SP2 PC with IIS, the PC has the IP 192.168.5.2.
The device obtains from the wireless network the IP 192.168.5.118 and the program works OK, it calls the method from the web service and executes the action that is needed. This program is going to be used in various buildings.
Now I have this problem, it turns that when I try to test it in another building (distances neraly about 100 mts. or 200 mts.) connected with the network, the program cannot connect to the webservice, at this moment the device gets from an Access Point the IP 192.168.10.25, and it accesses the same XP machine I stated before (192.168.5.2). I made a mobile aspx page to verify that I can reach the web server over the network and it loads it in the device, I even made a winform that access the same webservice in a PC from that building and also works there so I don't understand what is going on. I also tried to ping that 192.168.5.2 PC and it responds alive.
After that fail I returned to the original place where I tested the program before and it happens that it works normally.
The only thing that I look different here is that the third number in the IP is 10 instead of 5, another observation is that I can't ping to the mobile device. I feel confused I don't know what happens here? What could be the problem?
This is how I call the web service;
//Connect to webservice
svc = new TheWebService();
svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password);
svc.AllowAutoRedirect = false;
svc.UserAgent = Settings.UserAgent;
svc.PreAuthenticate = true;
svc.Url = Settings.Url;
svc.Timeout = System.Threading.Timeout.Infinite;
//Send information to webservice
svc.ExecuteMethod(info);
the content of the app.config in the mobile device is;
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="UserName" value="administrator" />
<add key="Password" value="************" />
<add key="UserAgent" value="My User Agent" />
<add key="Url" value="http://192.168.5.2/WebServices/TWUD.asmx" />
</appSettings>
</configuration>
Does anyone have an idea what is going on?
A: It was a network issue, we configurated a proxy server and that was the problem, I need to learn more about network.
A: Not an expert with this stuff but it looks like the first 3 parts of the address are being masked out. Is it possible that the mobile device is being given a network mask of:
255.255.255.0
As to reach beyond the range of the first 3 parts you need the mask to be:
255.255.0.0
This may be an oversimplification or completely wrong but that's was my gut response to the question.
A: This looks like a network issue, unless there's an odd bug in .Net CF that doesn't allow you to traverse subnets in certain situations (I can find no evidence of such a thing from googling).
Can you get any support from the network/IT team? Also, have you tried it from a different subnet? I.e. not the same as the XP machine (192.168.5.x) and not the same as the one that's not worked so far (192.168.10.).
@Shaun Austin - that wouldn't explain why they can get at a regular web page on the XP machine from the different subnet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Checklist for Database Schema Upgrades Having to upgrade a database schema makes installing a new release of software a lot trickier. What are the best practices for doing this?
I'm looking for a checklist or timeline of action items, such as
*
*8:30 shut down apps
*8:45 modify schema
*9:15 install new apps
*9:30 restart db
etc, showing how to minimize risk and downtime. Issues such as
*
*backing out of the upgrade if things go awry
*minimizing impact to existing apps
*"hot" updates while the database is running
*promoting from dev to test to production servers
are especially of interest.
A: I have a lot of experience with this. My application is highly iterative, and schema changes happen frequently. I do a production release roughly every 2 to 3 weeks, with 50-100 items cleared from my FogBugz list for each one. Every release we've done over the last few years has required schema changes to support new features.
The key to this is to practice the changes several times in a test environment before actually making them on the live servers.
I keep a deployment checklist file that is copied from a template and then heavily edited for each release with anything that is out of the ordinary.
I have two scripts that I run on the database, one for schema changes, one for programmability (procedures, views, etc). The changes script is coded by hand, and the one with the procs is scripted via Powershell. The change script is run when everything is turned off (you have to pick a time that annoys the least amount of users for this), and it is run command by command, manually, just in case anything goes weird. The most common problem I have run into is adding a unique constraint that fails due to duplicate rows.
When preparing for an integration testing cycle, I go through my checklist on a test server, as if that server was production. Then, in addition to that, I go get an actual copy of the production database (this is a good time to swap out your offsite backups), and I run the scripts on a restored local version (which is also good because it proves my latest backup is sound). I'm killing a lot of birds with one stone here.
So that's 4 databases total:
*
*Dev: all changes must be made in the change script, never with studio.
*Test: Integration testing happens here
*Copy of production: Last minute deployment practice
*Production
You really, really need to get it right when you do it on production. Backing out schema changes is hard.
As far as hotfixes, I will only ever hotfix procedures, never schema, unless it's a very isolated change and crucial for the business.
A: I guess you have considered the reads of Scott Ambler?
http://www.agiledata.org/essays/databaseRefactoring.html
A: This is a topic that I was just talking about at work. Mainly the problem is that unless database migrations is handled for you nicely by your framework, eg rails and their migration scripts, then it is left up to you.
The current way that we do it has apparent flaws, and I am open to other suggestions.
*
*Have a schema dump with static data that is required to be there kept up to date and in version control.
*Every time you do a schema changing action, ALTER, CREATE, etc. dump it to a file and throw it in version control.
*Make sure you update the original sql db dump.
*When doing pushes to live make sure you or your script applies the sql files to the db.
*Clean up old sql files that are in version control as they become old.
This is by no means optimal and is really not intended as a "backup" db. It's simply to make pushes to live easy, and to keep developers on the same page. There is probably something cool you could setup with capistrano as far as automating the application of the sql files to the db.
Db specific version control would be pretty awesome. There is probably something that does that and if there isn't there probably should be.
A: And if the Scott Ambler paper whets your appetite I can recommend his book with Pramod J Sadolage called 'Refactoring Databases' - http://www.ambysoft.com/books/refactoringDatabases.html
There is also a lot of useful advice and information at the Agile Database group at Yahoo - http://tech.groups.yahoo.com/group/agileDatabases/
A: Two quick notes:
*
*It goes without saying... So I'll say it twice.
Verify that you have a valid backup.
Verify that you have a valid backup.
*@mk. Check out Jeff's blog post on database version control (if you haven't already)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Problems passing special chars with observe_field I am working on a rails project. Using the tag observe_field, I am taking text typed into a text area, processing it in a control, and displaying the result in a div (very similar to the preview in stack overflow). Everything works fine until I type certain special chars.
*
*? => causes the variable not to be found in the params object
*(pound) => causes an invalid authenticity error
*% => stops the div from being updated
*& => every thing after the & is no longer passed into the variable on the server.
Is there a way to solve this?
--- code sample ---
this is the view. ( 'postbody' is a text area)
<%= observe_field 'postbody',
:update => 'preview',
:url => {:controller => 'blog', :action => 'textile_to_html'},
:frequency => 0.5,
:with => 'postbody' -%>
this is the controller that is called
def textile_to_html
text = params['postbody']
if text == nil then
@textile_to_html = '<br/>never set'
else
r = RedCloth.new text
@textile_to_html = r.to_html
end
render :layout => false
end
and this is the javascript that is created:
new Form.Element.Observer('postbody', 0.5, function(element, value) {new Ajax.Updater('preview', '/blog/textile_to_html', {asynchronous:true, evalScripts:true, parameters:'postbody=' + value + '&authenticity_token=' + encodeURIComponent('22f7ee12eac9efd418caa0fe76ae9e862025ef97')})})
A: This is an escaping issue (as stated by others).
You'll want to change your observe_field :with statement to something like:
:with => "'postbody=' + encodeURIComponent(value)"
Then in your controller:
def textile_to_html
text = URI.unescape(params['postbody'])
...
A: Can you provide a code sample?
More likely than not you'll just need to escape your HTML entities using encodeuri or something like that.
A: What does the generated Javascript look like?
Sounds (at first glance) like it's not being escaped.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Profile a rails controller action What is the best way to profile a controller action in Ruby on Rails. Currently I am using the brute-force method of throwing in puts Time.now calls between what I think will be a bottleneck. But that feels really, really dirty. There has got to be a better way.
A: Use the Benchmark standard library and the various tests available in Rails (unit, functional, integration). Here's an example:
def test_do_something
elapsed_time = Benchmark.realtime do
100.downto(1) do |index|
# do something here
end
end
assert elapsed_time < SOME_LIMIT
end
So here we just do something 100 times, time it via the Benchmark library, and ensure that it took less than SOME_LIMIT amount of time.
You also may find these links useful: The Benchmark.realtime reference and the Test::Unit reference. Also, if you're into the 'book reading' thing, I picked up the idea for the example from Agile Web Development with Rails, which talks all about the different testing types and a little on performance testing.
A: There's a Railscast on profiling that's well worth watching
http://railscasts.com/episodes/98-request-profiling
A: I picked up this technique a while back and have found it quite handy.
When it's in place, you can add ?profile=true to any URL that hits a controller. Your action will run as usual, but instead of delivering the rendered page to the browser, it'll send a detailed, nicely formatted ruby-prof page that shows where your action spent its time.
First, add ruby-prof to your Gemfile, probably in the development group:
group :development do
gem "ruby-prof"
end
Then add an around filter to your ApplicationController:
around_action :performance_profile if Rails.env == 'development'
def performance_profile
if params[:profile] && result = RubyProf.profile { yield }
out = StringIO.new
RubyProf::GraphHtmlPrinter.new(result).print out, :min_percent => 0
self.response_body = out.string
else
yield
end
end
Reading the ruby-prof output is a bit of an art, but I'll leave that as an exercise.
Additional note by ScottJShea:
If you want to change the measurement type place this:
RubyProf.measure_mode = RubyProf::GC_TIME #example
Before the if in the profile method of the application controller. You can find a list of the available measurements at the ruby-prof page. As of this writing the memory and allocations data streams seem to be corrupted (see defect).
A: You might want to give the FiveRuns TuneUp service a try, as it's really rather impressive. Disclaimer: I'm not associated with FiveRuns in any way, I've just tried this service out.
TuneUp is a free service whereby you download a plugin and when you run your application it injects a panel at the top of the screen that can be expanded to display detailed performance metrics.
It gives you some nice graphs, including one that shows what proportion of time is spent in the Model, View and Controller. You can even drill right down to see the individual SQL queries that ActiveRecord is executing if you need to and it can show you the underlying database schema with another click.
Finally, you can optionally upload your profiling data to the FiveRuns site for community performance analysis and advice.
A: This works in Rails 4.2.6:
o=OpenStruct.new(logger: Rails.logger)
o.extend ActiveSupport::Benchmarkable
o.benchmark 'name' do
# ... your code ...
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: How do I add a constant column value during data transfer from CSV to SQL? I am reading in CSV file and translating it to an SQL Table. The kicker is that one of the columns in the table is of data type ID that needs to be set to a constant (in this case 2). I am not sure how to do this.
A: You can use a Derived Column Transformation in which you'll create a new output column and set its value to 2. You can then use that column when outputting to SQL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Is there a browser equivalent to IE's ClearAuthenticationCache? I have a few internal .net web application here that require users to "log out" of them. I know this may seem moot on an Intranet application, but nonetheless it is there.
We are using Windows authentication for our Intranet apps, so we tie in to our Active Directory with Basic Authentication and the credentials get stored in the browser cache, as opposed to a cookie when using .net forms authentication.
In IE6+ you can leverage a special JavaScript function they created by doing the following:
document.execCommand("ClearAuthenticationCache", "false")
However, for the other browsers that are to be supported (namely Firefox at the moment, but I strive for multi-browser support), I simply display message to the user that they need to close their browser to log out of the application, which effectively flushes the application cache.
Does anybody know of some commands/hacks/etc. that I can use in other browsers to flush the authentication cache?
A: A couple of notes. A few people have said that you need to fire off a ajax request with invalid credentials to get the browser to drop it's own credentials.
This is true but as Keith pointed out, it is essential that the server page claims to accept these credentials for this method to work consistently.
On a similar note: It is NOT good enough for your page to just bring up the login dialog via a 401 error. If the user cancels out of the dialog then their cached credentials are also unaffected.
Also if you can please poke MOZILLA at https://bugzilla.mozilla.org/show_bug.cgi?id=287957 to add a proper fix for FireFox. A webkit bug was logged at https://bugs.webkit.org/show_bug.cgi?id=44823. IE implements a poor but functional solution with the method:
document.execCommand("ClearAuthenticationCache", "false");
It is unfortunate that we need to go to these lengths just to log out a user.
A: Mozilla implemented the crypto object, available via the DOM window object, which has the logout function (Firefox 1.5 upward) to clear the SSL session state at the browser level so that "the next private operation on any token will require the user password again" (see this).
The crypto object seems to be an implementation of the Web Crypto API, and according to this document, the DOMCrypt API will add even more functions.
As stated above Microsoft IE (6 upward) has:
document.execCommand("ClearAuthenticationCache", "false")
I have found no way of clearing the SLL cache in Chrome (see this and this bug reports).
In case the browser does not offer any API to do this, I think the better we can do is to instruct the user to close the browser.
Here's what I do:
var agt=navigator.userAgent.toLowerCase();
if (agt.indexOf("msie") !== -1) {
document.execCommand("ClearAuthenticationCache","false");
}
//window.crypto is defined in Chrome, but it has no logout function
else if (window.crypto && typeof window.crypto.logout === "function"){
window.crypto.logout();
}
else{
window.location = "/page/to/instruct/the/user/to/close/the/browser";
}
A: I've been searching for a similar solution and came across a patch for Trac (an issue management system) that does this.
I've looked through the code (and I'm tired, so I'm not explaining everything); basically you need to do an AJAX call with guaranteed invalid credentials to your login page. The browser will get a 401 and know it needs to ask you for the right credentials next time you go there. You use AJAX instead of a redirect so that you can specify incorrect credentials and the browser doesn't popup a dialog.
On the patch (http://trac-hacks.org/wiki/TrueHttpLogoutPatch) page they use very rudimentary AJAX; something better like jQuery or Prototype, etc. is probably better, although this gets the job done.
A: Why not use FormsAuth, but against ActiveDirectory instead as per the info in this thread. It's just as (in)secure as Basic Auth, but logging out is simply a matter of blanking a cookie (or rather, calling FormsAuthentication.SignOut)
A: I've come up with a fix that seems fairly consistent but is hacky and I'm still not happy with it.
It does work though :-)
1) Redirect them to a Logoff page
2) On that page fire a script to ajax load another page with dummy credentials (sample in jQuery):
$j.ajax({
url: '<%:Url.Action("LogOff401", new { id = random })%>',
type: 'POST',
username: '<%:random%>',
password: '<%:random%>',
success: function () { alert('logged off'); }
});
3) That should always return 401 the first time (to force the new credentials to be passed) and then only accept the dummy credentials (sample in MVC):
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogOff401(string id)
{
// if we've been passed HTTP authorisation
string httpAuth = this.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(httpAuth) &&
httpAuth.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
{
// build the string we expect - don't allow regular users to pass
byte[] enc = Encoding.UTF8.GetBytes(id + ':' + id);
string expected = "basic " + Convert.ToBase64String(enc);
if (string.Equals(httpAuth, expected, StringComparison.OrdinalIgnoreCase))
{
return Content("You are logged out.");
}
}
// return a request for an HTTP basic auth token, this will cause XmlHttp to pass the new header
this.Response.StatusCode = 401;
this.Response.StatusDescription = "Unauthorized";
this.Response.AppendHeader("WWW-Authenticate", "basic realm=\"My Realm\"");
return Content("Force AJAX component to sent header");
}
4) Now the random string credentials have been accepted and cached by the browser instead. When they visit another page it will try to use them, fail, and then prompt for the right ones.
A: Well, I've been browsing around Bugzilla for a bit now and seemingly the best way you can go for clearing the authentication would be to send non-existant credentials.
Read more here: https://bugzilla.mozilla.org/show_bug.cgi?id=287957
A: Hopefully this will be useful until someone actually comes along with an explicit answer - this issue was discussed two years ago on a message board.
HTH
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: How do threads work in Python, and what are common Python-threading specific pitfalls? I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up.
From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so?
Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.
A: Yes, because of the Global Interpreter Lock (GIL) there can only run one thread at a time. Here are some links with some insights about this:
*
*http://www.artima.com/weblogs/viewpost.jsp?thread=214235
*http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/
From the last link an interesting quote:
Let me explain what all that means.
Threads run inside the same virtual
machine, and hence run on the same
physical machine. Processes can run
on the same physical machine or in
another physical machine. If you
architect your application around
threads, you’ve done nothing to access
multiple machines. So, you can scale
to as many cores are on the single
machine (which will be quite a few
over time), but to really reach web
scales, you’ll need to solve the
multiple machine problem anyway.
If you want to use multi core, pyprocessing defines an process based API to do real parallelization. The PEP also includes some interesting benchmarks.
A: Python's a fairly easy language to thread in, but there are caveats. The biggest thing you need to know about is the Global Interpreter Lock. This allows only one thread to access the interpreter. This means two things: 1) you rarely ever find yourself using a lock statement in python and 2) if you want to take advantage of multi-processor systems, you have to use separate processes. EDIT: I should also point out that you can put some of the code in C/C++ if you want to get around the GIL as well.
Thus, you need to re-consider why you want to use threads. If you want to parallelize your app to take advantage of dual-core architecture, you need to consider breaking your app up into multiple processes.
If you want to improve responsiveness, you should CONSIDER using threads. There are other alternatives though, namely microthreading. There are also some frameworks that you should look into:
*
*stackless python
*greenlets
*gevent
*monocle
A: One easy solution to the GIL is the multiprocessing module. It can be used as a drop in replacement to the threading module but uses multiple Interpreter processes instead of threads. Because of this there is a little more overhead than plain threading for simple things but it gives you the advantage of real parallelization if you need it.
It also easily scales to multiple physical machines.
If you need truly large scale parallelization than I would look further but if you just want to scale to all the cores of one computer or a few different ones without all the work that would go into implementing a more comprehensive framework, than this is for you.
A: Below is a basic threading sample. It will spawn 20 threads; each thread will output its thread number. Run it and observe the order in which they print.
import threading
class Foo (threading.Thread):
def __init__(self,x):
self.__x = x
threading.Thread.__init__(self)
def run (self):
print str(self.__x)
for x in xrange(20):
Foo(x).start()
As you have hinted at Python threads are implemented through time-slicing. This is how they get the "parallel" effect.
In my example my Foo class extends thread, I then implement the run method, which is where the code that you would like to run in a thread goes. To start the thread you call start() on the thread object, which will automatically invoke the run method...
Of course, this is just the very basics. You will eventually want to learn about semaphores, mutexes, and locks for thread synchronization and message passing.
A: Try to remember that the GIL is set to poll around every so often in order to do show the appearance of multiple tasks. This setting can be fine tuned, but I offer the suggestion that there should be work that the threads are doing or lots of context switches are going to cause problems.
I would go so far as to suggest multiple parents on processors and try to keep like jobs on the same core(s).
A: Note: wherever I mention thread i mean specifically threads in python until explicitly stated.
Threads work a little differently in python if you are coming from C/C++ background. In python, Only one thread can be in running state at a given time.This means Threads in python cannot truly leverage the power of multiple processing cores since by design it's not possible for threads to run parallelly on multiple cores.
As the memory management in python is not thread-safe each thread require an exclusive access to data structures in python interpreter.This exclusive access is acquired by a mechanism called GIL ( global interpretr lock ).
Why does python use GIL?
In order to prevent multiple threads from accessing interpreter state simultaneously and corrupting the interpreter state.
The idea is whenever a thread is being executed (even if it's the main thread), a GIL is acquired and after some predefined interval of time the
GIL is released by the current thread and reacquired by some other thread( if any).
Why not simply remove GIL?
It is not that its impossible to remove GIL, its just that in prcoess of doing so we end up putting mutiple locks inside interpreter in order to serialize access, which makes even a single threaded application less performant.
so the cost of removing GIL is paid off by reduced performance of a single threaded application, which is never desired.
So when does thread switching occurs in python?
Thread switch occurs when GIL is released.So when is GIL Released?
There are two scenarios to take into consideration.
If a Thread is doing CPU Bound operations(Ex image processing).
In Older versions of python , Thread switching used to occur after a fixed no of python instructions.It was by default set to 100.It turned out that its not a very good policy to decide when switching should occur since the time spent executing a single instruction can
very wildly from millisecond to even a second.Therefore releasing GIL after every 100 instructions regardless of the time they take to execute is a poor policy.
In new versions instead of using instruction count as a metric to switch thread , a configurable time interval is used.
The default switch interval is 5 milliseconds.you can get the current switch interval using sys.getswitchinterval().
This can be altered using sys.setswitchinterval()
If a Thread is doing some IO Bound Operations(Ex filesystem access or
network IO)
GIL is release whenever the thread is waiting for some for IO operation to get completed.
Which thread to switch to next?
The interpreter doesn’t have its own scheduler.which thread becomes scheduled at the end of the interval is the operating system’s decision. .
A: Use threads in python if the individual workers are doing I/O bound operations. If you are trying to scale across multiple cores on a machine either find a good IPC framework for python or pick a different language.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "91"
} |
Q: Do you need the .NET 1.0 framework to target the .NET 1.0 framework? I have a bunch of .NET frameworks installed on my machine.
I know that with the Java JDK, I can use the 6.0 version to target 5.0 and earlier.
Can I do something similar with the .NET framework - target 1.0 and 2.0 with the 3.0 framework?
A: Visual Studio 2008 was the first to support targeting older versions of .NET. Unfortunately, it supports only .NET 2 and up.
In other words, you'll need .NET framework SDK 1 or 1.1 to do this.
A: We use Visual Studio 2008 to maintain a .NET 1.1 WebForms app using MSBee. It required a bit of initial *.csproj/msbuild file hackery, but works very well. Of course, you're limited to .NET 1.1 features (it uses the old 1.1 compilers), so no Generics or LINQ. But if you're wanting just one copy of Visual Studio installed it's the way to go.
A: (Updated)
You need to compile with the 1.0 compilers. These are only available with the 1.0 release of the runtime/SDK.
The 2.0/3.5 compilers won't emit 1.0-compatible assemblies.
Visual Studio 2008 can generate 2.0 assemblies, but 1.0 was left off.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What's the best way to display a video with rounded corners in Silverlight? The MediaElement doesn't support rounded corners (radiusx, radiusy). Should I use a VideoBrush on a Rectangle with rounded corners?
A: Yeah - In a way you're both asking and answering the question yourself... But that is one of the two options I can think of. The reasons that might be a problem is that you lose some of the features/control you get from the MediaElement control. Another option is to do this:
*
*Add your MediaElement to your page.
*Draw a Rectangle on top of it and set wanted corner radius
*Right click the rectangle in Blend and choose "Create Clipping Path"
*Apply the clipping path to your MediaElement
That way you're still using a MediaElement control, but you can "clip" away what ever you want to get the desired rounded effect.
This example shows a clipped MediaElement. I know it's not easy to picture the vector path, but if you open it open in Blend you will see a rounded MediaElement.
<MediaElement
Height="132" Width="176" Source="Egypt2007.wmv"
Clip="M0.5,24.5 C0.5,11.245166 11.245166,0.5 24.5,0.5 L151.5,0.5
C164.75484,0.5 175.5,11.245166 175.5,24.5 L175.5,107.5 C175.5,
120.75484 164.75484,131.5 151.5,131.5 L24.5,131.5 C11.245166,
131.5 0.5,120.75484 0.5,107.5 z"/>
A: Using a rounded rectangle and a VideoBrush doesn't lose you any features/control over using a displayed MediaElement - since the element has to be in the Xaml anyway, you can control it using the usual Play/Pause/Stop methods, except that the playback happens in your rectangle. Using a clip region is a little unwieldy because it's harder to resize the region. A Rectangle is better because you have flexibility of layout.
<MediaElement x:Name="myElement" Source="clip.wmv" Visibility="Collapsed"/>
<Rectangle RadiusX="10" RadiusY="10" Width="640" Height="480">
<Rectangle.Fill>
<VideoBrush Source="myElement" Stretch="Uniform"/>
</Rectangle.Fill>
<Rectangle/>
A: The clip path with give you "hard" edges - you could also use an OpacityMask as well (though I imagine this requires much more processing power).
A: Try this
<Border CornerRadius="8" BorderBrush="Black" Background="Black" BorderThickness="3">
<MediaElement HorizontalAlignment="Center" VerticalAlignment="Top" Stretch="Fill" x:Name="Player" Source="/Assets/Videos/x.mp3" />
</Border>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Find and Replace with Unique I am performing a find and replace on the line feed character ( ) and replacing it with the paragraph close and paragraph open tags using the following code:
<xsl:template match="/STORIES/STORY">
<component>
<xsl:if test="boolean(ARTICLEBODY)">
<p>
<xsl:call-template name="replace-text">
<xsl:with-param name="text" select="ARTICLEBODY" />
<xsl:with-param name="replace" select="' '" />
<xsl:with-param name="by" select="'</p><p>'" />
</xsl:call-template>
</p>
</xsl:if>
</component>
</xsl:template>
<xsl:template name="replace-text">
<xsl:param name="text"/>
<xsl:param name="replace" />
<xsl:param name="by" />
<xsl:choose>
<xsl:when test="contains($text, $replace)">
<xsl:value-of select="substring-before($text, $replace)"/>
<xsl:value-of select="$by" disable-output-escaping="yes"/>
<xsl:call-template name="replace-text">
<xsl:with-param name="text" select="substring-after($text, $replace)"/>
<xsl:with-param name="replace" select="$replace" />
<xsl:with-param name="by" select="$by" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
This almost works perfectly, except that I really need it to de-dup the line feeds as the paragraphs tend to be separated by 2 or more resulting in </p><p></p><p>.
Is it possible to get it so that it will only ever replace this once per paragraph?
A: disable-output-escaping isn't evil in itself, but there are only few cases where you should use it and this isn't one of them. In XSLT you work with trees, not markup string. Here's an XSTL 1.0 solution:
<xsl:template match="/STORIES/STORY">
<component>
<xsl:if test="ARTICLEBODY">
<xsl:call-template name="wrap-text">
<xsl:with-param name="text" select="ARTICLEBODY"/>
<xsl:with-param name="delimiter" select="' '"/>
<xsl:with-param name="element" select="'p'"/>
</xsl:call-template>
</xsl:if>
</component>
</xsl:template>
<xsl:template name="wrap-text">
<xsl:param name="text"/>
<xsl:param name="delimiter"/>
<xsl:param name="element"/>
<xsl:choose>
<xsl:when test="contains($text, $delimiter)">
<xsl:variable name="t" select="substring-before($text, $delimiter)"/>
<xsl:if test="normalize-space($t)">
<xsl:element name="{$element}">
<xsl:value-of select="$t"/>
</xsl:element>
</xsl:if>
<xsl:call-template name="wrap-text">
<xsl:with-param name="text" select="substring-after($text, $delimiter)"/>
<xsl:with-param name="delimiter" select="$delimiter"/>
<xsl:with-param name="element" select="$element"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:if test="normalize-space($text)">
<xsl:element name="{$element}">
<xsl:value-of select="$text"/>
</xsl:element>
</xsl:if>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
A: Given the XPath functions that you're calling which I don't remember having the luxury of in my MSXSL work, it looks like you're using an XPath 2-compatible processor.
If that's the case, doesn't XPath 2 have a replace(string, pattern, replacement) function that takes a regex as a second parameter?
<xsl:value-of
select="replace(string(.), ' (\s| )*', '</p><p>')" />
It might help to have some sample Xml input and to know what processor you plan to use.
From your original example, it seems that the duplicate paragraphs all have a white-space only prefix. So something like this slight modification might trim the dupes.
<xsl:when test="contains($text, $replace)">
<xsl:variable name="prefix" select="substring-before($text, $replace)" />
<xsl:choose>
<xsl:when test="normalize-string($prefix)!=''">
<xsl:value-of select="$prefix"/>
<xsl:value-of select="$by" disable-output-escaping="yes"/>
</xsl:when>
</xsl:choose>
<xsl:call-template name="replace-text">
<xsl:with-param name="text" select="substring-after($text, $replace)"/>
<xsl:with-param name="replace" select="$replace" />
<xsl:with-param name="by" select="$by" />
</xsl:call-template>
A: Try this (XSLT 2.0):
<xsl:template match="/STORIES/STORY">
<component>
<xsl:if test="boolean(ARTICLEBODY)">
<xsl:call-template name="insert_paras">
<xsl:with-param name="text" select="ARTICLEBODY/text()"/>
</xsl:call-template>
</xsl:if>
</component>
</xsl:template>
<xsl:template name="insert_paras">
<xsl:param name="text" />
<xsl:variable name="regex">
<xsl:text> ( |\s)*</xsl:text>
</xsl:variable>
<xsl:variable name="tokenized-text" select="tokenize($text, $regex)"/>
<xsl:for-each select="$tokenized-text">
<p>
<xsl:value-of select="."/>
</p>
</xsl:for-each>
</xsl:template>
It's generally a bad idea to use literal strings to put in XML markup, since you can't guarantee that the results are balanced.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Is there a reason to use BufferedReader over InputStreamReader when reading all characters? I currently use the following function to do a simple HTTP GET.
public static String download(String url) throws java.io.IOException {
java.io.InputStream s = null;
java.io.InputStreamReader r = null;
//java.io.BufferedReader b = null;
StringBuilder content = new StringBuilder();
try {
s = (java.io.InputStream)new URL(url).getContent();
r = new java.io.InputStreamReader(s);
//b = new java.io.BufferedReader(r);
char[] buffer = new char[4*1024];
int n = 0;
while (n >= 0) {
n = r.read(buffer, 0, buffer.length);
if (n > 0) {
content.append(buffer, 0, n);
}
}
}
finally {
//if (b != null) b.close();
if (r != null) r.close();
if (s != null) s.close();
}
return content.toString();
}
I see no reason to use the BufferedReader since I am just going to download everything in sequence. Am I right in thinking there is no use for the BufferedReader in this case?
A: In this case, I would do as you are doing (use a byte array for buffering and not one of the stream buffers).
There are exceptions, though. One place you see buffers (output this time) is in the servlet API. Data isn't written to the underlying stream until flush() is called, allowing you to buffer output but then dump the buffer if an error occurs and write an error page instead. You might buffer input if you needed to reset the stream for rereading using mark(int) and reset(). For example, maybe you'd inspect the file header before deciding on which content handler to pass the stream to.
Unrelated, but I think you should rewrite your stream handling. This pattern works best to avoid resource leaks:
InputStream stream = new FileInputStream("in");
try { //no operations between open stream and try block
//work
} finally { //do nothing but close this one stream in the finally
stream.close();
}
If you are opening multiple streams, nest try/finally blocks.
Another thing your code is doing is making the assumption that the returned content is encoded in your VM's default character set (though that might be adequate, depending on the use case).
A: You are correct, if you use BufferedReader for reading HTTP content and headers you will want InputStreamReader so you can read byte for byte.
BufferedReader in this scenario sometimes does weird things...escpecially when it comes to reading HTTP POST headers, sometimes you will be unable to read the POST data, if you use the InputStreamReader you can read the content length and read that many bytes...
A: Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. To enable the efficient conversion of bytes to characters, more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation.
A: My gut tells me that since you're already performing buffering by using the byte array, it's redundant to use the BufferedReader.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Java: Programatic Way to Determine Current Windows User I see many similar questions, however I want to find the Username of the currently logged in user using Java.
Its probably something like:
System.getProperty(current.user);
But, I'm not quite sure.
A: The commonly available system properties are documented in the System.getProperties() method.
As Chris said "user.name" is the property to get the user running your app.
A: You're actually really close. This is what you're looking for:
System.getProperty("user.name")
A: As mentioned above (and linked for Java 6), to get the current user:
System.getProperty("user.name")
For Java 7: System.getProperties()
For Java 8: System.getProperties()
For Java 9: System.getProperties()
For Java 10: System.getProperties()
For Java 11: System.getProperties()
For Java 12: System.getProperties()
For Java 13: System.getProperties()
For Java 14: System.getProperties()
For Java 15: System.getProperties()
For Java 16: System.getProperties()
For Java 17: System.getProperties()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Where can I find a good ASP.NET MVC sample? I have been using Castle MonoRail for the last two years, but in a new job I am going to be the one to bring in ASP.NET MVC with me.
I understand the basics of views, actions and the like. I just need a good sample for someone with MVC experience.
Any good links besides Scott's Northwind traders sample?
A: Rob Conery's MVC Storefront project is a good from-the-ground-up step-by-step series on how to put up an ASP.NET MVC site.
A: Check out Billy McCafferty's S#arp Architecture project for a great ASP.NET MVC starter project filled with best practices.
If you want something a little simpler, I threw together a rudimentary version of the S#arp Architecture project, called Blunt Architecturehere.
A: Maybe you're looking for something like Kigg - Building a Digg Clone with ASP.NET MVC.
Or maybe Jeff and the team are willing to provide you the souce code for SO... :P
A: What about the MVC Membership application that Troy Goode wrote. I'm not sure what Preview he wrote it in but it could be worth a look.
Also, if you want to go right from the beginning, scott gu has a great series of posts on MVC
Finally, I haven't personally taken a look at this code, but I noticed the MVCSample app on codeplex and bookmarked it for future reference, but I'm not sure of the quality.
Edit: he has an updated version as well
A: Please take a look at WineCellarManagerOnASPNETMVC. It is a good sample project that is done using ASP.NET MVC and Rhino Tools.
A: CodeCampServer - Built with ASP.NET MVC, pretty light and small project. No cruft at all.
@lomaxx - Just FYI, most of what Troy Goode wrote is now part of ASP.NET MVC as of Preview 4.
A: Check out some of these:
*
*MVCPress/Blog
*CarTrackr
*HaackOverflow by Phil Haack
*Forums by Stephen Walther
A: You should check out TheBeerHouse MVC Edition. Its a full featured website that uses the latest MVC Framework RC1, SQL Server 2008, LINQ to SQL, jQuery, and much more. There is even an Ecommerce piece integrated into it!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Visual Studio 2008 debugging issue I'm working in VS 2008 and have three projects in one solution. I'm debugging by attaching to a .net process invoked by a third party app (SalesLogix, a CRM app).
Once it has attached to the process and I attempt to set a breakpoint in one of the projects, it doesn't set a breakpoint in that file. It actually switches the current tab to another file in another project and sets a breakpoint in that document. If the file isn't open, it even goes so far as to open it for me. I can't explain this. I've got no clue. Anyone seen such odd behavior? I wouldn't believe it if I wasn't seeing it myself.
A little more info: if I set a breakpoint before attaching, it shows the "red dot" and says no symbols loaded...no problem...I expect that. When I attach and invoke my .net code from SalesLogix and switch back to VS, my breakpoint is completely gone (not even a warning that the source doesn't match the debug file). When I attempt to manually load the debug file, then I get a message that the symbol file does not match the module. The .pdb and the .dll are timestamped the same, so I'm stumped.
Anyone have any ideas?
Thx,
Jeff
A: I saw this functionality in older versions of VS.Net (2003 I think). It may still exist in current versions, but I haven't encountered it. Seems that files with the same name, even in different directories confuse VS.Net, and it ends up setting a break point in a file with the same name. May only happen if the classes in the file both have the same name also. So much for namespaces I guess.
You also may want to check your build configuration to make sure that all the projects are in fact building in debug mode. I know I've been caught a couple times when the configuration got changed somehow for the solution, and some projects weren't compiling in debug mode.
A: Kibbee, you were right! It was two files with the same name in different folders. I was setting the breakpoint in the correct file on line 58 - it was putting the breakpoint on the other file at line 58. I was finally able to set a breakpoint by using the "Debug-->New Breakpoint-->Break at Function Name" menu option and entering my function name. It stopped exactly like it should have then.
I agree - so much for namespaces, right? Damn thing cost me a couple of hours. Oh, well...at least it's solved and I know why.
Thx for the answer and thx to Matt for his reply, too!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Proprietary plug-ins for GPL programs: what about interpreted languages? I am developing a GPL-licensed application in Python and need to know if the GPL allows my program to use proprietary plug-ins. This is what the FSF has to say on the issue:
If a program released under the GPL uses plug-ins, what are the requirements for the licenses of a plug-in?
It depends on how the program invokes its plug-ins. If the program uses fork and exec to invoke plug-ins, then the plug-ins are separate programs, so the license for the main program makes no requirements for them.
If the program dynamically links plug-ins, and they make function calls to each other and share data structures, we believe they form a single program, which must be treated as an extension of both the main program and the plug-ins. This means the plug-ins must be released under the GPL or a GPL-compatible free software license, and that the terms of the GPL must be followed when those plug-ins are distributed.
If the program dynamically links plug-ins, but the communication between them is limited to invoking the ‘main’ function of the plug-in with some options and waiting for it to return, that is a borderline case.
The distinction between fork/exec and dynamic linking, besides being kind of artificial, doesn't carry over to interpreted languages: what about a Python/Perl/Ruby plugin, which gets loaded via import or execfile?
(edit: I understand why the distinction between fork/exec and dynamic linking, but it seems like someone who wanted to comply with the GPL but go against the "spirit" --I don't-- could just use fork/exec and interprocess communication to do pretty much anything).
The best solution would be to add an exception to my license to explicitly allow the use of proprietary plugins, but I am unable to do so since I'm using Qt/PyQt which is GPL.
A:
he distinction between fork/exec and dynamic linking, besides being kind of artificial,
I don't think its artificial at all. Basically they are just making the division based upon the level of integration. If the program has "plugins" which are essentially fire and forget with no API level integration, then the resulting work is unlikely to be considered a derived work. Generally speaking a plugin which is merely forked/exec'ed would fit this criteria, though there may be cases where it does not. This case especially applies if the "plugin" code would work independently of your code as well.
If, on the other hand, the code is deeply dependent upon the GPL'ed work, such as extensively calling APIs, or tight data structure integration, then things are more likely to be considered a derived work. Ie, the "plugin" cannot exist on its own without the GPL product, and a product with this plugin installed is essentially a derived work of the GPLed product.
So to make it a little more clear, the same principles could apply to your interpreted code. If the interpreted code relies heavily upon your APIs (or vice-versa) then it would be considered a derived work. If it is just a script that executes on its own with extremely little integration, then it may not.
Does that make more sense?
A: @Daniel The distinction between fork/exec and dynamic linking, besides being kind of artificial, doesn't carry over to interpreted languages: what about a Python/Perl/Ruby plugin, which gets loaded via import or execfile?
I'm not sure that the distinction is artificial. After a dynamic load the plugin code shares an execution context with the GPLed code. After a fork/exec it does not.
In anycase I would guess that importing causes the new code to run in the same execution context as the GPLed bit, and you should treat it like the dynamic link case. No?
A: How much info are you sharing between the Plugins and the main program? If you are doing anything more than just executing them and waiting for the results (sharing no data between the program and the plugin in the process) then you could most likely get away with them being proprietary, otherwise they would probably need to be GPL'd.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Quick way to find a value in HTML (Java) Using regular expressions, what is the simplest way to fetch a websites HTML and find the value inside this tag (or any attribute's value for that matter):
<html>
<head>
[snip]
<meta name="generator" value="thevalue i'm looking for" />
[snip]
A: Its amazing how noone, when addressing the problem of using RegEx with HTML, confronts the problem of HTML often NOT being well-formed, thus rendering a lot of HTML-parsers completely useless.
If you are developing tools to analyze webpages and its a fact that these are not well-formed HTML, the statement "Regex should never be used to parse HTML" og "use a HTML parser" is just completely bogus. Facts are that in the real world, people create HTML as they feel like - and not necessarily suited for parsers.
RegEx is a completely valid way to find elements in text, thus in HTML. If there are any other reasonable way to confront the problems the Original Poster has, then post them instead of referring to a "use a parser" or "RTFM" statement.
A: Depends on how sophisticated of an Http request you need to build (authentication, etc). Here's one simple way I've seen used in the past.
StringBuilder html = new StringBuilder();
java.net.URL url = new URL("http://www.google.com/");
BufferedReader input = null;
try {
input new BufferedReader(
new InputStreamReader(url.openStream()));
String htmlLine;
while ((htmlLine=input.readLine())!=null) {
html.appendLine(htmlLine);
}
}
finally {
input.close();
}
Pattern exp = Pattern.compile(
"<meta name=\"generator\" value=\"([^\"]*)\" />");
Matcher matcher = exp.matcher(html.toString());
if(matcher.find())
{
System.out.println("Generator: "+matcher.group(1));
}
Probably plenty of typos here to be found when compiled.
(hope this wasn't homework)
A: You should be using XPath query.
It's as simple as getting value of /html/head/meta[@name=generator]/@value.
A good tutorial: Parsing an XML Document with XPath
A: You may want to check the documentation for Apache's org.apache.commons.HttpClient package and the related packages here. Sending an HTTP request from a Java application is pretty easy to do. Poking through the documentation should get you off in the right direction.
A: I haven't tried this, but wouldn't the basic framework be
*
*Open a java.net.HttpURLConnection
*Get an input stream using getInputStream
*Use the regular expression in Mike's answer to parse out the bit you want
A: Strictly speaking you can't really be sure you got the right value, since the meta tag may be commented out, or the meta tag may be in uppercase etc. It depends on how certain you are that the HTML can be considered as "nice".
A: It depends.
If you are extracting information from a site or sites that are guaranteed to be well-formed HTML, and you know that the <meta> won't be obfuscated in some way then a reading the <head> section line by line and applying a regex is a good approach.
On the other hand, if the HTML may be mangled or "tricky" then you need to use a proper HTML parser, possibly a permissive one like HTMLTidy. Beware of using a strict HTML or XML parser on stuff trawled from random websites. Lots of so-called HTML you find out there is actually malformed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NHIbernate: Difference between Restriction.In and Restriction.InG When creating a criteria in NHibernate I can use
Restriction.In() or
Restriction.InG()
What is the difference between them?
A: InG is the generic equivalent of In (for collections)
The signatures of the methods are as follows (only the ICollection In overload is shown):
In(string propertyName, ICollection values)
vs.
InG<T>(string propertyName, ICollection<T> values)
Looking at NHibernate's source code (trunk) it seems that they both copy the collection to an object array and use that going forward, so I don't think there is a performance difference between them.
I personally just use the In one most of the time - its easier to read.
A: Restriction.In definately creates a subquery with whatever criteria you pass to the .In() method, but not sure what InG() does. never seen it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Detach an entity from JPA/EJB3 persistence context What would be the easiest way to detach a specific JPA Entity Bean that was acquired through an EntityManager. Alternatively, could I have a query return detached objects in the first place so they would essentially act as 'read only'?
The reason why I want to do this is becuase I want to modify the data within the bean - with in my application only, but not ever have it persisted to the database. In my program, I eventually have to call flush() on the EntityManager, which would persist all changes from attached entities to the underyling database, but I want to exclude specific objects.
A: (may be too late to answer, but can be useful for others)
I'm developing my first system with JPA right now. Unfortunately I'm faced with this problem when this system is almost complete.
Simply put. Use Hibernate, or wait for JPA 2.0.
In Hibernate, you can use 'session.evict(object)' to remove one object from session. In JPA 2.0, in draft right now, there is the 'EntityManager.detach(object)' method to detach one object from persistence context.
A: As far as I know, the only direct ways to do it are:
*
*Commit the txn - Probably not a reasonable option
*Clear the Persistence Context - EntityManager.clear() - This is brutal, but would clear it out
*Copy the object - Most of the time your JPA objects are serializable, so this should be easy (if not particularly efficient).
A: If using EclipseLink you also have the options,
Use the Query hint, eclipselink.maintain-cache"="false - all returned objects will be detached.
Use the EclipseLink JpaEntityManager copy() API to copy the object to the desired depth.
A: No matter which JPA implementation you use, Just use entityManager.detach(object) it's now in JPA 2.0 and part of JEE6.
A: If you need to detach an object from the EntityManager and you are using Hibernate as your underlying ORM layer you can get access to the Hibernate Session object and use the Session.evict(Object) method that Mauricio Kanada mentioned above.
public void detach(Object entity) {
org.hibernate.Session session = (Session) entityManager.getDelegate();
session.evict(entity);
}
Of course this would break if you switched to another ORM provider but I think this is preferably to trying to make a deep copy.
A: Unfortunately, there's no way to disconnect one object from the entity manager in the current JPA implementation, AFAIR.
EntityManager.clear() will disconnect all the JPA objects, so that might not be an appropriate solution in all the cases, if you have other objects you do plan to keep connected.
So your best bet would be to clone the objects and pass the clones to the code that changes the objects. Since primitive and immutable object fields are taken care of by the default cloning mechanism in a proper way, you won't have to write a lot of plumbing code (apart from deep cloning any aggregated structures you might have).
A: If there aren't too many properties in the bean, you might just create a new instance and set all of its properties manually from the persisted bean.
This could be implemented as a copy constructor, for example:
public Thing(Thing oldBean) {
this.setPropertyOne(oldBean.getPropertyOne());
// and so on
}
Then:
Thing newBean = new Thing(oldBean);
A: this is quick and dirty, but you can also serialize and deserialize the object.
A: Since I am using SEAM and JPA 1.0 and my system has a fuctinality that needs to log all fields changes, i have created an value object or data transfer object if same fields of the entity that needs to be logged. The constructor of the new pojo is:
public DocumentoAntigoDTO(Documento documentoAtual) {
Method[] metodosDocumento = Documento.class.getMethods();
for(Method metodo:metodosDocumento){
if(metodo.getName().contains("get")){
try {
Object resultadoInvoke = metodo.invoke(documentoAtual,null);
Method[] metodosDocumentoAntigo = DocumentoAntigoDTO.class.getMethods();
for(Method metodoAntigo : metodosDocumentoAntigo){
String metodSetName = "set" + metodo.getName().substring(3);
if(metodoAntigo.getName().equals(metodSetName)){
metodoAntigo.invoke(this, resultadoInvoke);
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
A: In JPA 1.0 (tested using EclipseLink) you could retrieve the entity outside of a transaction. For example, with container managed transactions you could do:
public MyEntity myMethod(long id) {
final MyEntity myEntity = retrieve(id);
// myEntity is detached here
}
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public MyEntity retrieve(long id) {
return entityManager.find(MyEntity.class, id);
}
A: Do deal with a similar case I have created a DTO object that extends the persistent entity object as follows:
class MyEntity
{
public static class MyEntityDO extends MyEntity {}
}
Finally, an scalar query will retrieve the desired non managed attributes:
(Hibernate) select p.id, p.name from MyEntity P
(JPA) select new MyEntity(p.id, p.name) from myEntity P
A: If you get here because you actually want to pass an entity across a remote boundary then you just put some code in to fool the hibernazi.
for(RssItem i : result.getChannel().getItem()){
}
Cloneable wont work because it actually copies the PersistantBag across.
And forget about using serializable and bytearray streams and piped streams. creating threads to avoid deadlocks kills the entire concept.
A: I think there is a way to evict a single entity from EntityManager by calling this
EntityManagerFactory emf;
emf.getCache().evict(Entity);
This will remove particular entity from cache.
A: Im using entityManager.detach(returnObject);
which worked for me.
A: I think you can also use method EntityManager.refresh(Object o) if primary key of the entity has not been changed. This method will restore original state of the entity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "60"
} |
Q: How to fetch HTML in Java Without the use of any external library, what is the simplest way to fetch a website's HTML content into a String?
A: I'm currently using this:
String content = null;
URLConnection connection = null;
try {
connection = new URL("http://www.google.com").openConnection();
Scanner scanner = new Scanner(connection.getInputStream());
scanner.useDelimiter("\\Z");
content = scanner.next();
scanner.close();
}catch ( Exception ex ) {
ex.printStackTrace();
}
System.out.println(content);
But not sure if there's a better way.
A: This has worked well for me:
URL url = new URL(theURL);
InputStream is = url.openStream();
int ptr = 0;
StringBuffer buffer = new StringBuffer();
while ((ptr = is.read()) != -1) {
buffer.append((char)ptr);
}
Not sure at to whether the other solution(s) provided are any more efficient or not.
A: I just left this post in your other thread, though what you have above might work as well. I don't think either would be any easier than the other. The Apache packages can be accessed by just using import org.apache.commons.HttpClient at the top of your code.
Edit: Forgot the link ;)
A: Whilst not vanilla-Java, I'll offer up a simpler solution. Use Groovy ;-)
String siteContent = new URL("http://www.google.com").text
A: Its not library but a tool named curl generally installed in most of the servers or you can easily install in ubuntu by
sudo apt install curl
Then fetch any html page and store it to your local file like an example
curl https://www.facebook.com/ > fb.html
You will get the home page html.You can run it in your browser as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: Stackoverflow Style Notifications in asp.net Ajax When you get a badge or aren't logged in to stack overflow there's a groovy little notification bar at the top of the page that lets you know there's something going on.
I know the SOflow team use JQuery, but I was wondering if anyone knew of an implementation of the same style of notification system in asp.net AJAX.
On a side note, what's the "official" name for this style of notification bar?
A: I like it to.
div tag with a fade.
http://www.asp.net/AJAX/AjaxControlToolkit/Samples/Walkthrough/UsingAnimations.aspx
A: In this post ( http://www.pieterg.com/post/2010/05/24/ASPNET-and-Stackoverflow-Type-Notification-Bar.aspx ) Pieter Germishuys explains how to implement the functionality using Dmitri's Smirnov plugin ( http://www.dmitri.me/blog/notify-bar/ )
Really easy !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Does Amazon S3 download fail sometimes? We just added an autoupdater in our software and got some bug report saying
that the autoupdate wouldn't complete properly because the downloaded file's sha1 checksum wasn't matching. We're hosted on Amazon S3...
That's either something wrong with my code or something wrong with S3.
I reread my code for suspicious stuff and wrote a simple script downloading and checking the checksum of the downloaded file, and indeed got a few errors once in while (1 out of 40 yesterday). Today it seems okay.
Did you experience that kind of problem? Is there some kind of workaround ?
extra info: test were ran in Japan.
A: Other than the downtime a few weeks ago. None that I heard of.
They did a good job considering the one time it was down was because of an obscure server error that cascaded throughout the cloud. They was very open about it and resolve it as soon as they found out.(it happened during a weekend, iirc)
So they are pretty reliable. My advice is double check your code. And bring it up to amazon support if it is still a problem.
A: ok, this is all a bit old now, but for reference. I've just been running data migration of several gigs of data from an EC2 server directly into s3. I'm getting 500 errors about every 10 minutes or so, representing an error rate of about 1% of PUTs. So, yes, S3 does have a problem with 500 errors.
Haven't done much in the way of GET's though, so cant comment
A: Amazon's S3 will occasionally fail with errors during uploads or downloads -- generally "500: Internal Server" errors. The error rate is normally pretty low, but it can spike if the service is under heavy load. The error rate is never 0%, so even at the best of times the occasional request will fail.
Are you checking the HTTP response code in your autoupdater? If not, you should check that your download succeeded (HTTP 200) before you perform a checksum. Ideally, your app should retry failed downloads, because transient errors are an unavoidable "feature" of S3 that clients need to deal with.
It is worth noting that if your clients are getting 500 errors, you will probably not see any evidence of these in the S3 server logs. These errors seem to occur before the request reaches the service's logging component.
A: I agree, quad-checking your code would be a good idea. I'm not saying that it can't happen, but I don't believe that I have ever seen it, and I've used S3 a pretty good bit now. I have, however, mismanaged exceptions/connection breaks a few times and ended up with pieces that didn't match what I was expecting.
I would be pretty surprised if they actually send bad data, but, as always, anything is possible.
A: Never heard of a problem during download. That's weird. I get TONS of 500 Internal Server Error messages when uploading. That's why I have a daemon that uploads while the user is doing something else.
It doesn't seem to be something in your code, maybe there is really something wrong with S3 (or with S3->Japan.)
You can try firing up an EC2 server, and just run the test from there (traffic won't cost any money, so use as much as you want!) and see if you get errors. If you do, then you're out of luck and S3 isn't for you :)
Good luck!
A: More than sending bad data, I think I got an ERROR403. If I just try again it's usually ok.
And I agree : I saw a lot of report about people talking about amazon being totally down, but nobody talking about a "sometimes my access is refused" error, so I guess there might be an error on my side. I just set up the log on amazon.
Anyway thank you! I'll follow your advise and stop blaming "the other guy".
A: I occasionally get unexpected 404 errors with GETs objects that are part of a preceeding LIST but new to the bucket, and other misc. errors (eg: 403 on my access id and secret key), but nothing catastrophic.
My code runs server side, so I've put in some robust error handling and logging. I think this is a wise thing to do anytime you have one server on the net communicating with another server. :P
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How stable is WPF? How stable is WPF not in terms of stability of a WPF program, but in terms of the 'stability' of the API itself.
Let me explain:
Microsoft is notorious for changing its whole methodology around with new technology. Like with the move from silverlight 1 to silverlight 2. With WPF, I know that MS changed a bunch of stuff with the release of the .NET service pack. I don't know how much they changed things around. So the bottom line is, in your opinion are they going to revamp the system again with the next release or do you think that it is stable enough now that they won't change the bulk of the system. I hate to have to unlearn stuff with every release.
I hope that the question wasn't too long winded.
A: We've been using WPF since it was first released and yes it had it's problems at the beginning that caused us headaches and had us scratching our heads to find a work around, but each new update the stack has actually become pretty stable.
It definitely became easier and easier to develop with it with the addition of Expression Blend. Creating the XAML in VS 2005 was not fun. The templating engine alone is enough to switch from WinForms, let alone the animation support.
Either way, I agree with Matt that it is pretty stable as a framework for developing client applications.
A: MS do have a history of "fire and movement" with regards to introducing new technology into their development stack, but they also have a strong history of maintaining support for the older stuff, and backwards-compatibility. WPF seems to be getting stuff added to it with each new release of the framework but the things you learn aren't being superceded or invalidated.
The only breaking change I've seen in my own WPF applications with a new release of the framework was one recently in 3.5 SP1, and that was because we were unknowingly relying on a bug to get a certain behaviour from our code. We adjusted the XAML to be more correct and it started working fine.
So yeah, I think WPF is pretty "stable" as a client-side development technology.
A: WPF is pretty stable as far as changes go. Silverlight is still in flux. Though you may watch out since silverlight brought the concept of the state manager(instead of implementing triggers) which may get adopted in wpf...
If that happens there will be multiple ways to defining control templates and behavior...
and that will be a headache.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to detect duplicate data? I have got a simple contacts database but I'm having problems with users entering in duplicate data. I have implemented a simple data comparison but unfortunately the duplicated data that is being entered is not exactly the same. For example, names are incorrectly spelled or one person will put in 'Bill Smith' and another will put in 'William Smith' for the same person.
So is there some sort of algorithm that can give a percentage for how similar an entry is to another?
A:
So is there some sort of algorithm
that can give a percentage for how
similar an entry is to another?
Algorithms as Soundex and Edit distances (as suggested in a previous post) can solve some of your problems. However, if you are serious about cleaning your data, this will not be enough. As others have stated "Bill" does not sound anything like "William".
The best solution I have found is to use a reduction algorithm and table to reduce the names to it's root name.
To your regular Address table, add Root-versions of the names, e.g
Person (Firstname, RootFirstName, Surname, Rootsurname....)
Now, create a mapping table.
FirstNameMappings (Primary KEY Firstname, Rootname)
Populate your Mapping table by:
Insert IGNORE (select Firstname, "UNDEFINED" from Person) into FirstNameMappings
This will add all firstnames that you have in your person table together with the RootName of "UNDEFINED"
Now, sadly, you will have to go through all the unique first names and map them to a RootName. For example "Bill", "Billl" and "Will" should all be translated to "William"
This is very time consuming, but if data quality really is important for you I think it's one of the best ways.
Now use the newly created mapping table to update the "Rootfirstname" field in your Person table. Repeat for surname and address. Once this is done you should be able to detect duplicates without suffering from spelling errors.
A: You can compare the names with the Levenshtein distance. If the names are the same, the distance is 0, else it is given by the minimum number of operations needed to transform one string into the other.
A: I imagine that this problem is well understood but what occurs to me on first reading is:
*
*compare fields individually
*count those that match (for a possibly loose definition of match, and possibly weighing the fields differently)
*present for human intervention any cases which pass some threshold
Use your existing database to get a good first guess for the threshold, and correct as you accumulate experience.
You may prefer a fairly strong bias toward false positives, at least at first.
A: While I do not have an algorithm for you, my first action would be to take a look at the process involved in entering a new contact. Perhaps users do not have an easy way to find the contact they are looking for. Much like on Stack Overflow's new question form, you could suggest contacts that already exist on the new contact screen.
A: If you have access SSIS check out the Fuzzy grouping and Fuzzy lookup transformation.
http://www.sqlteam.com/article/using-fuzzy-lookup-transformations-in-sql-server-integration-services
http://msdn.microsoft.com/en-us/library/ms137786.aspx
A: If you have a large database with string fields, you can very quickly find a lot of duplicates by using the simhash algorithm.
A: This may or may not be related but, minor misspellings might be detected by a Soundex search, e.g., this will allow you to consider Britney Spears, Britanny Spares, and Britny Spears as duplicates.
Nickname contractions, however, are difficult to consider as duplicates and I doubt if it is wise. There are bound to be multiple people named Bill Smith and William Smith, and you would have to iterate that with Charles->Chuck, Robert->Bob, etc.
Also, if you are considering, say, Muslim users, the problems become more difficult (there are too many Muslims, for example, that are named Mohammed/Mohammad).
A: I'm not sure it will work well for the names vs nicknames problem, but the most common algorithm in this sort of area would be the edit distance / Levenshtein distance algorithm. It's basically a count of the number of character changes, additions and removals required to turn one item into another.
For names, I'm not sure you're ever going to get good results with a purely algorithmic approach - What you really need is masses of data. Take, for example, how much better Google spelling suggestions are than those in a normal desktop application. This is because Google can process billions of web queries and look at what queries lead to each other, what 'did you mean' links actually get clicked etc.
There are a few companies which specialise in the name matching problem (mostly for national security and fraud applications). The one I could remember, Search Software America seems to have been bought out by these guys http://www.informatica.com/products_services/identity_resolution/Pages/index.aspx, but I suspect any of these sorts of solutions would be far to expensive for a contacts application.
A: FullContact.com has API's that can solve this for you, see their documentation here: http://www.fullcontact.com/developer/docs/?category=name.
They have APIs for Name Normalization (Bill into William), Name Deducer (for raw text), and Name Similarity (comparing two names).
All APIs are free at the moment, it could be a good way to get started.
A: You might also want to look into probabilistic matching.
A: For those wandering around the web and end up here, might I suggest that you try using a Google Sheet add-on I created called Flookup.
It's particularly good with names and it has a couple of other awesome features which I'll describe below:
*
*Say you have a list of names and there are 2 people called "John Smith". You can use the rank parameter from Flookup to instruct the algorithm to return the 1st, 2nd, 3rd or nth best match. This is helpful if you have additional information that you can use to identify the "John Smith" you want.
*Say you have an additional database/list of apartment numbers. You an specify which "John Smith" you want by typing: John Smith & Apartment A or John Smith & Apartment B as the lookup parameter to help distinguish between the two names.
I hope you find Flookup as beneficial as others have.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: How do I check the active solution configuration Visual Studio built with at runtime? I would like to enable/disable some code based on a custom solution configuration I added in Visual Studio. How do I check this value at runtime?
A: You can use precompiler directives within Visual Studio. The #if directive will allow you to determine if you are going to include code or not based on your custom solution configuration.
A: add a const value assign to a value that designate the configuration you are in.
like
#ifdef _ENABLE_CODE1_
const codeconfig = 1;
#else
const codeconfig = 2;
#endif
and add _ENABLE_CODE1_ in your configuration preprocessor.
A: In each project's properties under the build section you can set different custom constants for each solution configuration. This is where you define custom pre-compiler directives.
A: I'm not sure if you can figure out the exact name of the build configuration. Howerver, if you use Debug.Assert(...), that code will only be run when you compile in debug mode. Not sure it that helps you at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Where do I use delegates? What are some real world places that call for delegates? I'm curious what situations or patterns are present where this method is the best solution. No code required.
A: I had the same question as you and went to this site for an answer.
Apparently, I didn't understood it better even though I skimmed through the examples on this thread.
I found a great use for delegates now that I read: http://www.c-sharpcorner.com/UploadFile/thiagu304/passdata05172006234318PM/passdata.aspx
This might seem more obvious for new users because Forms is much more complicated to pass values than ASP.NET websites with POST/GET (QueryString) ..
Basically you define a delegate which takes "TextBox text" as parameters.
// Form1
// Class Property Definition
public delegate void delPassData(TextBox text);
// Click Handler
private void btnSend_Click(object sender, System.EventArgs e)
{
Form2 frm= new Form2();
delPassData del=new delPassData(frm.funData);
del(this.textBox1);
frm.Show();
}
// SUMMARY: Define delegate, instantiate new Form2 class, assign funData() function to delegate, pass in your textBox to the delegate. Show the form.
// Form2
public void passData(TextBox txtForm1)
{
label1.Text = txtForm1.Text;
}
// SUMMARY: Simply take TextBox txtForm1 as parameters (as defined in your delegate) and assign label text to textBox's text.
I hope this enlightens some use on delegates :) ..
A: If you're interested in seeing how the Delegate pattern is used in real-world code, look no further than Cocoa on Mac OS X. Cocoa is Apple's preferred UI toolkit for programming under Mac OS X, and is coded in Objective C. It's designed so that each UI component is intended to be extended via delegation rather than subclassing or other means.
For more information, I recommend checking out what Apple has to say about delegates here.
A: I had a project which used win32 Python.
Due to various reasons, some modules used odbc.py to access the DB, and other modules - pyodbc.py.
There was a problem when a function needed to be used by both kinds of modules. It had an connection object passed to it as an argument, but then it had to know whether to use dbi.dbiDate or datetime to represent times.
This was because odbc.py expected, as values in SQL statements, dates as dbi.dbiDate whereas pyodbc.py expected datetime values.
One further complication was that the connection objects created by odbc.py and pyodbc.py did not allow one to set additional fields.
My solution was to wrap the connection objects returned by odbc.odbc(...) and pyodbc.pyodbc(...) by a delegate class, which contains the desired time representation function as the value of an extra field, and which delegates all other field requests to the original connection object.
A:
A delegate is a named type that defines a particular kind of method. Just as a class definition lays out all the members for the given kind of object it defines, the delegate lays out the method signature for the kind of method it defines.
Based on this statement, a delegate is a function pointer and it defines what that function looks like.
A great example for a real world application of a delegate is the Predicate. In the example from the link, you will notice that Array.Find takes the array to search and then a predicate to handle the criteria of what to find. In this case it passes a method ProductGT10 which matches the Predicate signature.
A: One common use of delegates for generic Lists are via Action delegates (or its anonymous equivalent) to create a one-line foreach operation:
myList.Foreach( i => i.DoSomething());
I also find the Predicate delegate quite useful in searching or pruning a List:
myList.FindAll( i => i.Name == "Bob");
myList.RemoveAll( i => i.Name == "Bob");
I know you said no code required, but I find it easier to express its usefulness via code. :)
A: As stated in "Learning C# 3.0: Master the fundamentals of C# 3.0"
General Scenario: When a head of state dies, the President of the United States typically does not have time to attend the funeral
personally. Instead, he dispatches a delegate. Often this delegate is
the Vice President, but sometimes the VP is unavailable and the
President must send someone else, such as the Secretary of State or
even the First Lady. He does not want to “hardwire” his delegated
authority to a single person; he might delegate this responsibility to
anyone who is able to execute the correct international protocol.
The President defines in advance what responsibility will be delegated
(attend the funeral), what parameters will be passed (condolences,
kind words), and what value he hopes to get back (good will). He then
assigns a particular person to that delegated responsibility at
“runtime” as the course of his presidency progresses.
In programming Scenario: You are often faced with situations where you need to execute a particular action, but you don’t know in
advance which method, or even which object, you’ll want to call upon
to execute it.
For Example: A button might not know which object or objects need to be notified. Rather than wiring the button to a particular
object, you will connect the button to a delegate and then resolve
that delegate to a particular method when the program executes.
A: Binding Events to Event Handlers is usually your first introduction to delegates...You might not even know you were using them because the delegate is wrapped up in the EventHandler class.
A: A quick google search came up with this http://en.wikipedia.org/wiki/Delegation_pattern . Basically, anytime that you use an object that forwards it's calls to another object then you are delegating.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "111"
} |
Q: Best way to test if a generic type is a string? (C#) I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using default(T). When you call default on a value type or a string, it initializes it to a reasonable value (such as empty string). When you call default(T) on an object, it returns null. For various reasons we need to ensure that if it is not a primitive type, then we will have a default instance of the type, not null. Here is attempt 1:
T createDefault()
{
if(typeof(T).IsValueType)
{
return default(T);
}
else
{
return Activator.CreateInstance<T>();
}
}
Problem - string is not a value type, but it does not have a parameterless constructor. So, the current solution is:
T createDefault()
{
if(typeof(T).IsValueType || typeof(T).FullName == "System.String")
{
return default(T);
}
else
{
return Activator.CreateInstance<T>();
}
}
But this feels like a kludge. Is there a nicer way to handle the string case?
A: You can use the TypeCode enumeration. Call the GetTypeCode method on classes that implement the IConvertible interface to obtain the type code for an instance of that class. IConvertible is implemented by Boolean, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, DateTime, Char, and String, so you can check for primitive types using this. More info on "Generic Type Checking".
A: Personally, I like method overloading:
public static class Extensions {
public static String Blank(this String me) {
return String.Empty;
}
public static T Blank<T>(this T me) {
var tot = typeof(T);
return tot.IsValueType
? default(T)
: (T)Activator.CreateInstance(tot)
;
}
}
class Program {
static void Main(string[] args) {
Object o = null;
String s = null;
int i = 6;
Console.WriteLine(o.Blank()); //"System.Object"
Console.WriteLine(s.Blank()); //""
Console.WriteLine(i.Blank()); //"0"
Console.ReadKey();
}
}
A: Keep in mind that default(string) is null, not string.Empty. You may want a special case in your code:
if (typeof(T) == typeof(String)) return (T)(object)String.Empty;
A: if (typeof(T).IsValueType || typeof(T) == typeof(String))
{
return default(T);
}
else
{
return Activator.CreateInstance<T>();
}
Untested, but the first thing that came to mind.
A: The discussion for String is not working here.
I had to have following code for generics to make it work -
private T createDefault()
{
{
if(typeof(T).IsValueType)
{
return default(T);
}
else if (typeof(T).Name == "String")
{
return (T)Convert.ChangeType(String.Empty,typeof(T));
}
else
{
return Activator.CreateInstance<T>();
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "109"
} |
Q: Do indexes work with "IN" clause If I have a query like:
Select EmployeeId
From Employee
Where EmployeeTypeId IN (1,2,3)
and I have an index on the EmployeeTypeId field, does SQL server still use that index?
A: Usually it would, unless the IN clause covers too much of the table, and then it will do a table scan. Best way to find out in your specific case would be to run it in the query analyzer, and check out the execution plan.
A: Unless technology has improved in ways I can't imagine of late, the "IN" query shown will produce a result that's effectively the OR-ing of three result sets, one for each of the values in the "IN" list. The IN clause becomes an equality condition for each of the list and will use an index if appropriate. In the case of unique IDs and a large enough table then I'd expect the optimiser to use an index.
If the items in the list were to be non-unique however, and I guess in the example that a "TypeId" is a foreign key, then I'm more interested in the distribution. I'm wondering if the optimiser will check the stats for each value in the list? Say it checks the first value and finds it's in 20% of the rows (of a large enough table to matter). It'll probably table scan. But will the same query plan be used for the other two, even if they're unique?
It's probably moot - something like an Employee table is likely to be small enough that it will stay cached in memory and you probably wouldn't notice a difference between that and indexed retrieval anyway.
And lastly, while I'm preaching, beware the query in the IN clause: it's often a quick way to get something working and (for me at least) can be a good way to express the requirement, but it's almost always better restated as a join. Your optimiser may be smart enough to spot this, but then again it may not. If you don't currently performance-check against production data volumes, do so - in these days of cost-based optimisation you can't be certain of the query plan until you have a full load and representative statistics. If you can't, then be prepared for surprises in production...
A: Yeah, that's right. If your Employee table has 10,000 records, and only 5 records have EmployeeTypeId in (1,2,3), then it will most likely use the index to fetch the records. However, if it finds that 9,000 records have the EmployeeTypeId in (1,2,3), then it would most likely just do a table scan to get the corresponding EmployeeIds, as it's faster just to run through the whole table than to go to each branch of the index tree and look at the records individually.
SQL Server does a lot of stuff to try and optimize how the queries run. However, sometimes it doesn't get the right answer. If you know that SQL Server isn't using the index, by looking at the execution plan in query analyzer, you can tell the query engine to use a specific index with the following change to your query.
SELECT EmployeeId FROM Employee WITH (Index(Index_EmployeeTypeId )) WHERE EmployeeTypeId IN (1,2,3)
Assuming the index you have on the EmployeeTypeId field is named Index_EmployeeTypeId.
A:
So there's the potential for an "IN" clause to run a table scan, but the optimizer will
try and work out the best way to deal with it?
Whether an index is used doesn't so much vary on the type of query as much of the type and distribution of data in the table(s), how up-to-date your table statistics are, and the actual datatype of the column.
The other posters are correct that an index will be used over a table scan if:
*
*The query won't access more than a certain percent of the rows indexed (say ~10% but should vary between DBMS's).
*Alternatively, if there are a lot of rows, but relatively few unique values in the column, it also may be faster to do a table scan.
The other variable that might not be that obvious is making sure that the datatypes of the values being compared are the same. In PostgreSQL, I don't think that indexes will be used if you're filtering on a float but your column is made up of ints. There are also some operators that don't support index use (again, in PostgreSQL, the ILIKE operator is like this).
As noted though, always check the query analyser when in doubt and your DBMS's documentation is your friend.
A: @Mike: Thanks for the detailed analysis. There are definately some interesting points you make there. The example I posted is somewhat trivial but the basis of the question came from using NHibernate.
With NHibernate, you can write a clause like this:
int[] employeeIds = new int[]{1, 5, 23463, 32523};
NHibernateSession.CreateCriteria(typeof(Employee))
.Add(Restrictions.InG("EmployeeId",employeeIds))
NHibernate then generates a query which looks like
select * from employee where employeeid in (1, 5, 23463, 32523)
So as you and others have pointed out, it looks like there are going to be times where an index will be used or a table scan will happen, but you can't really determine that until runtime.
A: Select EmployeeId From Employee USE(INDEX(EmployeeTypeId))
This query will search using the index you have created. It works for me. Please do a try..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "62"
} |
Q: Best way to fetch a varying HTML tag I'm trying to fetch some HTML from various blogs and have noticed that different providers use the same tag in different ways.
For example, here are two major providers that use the meta name generator tag differently:
*
*Blogger: <meta content='blogger' name='generator'/> (content first, name later and, yes, single quotes!)
*WordPress: <meta name="generator" content="WordPress.com" /> (name first, content later)
Is there a way to extract the value of content for all cases (single/double quotes, first/last in the row)?
P.S. Although I'm using Java, the answer would probably help more people if it where for regular expressions generally.
A: Actually, you should probably use some sort of HTML parser where you can inspect each node (and therefore node attributes) in the DOM of the page. I've not used any of these for a while so I don't know the pros and cons but here's a list http://java-source.net/open-source/html-parsers
A: Those differences are not really important according to the XHTML standard.
In other words, they are exactly the same thing.
Also, if you replace double quotes with single quotes would be the same.
The typical way of 'normalizing' an xml document is to pare it using some API that treats the document as its Infoset representation. Both DOM and SAX style APIs work that way.
If you want to parse them by hand (or with a RegEx) you have to replicate all those things in your code and, in my opinion, that's not practical.
A: Note: single quotes (even no quotes, if the value doesn't contain a space) is valid according to the W3C HTML spec. Quote:
By default, SGML requires that all attribute values be delimited using either double quotation marks (ASCII decimal 34) or single quotation marks (ASCII decimal 39)... In certain cases, authors may specify the value of an attribute without any quotation marks.
Also, don't forget that the order of attributes can be reversed and that other attributes can appear in the tag.
A: The answer is: don't use regular expressions.
Seriously. Use a SGML parser, or an XML parser if you happen to know it's valid XML (probably almost never true). You will absolutely screw up and waste tons of time trying to get it right. Just use what's already available.
A: You may want to give Java's HTMLEditorKit a shot. It is easy to experiment with to see if the parsing provides what you are looking for.
A: Ok, since you are looking for language-agnostic then you can try a REGEX like /<meta\s.*content=.*>/ and take the result from that and parse out the specific values that you are looking for. I'm by no means a REGEX expert so there is probably a better way but in using the tool at http://www.codehouse.com/webmaster_tools/regex/ I matched both of the strings you provided.
A: If you must use regex, here is a regex to get just the content part:
content\s*=\s*['"].*?['"]
returns
content = "blogger"
and
content='Worpress.com'
respectively. I'm no regex expert, but it gets those when given your examples in regexpal.
Once you get that you can get everything between the quotes however you choose, be it another regex (which is just immoral at that point) or just looping over the characters.
A: If your using java you may want to look at tagsoup, which is a SAX-compliant parser for "[parsing] HTML as it is found in the wild".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Good way to use table alias in Update statement? Using SqlServer, and trying to update rows from within the same table. I want to use a table alias for readability.
This is the way I am doing it at the moment:
UPDATE ra
SET ra.ItemValue = rb.ItemValue
FROM dbo.Rates ra, dbo.Rates rb
WHERE ra.ResourceID = rb.ResourceID
AND ra.PriceSched = 't8'
AND rb.PriceSched = 't9'
Are there easier / better ways?
A: UPDATE ra
SET ra.ItemValue = rb.ItemValue
FROM dbo.Rates ra
INNER JOIN dbo.Rates rb
ON ra.ResourceID = rb.ResourceID
WHERE ra.PriceSched = 't8'
AND rb.PriceSched = 't9';
This might help in improving performance.
A: Table alias in Update Query in T-SQL( Microsoft SQL) .
for MS SQL Server 2008 R2 it's work just fine
UPDATE A_GeneralLedger set ScheduleId=g.ScheduleId
from A_GeneralLedger l inner join A_AcGroup g on g.ACGroupID=l.AccountGroupID
A: Use the following code :
UPDATE ra
SET ra.ItemValue = rb.ItemValue
FROM dbo.Rates ra, dbo.Rates rb
WHERE ra.ResourceID = rb.ResourceID
AND ra.PriceSched = 't8'
AND rb.PriceSched = 't9'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "96"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.