text stringlengths 8 267k | meta dict |
|---|---|
Q: WinForms: color DataGridView border How can I change the color of a DataGridView border when BorderStyle = FixedSingle?
A: this.dataGridView1.GridColor = Color.BlueViolet;
source: http://msdn.microsoft.com/en-us/library/ehz9ksfa.aspx
A: You could change the border if you make your own DataGridView and override the OnPaint() method. Be sure to call base.OnPaint(e) before you do your own magic.
Also, you could add a property "GridBorderColor" which set color, your own painting would use.
A: You cannot change the border color, it is system defined.
Instead you could try turning off the border setting and then placing the DataGridView inside a Panel. Where the DataGridView is set to Dock.Fill and the Panel has a Padding of 1 pixel on all edges. Then setting the background color of the Panel will show as a border around the contained DataGridView.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Linking an external .jar from an Xcode java project? How do I link an external .jar into my Xcode java project? That is, have it in the classpath during compilation and execution. I'm using Xcode 3.0 and this seems to have changed since 2.4.
A: In Xcode 3.1.2
Checking in file build.xml we see:
<!-- lib directory should contain any pre-built jar files needed to build the project
AppleJavaExtensions.jar is included to allow the built jars to run cross-platform if you depend on Apple eAWT or eIO classes.
See http://developer.apple.com/samplecode/AppleJavaExtensions/index.html for more information -->
<fileset id="lib.jars" dir="${lib}">
<include name="**/*.jar"/>
</fileset>
okay so, copy the external jar by hand into projectName/lib and compile. (Maybe clean first)
Edit: I had to copy the jar by hand, Xcode would not put it in the right place
A: Xcode 3.1 (I'm not certain about 3.0) uses an ant buildfile in its Java project templates. There's a ton of documentation out there on Ant. To change the classpath used when actually running the compiled code, edit the executable and add in an argument -classpath path/to/lib
A: I don't have a Mac to hand, but what if you drop the jar file into your ~/Library/Java/extensions (IIRC) folder?
Edit: I presume that you are using Mac OS X specific Java libraries, hence your use of Xcode? Otherwise I would recommend Eclipse. Actually I'd be willing to bet that Eclipse can use the Mac OS X specific Java APIs as well...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I insert HTML-Formatted Strings into a Microsoft Word Document using Visual Basic while preserving formatting? I use Visual Basic and an automation interface to retrieve strings from an external application. These strings contain simple html formatting codes (<b>, <i>, etc.).
Is there any easy function in Visual Basic for Word to insert these strings into a word document and convert the html formatting codes to word formatting?
A: Use InsertFile
Set objdoc = objInsp.WordEditor
Set objword = objdoc.Application
Set objsel = objword.Selection
objsel.WholeStory
vs_html = "<html><body>" + vs_body + "</body></html>"
vs_file = "C:\temp\1.html"
Call DumptoFile(vs_file, "", vs_html, False)
RetVal = objsel.InsertFile(vs_file, , , False, False)
A: Here's a link to add HTML to the clipboard using VB:
http://support.microsoft.com/kb/274326
Once you have the HTML on the clipboard, paste it into your word doc using something like this:
ActiveDocument.Range.PasteSpecial ,,,,WdPasteDataType.wdPasteHTML
This is pretty much the equivalent of you cutting and pasting it in manually.
A: I'm using 2016. The only thing that worked was Range.InsertFile(path). Pasting Special didn't work.
A: AFAIK there is no builtin function to do that in VBA. You will have to write it yourself, which would be not too difficult if you restirct it to parse <b>, <i>, <a> and <p>, for example. All other tags would have to be ignored.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Does this query look optimized? I'm writing a query for an application that needs to list all the products with the number of times they have been purchased.
I came up with this and it works, but I am not too sure how optimized it is. My SQL is really rusty due to my heavy usage of ORM's, But in this case a query is a much more elegant solution.
Can you spot anything wrong (approach wise) with the query?
SELECT products.id,
products.long_name AS name,
count(oi.order_id) AS sold
FROM products
LEFT OUTER JOIN
( SELECT * FROM orderitems
INNER JOIN orders ON orderitems.order_id = orders.id
AND orders.paid = 1 ) AS oi
ON oi.product_id = products.id
GROUP BY products.id
The schema (with relevant fields) looks like this:
*orders* id, paid
*orderitems* order_id, product_id
*products* id
UPDATE
This is for MySQL
A: I'm not sure about the "(SELECT *" ... business.
This executes (always a good start) and I think is equivalent to what was posted.
SELECT products.id,
products.long_name AS name,
count(oi.order_id) AS sold
FROM products
LEFT OUTER JOIN
orderitems AS oi
INNER JOIN
orders
ON oi.order_id = orders.id AND orders.paid = 1
ON oi.product_id = products.id
GROUP BY products.id
A: Here a solution for those of us who are nesting impaired. (I get so confused when I start nesting joins)
SELECT products.id,
products.long_name AS name,
count(oi.order_id) AS sold
FROM orders
INNER JOIN orderitems AS oi ON oi.order_id = orders.id AND orders.paid = 1
RIGHT JOIN products ON oi.product_id = products.id
GROUP BY products.id
However, I tested your solution, Mike's and mine on MS SQL Server and the query plans are identical. I can't speak for MySql but if MS SQL Server is anything to go by, you may find the performance of all three solutions equivalent. If that is the case I guess you pick which solution is clearest to you.
A: Does it give you the right answer?
Except for just modifying it to get rid of the SELECT in the inner query, I don't see anything wrong with it.
A: Well you have "LEFT OUTER JOIN" that can be a performance issue depending on your Database.
Last time I remember it caused hell on MySQL, and it doesn't exist in SQLite. I think Oracle can handle it ok, and I guess DB and MSSQL too.
EDIT: If I remember correctly LEFT OUTER JOIN can be orders of magnitude slower on MySQL, but please correct me if I'm outdated here :)
A: Untested code, but try it:
SELECT products.id,
MIN(products.long_name) AS name,
count(oi.order_id) AS sold
FROM (products
LEFT OUTER JOIN orderitemss AS oi ON oi.product_id = products.id)
INNER JOIN orders AS o ON oi.order_id = o.id
WHERE orders.paid = 1
GROUP BY products.id
I don't know if the parentheses are needed for the LEFT OUTER JOIN, neither if MySQL allows multiple joins, however the MIN(products.long_name) gives just the description, since for every products.id you have only one description.
Perhaps the parentheses need to be around the INNER JOIN.
A: Here's a subquery form.
SELECT
p.id,
p.long_name AS name,
(SELECT COUNT(*) FROM OrderItems oi WHERE oi.order_id in
(SELECT o.id FROM Orders o WHERE o.Paid = 1 AND o.Product_id = p.id)
) as sold
FROM Products p
It should perform roughly equivalent to the join form. If it doesn't, let me know.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: is there a "best practice" to access another process in the OS through java? I've been reading Skype4Java (java api for skype) and noticed they use jni to access the skype client.
intuitively I'd assume that there already is a standard library in java that has an OS-sensitive jni implementation to access other processes. I set up to look for one, but couldn't find it.
Is there such a library? if not, is there a best practice to access another process in the os, not necessarily a skype client?
A: From Java 1.4 onwards you can use memory mapped files to exchange arbitrary information with another process. See java.nio.MappedByteBuffer for details.
A: This is not quite what you're looking for, but will probably help a great deal nonetheless: the Java Native Access project on java.net.
A: Don't forget sockets...
A: I think that maybe you need to define what 'access' means to you. IF you are talking about plain old inter-process communication, then sockets or JNI are really your best bet.
Garth's comment about using memory mapped files is interesting - I've used MMFs and virtual files for IPC between C applications many times, but it never occurred to me that Java's MMF implementation might be compatible with the native OS virtual file system. These kinds of virtual files usually require non-trivial setup, so I'd be surprised if it would work...
All said, unless you are pumping massive amounts of data between apps, using sockets is probably the most universal and effective way of doing it. Be sure you account for endianness between the host OS and Java VM :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Submitting a form on a user control by pressing enter on a text field does not work This seems to be a common problem but I cannot find a solution.
I type in my username and password which are in a login control I have created.
I then press enter once I've typed in my password and the page just refreshes. It triggers the page load event but not the button on click event.
If I press the submit button then everything works fine.
A: using your forms default button is correct, but you need to supply it the correct id as it will be rendered to HTML.
so you do as Jon said above:
<form runat="server" DefaultButton="SubmitButton">
But ensure you use the Button name that will be rendered.
You can achieve this my making the Button public in your control, or a method that will return it's ClientId.
Let's say your button is called btnSubmit, and your implementation of your control ucLogin.
Give your form an id
<form runat="server" id="form1">
Then in your page load in your code behind of your page, set the DefaultButton by handing it your button client id.
protected void Page_Load(object sender, EventArgs e)
{
form1.DefaultButton = ucLogin.btnSubmit.ClientID;
}
A: If you're using ASP.NET 2.0 or higher, you can set a default button attribute for your page's Form:
<form runat="server" DefaultButton="SubmitButton">
A: Pressing ENTER on a text input executes Form.onsubmit, not Button.onclick.
I suppose this was inspired by the fact that you can have a form without an actual submit button (depending solely on the use of ENTER).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What's the purpose of instance methods in Modules without classes? Imagine the following Ruby Module:
module Foo
def inst_method
puts "Called Foo.inst_method"
end
def self.class_method
puts "Called Foo.class_method"
end
end
Obviously Foo.class_method can be called without any class instances. However, what's happening to Foo.inst_method? Is it possible to call Foo.inst_method without previously including/extending a class?
Disclaimer: The question isn't focused on solving a real problem. I'm just trying to improve my understanding of the Ruby object system.
A: My answer would be : "no you can't call module instance methods without first extending or including that module in a class"
now knowing ruby and all the meta programming trickery it contains there probably is a way to call it but it would be outside the intended use of modules
module Tester
def inst_meth
puts "test inst meth\n"
end
def self.meth
puts "test self meth\n"
end
end
begin
Tester.meth
rescue;
puts $!
end
begin
Tester.inst_meth
rescue
puts $!
end
begin
Tester.new.inst_meth
rescue
puts $!
end
begin
extend Tester
inst_meth
rescue
puts $!
end
begin
include Tester
inst_meth
rescue
puts $!
end
gives
>ruby test.rb
test self meth
undefined method `inst_meth' for Tester:Module
undefined method `new' for Tester:Module
test inst meth
test inst meth
A: The primary purpose of instance methods within modules is to give that functionality to classes that include it.
"Mixing in" a module this way is most commonly used as a method of simulating multiple inheritance, or in other situations where inheritance is not the right paradigm (not quite a perfect "is a" relationship) but you want to share behavior. It's one more tool to keep your code DRY.
A good example of this in core Ruby is noting how Array and Hash can both be traveled and sorted, etc. They each get this functionality from the Enumerable module (each_with_index, select, reject, sort and more are all defined in the included module, not in the classes).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Where is GDB documentation specific to the Cell Linux environment? Where can documentation be found for the features of GDB, and the debugging process, specific to debugging of Cell Linux programs mixing PPU and SPU code?
A: Documents at the IBM developerWorks site for Cell can be found here:
Cell @developerWorks
You sound like you'd want the Programmer's Guide, which goes through debugging Cell applications.
Edit to add sample topics:
*
*Chapter 3. Debugging Cell BE applications
*
*...
*Debugging PPE code
*Debugging SPE code
*...
*Debugging in the Cell BE environment
*Debugging multithreaded code
*Debugging architecture
*Switching architectures within a single thread
*...
*Using the combined debugger
*...
A: One comprehensive overview seems to be here http://www.redbooks.ibm.com/redpieces/abstracts/sg247575.html?Open
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Should I use SVN or Git? I am starting a new distributed project. Should I use SVN or Git, and why?
A: Not really answering your question but if you want the benefits of Distributed Revision Control - it sounds like you do - and you're using Windows I think you'd be better off using Mercurial rather that Git as Mercurial has much better Windows support. Mercurial does have a Mac port too.
A: If your team is already familiar with version and source control softwares like cvs or svn, then, for a simple and small project (such as you claim it is), I would recommend you stick to SVN. I am really comfortable with svn, but for the current e-commerce project I am doing on django, I decided to work on git (I am using git in svn-mode, that is, with a centralised repo that I push to and pull from in order to collaborate with at least one other developer). The other developer is comfortable with SVN, and while others' experiences may differ, both of us are having a really bad time embracing git for this small project. (We are both hardcore Linux users, if it matters at all.)
Your mileage may vary, of course.
A: The main point is, that Git is a distributed VCS and Subversion a centralized one. Distributed VCSs are a little bit more difficult to understand, but have many advantages. If you don't need this advantages, Subversion may the better choice.
Another question is tool-support. Which VCS is better supported by the tools you plan to use?
EDIT: Three years ago I answered this way:
And Git works on Windows at the moment only via Cygwin or MSYS.
Subversion supported Windows from the beginning. As the git-solutions
for windows may work for you, there may be problems, as the most
developers of Git work with Linux and didn't have portability in the
mind from the beginning. At the moment I would prefer Subversion for
development under Windows. In a few years this may be irrelevant.
Now the world has changed a little bit. Git has a good implementation on windows now. Although I tested not thouroughly on windows (as I no longer use this system), I'm quite confident, that all the major VCS (SVN, Git, Mercurial, Bazaar) have proper Windows-implementation now. This advantage for SVN is gone. The other points (Centralized vs. Distributed and the check for tool support) stay valid.
A: Here is a copy of an answer I made of some duplicate question since then deleted about Git vs. SVN (September 2009).
Better? Aside from the usual link WhyGitIsBetterThanX, they are different:
one is a Central VCS based on cheap copy for branches and tags
the other (Git) is a distributed VCS based on a graph of revisions.
See also Core concepts of VCS.
That first part generated some mis-informed comments pretending that the fundamental purpose of the two programs (SVN and Git) is the same, but that they have been implemented quite differently.
To clarify the fundamental difference between SVN and Git, let me rephrase:
*
*SVN is the third implementation of a revision control: RCS, then CVS and finally SVN manage directories of versioned data. SVN offers VCS features (labeling and merging), but its tag is just a directory copy (like a branch, except you are not "supposed" to touch anything in a tag directory), and its merge is still complicated, currently based on meta-data added to remember what has already been merged.
*Git is a file content management (a tool made to merge files), evolved into a true Version Control System, based on a DAG (Directed Acyclic Graph) of commits, where branches are part of the history of datas (and not a data itself), and where tags are a true meta-data.
To say they are not "fundamentally" different because you can achieve the same thing, resolve the same problem, is... plain false on so many levels.
*
*if you have many complex merges, doing them with SVN will be longer and more error prone.
if you have to create many branches, you will need to manage them and merge them, again much more easily with Git than with SVN, especially if a high number of files are involved (the speed then becomes important)
*if you have partial merges for a work in progress, you will take advantage of the Git staging area (index) to commit only what you need, stash the rest, and move on on another branch.
*if you need offline development... well with Git you are always "online", with your own local repository, whatever the workflow you want to follow with other repositories.
Still the comments on that old (deleted) answer insisted:
VonC: You are confusing fundamental difference in implementation (the differences are very fundamental, we both clearly agree on this) with difference in purpose.
They are both tools used for the same purpose: this is why many teams who've formerly used SVN have quite successfully been able to dump it in favor of Git.
If they didn't solve the same problem, this substitutability wouldn't exist.
, to which I replied:
"substitutability"... interesting term (used in computer programming).
Off course, Git is hardly a subtype of SVN.
You may achieve the same technical features (tag, branch, merge) with both, but Git does not get in your way and allow you to focus on the content of the files, without thinking about the tool itself.
You certainly cannot (always) just replace SVN by Git "without altering any of the desirable properties of that program (correctness, task performed, ...)" (which is a reference to the aforementioned substitutability definition):
*
*One is an extended revision tool, the other a true version control system.
*One is suited small to medium monolithic project with simple merge workflow and (not too much) parallel versions. SVN is enough for that purpose, and you may not need all the Git features.
*The other allows for medium to large projects based on multiple components (one repo per component), with large number of files to merges between multiple branches in a complex merge workflow, parallel versions in branches, retrofit merges, and so on. You could do it with SVN, but you are much better off with Git.
SVN simply can not manage any project of any size with any merge workflow. Git can.
Again, their nature is fundamentally different (which then leads to different implementation but that is not the point).
One see revision control as directories and files, the other only see the content of the file (so much so that empty directories won't even register in Git!).
The general end-goal might be the same, but you cannot use them in the same way, nor can you solve the same class of problem (in scope or complexity).
A: Definitely svn, since Windows is—at best—a second-class citizen in the world of git (see http://en.wikipedia.org/wiki/Git_(software)#Portability for more details).
UPDATE: Sorry for the broken link, but I've given up trying to get SO to work with URIs that contain parentheses. [link fixed now. -ed]
A: I would opt for SVN since it is more widely spread and better known.
I guess, Git would be better for Linux user.
A: Git is not natively supported under Windows, just yet. It is optimized for Posix systems. However running Cygwin or MinGW lets you run Git successful.
Nowadays I prefer Git over SVN, but it takes a while to get over the threshold if you come from CVS, SVN land.
A: I would probably choose Git because I feel it's much more powerful than SVN. There are cheap Code Hosting services available which work just great for me - you don't have to do backups or any maintenance work - GitHub is the most obvious candidate.
That said, I don't know anything regarding the integration of Visual Studio and the different SCM systems. I imagine the integration with SVN to notably better.
A: I have used SVN for a long time, but whenever I used Git, I felt that Git is much powerful, lightweight, and although a little bit of learning curve involved but is better than SVN.
What I have noted is that each SVN project, as it grows, becomes a very big size project unless it is exported. Where as, GIT project (along with Git data) is very light weight in size.
In SVN, I've dealt with developers from novice to experts, and the novices and intermediates seem to introduce File conflicts if they copy one folder from another SVN project in order to re-use it. Whereas, I think in Git, you just copy the folder and it works, because Git doesn't introduce .git folders in all its subfolders (as SVN does).
After dealing alot with SVN since long time, I'm finally thinking to move my developers and me to Git, since it is easy to collaborate and merge work, as well as one great advantage is that a local copy's changes can be committed as much desired, and then finally pushed to the branch on server in one go, unlike SVN (where we have to commit the changes from time to time in the repository on server).
Anyone who can help me decide if I should really go with Git?
A: It comes down to this:
Will your development be linear? If so, you should stick with Subversion.
If on the other hand, your development will not be linear, which means that you will need to create branching for different changes, and then merging such changes back to the main development line (known to Git as the master branch) then Git will do MUCH more for you.
A: 2 key advantages of SVN that are rarely cited:
*
*Large file support. In addition to code, I use SVN to manage my home directory. SVN is the only VCS (distributed or not) that doesn't choke on my TrueCrypt files (please correct me if there's another VCS that handles 500MB+ files effectively). This is because diff comparisons are streamed (this is a very essential point). Rsync is unacceptable because it's not 2-way.
*Partial repository (subdir) checkout/checkin. Mercurial and bzr don't support this, and git's support is limited. This is bad in a team environment, but invaluable if I want to check something out on another computer from my home dir.
Just my experiences.
A: May I expand on the question and ask if Git work well on MacOS?
Reply to Comments: Thanks for the news, I'd been looking forward to trying it out. I'll install it at home on my Mac.
A: have you tried Bzr?
It's pretty good, connonical (the people who make Ubuntu) made it because they didn't like anything else on the market...
A: There is an interesting Video on YouTube about this. Its from Linus Torwalds himself: Goolge Tech Talk: Linus Torvalds on git
A: SVN is one repo and lots of clients. Git is a repo with lots of client repos, each with a user. It's decentralised to a point where people can track their own edits locally without having to push things to an external server.
SVN is designed to be more central where Git is based on each user having their own Git repo and those repos push changes back up into a central one. For that reason, Git gives individuals better local version control.
Meanwhile you have the choice between TortoiseGit, GitExtensions (and if you host your "central" git-repository on github, their own client – GitHub for Windows).
If you're looking on getting out of SVN, you might want to evaluate Bazaar for a bit. It's one of the next generation of version control systems that have this distributed element. It isn't POSIX dependant like git so there are native Windows builds and it has some powerful open source brands backing it.
But you might not even need these sorts of features yet. Have a look at the features, advantages and disadvantages of the distributed VCSes. If you need more than SVN offers, consider one. If you don't, you might want to stick with SVN's (currently) superior desktop integration.
A: After doing more research, and reviewing this link: https://git.wiki.kernel.org/articles/g/i/t/GitSvnComparison_cb82.html
(Some extracts below):
*
*It's incredibly fast.
No other SCM that I have used has been able to keep up with it, and I've used a lot, including Subversion, Perforce, darcs, BitKeeper, ClearCase and CVS.
*It's fully distributed.
The repository owner can't dictate how I work. I can create branches and commit changes while disconnected on my laptop, then later synchronize that with any number of other repositories.
*Synchronization can occur over many media.
An SSH channel, over HTTP via WebDAV, by FTP, or by sending emails holding patches to be applied by the recipient of the message. A central repository isn't necessary, but can be used.
*Branches are even cheaper than they are in Subversion.
Creating a branch is as simple as writing a 41 byte file to disk. Deleting a branch is as simple as deleting that file.
*Unlike Subversion branches carry along their complete history.
without having to perform a strange copy and walk through the copy. When using Subversion I always found it awkward to look at the history of a file on branch that occurred before the branch was created. from #git: spearce: I don't understand one thing about SVN in the page. I made a branch i SVN and browsing the history showed the whole history a file in the branch
*Branch merging is simpler and more automatic in Git.
In Subversion you need to remember what was the last revision you merged from so you can generate the correct merge command. Git does this automatically, and always does it right. Which means there's less chance of making a mistake when merging two branches together.
*Branch merges are recorded as part of the proper history of the
repository. If I merge two branches together, or if I merge a branch back into the trunk it came from, that merge operation is recorded as part of the repostory history as having been performed by me, and when. It's hard to dispute who performed the merge when it's right there in the log.
*Creating a repository is a trivial operation:
mkdir foo; cd foo; git init
That's it. Which means I create a Git repository for everything these days. I tend to use one repository per class. Most of those repositories are under 1 MB in disk as they only store lecture notes, homework assignments, and my LaTeX answers.
*The repository's internal file formats are incredible simple.
This means repair is very easy to do, but even better because it's so simple its very hard to get corrupted. I don't think anyone has ever had a Git repository get corrupted. I've seen Subversion with fsfs corrupt itself. And I've seen Berkley DB corrupt itself too many times to trust my code to the bdb backend of Subversion.
*Git's file format is very good at compressing data, despite
it's a very simple format. The Mozilla project's CVS repository is about 3 GB; it's about 12 GB in Subversion's fsfs format. In Git it's around 300 MB.
After reading all this, I'm convinced that Git is the way to go (although a little bit of learning curve exists). I have used Git and SVN on Windows platforms as well.
I'd love to hear what others have to say after reading the above?
A: SVN seems like a good choice under Windows, as pointed by other people.
If some of your developper wants to try GIT, it may always use GIT-SVN where the SVN repository is recreated in a GIT repository. Then he should be able to work locally with GIT and then use SVN to publish its changes to the main repository.
A: I would set up a Subversion repository. By doing it this way, individual developers can choose whether to use Subversion clients or Git clients (with git-svn). Using git-svn doesn't give you all the benefits of a full Git solution, but it does give individual developers a great deal of control over their own workflow.
I believe it will be a relatively short time before Git works just as well on Windows as it does on Unix and Mac OS X (since you asked).
Subversion has excellent tools for Windows, such as TortoiseSVN for Explorer integration and AnkhSVN for Visual Studio integration.
A: I have never understand this concept of "git not being good on Windows"; I develop exclusively under Windows and I have never had any problems with git.
I would definitely recommend git over subversion; its simply so much more versatile and allows "offline development" in a way subversion never really could. Its available on almost every platform imaginable and has more features than you'll probably ever use.
A: The funny thing is:
I host projects in Subversion Repos, but access them via the Git Clone command.
Please read Develop with Git on a Google Code Project
Although Google Code natively speaks
Subversion, you can easily use Git
during development. Searching for "git
svn" suggests this practice is
widespread, and we too encourage you
to experiment with it.
Using Git on a Svn Repository gives me benefits:
*
*I can work distributed on several
machines, commiting and pulling from
and to them
*I have a central backup/public svn repository for others to check out
*And they are free to use Git for their own
A: You have to go with a DVCS, it is like a quantum leap in source management. Personally I use Monotone and its sped up development time no end. We are using it for Windows, Linux and Mac and it has been very stable. I even have buildbot doing nightly builds of the project on each of the platforms.
DVCS while being distributed usually means you will create a central server just for people to push changes to and from.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "325"
} |
Q: AJAX Toolkit - AJAX Framework What's the difference between toolkits and frameworks? Do you know a good comparison?
A: If I had to make a distinction, then I'd say a toolkit provides specific tools to do specific jobs, whereas a framework provides you with a foundation on which to build further, higher-level structures.
Tools are useful on their own, frameworks have no innate function.
A: jQuery, prototype, Yahoo! User Interface, MooTools, dojo, and ExtJS will have you working with very solid code.
Other posibilities that I can't vouch for myself: QooxDoo
I believe he's looking for a comparison of the javascript libraries/toolkits(whatever they happen to call themselves).
A: The names say it all really, a toolkit is a set of tools that you can use however you wish. A framework is an empty frame that you can fill in to form your application. The line between them is blurry though a framework contains tools, and a toolkit sometimes forces you to perform actions in a specific sequence.
I wouldn't know of a generic comparison, i guess it depends on the toolkits and frameworks themselves.
A: Not Specific to AJAX though. But a have a read..
What is the difference between a framework and a library?
A: A toolkit provides the basic, minimum building blocks for building something. A framework already has an approach laid for your. A framework defines the application architecture for you (most of the times), where a toolkit only gives you the tools, so you define your own architecture.
For example, GWT(Google Web Tookit) is a toolkit; it does not impose a certain way of doing things, the Java JDK is also a toolkit (Java Developer's Kit), but Rails (from Ruby on Rails) is a framework. It encourages the use of their worflow and classes (MVC, share-nothing, etc).
A: A toolkit is like a library. You pull it into your application and you use it. A framework provides a structure to your application, so all of your code goes inside of it. The strength of a framework is that by following it's conventions and staying inside of its process it is capable of doing a lot of heavy lifting for you. A toolkit is more flexible, but there are many types of problems that are better solved by a framework. With Ajax, it is a little harder to define. For example, simple widgets and dom manipulation can be done in a toolkit style, but if all of your javascript uses special event wrappers and framework based class functionality and inheritence, all of your code becomes dependent on that framework and is really contained inside of it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Programmatically renaming a table in SQL Server 2000 - is sp_rename the only solution? I recently had to rename a table (and a column and FK/PK contraints) in SQL Server 2000 without losing an data. There did not seem to be an obvious DDL T-SQL statements for performing this action, so I used sp_rename to directly fiddle with object names.
Was this the only solution to the problem? (other, than give the table the correct name in the first place - doh!)
A: Ya
EXEC sp_rename 'Old_TableName', 'New_TableName'
work fine but are any key word like
"alter tabel old_name to new_name "
A: sp_rename is the correct way to do it.
EXEC sp_rename 'Old_TableName', 'New_TableName'
A: Maybe not the only: I guess you could always toy with the master database and update the table name there - but this is highly unrecommendable.
A: There is a solution that can let you work concurrently with both old and new versions of the table. This is particularly important if your data is replicated and/or is accessed through client interface (meaning old versions of the client interface will still work with the old table name):
*
*Modify the constraints (including FKs) on your table through "ALTER TABLE" command
*Do not change table name or
field name but create a view such
as:
SELECT oldTable.oldField1 as newField1, ...
save it as newTable (and, if requested, distribute it on your different servers)
Note that you cannot modify your PK this way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Convert IDictionary keys to lowercase (C#) I've got a Method that gets a IDictionary as a parameter.
Now I want to provide a method that retrieves the value from this dictionary, but it should be case-invariant.
So my solution to this right now was to have a static function that loops through the keys and converts them toLower() like this:
private static IDictionary<ILanguage, IDictionary<string, string>> ConvertKeysToLowerCase(
IDictionary<ILanguage, IDictionary<string, string>> dictionaries)
{
IDictionary<ILanguage, IDictionary<string, string>> resultingConvertedDictionaries
= new Dictionary<ILanguage, IDictionary<string, string>>();
foreach(ILanguage keyLanguage in dictionaries.Keys)
{
IDictionary<string, string> convertedDictionatry = new Dictionary<string, string>();
foreach(string key in dictionaries[keyLanguage].Keys)
{
convertedDictionatry.Add(key.ToLower(), dictionaries[keyLanguage][key]);
}
resultingConvertedDictionaries.Add(keyLanguage, convertedDictionatry);
}
return resultingConvertedDictionaries;
}
Now, this is ok, but still it's a pretty huge chunk of code that contradicts my idea of "clean and efficient". Do you know any alternatives to this so that the .ContainsKey() method of the dictionary doesn't differentiate between casing?
A: Yes - pass the Dictionary constructor StringComparer.OrdinalIgnoreCase (or another case-ignoring comparer, depending on your culture-sensitivity needs).
A: By using a StringDictionary the keys are converted to lower case at creating time.
http://simiansoftware.blogspot.com/2008/11/have-const-string-with-ui-description.html
A: You could use the var keyword to remove some clutter. Technically the source remains the same. Also I would just pass and return a Dictionary<string, string> because you're not doing anything with that ILanguage parameter and make the method more reusable:
private static IDictionary<string, string> ConvertKeysToLowerCase(
IDictionary<string, string> dictionaries)
{
var convertedDictionatry = new Dictionary<string, string>();
foreach(string key in dictionaries.Keys)
{
convertedDictionatry.Add(key.ToLower(), dictionaries[key]);
}
return convertedDictionatry;
}
... and call it like so:
// myLanguageDictionaries is of type IDictionary<ILanguage, IDictionary<string, string>>
foreach (var dictionary in myLanguageDictionaries.Keys)
{
myLanguageDictionaries[dictionary].Value =
ConvertKeysToLowerCase(myLanguageDictionaries[dictionary].Value);
}
A: You could inherit from IDictionary yourself, and simply marshal calls to an internal Dictionary instance.
Add(string key, string value) { dictionary.Add(key.ToLowerInvariant(), value) ; }
public string this[string key]
{
get { return dictionary[key.ToLowerInvariant()]; }
set { dictionary[key.ToLowerInvariant()] = value; }
}
// And so forth.
A: System.Collections.Specialized.StringDictionary() may help. MSDN states:
"The key is handled in a case-insensitive manner; it is translated to lowercase before it is used with the string dictionary.
In .NET Framework version 1.0, this class uses culture-sensitive string comparisons. However, in .NET Framework version 1.1 and later, this class uses CultureInfo.InvariantCulture when comparing strings. For more information about how culture affects comparisons and sorting, see Comparing and Sorting Data for a Specific Culture and Performing Culture-Insensitive String Operations."
A: You can also try this way
convertedDictionatry = convertedDictionatry .ToDictionary(k => k.Key.ToLower(), k => k.Value.ToLower());
A: LINQ version using the IEnumerable<T> extension methods:
private static IDictionary<ILanguage, IDictionary<string, string>> ConvertKeysToLowerCase(
IDictionary<ILanguage, IDictionary<string, string>> dictionaries)
{
return dictionaries.ToDictionary(
x => x.Key, v => CloneWithComparer(v.Value, StringComparer.OrdinalIgnoreCase));
}
static IDictionary<K, V> CloneWithComparer<K,V>(IDictionary<K, V> original, IEqualityComparer<K> comparer)
{
return original.ToDictionary(x => x.Key, x => x.Value, comparer);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How do I launch a standalone SWF from within an Adobe AIR application? I'm completely new to AIR but what I'm trying to do feels like it should be quite easy.
I want my AIR app to execute (launch) an SWF in the standalone Flash Player (just like if I were to double click it).
Please note that I don't want the AIR app to embed the SWF. Just run it.
Can this be done?
A: Using Adobe AIR, you could launch / load the SWF into a separate native window. It would run in the same process as the AIR app loading / launching it, but the experience would be the similar if not the same for the end user.
mike chambers
mesh@adobe.com
A: The AIR-Runtime is (still) not able to launch external Applications, except Acrobat Reader for PDFs and the default Browser (you can let the browser display the swf).
I think you need some of this Frameworks:
*
*FluorineFx Aperture
*Merapi
What's the sense behind your plan, why AIR?
A: Thanks for the this, running it through a browser might be my solution then. FYI I'm using AIR to write some settings to a local text file that the SWF then can read.
A: Most people don't have the standalone player - only people with Flash installed, so this isn't a very good idea, I don't think. Could you open a new AIR window with just the swf in it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Usability: Should the ENTER key close a wizard form as OK even if the focus is not set on the OK/DONE button? I have the in my opinion odd request to close a wizard form as Done or OK if Enter was pressed on the keyboard even if the OK/DONE button is not focused.
In my opinion that would be a usability mistake. For example: In the wizard you may have multiple controls, buttons, check boxes, multiple line controls and they all have a different behavior on actions from the ENTER key. And don't forget the other buttons in the navigation of the wizard, what if they are focused?
Should these controls don't react on Enter like expected before? Should they do their actions but in other cases where Enter does no further action for the control it should close the form == inconsistent?
I think that is a typical request where the needs of one person would help him but confuse many other.
In my opinion Wizards are very special because they are not only made to make things easier but also very often focus on people with less experience with the functionality of an application. So I take every request serious and try to look into all arguments for and against the request.
Is my point of view to narrow? Are there some usability studies or guidelines especially for Wizards to backup my opinion or maybe proof me wrong?
Thank you very much!
Michael
A: Well, here's the thing: there are two kinds of users you have to take into account here.
First kind of users are the Baby Boomers and Gen Xers (e.g., people who have been using computers in the 70s/80s) who are accustomed to pressing Enter to move to the next field. These are the ones who learned how to use computers in terminals/consoles and enter means you're finished typing on that field and would move on to the next.
Second kind of users are those who were weaned on Windows. These people are used to pressing the Tab key to move to the next field. Pressing enter to them means they are done with the whole thing.
So which convention should you follow? That will depend on whether you're targetting the first or second type of users, the environment (Windows or Web?), and the OS.
If you're targetting Windows forms, it is much advisable to be consistent to the OS (e.g., letting people use Tab instead of Enter) for form entry. In the web, you're in a quandary, since Enter is trapped by the web browser as a submit event.
In the end the only useful advice I can offer is to try it out with your target customers and see whether they prefer Enter over Tab.
A: I think the key is to test. You can't really guess what your users will find comfortable, you have to watch them try it. Especially since there are multiple incompatible standards you could follow, you are just going to have to see if this change works for most users in your audience.
A: I would be of the same opinion, perhaps mention it to the client and let them use the final version in both modes. I guess you have to give them what they ask for when they are paying.
A: To me this also seems to be an odd request but as Paul says, if the client wants it, then the client gets it.
However from a usability/comprehension standpoint, I would make the border of the ok/done button much thicker then normal so that it stands out a bit and maybe indicate to people that it has special behaviour.
Also I would perhaps make a note in the dialog/wizard box that hitting enter will cause the wizard to close as if the OK/Done button had been pressed.
While the one user may know that hitting enter will close it, unless someone else is specifically told, they will not be expecting that behaviour.
A: Is this request perhaps because the UAT that was undertaken on the wizard involved users that weren't aware that pressing ENTER will have the same effect as clicking the button?
If when the final page of the wizard is displayed, the 'Finish' button is already highlighted (as I would expect) that maybe it's a matter of giving the user some cue that they can also press ENTER at this point.
If you take Google for example, I seem to remember that if you tend to systematically type your search term in and then click the 'Search' button with the mouse, a message is displayed at the top of the search results that kindly hints to you that you can also just press ENTER. Obviously, this is not something that can easily be done in your case because this is the last page of the wizard, but maybe this is the sort of thing that your client is trying to get you to engineer around?
A: I think you should have a finish page to facilitate this. If the user presses enter by mistake the worst is that he won't finish the wizard, only go to the next page (which may be the finish page). This is good for situations where nuclear bombs are controlled by said wizards.
On the finish page pressing enter would finish the wizard (and blow up Iraq, bring down a satellite, or erase Jimbob's farm).
If the user can re-run the wizard I don't think it would be disasterous if they accidentally finished it.
Remember, wizards should never take any action until they are finished, in case the user cancels or such. Confirmation dialog boxes on a finish are tedious and I will hunt you down if you use them, I think once the user has finished the wizard he is pretty sure about his intent.
A: Maybe the client has good reasons for it.
Imagine the following situation:
A screen with lots of optional fields that gets opened/closed a lot and where data accuracy is not really critical.
Think of a little program that pops up every half hour to ask you what you have been doing, for what client and maybe some notes so it can gather this info and generate your timesheet.
Being able to open up the screen, enter the info and close it all really quick and with as little hassle as possible is way more important than the accuracy of the data.
I can imagine lots of situations where being able to confirm the field without having focus can be usefull.
A: Educate your clients. Show them some documentation as why that suggestion might not be a good usability practice.
Some reputable website will work best, as clients will usually believe a third party before believing you. After all, to them you are probably just being lazy and don't want to work more.
If the client still doesn't concede, then just do what they want, and warn them that it is not the good thing to do.
Although in your case, the "good thing to do" seems a little on the gray area.
A: I would argue that you could possibly use this functionality to move forward through the wizard but ONLY if no other action had been taken on that page.
The moment a field is completed or a button clicked/highlighted or the cursor is moved from the default position, the Enter functionality should revert to that of the standard OS.
As others have said, clearly this would only work if those using the wizard were made aware of this as part of their application training, but it might prove useful for moving quickly through un-used pages of the wizard to get to where the user needs to be.
A: Doesn't matter. Choose and be consistant in all your applications
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do you get the Class of an Abstract class (Object) in JavaME? I need to get the Class of an object at runtime.
For an non-abstract class I could do something like:
public class MyNoneAbstract{
public static Class MYNONEABSTRACT_CLASS = new MyNoneAbstract().getClass();
But for an abstract class this does NOT work (always gives me Object)
public abstract class MyAbstract{
public static Class MYABSTRACT_CLASS = MyAbstract.class.getClass();
This code will be running in JavaME environments.
A: You just need
MyAbstract.class
That expression returns the Class object representing MyAbstract.
A: The code you want in the abstract case is:
public abstract class MyAbstract{
public static Class MYABSTRACT_CLASS = MyAbstract.class;
}
although I personally wouldn't bother defining the constant and just used MyAbstract.class throughout.
I would have expected the code you wrote to have returned the class 'Class', not the class 'Object'.
A: I think more information is required here.
In Java, an abstract class cannot be instantiated.
That means an Object at runtime cannot have its class be abstract.
It would need to be a subclass that implements all abstract methods.
In JavaME, Object.getClass() should be all you need.
Are you somehow trying to reconstitute your class hierarchy at runtime?
In that case, you could implement something like this instead:
public String getClassHierarchy() {
return super.getClassHierarchy() + ".MyAbstract";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why is Apache + Rails is spitting out two status headers for code 500? I have a rails app that is working fine except for one thing.
When I request something that doesn't exist (i.e. /not_a_controller_or_file.txt) and rails throws a "No Route matches..." exception, the response is this (blank line intentional):
HTTP/1.1 200 OK
Date: Thu, 02 Oct 2008 10:28:02 GMT
Content-Type: text/html
Content-Length: 122
Vary: Accept-Encoding
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Status: 500 Internal Server Error
Content-Type: text/html
<html><body><h1>500 Internal Server Error</h1></body></html>
I have the ExceptionLogger plugin in /vendor, though that doesn't seem to be the problem. I haven't added any error handling beyond the custom 500.html in public (though the response doesn't contain that HTML) and I have no idea where this bit of html is coming from.
So Something, somewhere is adding that HTTP/1.1 200 status code too early, or the Status: 500 too late. I suspect it's Apache because I get the appropriate HTTP/1.1 500 header (at the top) when I use Webrick.
My production stack is as follows:
Apache 2
Mongrel (5 instances)
RubyOnRails 2.1.1 (happens in both 1.2 and 2.1.1)
I forgot to mention, the error is caused by a "no route matches..." exception
A: This is a fairly old thread, but for what it's worth I found a great resource that includes a detailed description of the problem and the solution. Apparently this bug affects Rails < 2.3 when used with Mongrel.
*
*The article that helped me understand the problem & write my own patch.
*An official Rails bug ticket that includes a patch for Rails 2.2.2.
A: This html file is coming from Rails. It is encountering some sort of error (probably an exception of some kind, or some other unrecoverable error).
If the extra blank line between the Status: header and the actual headers is there, and not just a typo, then this would go a long way to explaining why Apache is reporting a 200 OK message.
The Status header is how Rails, PHP, or whatever tells Apache "There was an error, please return this code instead of 200 OK." The fact there is a blank line means something extra is going on and Ruby is outputting a blank line before the error output for whatever reason. Maybe it's previous output from your script. The long and short of it is though, the extra blank line means that Apache thinks "Oh, blank line, no extra headers, this is all content now.", which would be consistent with the Content-Length header you provided.
My guess for why there's a blank line would be previous script output, perhaps a line ending at the end of a fully script page. As to why the 500 error is happening, there isn't nearly enough info here to tell you that. Maybe a file I/O error.
Edit: Given the extra information provided by Dave about the internals, I'd say this is actually an issue with the proxying that goes on behind the scenes... I couldn't tell you exactly what though, beyond what's already been said.
A: This is coming from rails itself.
http://github.com/rails/rails/tree/master/actionpack/lib/action_controller/dispatcher.rb#L60
The dispatcher is return an error page with the status code of 200 (Success).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Should methods in a Java interface be declared with or without a public access modifier? Should methods in a Java interface be declared with or without the public access modifier?
Technically it doesn't matter, of course. A class method that implements an interface is always public. But what is a better convention?
Java itself is not consistent in this. See for instance Collection vs. Comparable, or Future vs. ScriptEngine.
A: I disagree with the popular answer, that having public implies that there are other options and so it shouldn't be there. The fact is that now with Java 9 and beyond there ARE other options.
I think instead Java should enforce/require 'public' to be specified. Why? Because the absence of a modifier means 'package' access everywhere else, and having this as a special case is what leads to the confusion. If you simply made it a compile error with a clear message (e.g. "Package access is not allowed in an interface.") we would get rid of the apparent ambiguity that having the option to leave out 'public' introduces.
Note the current wording at: https://docs.oracle.com/javase/specs/jls/se9/html/jls-9.html#jls-9.4
"A method in the body of an interface may be declared public or
private (§6.6). If no access modifier is given, the method is implicitly public. It is permitted, but discouraged as a matter of
style, to redundantly specify the public modifier for a method
declaration in an interface."
See that 'private' IS allowed now. I think that last sentence should have been removed from the JLS. It is unfortunate that the "implicitly public" behaviour was ever allowed as it will now likely remain for backward compatibilty and lead to the confusion that the absence of the access modifier means 'public' in interfaces and 'package' elsewhere.
A: I always write what I would use if there was no interface and I was writing a direct implementation, i.e., I would use public.
A: I would avoid to put modifiers that are applied by default. As pointed out, it can lead to inconsistency and confusion.
The worst I saw is an interface with methods declared abstract...
A: I used declare methods with the public modifier, because it makes the code more readable, especially with syntax highlighting. In our latest project though, we used Checkstyle which shows a warning with the default configuration for public modifiers on interface methods, so I switched to ommitting them.
So I'm not really sure what's best, but one thing I really don't like is using public abstract on interface methods. Eclipse does this sometimes when refactoring with "Extract Interface".
A: The public modifier should be omitted in Java interfaces (in my opinion).
Since it does not add any extra information, it just draws attention away from the important stuff.
Most style-guides will recommend that you leave it out, but of course, the most important thing is to be consistent across your codebase, and especially for each interface. The following example could easily confuse someone, who is not 100% fluent in Java:
public interface Foo{
public void MakeFoo();
void PerformBar();
}
A: The JLS makes this clear:
It is permitted, but discouraged as a matter of style, to redundantly specify the public and/or abstract modifier for a method declared in an interface.
A: I prefer skipping it, I read somewhere that interfaces are by default, public and abstract.
To my surprise the book - Head First Design Patterns, is using public with interface declaration and interface methods... that made me rethink once again and I landed up on this post.
Anyways, I think redundant information should be ignored.
A: The reason for methods in interfaces being by default public and abstract seems quite logical and obvious to me.
A method in an interface it is by default abstract to force the implementing class to provide an implementation and is public by default so the implementing class has access to do so.
Adding those modifiers in your code is redundant and useless and can only lead to the conclusion that you lack knowledge and/or understanding of Java fundamentals.
A: Despite the fact that this question has been asked long time ago but I feel a comprehensive description would clarify why there is no need to use public abstract before methods and public static final before constants of an interface.
First of all Interfaces are used to specify common methods for a set of unrelated classes for which every class will have a unique implementation. Therefore it is not possible to specify the access modifier as private since it cannot be accessed by other classes to be overridden.
Second, Although one can initiate objects of an interface type but an interface is realized by the classes which implement it and not inherited. And since an interface might be implemented (realized) by different unrelated classes which are not in the same package therefore protected access modifier is not valid as well. So for the access modifier we are only left with public choice.
Third, an interface does not have any data implementation including the instance variables and methods. If there is logical reason to insert implemented methods or instance variables in an interface then it must be a superclass in an inheritance hierarchy and not an interface. Considering this fact, since no method can be implemented in an interface therefore all the methods in interface must be abstract.
Fourth, Interface can only include constant as its data members which means they must be final and of course final constants are declared as static to keep only one instance of them. Therefore static final also is a must for interface constants.
So in conclusion although using public abstract before methods and public static final before constants of an interface is valid but since there is no other options it is considered redundant and not used.
A: With the introduction of private, static, default modifiers for interface methods in Java 8/9, things get more complicated and I tend to think that full declarations are more readable (needs Java 9 to compile):
public interface MyInterface {
//minimal
int CONST00 = 0;
void method00();
static void method01() {}
default void method02() {}
private static void method03() {}
private void method04() {}
//full
public static final int CONST10 = 0;
public abstract void method10();
public static void method11() {}
public default void method12() {}
private static void method13() {}
private void method14() {}
}
A: It's totally subjective. I omit the redundant public modifier as it seems like clutter. As mentioned by others - consistency is the key to this decision.
It's interesting to note that the C# language designers decided to enforce this. Declaring an interface method as public in C# is actually a compile error. Consistency is probably not important across languages though, so I guess this is not really directly relevant to Java.
A: People will learn your interface from code completion in their IDE or in Javadoc, not from reading the source. So there's no point in putting "public" in the source - nobody's reading the source.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "321"
} |
Q: Visual Studio 2005 - can not open form on designer My team developed a GUI application on Visual Studio 2005, managed C++. Since some deliveries it is not possible to open the form in the designer, even if the source code and the project settings have not been changed. The designer reports this error:
Exception of type 'System.OutOfMemoryException' was thrown.
at Microsoft.VisualStudio.Design.VSDynamicTypeService.ShadowCopyAssembly(String fileName)
at Microsoft.VisualStudio.Design.VSDynamicTypeService.CreateDynamicAssembly(String codeBase)
at Microsoft.VisualStudio.Design.VSTypeResolutionService.AssemblyEntry.get_Assembly()
at Microsoft.VisualStudio.Design.VSTypeResolutionService.AssemblyEntry.Search(String fullName, String typeName, Boolean ignoreTypeCase, Assembly& assembly, String description)
...
We successfully recompiled the project but we still encounter this problem.
Any idea?
A: This is how I used to debug these issues, Start a second instance of visual studio, load your project and attach to the first instance which also has the project loaded. Now set a breakpoint in the constructor and Page Load events and also any custom paint events that you may have in the form in the second instance and try to open the designer in the first instance, the breakpoints should get hit and you should be able to see what's going on.
A: I suspect that you have a Design Mode error where an infinite loop (or recursive control creation) occurs on the concerned Form.
One thing that helped me in these kinds of error on Windows Forms would be the following:
*
*Open your Visual Studio 2005 solution for your GUI application. Don't open your form yet
*Open another instance of Visual Studio 2005
*In the second instance, Attach (Debug -> Attach to Process) the first instance of devenv.exe to the debugger. Make sure exceptions (Debug -> Exceptions) have all exceptions checkboxes under "Thrown" checked.
*Now go to your first VS2005 instance and open the form. The second VS2005 instance will stop at the line where the error occurs.
A: This is a long shot, but try closing and opening the designer several times in a row. I have had the same kinds of problems with the C# Windows Forms designer (VS2005) : the form usually ended up opening correctly (after 5 tries, quite consistently).
A: I've run into the same issue intermittently when working with a large multi-project solution, or a project with an exceedingly large and complicated windows form.
I was able to solve the problem by enabling Visual Studio to use more than 2GB of memory. Here's the process...
(note: this assumes XP and Visual Studio 2005 - Vista and/or VS2008 will require slight changes)
Edit Boot.ini
Right-click My Computer, properties, Advanced tab. Under Startup and Recovery click Settings. Click the Edit button, and add the /3GB switch to the end of the [operating systems] line:
multi(0)disk(0)rdisk(0)partition(2)\WINDOWS="Microsoft Windows XP Professional" /noexecute=optin /fastdetect /3GB
Make Visual Studio "Large Address Aware"
Run a Visual Studio Command Prompt, and change to the IDE directory:
cd %ProgramFiles%\Microsoft Visual Studio 8\Common7\IDE
Use the microsoft tool editbin to modify devenv.exe:
editbin /LARGEADDRESSAWARE devenv.exe
Now reboot, and you're done!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Windbg: How to set breakpoint on one of the overloads of a C++ function? I have two overloads of a c++ function and I would like to set a breakpoint on one of them:
0:000> bu myexe!displayerror
Matched: 00000000`ff3c6100 myexe!displayError (int, HRESULT, wchar_t *)
Matched: 00000000`ff3c60d0 myexe!displayError (int, HRESULT)
Ambiguous symbol error at 'myexe!displayerror'
Heck I would be fine with setting breakpoints on all overloads, but can't seem to figure out how:
0:000> bu myexe!displayerror*
Matched: 00000000`ff3c6100 myexe!displayError (int, HRESULT, wchar_t *)
Matched: 00000000`ff3c60d0 myexe!displayError (int, HRESULT)
Ambiguous symbol error at 'myexe!displayerror*'
A: Try:
bu 0xff3c6100
If I remember right, WinDbg allows setting breakpoints by address too.
A: Have you tried "bm myexe!displayerror*" ?
A: bm myexe!displayerror
This will set breakpoints all all overloads, than you use bc to clear the ones you don't want
bc 1-3
Or just disable them
bd 1-3
The problem with bm is that the breakpoints it produces will sometimes fail to be evaluate and trigger a break. Annoying sometimes.
A: bp @@( MyClass::MyMethod ) break on methods (useful if the same method is overloaded and thus present on several addresses)
A: Search your dll for all entry point matching your symbol
x myexe!displayerror
this will output all symbols matching the search string and their entry points, then set the breakpoint on the address
bp ff3c6100 // for myexe!displayError (int, HRESULT, wchar_t *)
This will set a specific breakpoint when that address is hit, or you set bp against the other address. You can set the breakpoint to just hit once, clear the breakpoint and exit
bp /1 ff3c6100
and you can also execute commands such as dump the call stack, variables and continue:
bp ff3c6100 "kb;dv;g"
You may also just open your source code when WinDbg is attached, navigate to the line of code you want to set the breakpoint on and hit F9 (same as you would do using Visual Studio), it will pause for a while before setting a breakpoint at that line, this assumes you have access to the source code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Truncating Method calls This is a subjective question as I want to gauge if it's worth me moaning at my co-workers for doing something which I find utterly detestable.
The issue is that a bunch of my co-workers will truncate method calls to fit a width. We all use widescreen laptops that can handle large resolutions (mine is 1920x1200) and when it comes to debugging and reading code I find it much easier to read one line method calls as opposed to multiple line calls.
Here's an example of a method (how I would like it):
IReallyLongInterfaceName instanceOfInterfaceName = OurContainer.retrieveClass(IReallyLongInterfaceName.class, param1, param2, param3);
(I do hate really long interface/class names as well :)
It seems that this doesn't render well on StackOverflow, but I think most of you know what I mean. Anyway, some of the other devs do the following.
IReallyLongInterfaceName instanceOfInterfaceName = OurContainer.retrieveClass(IReallyLongInterfaceName.class,
param1,
param2,
param3);
Which is the easier to read at the end of the day for you and would I be unreasonable in asking them to use the first of the two (as it is part of our standard)?
A: I find the first example more readable in general, though if it is longer than some predefined limit (120 characters, for me), I would break the lines:
IReallyLongInterfaceName instanceOfInterfaceName =
OurContainer.retrieveClass(IReallyLongInterfaceName.class,
param1, param2, param3);
A: Maybe you should have as part of your standard build process some sort of checkstyle plugin which checks for exactly that kind of thing? If you've agreed the standard with your co-workers it seems reasonable to ask them to keep to it.
I personally find the second of the two options the more readable, but that's just because I don't have a widescreen monitor ;)
A: If its exlicitly stated in the companies coding standard that method one is the correct method then by all means moan at them, after all they are not adhering to the company standards.
If its not exlicitly stated then I guess now would be a good time to get it into the standard.
One thing to be aware of though, if you are using an IDE with autoformatting is that it may take it upon itself to reformat the methods to style 2 when its run.
So even if everyone is writing to style 1, it may not end up looking like that when they are finished with it.
and like Phil, I find method 2 much more readable, since you can see everything you need to see without having to scroll your eyes sideways :)
A: I prefer the second example. Even though you may have widescreen laptops, you might not always have windows full screen, or in your IDE you may have a lot of other panels around the main coding area that reduce the available width for displaying code.
If the line can't fit without scrolling, then vertical scrolling is preferable to horizontal scrolling. Since we read left-to-right, horizontal scrolling would mean moving backwards and forwards all the time.
I prefer one parameter per line to Avi's suggestion, which is arbitrary to me. If you spread the parameters over multiple lines but have several on each line, it makes it more difficult to find particular parameters when reading the code.
A: I prefer option #2, as well. The issue isn't just how it looks on screen (and if I had 1920 horizontal pixels, I'd have a lot more docked windows), it's how it looks if I need to print it and read it. Long lines will print terribly out of most IDEs, whereas lines broken by an author with the intent to improve legibility will print well.
Another point is general legibility. There's a reason magazines and newspapers are printed in columns -- generally, readability of text (particularly text on-screen) is improved by shorter lines and better layout/formatting.
I think 80 might be overly arbitrary, but I'm using 10pt Consolas, and I seem to be able to get about 100 characters per line on a standard 8.5" printed page.
Now at the end of the day, this is a holy war. Maybe not as bad as where to put your curly braces, but it's up there. I've given you my preference, but the real question goes back to you: What's your company's standard? It sounds to me like they've standardized on option #2, which means for the sake of the team, you should probably adapt to them.
A: I prefer option 2, but optionally with comments for parameters where the variable name is not obvious. When you have a function call that is asking for a bunch of parameters, it can be pretty hard for reviewers to tell what the code is doing.
So, I generally code like this if there are more than 3 parameters to a given function:
applyEncryptionParameters(key,
certificate,
0, // strength - set to 0 to accept default for platform
algorithm);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I maintain history of a file that is moved to a directory overwriting a file of the same name Consider the following subversion directory structure
/dir1/file.txt
/dir2/file.txt
I want to move the file.txt in dir1 to replace the same file in dir2 and ensure that the history for the dir1 file is maintained. I don't care about the history of original dir2 file.
Is this possible using subversion commands and not hacking the backend?
A: Firstly you should never consider hacking the backend - it negates the point of using SVN in the first place.
I don't see why you couldn't just do
svn rm /dir2/file.txt
svn mv /dir1/file.txt /dir2/file.txt
the history of the file will follow it after the move.
A: Try
*
*Delete dir2/file.txt and commit
*issue a svn move command to move dir1/file.txt to dir2/file.txt and commit - The history should be preserved.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SICP Exercise 1.3 request for comments I'm trying to learn scheme via SICP. Exercise 1.3 reads as follow: Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers. Please comment on how I can improve my solution.
(define (big x y)
(if (> x y) x y))
(define (p a b c)
(cond ((> a b) (+ (square a) (square (big b c))))
(else (+ (square b) (square (big a c))))))
A: Using only the concepts introduced up to that point of the text, which I think is rather important, here is a different solution:
(define (smallest-of-three a b c)
(if (< a b)
(if (< a c) a c)
(if (< b c) b c)))
(define (square a)
(* a a))
(define (sum-of-squares-largest a b c)
(+ (square a)
(square b)
(square c)
(- (square (smallest-of-three a b c)))))
A: (define (sum-sqr x y)
(+ (square x) (square y)))
(define (sum-squares-2-of-3 x y z)
(cond ((and (<= x y) (<= x z)) (sum-sqr y z))
((and (<= y x) (<= y z)) (sum-sqr x z))
((and (<= z x) (<= z y)) (sum-sqr x y))))
A: (define (f a b c)
(if (= a (min a b c))
(+ (* b b) (* c c))
(f b c a)))
A: Looks ok to me, is there anything specific you want to improve on?
You could do something like:
(define (max2 . l)
(lambda ()
(let ((a (apply max l)))
(values a (apply max (remv a l))))))
(define (q a b c)
(call-with-values (max2 a b c)
(lambda (a b)
(+ (* a a) (* b b)))))
(define (skip-min . l)
(lambda ()
(apply values (remv (apply min l) l))))
(define (p a b c)
(call-with-values (skip-min a b c)
(lambda (a b)
(+ (* a a) (* b b)))))
And this (proc p) can be easily converted to handle any number of arguments.
A: Using only the concepts presented at that point of the book, I would do it:
(define (square x) (* x x))
(define (sum-of-squares x y) (+ (square x) (square y)))
(define (min x y) (if (< x y) x y))
(define (max x y) (if (> x y) x y))
(define (sum-squares-2-biggest x y z)
(sum-of-squares (max x y) (max z (min x y))))
A: With Scott Hoffman's and some irc help I corrected my faulty code, here it is
(define (p a b c)
(cond ((> a b)
(cond ((> b c)
(+ (square a) (square b)))
(else (+ (square a) (square c)))))
(else
(cond ((> a c)
(+ (square b) (square a))))
(+ (square b) (square c)))))
A: You can also sort the list and add the squares of the first and second element of the sorted list:
(require (lib "list.ss")) ;; I use PLT Scheme
(define (exercise-1-3 a b c)
(let* [(sorted-list (sort (list a b c) >))
(x (first sorted-list))
(y (second sorted-list))]
(+ (* x x) (* y y))))
A: Here's yet another way to do it:
#!/usr/bin/env mzscheme
#lang scheme/load
(module ex-1.3 scheme/base
(define (ex-1.3 a b c)
(let* ((square (lambda (x) (* x x)))
(p (lambda (a b c) (+ (square a) (square (if (> b c) b c))))))
(if (> a b) (p a b c) (p b a c))))
(require scheme/contract)
(provide/contract [ex-1.3 (-> number? number? number? number?)]))
;; tests
(module ex-1.3/test scheme/base
(require (planet "test.ss" ("schematics" "schemeunit.plt" 2))
(planet "text-ui.ss" ("schematics" "schemeunit.plt" 2)))
(require 'ex-1.3)
(test/text-ui
(test-suite
"ex-1.3"
(test-equal? "1 2 3" (ex-1.3 1 2 3) 13)
(test-equal? "2 1 3" (ex-1.3 2 1 3) 13)
(test-equal? "2 1. 3.5" (ex-1.3 2 1. 3.5) 16.25)
(test-equal? "-2 -10. 3.5" (ex-1.3 -2 -10. 3.5) 16.25)
(test-exn "2+1i 0 0" exn:fail:contract? (lambda () (ex-1.3 2+1i 0 0)))
(test-equal? "all equal" (ex-1.3 3 3 3) 18))))
(require 'ex-1.3/test)
Example:
$ mzscheme ex-1.3.ss
6 success(es) 0 failure(s) 0 error(s) 6 test(s) run
0
A: It's nice to see how other people have solved this problem. This was my solution:
(define (isGreater? x y z)
(if (and (> x z) (> y z))
(+ (square x) (square y))
0))
(define (sumLarger x y z)
(if (= (isGreater? x y z) 0)
(sumLarger y z x)
(isGreater? x y z)))
I solved it by iteration, but I like ashitaka's and the (+ (square (max x y)) (square (max (min x y) z))) solutions better, since in my version, if z is the smallest number, isGreater? is called twice, creating an unnecessarily slow and circuitous procedure.
A: big is called max. Use standard library functionality when it's there.
My approach is different. Rather than lots of tests, I simply add the squares of all three, then subtract the square of the smallest one.
(define (exercise1.3 a b c)
(let ((smallest (min a b c))
(square (lambda (x) (* x x))))
(+ (square a) (square b) (square c) (- (square smallest)))))
Whether you prefer this approach, or a bunch of if tests, is up to you, of course.
Alternative implementation using SRFI 95:
(define (exercise1.3 . args)
(let ((sorted (sort! args >))
(square (lambda (x) (* x x))))
(+ (square (car sorted)) (square (cadr sorted)))))
As above, but as a one-liner (thanks synx @ freenode #scheme); also requires SRFI 1 and SRFI 26:
(define (exercise1.3 . args)
(apply + (map! (cut expt <> 2) (take! (sort! args >) 2))))
A: What about something like this?
(define (p a b c)
(if (> a b)
(if (> b c)
(+ (square a) (square b))
(+ (square a) (square c)))
(if (> a c)
(+ (square a) (square b))
(+ (square b) (square c)))))
A: I did it with the following code, which uses the built-in min, max, and square procedures. They're simple enough to implement using only what's been introduced in the text up to that point.
(define (sum-of-highest-squares x y z)
(+ (square (max x y))
(square (max (min x y) z))))
A: (define (sum a b) (+ a b))
(define (square a) (* a a))
(define (greater a b )
( if (< a b) b a))
(define (smaller a b )
( if (< a b) a b))
(define (sumOfSquare a b)
(sum (square a) (square b)))
(define (sumOfSquareOfGreaterNumbers a b c)
(sumOfSquare (greater a b) (greater (smaller a b) c)))
A: I've had a go:
(define (procedure a b c)
(let ((y (sort (list a b c) >)) (square (lambda (x) (* x x))))
(+ (square (first y)) (square(second y)))))
A: ;exercise 1.3
(define (sum-square-of-max a b c)
(+ (if (> a b) (* a a) (* b b))
(if (> b c) (* b b) (* c c))))
A: I think this is the smallest and most efficient way:
(define (square-sum-larger a b c)
(+
(square (max a b))
(square (max (min a b) c))))
A: Below is the solution that I came up with. I find it easier to reason about a solution when the code is decomposed into small functions.
; Exercise 1.3
(define (sum-square-largest a b c)
(+ (square (greatest a b))
(square (greatest (least a b) c))))
(define (greatest a b)
(cond (( > a b) a)
(( < a b) b)))
(define (least a b)
(cond ((> a b) b)
((< a b) a)))
(define (square a)
(* a a))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: C++ class initialisation containing class variable initialization I noticed some code of a colleague today that initialized class variables in the initialization. However it was causing a warning, he says because of the order they are in. My question is why is it better to do variable initialization where it currently is and not within the curly brackets?
DiagramScene::DiagramScene( int slideNo, QRectF screenRect, MainWindow* parent )
: QGraphicsScene( screenRect, parent ),
myParent( parent ),
slideUndoImageCurrentIndex(-1),
nextGroupID(0),
m_undoInProgress(false),
m_deleteItemOnNextUndo(0)
line(0),
path(0)
{
/* Setup default brush for background */
scDetail->bgBrush.setStyle(Qt::SolidPattern);
scDetail->bgBrush.setColor(Qt::white);
setBackgroundBrush(scDetail->bgBrush);
}
A: It's better to do the initialization of the members in the initialization list because the members are then only initialized once. This can be a huge difference in performance (and even behavior) if the members are classes themselves. If the members are all non-const, non-reference fundamental data types, then the difference is usually negligible.
NOTE: There are times where initialization lists are required for fundamental data types -- specifically if the type is constant or a reference. For these types, the data can only be initialized once and thus it cannot be initialized in the body of the constructor. See this article for more information.
Note that the initialization order of the members is the order the members are declared in the class definition, not the order the members are declared in the initialization list. If the warning can be fixed by changing the order of the initialization list, then I highly recommend that you do so.
It's my recommendation that:
*
*You learn to like initialization lists.
*Your co-worker understand the rules for initialization order of members (and avoid warnings).
A: In addition to Greg Hewgill's excellent answer - const variables must be set in the initialisation list.
A: *
*It is more efficient (in general). All members of a class are initialised in the constructor, whether you explicitly initialise them or not. If you do not specify an initialiser, then the default constructor of the member is run. If you assign a value in the constructor body, then the assignment operator is called again. This does not apply to scalar values, as in your example, since scalar values do not have constructors.
*You can't accidentally assign a value twice in the initialiser list.
*The compiler can check to make sure that the order in which you write the initialisers matches the order in which the members are defined in the class. The C++ standard requires that the members are initialised in the order they are declared, regardless of the order you write the initialisers. Having the compiler check this order ensures that the programmer knows which order the initialisers will be run in (again, this is more important for non-POD members than for scalars).
*Reference types and const members must be initialised in the initialiser list, because you can't assign to a reference or to a const member.
A: Because, in the constructor's body ("within the curly brackets") the member variables are already default-constructed. That may have some performance implications, when you have a member variable of a type that has non-trivial construction, when you first have it default-constructed and then you assign it some other value in the constructor, when you could have custom-construct it directly.
Also, some types may not be default-constructed (for example references) and must be constructed in the initialization list.
A: If you have const variables, their value can not be set via assignment.
The initialization is also a bit more efficient when assigning values to objects (not built-ins or intrinsics) as a temporary object is not created like it would be for an assignment.
See C++ FAQ-Lite for more details
A: Take a look at the collected wisdom at http://web.tiscali.it/fanelia/cpp-faq-en/ctors.html#faq-10.6
A: Another addition to Greg's answer: members that are of types with no default constructor must be initialized in initialization list.
A: Greg Hegwell's answer contains some excellent advice, but it doesn't explain why the compiler is generating a warning.
When the initializer list of a constructor is processed by the compiler, the items are initialized in the order they are declared in the class declaration, not in the order they appear in the initializer list.
Some compilers generate a warning if the order in the initializer list is different from the declaration order (so you won't be surprised when items are not initialized in the order of the list). You don't include your class declaration, but this is the likely cause of the warning you're seeing.
The rationale for this behavior is that the members of a class should always be initialized in the same order: even when the class has more than one constructor (which could have the members ordered differently in their initializer lists).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Home/End keys in zsh don't work with putty I'm running zsh as the default shell on a Ubuntu box, and everything works fine using gnome-terminal (which as far as I know emulates xterm). When I login from a windows box via ssh and putty (which also emulates xterm) suddendly the home/end keys no longer work.
I've been able to solve that adding these lines to my zshrc file...
bindkey '\e[1~' beginning-of-line
bindkey '\e[4~' end-of-line
...but I'm still wondering what's wrong here. Any idea?
A: I found it's a combination:
One
The ZSH developers do not think that ZSH should define the actions of the Home, End, Del, ... keys.
Debian and Ubuntu fix this by defining the normal actions the average user would expect in the global /etc/zsh/zshrc file. Following the relevant code (it is the same on Debian and Ubuntu):
if [[ "$TERM" != emacs ]]; then
[[ -z "$terminfo[kdch1]" ]] || bindkey -M emacs "$terminfo[kdch1]" delete-char
[[ -z "$terminfo[khome]" ]] || bindkey -M emacs "$terminfo[khome]" beginning-of-line
[[ -z "$terminfo[kend]" ]] || bindkey -M emacs "$terminfo[kend]" end-of-line
[[ -z "$terminfo[kich1]" ]] || bindkey -M emacs "$terminfo[kich1]" overwrite-mode
[[ -z "$terminfo[kdch1]" ]] || bindkey -M vicmd "$terminfo[kdch1]" vi-delete-char
[[ -z "$terminfo[khome]" ]] || bindkey -M vicmd "$terminfo[khome]" vi-beginning-of-line
[[ -z "$terminfo[kend]" ]] || bindkey -M vicmd "$terminfo[kend]" vi-end-of-line
[[ -z "$terminfo[kich1]" ]] || bindkey -M vicmd "$terminfo[kich1]" overwrite-mode
[[ -z "$terminfo[cuu1]" ]] || bindkey -M viins "$terminfo[cuu1]" vi-up-line-or-history
[[ -z "$terminfo[cuf1]" ]] || bindkey -M viins "$terminfo[cuf1]" vi-forward-char
[[ -z "$terminfo[kcuu1]" ]] || bindkey -M viins "$terminfo[kcuu1]" vi-up-line-or-history
[[ -z "$terminfo[kcud1]" ]] || bindkey -M viins "$terminfo[kcud1]" vi-down-line-or-history
[[ -z "$terminfo[kcuf1]" ]] || bindkey -M viins "$terminfo[kcuf1]" vi-forward-char
[[ -z "$terminfo[kcub1]" ]] || bindkey -M viins "$terminfo[kcub1]" vi-backward-char
# ncurses fogyatekos
[[ "$terminfo[kcuu1]" == "^[O"* ]] && bindkey -M viins "${terminfo[kcuu1]/O/[}" vi-up-line-or-history
[[ "$terminfo[kcud1]" == "^[O"* ]] && bindkey -M viins "${terminfo[kcud1]/O/[}" vi-down-line-or-history
[[ "$terminfo[kcuf1]" == "^[O"* ]] && bindkey -M viins "${terminfo[kcuf1]/O/[}" vi-forward-char
[[ "$terminfo[kcub1]" == "^[O"* ]] && bindkey -M viins "${terminfo[kcub1]/O/[}" vi-backward-char
[[ "$terminfo[khome]" == "^[O"* ]] && bindkey -M viins "${terminfo[khome]/O/[}" beginning-of-line
[[ "$terminfo[kend]" == "^[O"* ]] && bindkey -M viins "${terminfo[kend]/O/[}" end-of-line
[[ "$terminfo[khome]" == "^[O"* ]] && bindkey -M emacs "${terminfo[khome]/O/[}" beginning-of-line
[[ "$terminfo[kend]" == "^[O"* ]] && bindkey -M emacs "${terminfo[kend]/O/[}" end-of-line
fi
So, if you are connecting to a Debian or Ubuntu box, you don't have to do anything. Everything should work automagically (if not, see below).
But... if you are connecting to another box (e.g. FreeBSD), there might be no user friendly default zshrc. The solution is of course to add the lines from the Debian/Ubuntu zshrc to your own .zshrc.
Two
Putty sends xterm as terminal type to the remote host. But messes up somewhere and doesn't send the correct control codes for Home, End, ... that one would expect from an xterm. Or an xterm terminal isn't expected to send those or whatever... (Del key does work in xterm however, if you configure it in ZSH). Also notice that your Numpad-keys act funny in Vim for example with xterm terminal.
The solution is to configure Putty to send another terminal type. I've tried xterm-color and linux. xterm-color fixed the Home/End problem, but the Numpad was still funny. Setting it to linux fixed both problems.
You can set terminal type in Putty under Connection -> Data. Do not be tempted to set your terminal type in your .zshrc with export TERM=linux, that is just wrong. The terminal type should be specified by your terminal app. So that if, for example, you connect from a Mac box with a Mac SSH client it can set it's own terminal type.
Notice that TERM specifies your terminal type and has nothing to do with the host you are connecting to. I can set my terminal type to linux in Putty and connect to FreeBSD servers without problems.
So, fix both these things and you should be fine :)
A: This is working for me
bindkey -v
bindkey '\eOH' beginning-of-line
bindkey '\eOF' end-of-line
A: It's now been nearly 11 years since this question was first posted. At the time, some distros did ship with a putty terminfo entry, but it was mediocre at best. In the years since, the situation has improved, and the hacks that were necessary for over a decade are no longer required. PuTTY still defaults to setting TERM to xterm for compatibility, but if you're connecting to modern, up-to-date systems, you'll likely have luck overriding this and setting it to putty-256color:
*
*Ensure the host has a terminfo entry for putty-256color: toe -a | grep -F putty
*Undo any hacks you may have enabled to get PuTTY working properly with zsh or other programs.
*Ensure PuTTY is up-to-date. It won't notify you when updates are available, and if it's out-of-date, you're likely going to run into a lot of the same issues. You may want to keep it up-to-date automatically with something like Chocolatey.
*In PuTTY's configuration dialog, go to Connection -> Data and set "Terminal-type string" to putty-256color.
*While you're at it, on the same configuration screen, add a new environment variable to enable 24-bit color. This variable isn't standardized, but it's sent by a number of other mainstream terminal emulators (e.g., iTerm2), and many programs understand it.
*
*Variable: COLORTERM
*Value: truecolor
*As of writing, I haven't found a distro that accepts the COLORTERM variable over SSH by default. You'll need to edit your OpenSSH configuration on the host to allow it. For example, on Debian-like distros, edit /etc/ssh/sshd_config and add COLORTERM to the AcceptEnv line.
*Everything should now "just work". If it doesn't:
*
*Ensure you've reconnected after making the change, or at least run exec zsh after changing TERM. zsh won't react to changes in TERM while it's running.
*Ensure that TERM is actually set to what you intended: echo $TERM
*Are you on the latest version of your distro? If you're on a long-term support lifecycle build, for example, even if your version is technically still supported, it may not have up-to-date terminfo entries.
*Are you using screen or tmux? That's another whole can of worms. Test without those first to narrow down where the issue is occurring. Within tmux, try setting TERM=tmux-256color. Within screen, try TERM=screen-256color.
*Are you on the latest version of PuTTY?
*Do you have RC-files that are implementing keybindings or other hacks? Try using default RC-files.
*Did you already change various PuTTY settings to attempt to fix the issue before attempting the terminfo fix? You'll probably need to reset those settings.
A: the appropriate answer that should be portable across all distros (not necessarly all versions of zsh though, ymmv here) is to use the zkbd helper utility from zkbd.
Keyboard Definition
The large number of possible combinations of keyboards, workstations, terminals, emulators, and window systems makes it impossible for zsh to have built-in key bindings for every situation. The zkbd utility, found in Functions/Misc, can help you quickly create key bindings for your configuration.
Run zkbd either as an autoloaded function, or as a shell script:
zsh -f ~/zsh-4.3.17/Functions/Misc/zkbd
When you run zkbd, it first asks you to enter your terminal type; if the default it offers is correct, just press return. It then asks you to press a number of different keys to determine characteristics of your keyboard and terminal; zkbd warns you
if it finds anything out of the ordinary, such as a Delete key that sends neither ^H nor ^?.
The keystrokes read by zkbd are recorded as a definition for an associative array named key, written to a file in the subdirectory .zkbd within either your HOME or ZDOTDIR directory. The name of the file is composed from the TERM, VENDOR and OSTYPE
parameters, joined by hyphens.
You may read this file into your .zshrc or another startup file with the source or . commands, then reference the key parameter in bindkey commands, like this:
source ${ZDOTDIR:-$HOME}/.zkbd/$TERM-$VENDOR-$OSTYPE
[[ -n ${key[Left]} ]] && bindkey "${key[Left]}" backward-char
[[ -n ${key[Right]} ]] && bindkey "${key[Right]}" forward-char
# etc.
Note that in order for autoload zkbd to work, the zkbd file must be in one of the directories named in your fpath array (see zshparam(1)). This should already be the case if you have a standard zsh installation; if it is not, copy Functions/Misc/zkbd to an appropriate directory.
see man -P "less -p 'keyboard definition'" zshcontrib, or search the meta-manpage zshall
A: It seems a putty thing. Gnome-terminal sends the codes ^[OH and ^[OF for Home and End respectively, while putty sends ^[[1~ and ^[[4~. There's an option in putty to change the Home/End keys from standard mode to rxvt mode, and that seems to fix the Home key, but not the End key (which now sends ^[Ow). Guess it's time to file a bug report somewhere... :-)
A: On the PuTTY configuration dialog, go to Connection -> Data and type linux into the Terminal-type string before connecting.
A: These bindings simply don't appear to be part of the default bindings set in emacs mode.
executing "where-is beginning-of-line" on my default zsh installation after running "bindkey -e" shows it is only bound to ^a. Perhaps you should ask the zsh developers why :-)
A: This worked for me.
Adding these lines to ~/.zshrc
bindkey "\e[1;5D" backward-word
bindkey "\e[1;5C" forward-word
# ctrl-bs and ctrl-del
bindkey "\e[3;5~" kill-word
bindkey "\C-_" backward-kill-word
# del, home and end
bindkey "\e[3~" delete-char
bindkey "\e[H" beginning-of-line
bindkey "\e[F" end-of-line
# alt-bs
bindkey "\e\d" undo
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
} |
Q: iCalendar Format (Outlook 2007) I've got a little problem, I need to be able to have a reoccurring event (forever) that marks the day after the second Tuesday of each month.
Your probably thinking, why not just Wednesday of each month.
October 2008 is an example, it starts on a Wednesday. :(
Really I just need it in Outlook, probably (but not limited to) some iCalendar format file.
A: The following iCalendar rule should work:
RRULE:FREQ=MONTHLY;BYDAY=WE;BYMONTHDAY=9,10,11,12,13,14,15
It should be read as "The first Wednesday of every month that falls on the 9th or later".
Edit: To use, create a calendar with a recurring event and export it to .ics. Open the ics file, find the existing RRULE, replace it with this one and import the ics back into outlook.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: GWT Table that supports sorting, scrolling and filtering I have a project using GWT and it displays data in a table.
I need a Table for GWT that supports:
*
*sorting by particular column
*scrolling the data, while the header is immobile
*filtering rows for data searched in the table
The project is being created for internal purpose of the company, so I look for a solution that does not require commercial licensing for such uses.
A: The standard CellTable supports sorting.
(Hopefully more features will come soon.)
A: Here is a table supporting sorting and filtering : http://code.google.com/p/gwt-advanced-table/
Google itself is working on it. Look at this example in the incubator which supports multi-column sorting and fixed header but unfortunately no filtering : http://code.google.com/p/google-web-toolkit-incubator/wiki/ScrollTable
Other grids and tables are available in the incubator at this address : http://code.google.com/docreader/#p=google-web-toolkit-incubator&s=google-web-toolkit-incubator&t=Tables
Ext GWT proposes a very nice table, but it is not free (in your case) : http://extjs.com/products/gxt/
A: There is also EXT GWT (not to be confused with GWT EXT), build entirely in Java. You may have the pay for the license though. I do not known if you have to pay if the application is of internal use.
The Grid widget will do exactly want you want.
The rest of their widgets are also quite impressive.
A: Just to keep this up to date:
CellTable now supports paging and single column sorting: https://developers.google.com/web-toolkit/doc/latest/DevGuideUiCellTable?hl=de
You may want to adapt yout backend request for filtering, as this is usually more performant.
A: GWT Ext provides a table that meets these requirements.
It provides a wrapper around the Ext javascript library, so its best to commit to using either only GWT Ext widgets, or GWT widgests. They can be combined, but sometimes don't play well with each other.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Perl Challenge - Directory Iterator You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
A: There aren't six ways to do this, there's the old way, and the new way. The old way is with File::Find, and you already have a couple of examples of that. File::Find has a pretty awful callback interface, it was cool 20 years ago, but we've moved on since then.
Here's a real life (lightly amended) program I use to clear out the cruft on one of my production servers. It uses File::Find::Rule, rather than File::Find. File::Find::Rule has a nice declarative interface that reads easily.
Randal Schwartz also wrote File::Finder, as a wrapper over File::Find. It's quite nice but it hasn't really taken off.
#! /usr/bin/perl -w
# delete temp files on agr1
use strict;
use File::Find::Rule;
use File::Path 'rmtree';
for my $file (
File::Find::Rule->new
->mtime( '<' . days_ago(2) )
->name( qr/^CGItemp\d+$/ )
->file()
->in('/tmp'),
File::Find::Rule->new
->mtime( '<' . days_ago(20) )
->name( qr/^listener-\d{4}-\d{2}-\d{2}-\d{4}.log$/ )
->file()
->maxdepth(1)
->in('/usr/oracle/ora81/network/log'),
File::Find::Rule->new
->mtime( '<' . days_ago(10) )
->name( qr/^batch[_-]\d{8}-\d{4}\.run\.txt$/ )
->file()
->maxdepth(1)
->in('/var/log/req'),
File::Find::Rule->new
->mtime( '<' . days_ago(20) )
->or(
File::Find::Rule->name( qr/^remove-\d{8}-\d{6}\.txt$/ ),
File::Find::Rule->name( qr/^insert-tp-\d{8}-\d{4}\.log$/ ),
)
->file()
->maxdepth(1)
->in('/home/agdata/import/logs'),
File::Find::Rule->new
->mtime( '<' . days_ago(90) )
->or(
File::Find::Rule->name( qr/^\d{8}-\d{6}\.txt$/ ),
File::Find::Rule->name( qr/^\d{8}-\d{4}\.report\.txt$/ ),
)
->file()
->maxdepth(1)
->in('/home/agdata/redo/log'),
) {
if (unlink $file) {
print "ok $file\n";
}
else {
print "fail $file: $!\n";
}
}
{
my $now;
sub days_ago {
# days as number of seconds
$now ||= time;
return $now - (86400 * shift);
}
}
A: File::Find is the right way to solve this problem. There is no use in reimplementing stuff that already exists in other modules, but reimplementing something that is in a standard module should really be discouraged.
A: Others have mentioned File::Find, which is the way I'd go, but you asked for an iterator, which File::Find isn't (nor is File::Find::Rule). You might want to look at File::Next or File::Find::Object, which do have an iterative interfaces. Mark Jason Dominus goes over building your own in chapter 4.2.2 of Higher Order Perl.
A: My preferred method is to use the File::Find module as so:
use File::Find;
find (\&checkFile, $directory_to_check_recursively);
sub checkFile()
{
#examine each file in here. Filename is in $_ and you are chdired into it's directory
#directory is also available in $File::Find::dir
}
A: There's my File::Finder, as already mentioned, but there's also my iterator-as-a-tied-hash solution from Finding Files Incrementally (Linux Magazine).
A: I wrote File::Find::Closures as a set of closures that you can use with File::Find so you don't have to write your own. There's a couple of mtime functions that should handle
use File::Find;
use File::Find::Closures qw(:all);
my( $wanted, $list_reporter ) = find_by_modified_after( time - 86400 );
#my( $wanted, $list_reporter ) = find_by_modified_before( time - 86400 );
File::Find::find( $wanted, @directories );
my @modified = $list_reporter->();
You don't really need to use the module because I mostly designed it as a way that you could look at the code and steal the parts that you wanted. In this case it's a little trickier because all the subroutines that deal with stat depend on a second subroutine. You'll quickly get the idea from the code though.
Good luck,
A: This sounds like a job for File::Find::Rule:
#!/usr/bin/perl
use strict;
use warnings;
use autodie; # Causes built-ins like open to succeed or die.
# You can 'use Fatal qw(open)' if autodie is not installed.
use File::Find::Rule;
use Getopt::Std;
use constant SECONDS_IN_DAY => 24 * 60 * 60;
our %option = (
m => 1, # -m switch: days ago modified, defaults to 1
o => undef, # -o switch: output file, defaults to STDOUT
);
getopts('m:o:', \%option);
# If we haven't been given directories to search, default to the
# current working directory.
if (not @ARGV) {
@ARGV = ( '.' );
}
print STDERR "Finding files changed in the last $option{m} day(s)\n";
# Convert our time in days into a timestamp in seconds from the epoch.
my $last_modified_timestamp = time() - SECONDS_IN_DAY * $option{m};
# Now find all the regular files, which have been modified in the last
# $option{m} days, looking in all the locations specified in
# @ARGV (our remaining command line arguments).
my @files = File::Find::Rule->file()
->mtime(">= $last_modified_timestamp")
->in(@ARGV);
# $out_fh will store the filehandle where we send the file list.
# It defaults to STDOUT.
my $out_fh = \*STDOUT;
if ($option{o}) {
open($out_fh, '>', $option{o});
}
# Print our results.
print {$out_fh} join("\n", @files), "\n";
A: Where the problem is solved mainly by standard libraries use them.
File::Find in this case works nicely.
There may be many ways to do things in perl, but where a very standard library exists to do something, it should be utilised unless it has problems of it's own.
#!/usr/bin/perl
use strict;
use File::Find();
File::Find::find( {wanted => \&wanted}, ".");
sub wanted {
my (@stat);
my ($time) = time();
my ($days) = 5 * 60 * 60 * 24;
@stat = stat($_);
if (($time - $stat[9]) >= $days) {
print "$_ \n";
}
}
A: Using standard modules is indeed a good idea but out of interest here is my back to basic approach using no external modules. I know code syntax here might not be everyone's cup of tea.
It could be improved to use less memory via providing an iterator access (input list could temporarily be on hold once it reaches a certain size) and conditional check can be expanded via callback ref.
sub mfind {
my %done;
sub find {
my $last_mod = shift;
my $path = shift;
#determine physical link if symlink
$path = readlink($path) || $path;
#return if already processed
return if $done{$path} > 1;
#mark path as processed
$done{$path}++;
#DFS recursion
return grep{$_} @_
? ( find($last_mod, $path), find($last_mod, @_) )
: -d $path
? find($last_mod, glob("$path/*") )
: -f $path && (stat($path))[9] >= $last_mod
? $path : undef;
}
return find(@_);
}
print join "\n", mfind(time - 1 * 86400, "some path");
A: I'm riskying to get downvoted, but IMHO 'ls' (with appropriate params) command does it in a best known performant way. In this case it might be quite good solution to pipe 'ls' from perl code through shell, returning results to an array or hash.
Edit: It could also be 'find' used, as proposed in comments.
A: I write a subroutine that reads a directory with readdir, throws out the "." and ".." directories, recurses if it finds a new directory, and examines the files for what I'm looking for (in your case, you'll want to use utime or stat). By time the recursion is done, every file should have been examined.
I think all the functions you'd need for this script are described briefly here:
http://www.cs.cf.ac.uk/Dave/PERL/node70.html
The semantics of input and output are a fairly trivial exercise which I'll leave to you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Best Linux Distro for Web Development? I want to start learning HTML and AJAX using a Linux distribution.
Can anyone recommend a distribution that has these requirements:
*
*Local Host Admin interface (like PHPmyAdmin)
*IDE for Javascript... etc
A: First question - Why do you want to do this on Linux? You can do basic AJAX requests from any platform, simply drop in your JavaScript framework of choice (JQuery, Prototype, or even MooTools and you can be up and running on your existing development platform.
Get familiar with a decent editor, one that will provide basic syntax coloring for you. One tool you may want to look at is the Aptana web development IDE that is based on Eclipse. This will give you the capability to write and debug any AJAX work you do as well as provide you some documentation and access to other dynamic languages like PHP, Rails, Python as well as a basic HTML editor.
That should square you away more than enough for what you're looking to do.
A: I just setup my first linux hosting to do the same thing. I did a lot of looking around and was recommended by articles and friends to use Ubuntu. So I did and everything has been working just great.
I'm using slicehost They have lots of tutorials to get you going.
http://articles.slicehost.com/ubuntu-gutsy
A: There is no real best distro for web development.
All tools you need will run on any linux distro.
Pick something you have experience with.
If you don't have any experience I'd recommend one of the 'user friendly' distros like Ubuntu or SuSe.
A: I can't think of many distributions that won't do what you need. I'd suggest something that has a good package manager, and, works well on your hardware. There will be plenty of choice for your requirements with all the major distributions.
What are you currently using ?
Andrew
A: Ubuntu should get the job done but you might consider a slightly more server oriented distro. In my shop, we use CentOS 5 which is more of an enterprise-oriented distro.
A: It exists specialized distributions:
The best one for me: Noys
http://www.noysweb.net/
Other one is Excelixis:
http://excelixis.wordpress.com/excelixis/
Cheers
A: HTML and AJAx don't need to be on any particular distribution, Ubuntu makes it pretty easy to install all the required features. I like fedora personally.
Try http://www.eclipse.org/webtools and http://www.zend.com/phpide although screem http://www.screem.org/ may well do what you need if it is purely html, javascript and css
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How can I speed up my maven2 build? I'm using a local artifactory to proxy the request, but the build and test phases are still a bit slow. It's not the actual compile and tests that are slow, it's the "warmup" of the maven2 framework. Any ideas?
A: I don't know what version of Maven you are using, I assume 2, but I will give what I use for Maven 1.x to speed up and make things build a tiny bit quicker.
These will fork the junit tests into a new process (also helps when you use environment variables in tests etc and gives the tests a little more memory.
-Dmaven.junit.fork=true
-Dmaven.junit.jvmargs=-Xmx512m
This forks the compilation which might speed things up for you
-Dmaven.compile.fork=true
I hope this can help a little, try it out.
Also refer to get more speed with your maven2 build.
A: If you are using Maven3 ($ mvn -version), you can also follow this guide. In my case, the results are:
Normal execution:
$ mvn clean install
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 03:05 min
[INFO] Finished at: 2015-07-15T11:47:02+02:00
[INFO] Final Memory: 88M/384M
With Parallel Processing (4 threads):
$ mvn -T 4 clean install
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 02:22 min (Wall Clock)
[INFO] Finished at: 2015-07-15T11:50:57+02:00
[INFO] Final Memory: 80M/533M
Parallel Processing (2 threads per core)
$ mvn -T 2C clean install
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 02:12 min (Wall Clock)
[INFO] Finished at: 2015-07-15T12:00:29+02:00
[INFO] Final Memory: 87M/519M
[INFO] ------------------------------------------------------------------------
As we can see, the difference it's almost a minute, near 20-30% of speed improvement.
A: *
*Adjust memory configurations to optimum for eg: add this line to mvn.bat
set MAVEN_OPTS=-Xmx512m -XX:MaxPermSize=256m
*Clean phase of mvn normally deletes target folder. Instead if we are renaming target folder the cleaning phase will be much faster.<quickClean>
*-Dmaven.test.skip=true will skip the test execution.
*Add -Denforcer.skip=true to mvn command line argument (This is enforcing versions of maven, jdk etc ,we can skip it after initial runs)
*Disable non-critical operations during build phase: Analysis, javadoc generation, source packaging. This will save huge time.
*Spawnig new process also helps in time improvement
-Dmaven.junit.fork=true (fork the junit tests into a new process)
-Dmaven.compile.fork=true (forks the compilation)
Hope it helps.
A: You can use -DskipTests=true to skip unit tests. which would speed up builds
A: There are some possibilities to optimize some of the build tasks. For example the 'clean' task can be optimized from minutes to just milliseconds using simple trick - rename 'target' folder instead of delete.
To get details how to do it refer to Speed up Maven build.
A: I've found that parsing reactor projects is significantly slower than single-pom projects. If your build is reactor (multi-module) and your developers are not working on all modules at the same time, you can remove the parent POM and build them separately, resolving the dependencies using the local repo. The disadvantage is that you need to install or deploy a module in order for its dependents to see the changes.
Also, you might want to look at the new Maven 2.1 M1 which contains some significant speed improvements.
If none of these helps, post more details about your project configuration (modules structure and plugins), command line parameters and hardware config (memory and disk). Running Maven with -X might also show where is it taking its time.
A: I'd use locally installed Nexus.
A: Initially, you should get a finer analysis on your build times using something like this and identify the candidates that are taking the most time.
Are tests spinning up a H2 database per test? Is the download of external jar files taking the time? This will guide where to focus your investigation. Just applying go-fast flags don't usually work as they would have already been included by default, and you don't want to be sacrificing your tests with skip flags.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
} |
Q: Using Generic lists on serviced component I'm trying to use a generic List as a property on a ServicedComponent class...
public class MyCOM : ServicedComponent {
public enum MyEnumType {
Value1, Value2, Value3
}
public List<MyEnumType> MyList { private set; get; }
public MyCOM()
{
MyList = new List<MyEnumType>();
}
}
The code compiles without errors but when I try to use the MyList property on the com object from a different class no values get added to the list. Google "told me" that I can't use Generics on Components but I'm yet to find a good explanation why that is and a good solution to the problem.
Can someone help me out?
A: From MSDN:
Interoperating Using Generic Types
The COM model does not support the
concept of generic types.
Consequently, generic types cannot be
used directly for COM interop.
The answer why generics are not supported is very simple, generics are types that are constructed at runtime, and because of this there's no static interface declaraion to the constructed type that COM can refer to. In your case List< MyEnumType > doesn't exist as a type Until the CLR constructs it, so COM can't refer to it with and identifier (GUID).
This is where the workaround comes from, if your generic types implement a non generic interface, then they can be used for com interop using the non generic interface.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the size limit of the application object in classic asp? I am creating an ASP script that uses the application object to store the pages. The question in my mind is whether there is a size limit to this object. Anyone know?
A: An application pool may specifiy the Maximum virtual memory size that a worker process can allocate. This is setting will affect the maximum size of data that the application object can hold.
If this setting is not specified (or is larger than 2GB) then another factor will be whether the process is running in 32 Bit mode. If so then you could only expect to get a maximum of 1.5GB (if that) in the application object regardless of how much memory is present on the server.
On 64 bit server running the worker process as a 64 bit process it would be able to consume as much RAM and pagefile that it can get.
A: I'm fairly sure there's no explicit limit - but of course at some point you will use up so much memory that you'll see other effects - e.g. your application being recycled because it has exceeded its memory limit, or your application grinding to a halt as the server runs out of memory.
A: I am pretty sure the limit is really the RAM of the hosting server. If you have a very large number of pages, using a database or files for less frequently accessed pages may be helpful, but i have never seen any specific issues with a hard limit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to remotely Start/Stop SQLServer services kicking off existing connections? I know there is already a question about this but my issue is more oriented to remote scenarios.
With net start/stop you can specify a /y parameter to bounce users off current sessions but you cannot start/stop remotely.
With sc you can start/stop remotely but if the SQLServer instance is being used it won't let you stop the service (with a "[SC] ControlService FAILED 1051: A stop control has been sent to a service that other running services are dependent on." message)
So my question is: what's the best way of kicking out users stopping the SqlServer service remotely?
A: I think the /y just answers Yes to the "Are you sure?" prompt. I'd think that sc could be used as well, though it may time out waiting for the service to stop if there's a lot of inflight transactions. Does it give you any specifics of why it can't stop?
Here's a couple of other methods to stop a remote SQL instance. Except for SHUTDOWN WITH NOWAIT, I'd recommend any of them.
*
*psexec will let you run net stop remotely.
*There's also the SQL SHUTDOWN command - you can issue that WITH NOWAIT to avoid waiting for current transactions to finish and checkpointing, which will make shutdown faster (but subsequent startup slower, and could lead to lost data).
*Or you could use either Configuration Manager or Management Studio to stop a remote instance.
Edit: The error is pretty self explanatory. It means you must stop dependent services first. Sql Agent is probably at least one of them. Checking Admin Tools->Services will show you the rest.
A: Using SSMS is the best make sure you have the proper privileges to shutdown and check to see the status of replications and ALWAYS ON and Log Shipping.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Adding and removing content in jQuery If I create a function with jQuery that adds an empty div, performs some animation inside the blank space created by the div, then removes the div, the browser never makes room for the empty div (height and width are set).
If I don't remove the empty div in my function, then the browser will create the needed space and everything works correctly. However, I really need the blank space created by the div to be removed when the animation is complete.
Is there a way to queue up the div removall so that the browser will show the desired behavior?
A: Some jQuery effects have callbacks, which will are run after the effect, for example:
$('#someDiv').slideDown(100, function() {
$(this).remove();
});
A: By doing a Google search on jQuery and setTimeout, I found an example which sent me down a different track. The problem occurs, I think, because the div manipulation is on a separate selector from the actual animation. This causes the div to be created and removed even while the animation is still occuring. By adding a simple animate statement to the div which delays the removal until after the main animation completes, then I can achieve the desired effect.
A: Doesn't it work if you use a setTimeout ?-)
A: The problem is that the DOM isn't updated until your function ends. So using setTimeout will cause the dom to update and 100ms later the rest of your function can continue. If you don't want the new div to be seen, I'd set the position to absolute and the top to something like -5000. It will have dimensions etc, just wont' be visible. You can also set the visibility (in css) to hidden just incase you are worried it will show up on screen.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What are the best ASP.NET performance counters to monitor? There are truckloads of counters available in perfmon for ASP.NET. What are the best (I am thinking of choosing 5-10) that will be the best to monitor in our test environment so that we can feed back to developers.
I am thinking of things like request time, request queue length, active sessions etc.
A: The ones I use the most are the memory counters. All of them. I know that they aren't specific to ASP.NET, but the only problems I've ever had with a web app were memory issues.
Excessive heap, gen 2 collections and % time in GC are the most important ones. If your time in GC is spiraling out of control it's a sign that your UI and viewstate are too big. A large heap and lots of gen 2 collections says you're keeping too much stuff in memory (inproc session state, for example).
Regular ASP.NET apps based on web controls require lots of objects being created and then destroyed quickly, as a page is reconstructed and then disposed. High gen0 collections isn't bad. Its when you start seeing lots of objects make it into gen1 and then gen2 that suggests you're either leaking memory or are holding onto too much state.
A: Be aware of memory counters when running more than one ASP.NET Application Pool
check out the problem at http://blog.dynatrace.com/2009/02/27/can-you-trust-your-net-heap-performance-counters/
A: For a normal (not performance/stress testing) you would be OK with the following:
*
*Request Bytes Out Total (very important especially for web (not intranet) applications)
*Requests Failed
*Requests/Sec
*Errors During Execution
*Errors Unhandled During Execution
*Session SQL Server Connections Total
*State Server Sessions Active
For the performance testing you would probably want things like:
*
*% CPU Utilization (make sure you're checking for very low CPU utilisation as well as it might indicate that something is dead)
*Requests Queued
*Output Cache Hits
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: What is the best regular expression to check if a string is a valid URL? How can I check if a given string is a valid URL address?
My knowledge of regular expressions is basic and doesn't allow me to choose from the hundreds of regular expressions I've already seen on the web.
A: What platform? If using .NET, use System.Uri.TryCreate, not a regex.
For example:
static bool IsValidUrl(string urlString)
{
Uri uri;
return Uri.TryCreate(urlString, UriKind.Absolute, out uri)
&& (uri.Scheme == Uri.UriSchemeHttp
|| uri.Scheme == Uri.UriSchemeHttps
|| uri.Scheme == Uri.UriSchemeFtp
|| uri.Scheme == Uri.UriSchemeMailto
/*...*/);
}
// In test fixture...
[Test]
void IsValidUrl_Test()
{
Assert.True(IsValidUrl("http://www.example.com"));
Assert.False(IsValidUrl("javascript:alert('xss')"));
Assert.False(IsValidUrl(""));
Assert.False(IsValidUrl(null));
}
(Thanks to @Yoshi for the tip about javascript:)
A: function validateURL(textval) {
var urlregex = new RegExp(
"^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
return urlregex.test(textval);
}
Matches
http://site.com/dir/file.php?var=moo | ftp://user:pass@site.com:21/file/dir
Non-Matches
site.com | http://site.com/dir//
A: Here's what RegexBuddy uses.
(\b(https?|ftp|file)://)?[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]
It matches these below (inside the ** ** marks):
**http://www.regexbuddy.com**
**http://www.regexbuddy.com/**
**http://www.regexbuddy.com/index.html**
**http://www.regexbuddy.com/index.html?source=library**
**http://www.regexbuddy.com/index.html?source=library#copyright**
You can download RegexBuddy at http://www.regexbuddy.com/download.html.
A: If you really search for the ultimate match, you probably find it on "A Good Url Regular Expression?".
But a regex that really matches all possible domains and allows anything that is allowed according to RFCs is horribly long and unreadable, trust me ;-)
A: function validateURL(textval) {
var urlregex = new RegExp(
"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$");
return urlregex.test(textval);
}
Matches
http://www.asdah.com/~joe | ftp://ftp.asdah.co.uk:2828/asdah%20asdah.gif | https://asdah.gov/asdh-ah.as
A: Mathias Bynens has a great article on the best comparison of a lot of regular expressions: In search of the perfect URL validation regex
The best one posted is a little long, but it matches just about anything you can throw at it.
JavaScript version
/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i
PHP version (uses % symbol as delimiter)
%^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\x{00a1}-\x{ffff}][a-z0-9\x{00a1}-\x{ffff}_-]{0,62})?[a-z0-9\x{00a1}-\x{ffff}]\.)+(?:[a-z\x{00a1}-\x{ffff}]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$%iuS
A: I hope it's helpful for you...
^(http|https):\/\/+[\www\d]+\.[\w]+(\/[\w\d]+)?
A: Here is a regex I made which extracts the different parts from an URL:
^((?:(?:http|ftp|ws)s?|sftp):\/\/?)?([^:/\s.#?]+\.[^:/\s#?]+|localhost)(:\d+)?((?:\/\w+)*\/)?([\w\-.]+[^#?\s]+)?([^#]+)?(#[\w-]*)?$
((?:(?:http|ftp|ws)s?|sftp):\/\/?)?(group 1): extracts the protocol
([^:/\s.#?]+\.[^:/\s#?]+|localhost)(group 2): extracts the hostname
(:\d+)?(group 3): extracts the port number
((?:\/\w+)*\/)?([\w\-.]+[^#?\s]+)?(groups 4 & 5): extracts the path part
([^#]+)?(group 6): extracts the query part
(#[\w-]*)?(group 7): extracts the hash part
For every part of the regex listed above, you can remove the ending ? to force it (or add one to make it facultative). You can also remove the ^ at the beginning and $ at the end of the regex so it won't need to match the whole string.
See it on regex101.
Note: this regex is not 100% safe and may accept some strings which are not necessarily valid URLs but it does indeed validate some criterias. Its main goal was to extract the different parts of an URL not to validate it.
A: With regard to eyelidness' answer post that reads "This is based on my reading of the URI specification.": Thanks Eyelidness, yours is the perfect solution I sought, as it is based on the URI spec! Superb work. :)
I had to make two amendments. The first to get the regexp to match IP address URLs correctly in PHP (v5.2.10) with the preg_match() function.
I had to add one more set of parenthesis to the line above "IP Address" around the pipes:
)|((\d|[1-9]\d|1\d{2}|2[0-4][0-9]|25[0-5])\.){3}(?#
Not sure why.
I have also reduced the top level domain minimum length from 3 to 2 letters to support .co.uk and similar.
Final code:
/^(https?|ftp):\/\/(?# protocol
)(([a-z0-9$_\.\+!\*\'\(\),;\?&=-]|%[0-9a-f]{2})+(?# username
)(:([a-z0-9$_\.\+!\*\'\(\),;\?&=-]|%[0-9a-f]{2})+)?(?# password
)@)?(?# auth requires @
)((([a-z0-9]\.|[a-z0-9][a-z0-9-]*[a-z0-9]\.)*(?# domain segments AND
)[a-z][a-z0-9-]*[a-z0-9](?# top level domain OR
)|((\d|[1-9]\d|1\d{2}|2[0-4][0-9]|25[0-5])\.){3}(?#
)(\d|[1-9]\d|1\d{2}|2[0-4][0-9]|25[0-5])(?# IP address
))(:\d+)?(?# port
))(((\/+([a-z0-9$_\.\+!\*\'\(\),;:@&=-]|%[0-9a-f]{2})*)*(?# path
)(\?([a-z0-9$_\.\+!\*\'\(\),;:@&=-]|%[0-9a-f]{2})*)(?# query string
)?)?)?(?# path and query string optional
)(#([a-z0-9$_\.\+!\*\'\(\),;:@&=-]|%[0-9a-f]{2})*)?(?# fragment
)$/i
This modified version was not checked against the URI specification so I can't vouch for it's compliance, it was altered to handle URLs on local network environments and two digit TLDs as well as other kinds of Web URL, and to work better in the PHP setup I use.
As PHP code:
define('URL_FORMAT',
'/^(https?):\/\/'. // protocol
'(([a-z0-9$_\.\+!\*\'\(\),;\?&=-]|%[0-9a-f]{2})+'. // username
'(:([a-z0-9$_\.\+!\*\'\(\),;\?&=-]|%[0-9a-f]{2})+)?'. // password
'@)?(?#'. // auth requires @
')((([a-z0-9]\.|[a-z0-9][a-z0-9-]*[a-z0-9]\.)*'. // domain segments AND
'[a-z][a-z0-9-]*[a-z0-9]'. // top level domain OR
'|((\d|[1-9]\d|1\d{2}|2[0-4][0-9]|25[0-5])\.){3}'.
'(\d|[1-9]\d|1\d{2}|2[0-4][0-9]|25[0-5])'. // IP address
')(:\d+)?'. // port
')(((\/+([a-z0-9$_\.\+!\*\'\(\),;:@&=-]|%[0-9a-f]{2})*)*'. // path
'(\?([a-z0-9$_\.\+!\*\'\(\),;:@&=-]|%[0-9a-f]{2})*)'. // query string
'?)?)?'. // path and query string optional
'(#([a-z0-9$_\.\+!\*\'\(\),;:@&=-]|%[0-9a-f]{2})*)?'. // fragment
'$/i');
Here is a test program in PHP which validates a variety of URLs using the regex:
<?php
define('URL_FORMAT',
'/^(https?):\/\/'. // protocol
'(([a-z0-9$_\.\+!\*\'\(\),;\?&=-]|%[0-9a-f]{2})+'. // username
'(:([a-z0-9$_\.\+!\*\'\(\),;\?&=-]|%[0-9a-f]{2})+)?'. // password
'@)?(?#'. // auth requires @
')((([a-z0-9]\.|[a-z0-9][a-z0-9-]*[a-z0-9]\.)*'. // domain segments AND
'[a-z][a-z0-9-]*[a-z0-9]'. // top level domain OR
'|((\d|[1-9]\d|1\d{2}|2[0-4][0-9]|25[0-5])\.){3}'.
'(\d|[1-9]\d|1\d{2}|2[0-4][0-9]|25[0-5])'. // IP address
')(:\d+)?'. // port
')(((\/+([a-z0-9$_\.\+!\*\'\(\),;:@&=-]|%[0-9a-f]{2})*)*'. // path
'(\?([a-z0-9$_\.\+!\*\'\(\),;:@&=-]|%[0-9a-f]{2})*)'. // query string
'?)?)?'. // path and query string optional
'(#([a-z0-9$_\.\+!\*\'\(\),;:@&=-]|%[0-9a-f]{2})*)?'. // fragment
'$/i');
/**
* Verify the syntax of the given URL.
*
* @access public
* @param $url The URL to verify.
* @return boolean
*/
function is_valid_url($url) {
if (str_starts_with(strtolower($url), 'http://localhost')) {
return true;
}
return preg_match(URL_FORMAT, $url);
}
/**
* String starts with something
*
* This function will return true only if input string starts with
* niddle
*
* @param string $string Input string
* @param string $niddle Needle string
* @return boolean
*/
function str_starts_with($string, $niddle) {
return substr($string, 0, strlen($niddle)) == $niddle;
}
/**
* Test a URL for validity and count results.
* @param url url
* @param expected expected result (true or false)
*/
$numtests = 0;
$passed = 0;
function test_url($url, $expected) {
global $numtests, $passed;
$numtests++;
$valid = is_valid_url($url);
echo "URL Valid?: " . ($valid?"yes":"no") . " for URL: $url. Expected: ".($expected?"yes":"no").". ";
if($valid == $expected) {
echo "PASS\n"; $passed++;
} else {
echo "FAIL\n";
}
}
echo "URL Tests:\n\n";
test_url("http://localserver/projects/public/assets/javascript/widgets/UserBoxMenu/widget.css", true);
test_url("http://www.google.com", true);
test_url("http://www.google.co.uk/projects/my%20folder/test.php", true);
test_url("https://myserver.localdomain", true);
test_url("http://192.168.1.120/projects/index.php", true);
test_url("http://192.168.1.1/projects/index.php", true);
test_url("http://projectpier-server.localdomain/projects/public/assets/javascript/widgets/UserBoxMenu/widget.css", true);
test_url("https://2.4.168.19/project-pier?c=test&a=b", true);
test_url("https://localhost/a/b/c/test.php?c=controller&arg1=20&arg2=20", true);
test_url("http://user:password@localhost/a/b/c/test.php?c=controller&arg1=20&arg2=20", true);
echo "\n$passed out of $numtests tests passed.\n\n";
?>
Thanks again to eyelidness for the regex!
A: I've been working on an in-depth article discussing URI validation using regular expressions. It is based on RFC3986.
Regular Expression URI Validation
Although the article is not yet complete, I have come up with a PHP function which does a pretty good job of validating HTTP and FTP URLs. Here is the current version:
// function url_valid($url) { Rev:20110423_2000
//
// Return associative array of valid URI components, or FALSE if $url is not
// RFC-3986 compliant. If the passed URL begins with: "www." or "ftp.", then
// "http://" or "ftp://" is prepended and the corrected full-url is stored in
// the return array with a key name "url". This value should be used by the caller.
//
// Return value: FALSE if $url is not valid, otherwise array of URI components:
// e.g.
// Given: "http://www.jmrware.com:80/articles?height=10&width=75#fragone"
// Array(
// [scheme] => http
// [authority] => www.jmrware.com:80
// [userinfo] =>
// [host] => www.jmrware.com
// [IP_literal] =>
// [IPV6address] =>
// [ls32] =>
// [IPvFuture] =>
// [IPv4address] =>
// [regname] => www.jmrware.com
// [port] => 80
// [path_abempty] => /articles
// [query] => height=10&width=75
// [fragment] => fragone
// [url] => http://www.jmrware.com:80/articles?height=10&width=75#fragone
// )
function url_valid($url) {
if (strpos($url, 'www.') === 0) $url = 'http://'. $url;
if (strpos($url, 'ftp.') === 0) $url = 'ftp://'. $url;
if (!preg_match('/# Valid absolute URI having a non-empty, valid DNS host.
^
(?P<scheme>[A-Za-z][A-Za-z0-9+\-.]*):\/\/
(?P<authority>
(?:(?P<userinfo>(?:[A-Za-z0-9\-._~!$&\'()*+,;=:]|%[0-9A-Fa-f]{2})*)@)?
(?P<host>
(?P<IP_literal>
\[
(?:
(?P<IPV6address>
(?: (?:[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})?::
)
(?P<ls32>[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})?::
)
| (?P<IPvFuture>[Vv][0-9A-Fa-f]+\.[A-Za-z0-9\-._~!$&\'()*+,;=:]+)
)
\]
)
| (?P<IPv4address>(?:(?: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]?))
| (?P<regname>(?:[A-Za-z0-9\-._~!$&\'()*+,;=]|%[0-9A-Fa-f]{2})+)
)
(?::(?P<port>[0-9]*))?
)
(?P<path_abempty>(?:\/(?:[A-Za-z0-9\-._~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})*)*)
(?:\?(?P<query> (?:[A-Za-z0-9\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*))?
(?:\#(?P<fragment> (?:[A-Za-z0-9\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*))?
$
/mx', $url, $m)) return FALSE;
switch ($m['scheme']) {
case 'https':
case 'http':
if ($m['userinfo']) return FALSE; // HTTP scheme does not allow userinfo.
break;
case 'ftps':
case 'ftp':
break;
default:
return FALSE; // Unrecognized URI scheme. Default to FALSE.
}
// Validate host name conforms to DNS "dot-separated-parts".
if ($m['regname']) { // If host regname specified, check for DNS conformance.
if (!preg_match('/# HTTP DNS host name.
^ # Anchor to beginning of string.
(?!.{256}) # Overall host length is less than 256 chars.
(?: # Group dot separated host part alternatives.
[A-Za-z0-9]\. # Either a single alphanum followed by dot
| # or... part has more than one char (63 chars max).
[A-Za-z0-9] # Part first char is alphanum (no dash).
[A-Za-z0-9\-]{0,61} # Internal chars are alphanum plus dash.
[A-Za-z0-9] # Part last char is alphanum (no dash).
\. # Each part followed by literal dot.
)* # Zero or more parts before top level domain.
(?: # Explicitly specify top level domains.
com|edu|gov|int|mil|net|org|biz|
info|name|pro|aero|coop|museum|
asia|cat|jobs|mobi|tel|travel|
[A-Za-z]{2}) # Country codes are exactly two alpha chars.
\.? # Top level domain can end in a dot.
$ # Anchor to end of string.
/ix', $m['host'])) return FALSE;
}
$m['url'] = $url;
for ($i = 0; isset($m[$i]); ++$i) unset($m[$i]);
return $m; // return TRUE == array of useful named $matches plus the valid $url.
}
This function utilizes two regexes; one to match a subset of valid generic URIs (absolute ones having a non-empty host), and a second to validate the DNS "dot-separated-parts" host name. Although this function currently validates only HTTP and FTP schemes, it is structured such that it can be easily extended to handle other schemes.
A: I use this regex:
((https?:)?//)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,63}(:[\d]+)?(/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?
To support both:
http://stackoverflow.com
https://stackoverflow.com
And:
//stackoverflow.com
A: Here's a ready-to-go Java version from the Android source code. This is the best one I've found.
public static final Matcher WEB = Pattern.compile(new StringBuilder()
.append("((?:(http|https|Http|Https|rtsp|Rtsp):")
.append("\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)")
.append("\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_")
.append("\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?")
.append("((?:(?:[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}\\.)+") // named host
.append("(?:") // plus top level domain
.append("(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])")
.append("|(?:biz|b[abdefghijmnorstvwyz])")
.append("|(?:cat|com|coop|c[acdfghiklmnoruvxyz])")
.append("|d[ejkmoz]")
.append("|(?:edu|e[cegrstu])")
.append("|f[ijkmor]")
.append("|(?:gov|g[abdefghilmnpqrstuwy])")
.append("|h[kmnrtu]")
.append("|(?:info|int|i[delmnoqrst])")
.append("|(?:jobs|j[emop])")
.append("|k[eghimnrwyz]")
.append("|l[abcikrstuvy]")
.append("|(?:mil|mobi|museum|m[acdghklmnopqrstuvwxyz])")
.append("|(?:name|net|n[acefgilopruz])")
.append("|(?:org|om)")
.append("|(?:pro|p[aefghklmnrstwy])")
.append("|qa")
.append("|r[eouw]")
.append("|s[abcdeghijklmnortuvyz]")
.append("|(?:tel|travel|t[cdfghjklmnoprtvwz])")
.append("|u[agkmsyz]")
.append("|v[aceginu]")
.append("|w[fs]")
.append("|y[etu]")
.append("|z[amw]))")
.append("|(?:(?:25[0-5]|2[0-4]") // or ip address
.append("[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(?:25[0-5]|2[0-4][0-9]")
.append("|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1]")
.append("[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}")
.append("|[1-9][0-9]|[0-9])))")
.append("(?:\\:\\d{1,5})?)") // plus option port number
.append("(\\/(?:(?:[a-zA-Z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~") // plus option query params
.append("\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?")
.append("(?:\\b|$)").toString()
).matcher("");
A: I wrote my URL (actually IRI, internationalized) pattern to comply with RFC 3987 (http://www.faqs.org/rfcs/rfc3987.html). These are in PCRE syntax.
For absolute IRIs (internationalized):
/^[a-z](?:[-a-z0-9\+\.])*:(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\/\?])*)?$/i
To also allow relative IRIs:
/^(?:[a-z](?:[-a-z0-9\+\.])*:(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\/\?])*)?|(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=@])+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\/\?])*)?)$/i
How they were compiled (in PHP):
<?php
/* Regex convenience functions (character class, non-capturing group) */
function cc($str, $suffix = '', $negate = false) {
return '[' . ($negate ? '^' : '') . $str . ']' . $suffix;
}
function ncg($str, $suffix = '') {
return '(?:' . $str . ')' . $suffix;
}
/* Preserved from RFC3986 */
$ALPHA = 'a-z';
$DIGIT = '0-9';
$HEXDIG = $DIGIT . 'a-f';
$sub_delims = '!\\$&\'\\(\\)\\*\\+,;=';
$gen_delims = ':\\/\\?\\#\\[\\]@';
$reserved = $gen_delims . $sub_delims;
$unreserved = '-' . $ALPHA . $DIGIT . '\\._~';
$pct_encoded = '%' . cc($HEXDIG) . cc($HEXDIG);
$dec_octet = ncg(implode('|', array(
cc($DIGIT),
cc('1-9') . cc($DIGIT),
'1' . cc($DIGIT) . cc($DIGIT),
'2' . cc('0-4') . cc($DIGIT),
'25' . cc('0-5')
)));
$IPv4address = $dec_octet . ncg('\\.' . $dec_octet, '{3}');
$h16 = cc($HEXDIG, '{1,4}');
$ls32 = ncg($h16 . ':' . $h16 . '|' . $IPv4address);
$IPv6address = ncg(implode('|', array(
ncg($h16 . ':', '{6}') . $ls32,
'::' . ncg($h16 . ':', '{5}') . $ls32,
ncg($h16, '?') . '::' . ncg($h16 . ':', '{4}') . $ls32,
ncg($h16 . ':' . $h16, '?') . '::' . ncg($h16 . ':', '{3}') . $ls32,
ncg(ncg($h16 . ':', '{0,2}') . $h16, '?') . '::' . ncg($h16 . ':', '{2}') . $ls32,
ncg(ncg($h16 . ':', '{0,3}') . $h16, '?') . '::' . $h16 . ':' . $ls32,
ncg(ncg($h16 . ':', '{0,4}') . $h16, '?') . '::' . $ls32,
ncg(ncg($h16 . ':', '{0,5}') . $h16, '?') . '::' . $h16,
ncg(ncg($h16 . ':', '{0,6}') . $h16, '?') . '::',
)));
$IPvFuture = 'v' . cc($HEXDIG, '+') . cc($unreserved . $sub_delims . ':', '+');
$IP_literal = '\\[' . ncg(implode('|', array($IPv6address, $IPvFuture))) . '\\]';
$port = cc($DIGIT, '*');
$scheme = cc($ALPHA) . ncg(cc('-' . $ALPHA . $DIGIT . '\\+\\.'), '*');
/* New or changed in RFC3987 */
$iprivate = '\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}';
$ucschar = '\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}' .
'\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}' .
'\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}' .
'\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}' .
'\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}' .
'\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}';
$iunreserved = '-' . $ALPHA . $DIGIT . '\\._~' . $ucschar;
$ipchar = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . ':@'));
$ifragment = ncg($ipchar . '|' . cc('\\/\\?'), '*');
$iquery = ncg($ipchar . '|' . cc($iprivate . '\\/\\?'), '*');
$isegment_nz_nc = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . '@'), '+');
$isegment_nz = ncg($ipchar, '+');
$isegment = ncg($ipchar, '*');
$ipath_empty = '(?!' . $ipchar . ')';
$ipath_rootless = ncg($isegment_nz) . ncg('\\/' . $isegment, '*');
$ipath_noscheme = ncg($isegment_nz_nc) . ncg('\\/' . $isegment, '*');
$ipath_absolute = '\\/' . ncg($ipath_rootless, '?'); // Spec says isegment-nz *( "/" isegment )
$ipath_abempty = ncg('\\/' . $isegment, '*');
$ipath = ncg(implode('|', array(
$ipath_abempty,
$ipath_absolute,
$ipath_noscheme,
$ipath_rootless,
$ipath_empty
))) . ')';
$ireg_name = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . '@'), '*');
$ihost = ncg(implode('|', array($IP_literal, $IPv4address, $ireg_name)));
$iuserinfo = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . ':'), '*');
$iauthority = ncg($iuserinfo . '@', '?') . $ihost . ncg(':' . $port, '?');
$irelative_part = ncg(implode('|', array(
'\\/\\/' . $iauthority . $ipath_abempty . '',
'' . $ipath_absolute . '',
'' . $ipath_noscheme . '',
'' . $ipath_empty . ''
)));
$irelative_ref = $irelative_part . ncg('\\?' . $iquery, '?') . ncg('\\#' . $ifragment, '?');
$ihier_part = ncg(implode('|', array(
'\\/\\/' . $iauthority . $ipath_abempty . '',
'' . $ipath_absolute . '',
'' . $ipath_rootless . '',
'' . $ipath_empty . ''
)));
$absolute_IRI = $scheme . ':' . $ihier_part . ncg('\\?' . $iquery, '?');
$IRI = $scheme . ':' . $ihier_part . ncg('\\?' . $iquery, '?') . ncg('\\#' . $ifragment, '?');
$IRI_reference = ncg($IRI . '|' . $irelative_ref);
Edit 7 March 2011: Because of the way PHP handles backslashes in quoted strings, these are unusable by default. You'll need to double-escape backslashes except where the backslash has a special meaning in regex. You can do that this way:
$escape_backslash = '/(?<!\\)\\(?![\[\]\\\^\$\.\|\*\+\(\)QEnrtaefvdwsDWSbAZzB1-9GX]|x\{[0-9a-f]{1,4}\}|\c[A-Z]|)/';
$absolute_IRI = preg_replace($escape_backslash, '\\\\', $absolute_IRI);
$IRI = preg_replace($escape_backslash, '\\\\', $IRI);
$IRI_reference = preg_replace($escape_backslash, '\\\\', $IRI_reference);
A: For Python, this is the actual URL validating regex used in Django 1.5.1:
import re
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
This does both ipv4 and ipv6 addresses as well as ports and GET parameters.
Found in the code here, Line 44.
A: This one works for me very well. (https?|ftp)://(www\d?|[a-zA-Z0-9]+)?\.[a-zA-Z0-9-]+(\:|\.)([a-zA-Z0-9.]+|(\d+)?)([/?:].*)?
A: The post Getting parts of a URL (Regex) discusses parsing a URL to identify its various components. If you want to check if a URL is well-formed, it should be sufficient for your needs.
If you need to check if it's actually valid, you'll eventually have to try to access whatever's on the other end.
In general, though, you'd probably be better off using a function that's supplied to you by your framework or another library. Many platforms include functions that parse URLs. For example, there's Python's urlparse module, and in .NET you could use the System.Uri class's constructor as a means of validating the URL.
A: This might not be a job for regexes, but for existing tools in your language of choice. You probably want to use existing code that has already been written, tested, and debugged.
In PHP, use the parse_url function.
Perl: URI module.
Ruby: URI module.
.NET: 'Uri' class
Regexes are not a magic wand you wave at every problem that happens to involve strings.
A: For convenience here's a one-liner regexp for URL's that will also match localhost where you're more likely to have ports than .com or similar.
(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}(\.[a-z]{2,6}|:[0-9]{3,4})\b([-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)
A: I found the following Regex for URLs, tested successfully with 500+ URLs:
/\b(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?\b/gi
I know it looks ugly, but the good thing is that it works. :)
Explanation and demo with 581 random URLs on regex101.
Source: In search of the perfect URL validation regex
A: To Match a URL there are various option and it depend on you requirement.
below are few.
_(^|[\s.:;?\-\]<\(])(https?://[-\w;/?:@&=+$\|\_.!~*\|'()\[\]%#,☺]+[\w/#](\(\))?)(?=$|[\s',\|\(\).:;?\-\[\]>\)])_i
#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#iS
And there is a link which gives you more than 10 different variations of validation for URL.
https://mathiasbynens.be/demo/url-regex
A: This will match all URLs
*
*with or without http/https
*with or without www
...including sub-domains and those new top-level domain name extensions such as
.museum,
.academy,
.foundation
etc. which can have up to 63 characters (not just .com, .net, .info etc.)
(([\w]+:)?//)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,63}(:[\d]+)?(/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?
Because today maximum length of the available top-level domain name extension is 13 characters such as .international, you can change the number 63 in expression to 13 to prevent someone misusing it.
as javascript
var urlreg=/(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,63}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?/;
$('textarea').on('input',function(){
var url = $(this).val();
$(this).toggleClass('invalid', urlreg.test(url) == false)
});
$('textarea').trigger('input');
textarea{color:green;}
.invalid{color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>http://www.google.com</textarea>
<textarea>http//www.google.com</textarea>
<textarea>googlecom</textarea>
<textarea>https://www.google.com</textarea>
Wikipedia Article: List of all internet top-level domains
A: Non-validating URI-reference Parser
For reference purposes, here's the IETF Spec: (TXT | HTML). In particular, Appendix B. Parsing a URI Reference with a Regular Expression demonstrates how to parse a valid regex. This is described as,
for an example of a non-validating URI-reference parser that will take any given string and extract the URI components.
Here's the regex they provide:
^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
As someone else said, it's probably best to leave this to a lib/framework you're already using.
A: I think some people weren't able to use your php code because of the modifiers implied. I copied your code as is and used as an example:
if(
preg_match(
"/^{$IRI_reference}$/iu",
'http://www.url.com'
)
){
echo 'true';
}
Notice the "i" and "u" modifiers. without "u" php throws an exception saying:
Warning: preg_match() [function.preg-match]: Compilation failed: character value in \x{...} sequence is too large at offset XX
A: I tried to formulate my version of url. My requirement was to capture instances in a String where possible url can be cse.uom.ac.mu - noting that it is not preceded by http nor www
String regularExpression = "((((ht{2}ps?://)?)((w{3}\\.)?))?)[^.&&[a-zA-Z0-9]][a-zA-Z0-9.-]+[^.&&[a-zA-Z0-9]](\\.[a-zA-Z]{2,3})";
assertTrue("www.google.com".matches(regularExpression));
assertTrue("www.google.co.uk".matches(regularExpression));
assertTrue("http://www.google.com".matches(regularExpression));
assertTrue("http://www.google.co.uk".matches(regularExpression));
assertTrue("https://www.google.com".matches(regularExpression));
assertTrue("https://www.google.co.uk".matches(regularExpression));
assertTrue("google.com".matches(regularExpression));
assertTrue("google.co.uk".matches(regularExpression));
assertTrue("google.mu".matches(regularExpression));
assertTrue("mes.intnet.mu".matches(regularExpression));
assertTrue("cse.uom.ac.mu".matches(regularExpression));
//cannot contain 2 '.' after www
assertFalse("www..dr.google".matches(regularExpression));
//cannot contain 2 '.' just before com
assertFalse("www.dr.google..com".matches(regularExpression));
// to test case where url www must be followed with a '.'
assertFalse("www:google.com".matches(regularExpression));
// to test case where url www must be followed with a '.'
//assertFalse("http://wwwe.google.com".matches(regularExpression));
// to test case where www must be preceded with a '.'
assertFalse("https://www@.google.com".matches(regularExpression));
A: whats wrong with plain and simple FILTER_VALIDATE_URL ?
$url = "http://www.example.com";
if(!filter_var($url, FILTER_VALIDATE_URL))
{
echo "URL is not valid";
}
else
{
echo "URL is valid";
}
I know its not the question exactly but it did the job for me when I needed to validate urls so thought it might be useful to others who come across this post looking for the same thing
A: The following RegEx will work:
"@((((ht)|(f))tp[s]?://)|(www\.))([a-z][-a-z0-9]+\.)?([a-z][-a-z0-9]+\.)?[a-z][-a-z0-9]+\.[a-z]+[/]?[a-z0-9._\/~#&=;%+?-]*@si"
A: Use this one its working for me
function validUrl(Url) {
var myRegExp =/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i;
if (!RegExp.test(Url.value)) {
$("#urlErrorLbl").removeClass('highlightNew');
return false;
}
$("#urlErrorLbl").addClass('highlightNew');
return true;
}
A: You don't specify which language you're using.
If PHP is, there is a native function for that:
$url = 'http://www.yoururl.co.uk/sub1/sub2/?param=1¶m2/';
if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
// Wrong
}
else {
// Valid
}
Returns the filtered data, or FALSE if the filter fails.
Check it here >>
Hope it helps.
A: https?:\/{2}(?:[\/-\w.]|(?:%[\da-fA-F]{2}))+
You can use this pattern for detecting URLs.
Following is the proof of concept
RegExr: URL Detector
A: I've just written up a blog post for a great solution for recognizing URLs in most used formats such as:
*
*www.google.com
*http://www.google.com
*mailto:somebody@google.com
*somebody@google.com
*www.url-with-querystring.com/?url=has-querystring
The regular expression used is:
/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/
A: ^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$
live demo: https://regex101.com/r/HUNasA/2
I have tested various expressions to match my requirements.
As a user I can hit browser search bar with following strings:
valid urls
*
*https://www.google.com
*http://www.google.com
*http://google.com/
*https://google.com/
*www.google.com
*google.com
*https://www.google.com.ua
*http://www.google.com.ua
*http://google.com.ua
*https://google.com.ua/
*www.google.com.ua
*google.com.ua
*https://mail.google.com
*http://mail.google.com
*mail.google.com
invalid urls
*
*http://google
*https://google.c
*google
*google.
*.google
*.google.com
*goole.c
*...
A: The best regular expression for URL for me would be:
"(([\w]+:)?//)?(([\d\w]|%[a-fA-F\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?"
A: Here is a good rule that covers all possible cases: ports, params and etc
/(https?:\/\/(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9])(:?\d*)\/?([a-z_\/0-9\-#.]*)\??([a-z_\/0-9\-#=&]*)/g
A: I wrote a little groovy version that you can run
it matches the following URLs (which is good enough for me)
public static void main(args) {
String url = "go to http://www.m.abut.ly/abc its awesome"
url = url.replaceAll(/https?:\/\/w{0,3}\w*?\.(\w*?\.)?\w{2,3}\S*|www\.(\w*?\.)?\w*?\.\w{2,3}\S*|(\w*?\.)?\w*?\.\w{2,3}[\/\?]\S*/ , { it ->
"woof${it}woof"
})
println url
}
http://google.com
http://google.com/help.php
http://google.com/help.php?a=5
http://www.google.com
http://www.google.com/help.php
http://www.google.com?a=5
google.com?a=5
google.com/help.php
google.com/help.php?a=5
http://www.m.google.com/help.php?a=5 (and all its permutations)
www.m.google.com/help.php?a=5 (and all its permutations)
m.google.com/help.php?a=5 (and all its permutations)
The important thing for any URLs that don't start with http or www is that they must include a / or ?
I bet this can be tweaked a little more but it does the job pretty nice for being so short and compact... because you can pretty much split it in 3:
find anything that starts with http:
https?:\/\/w{0,3}\w*?\.\w{2,3}\S*
find anything that starts with www:
www\.\w*?\.\w{2,3}\S*
or find anything that must have a text then a dot then at least 2 letters and then a ? or /:
\w*?\.\w{2,3}[\/\?]\S*
A: I was not able to find the regex I was looking for so I modified a regex to fullfill my requirements, and apparently it seems to work fine now. My requirements were:
*
*Match URLs w/o protocol (www.gooogle.com)
*Match URLs with query parameters and path (http://subdomain.web-site.com/cgi-bin/perl.cgi?key1=value1&key2=value2e)
*Don't match URLs where there are not acceptable characters (e.g. "'£), for instance: (www.google.com/somthing"/somethingmore)
Here what I came up with, any suggestion is appreciated:
@Test
public void testWebsiteUrl(){
String regularExpression = "((http|ftp|https):\\/\\/)?[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?";
assertTrue("www.google.com".matches(regularExpression));
assertTrue("www.google.co.uk".matches(regularExpression));
assertTrue("http://www.google.com".matches(regularExpression));
assertTrue("http://www.google.co.uk".matches(regularExpression));
assertTrue("https://www.google.com".matches(regularExpression));
assertTrue("https://www.google.co.uk".matches(regularExpression));
assertTrue("google.com".matches(regularExpression));
assertTrue("google.co.uk".matches(regularExpression));
assertTrue("google.mu".matches(regularExpression));
assertTrue("mes.intnet.mu".matches(regularExpression));
assertTrue("cse.uom.ac.mu".matches(regularExpression));
assertTrue("http://www.google.com/path".matches(regularExpression));
assertTrue("http://subdomain.web-site.com/cgi-bin/perl.cgi?key1=value1&key2=value2e".matches(regularExpression));
assertTrue("http://www.google.com/?queryparam=123".matches(regularExpression));
assertTrue("http://www.google.com/path?queryparam=123".matches(regularExpression));
assertFalse("www..dr.google".matches(regularExpression));
assertFalse("www:google.com".matches(regularExpression));
assertFalse("https://www@.google.com".matches(regularExpression));
assertFalse("https://www.google.com\"".matches(regularExpression));
assertFalse("https://www.google.com'".matches(regularExpression));
assertFalse("http://www.google.com/path'".matches(regularExpression));
assertFalse("http://subdomain.web-site.com/cgi-bin/perl.cgi?key1=value1&key2=value2e'".matches(regularExpression));
assertFalse("http://www.google.com/?queryparam=123'".matches(regularExpression));
assertFalse("http://www.google.com/path?queryparam=12'3".matches(regularExpression));
}
A: To Check URL regex would be:
^http(s{0,1})://[a-zA-Z0-9_/\\-\\.]+\\.([A-Za-z/]{2,5})[a-zA-Z0-9_/\\&\\?\\=\\-\\.\\~\\%]*
A: This is not a regular expression but accomplishes the same thing (Javascript only):
function isAValidUrl(url) {
try {
new URL(url);
return true;
} catch(e) {
return false;
}
}
A: How about this:
^(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})$
These are the test cases:
You can try it out in here : https://regex101.com/r/mS9gD7/41
A: IMPROVED
Detects Urls like these:
*
*https://www.example.pl
*http://www.example.com
*www.example.pl
*example.com
*http://blog.example.com
*http://www.example.com/product
*http://www.example.com/products?id=1&page=2
*http://www.example.com#up
*http://255.255.255.255
*255.255.255.255
*http:// www.site.com:8008
Regex:
/^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/gm
A: This is a rather old thread now and the question asks for a regex based URL validator. I ran into the thread whilst looking for precisely the same thing. While it may well be possible to write a really comprehensive regex to validate URLs. I eventually settled on another way to do things - by using PHP's parse_url function.
It returns boolean false if the url cannot be parsed. Otherwise, it returns the scheme, the host and other information. This may well not be enough for a comprehensive URL check on its own, but can be drilled down into for further analysis. If the intent is to simply catch typos, invalid schemes etc. It is perfectly adequate!
A: Here is the best and the most matched regex for this situation
^(?:http(?:s)?:\/\/)?(?:www\.)?(?:[\w-]*)\.\w{2,}$
A: To match the URL up to the domain:
(^(\bhttp)(|s):\/{2})(?=[a-z0-9-_]{1,255})\.\1\.([a-z]{3,7}$)
It can be simplified to:
(^(\bhttp)(|s):\/{2})(?=[a-z0-9-_.]{1,255})\.([a-z]{3,7})
the latter does not check for the end for the end line so that it can be later used create full blown URL with full paths and query strings.
A: This should work:
function validateUrl(value){
return /^(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/gi.test(value);
}
console.log(validateUrl('google.com')); // true
console.log(validateUrl('www.google.com')); // true
console.log(validateUrl('http://www.google.com')); // true
console.log(validateUrl('http:/www.google.com')); // false
console.log(validateUrl('www.google.com/test')); // true
A: I think I found a more general regexp to validate urls, particularly websites
(https?:\/\/)?(www\.)[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)|(https?:\/\/)?(www\.)?(?!ww)[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)
it does not allow for instance www.something or http://www or http://www.something
Check it here: http://regexr.com/3e4a2
A: I created a similar regex (PCRE) to the one @eyelidlessness provided following RFC3987 along with other RFC documents. The major difference between @eyelidlessness and my regex are mainly readability and also URN support.
The regex below is all one piece (instead of being mixed with PHP) so it can be used in different languages very easily (so long as they support PCRE)
The easiest way to test this regex is to use regex101 and copy paste the code and test strings below with the appropriate modifiers (gmx).
To use this regex in PHP, insert the regex below into the following code:
$regex = <<<'EOD'
// Put the regex here
EOD;
You can match a link without a scheme by doing the following:
To match a link without a scheme (i.e. john.doe@gmail.com or www.google.com/pathtofile.php?query), replace this section:
(?:
(?<scheme>
(?<urn>urn)|
(?&d_scheme)
)
:
)?
with this:
(?:
(?<scheme>
(?<urn>urn)|
(?&d_scheme)
)
:
)?
Note, however, that by replacing this, the regex does not become 100% reliable.
Regex (PCRE) with gmx modifiers for the multi-line test string below
(?(DEFINE)
# Definitions
(?<ALPHA>[\p{L}])
(?<DIGIT>[0-9])
(?<HEX>[0-9a-fA-F])
(?<NCCHAR>
(?&UNRESERVED)|
(?&PCT_ENCODED)|
(?&SUB_DELIMS)|
@
)
(?<PCHAR>
(?&UNRESERVED)|
(?&PCT_ENCODED)|
(?&SUB_DELIMS)|
:|
@|
\/
)
(?<UCHAR>
(?&UNRESERVED)|
(?&PCT_ENCODED)|
(?&SUB_DELIMS)|
:
)
(?<RCHAR>
(?&UNRESERVED)|
(?&PCT_ENCODED)|
(?&SUB_DELIMS)
)
(?<PCT_ENCODED>%(?&HEX){2})
(?<UNRESERVED>
((?&ALPHA)|(?&DIGIT)|[-._~])
)
(?<RESERVED>(?&GEN_DELIMS)|(?&SUB_DELIMS))
(?<GEN_DELIMS>[:\/?#\[\]@])
(?<SUB_DELIMS>[!$&'()*+,;=])
# URI Parts
(?<d_scheme>
(?!urn)
(?:
(?&ALPHA)
((?&ALPHA)|(?&DIGIT)|[+-.])*
(?=:)
)
)
(?<d_hier_part_slashes>
(\/{2})?
)
(?<d_authority>(?&d_userinfo)?)
(?<d_userinfo>(?&UCHAR)*)
(?<d_ipv6>
(?![^:]*::[^:]*::[^:]*)
(
(
((?&HEX){0,4})
:
){1,7}
((?&d_ipv4)|:|(?&HEX){1,4})
)
)
(?<d_ipv4>
((?&octet)\.){3}
(?&octet)
)
(?<octet>
(
25[]0-5]|
2[0-4](?&DIGIT)|
1(?&DIGIT){2}|
[1-9](?&DIGIT)|
(?&DIGIT)
)
)
(?<d_reg_name>(?&RCHAR)*)
(?<d_urn_name>(?&UCHAR)*)
(?<d_port>(?&DIGIT)*)
(?<d_path>
(
\/
((?&PCHAR)*)*
(?=\?|\#|$)
)
)
(?<d_query>
(
((?&PCHAR)|\/|\?)*
)?
)
(?<d_fragment>
(
((?&PCHAR)|\/|\?)*
)?
)
)
^
(?<link>
(?:
(?<scheme>
(?<urn>urn)|
(?&d_scheme)
)
:
)
(?(urn)
(?:
(?<namespace_identifier>[0-9a-zA-Z\-]+)
:
(?<namespace_specific_string>(?&d_urn_name)+)
)
|
(?<hier_part>
(?<slashes>(?&d_hier_part_slashes))
(?<authority>
(?:
(?<userinfo>(?&d_authority))
@
)?
(?<host>
(?<ipv4>\[?(?&d_ipv4)\]?)|
(?<ipv6>\[(?&d_ipv6)\])|
(?<domain>(?&d_reg_name))
)
(?:
:
(?<port>(?&d_port))
)?
)
(?<path>(?&d_path))?
)
(?:
\?
(?<query>(?&d_query))
)?
(?:
\#
(?<fragment>(?&d_fragment))
)?
)
)
$
Test Strings
# Valid URIs
ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt
ldap://[2001:db8::7]/c=GB?objectClass?one
mailto:John.Doe@example.com
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:isbn:0451450523
urn:oid:2.16.840
urn:isan:0000-0000-9E59-0000-O-0000-0000-2
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
http://localhost/test/somefile.php?query=someval&variable=value#fragment
http://[2001:db8:a0b:12f0::1]/test
ftp://username:password@domain.com/path/to/file/somefile.html?queryVariable=value#fragment
https://subdomain.domain.com/path/to/file.php?query=value#fragment
https://subdomain.example.com/path/to/file.php?query=value#fragment
mailto:john.smith(comment)@example.com
mailto:user@[2001:DB8::1]
mailto:user@[255:192:168:1]
mailto:M.Handley@cs.ucl.ac.uk
http://localhost:4433/path/to/file?query#fragment
# Note that the example below IS a valid as it does follow RFC standards
localhost:4433/path/to/file
# These work with the optional scheme group although I'd suggest making the scheme mandatory as misinterpretations can occur
john.doe@gmail.com
www.google.com/pathtofile.php?query
[192a:123::192.168.1.1]:80/path/to/file.html?query#fragment
A: As far as I have found, this expression is good for me-
(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})
Working example-
function RegExForUrlMatch()
{
var expression = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})/g;
var regex = new RegExp(expression);
var t = document.getElementById("url").value;
if (t.match(regex)) {
document.getElementById("demo").innerHTML = "Successful match";
} else {
document.getElementById("demo").innerHTML = "No match";
}
}
<input type="text" id="url" placeholder="url" onkeyup="RegExForUrlMatch()">
<p id="demo">Please enter a URL to test</p>
A: Below expression will work for all popular domains. It will accept following urls:
*
*www.yourwebsite.com
*http://www.yourwebsite.com
*www.yourwebsite.com
*yourwebsite.com
*yourwebsite.co.in
In addition it will make message with url as link also
e.g. please visit yourwebsite.com
In above example it will make yourwebsite.com as hyperlink
if (new RegExp("([-a-z0-9]{1,63}\\.)*?[a-z0-9][-a-z0-9]{0,61}[a-z0-9]\\.(com|com/|org|gov|cm|net|online|live|biz|us|uk|co.us|co.uk|in|co.in|int|info|edu|mil|ca|co|co.au|org/|gov/|cm/|net/|online/|live/|biz/|us/|uk/|co.us/|co.uk/|in/|co.in/|int/|info/|edu/|mil/|ca/|co/|co.au/)(/[-\\w@\\+\\.~#\\?*&/=% ]*)?$").test(strMessage) || (new RegExp("^[a-z ]+[\.]?[a-z ]+?[\.]+[a-z ]+?[\.]+[a-z ]+?[-\\w@\\+\\.~#\\?*&/=% ]*").test(strMessage) && new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?").test(strMessage)) || (new RegExp("^[a-z ]+[\.]?[a-z ]+?[-\\w@\\+\\.~#\\?*&/=% ]*").test(strMessage) && new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?").test(strMessage))) {
if (new RegExp("^[a-z ]+[\.]?[a-z ]+?[\.]+[a-z ]+?[\.]+[a-z ]+?$").test(strMessage) && new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?").test(strMessage)) {
var url1 = /(^|<|\s)([\w\.]+\.(?:com|org|gov|cm|net|online|live|biz|us|uk|co.us|co.uk|in|co.in|int|info|edu|mil|ca|co|co.au))(\s|>|$)/g;
var html = $.trim(strMessage);
if (html) {
html = html.replace(url1, '$1<a style="color:blue; text-decoration:underline;" target="_blank" href="http://$2">$2</a>$3');
}
returnString = html;
return returnString;
} else {
var url1 = /(^|<|\s)(www\..+?\.(?:com|org|gov|cm|net|online|live|biz|us|uk|co.us|co.uk|in|co.in|int|info|edu|mil|ca|co|co.au)[^,\s]*)(\s|>|$)/g,
url2 = /(^|<|\s)(((https?|ftp):\/\/|mailto:).+?\.(?:com|org|gov|cm|net|online|live|biz|us|uk|co.us|co.uk|in|co.in|int|info|edu|mil|ca|co|co.au)[^,\s]*)(\s|>|$)/g,
url3 = /(^|<|\s)([\w\.]+\.(?:com|org|gov|cm|net|online|live|biz|us|uk|co.us|co.uk|in|co.in|int|info|edu|mil|ca|co|co.au)[^,\s]*)(\s|>|$)/g;
var html = $.trim(strMessage);
if (html) {
html = html.replace(url1, '$1<a style="color:blue; text-decoration:underline;" target="_blank" href="http://$2">$2</a>$3').replace(url2, '$1<a style="color:blue; text-decoration:underline;" target="_blank" href="$2">$2</a>$5').replace(url3, '$1<a style="color:blue; text-decoration:underline;" target="_blank" href="http://$2">$2</a>$3');
}
returnString = html;
return returnString;
}
}
A: After rigorous searching i finally settled with the following
^[a-zA-Z0-9]+\:\/\/[a-zA-Z0-9]+\.[-a-zA-Z0-9]+\.?[a-zA-Z0-9]+$|^[a-zA-Z0-9]+\.[-a-zA-Z0-9]+\.[a-zA-Z0-9]+$
And this thing work for general in future URLs.
A: The best regex, i've found is: /(^|\s)((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/gi
For ios swift : (^|\\s)((https?:\\/\\/)?[\\w-]+(\\.[\\w-]+)+\\.?(:\\d+)?(\\/\\S*)?)
http://jsfiddle.net/9BYdp/1/
Found here
A: Interestingly, none of the answers above worked for what I needed, so I figured I would offer my solution. I needed to be able to do the following:
*
*Match http(s)://www.google.com, http://google.com, www.google.com, and google.com
*Match Github markdown style links like [Google](http://www.google.com)
*Match all possible domain extensions, like .com, or .io, or .guru, etc. Basically anything between 2-6 characters in length
*Split everything into proper groupings so that I could access each part as needed.
Here was the solution:
/^(\[[A-z0-9 _]*\]\()?((?:(http|https):\/\/)?(?:[\w-]+\.)+[a-z]{2,6})(\))?$
This gives me all of the above requirements. You could optionally add the ability for ftp and file if necessary:
/^(\[[A-z0-9 _]*\]\()?((?:(http|https|ftp|file):\/\/)?(?:[\w-]+\.)+[a-z]{2,6})(\))?$
A: I think it is a very simple way. And it works very good.
var hasURL = (str) =>{
var url_pattern = new RegExp("(www.|http://|https://|ftp://)\w*");
if(!url_pattern.test(str)){
document.getElementById("demo").innerHTML = 'No URL';
}
else
document.getElementById("demo").innerHTML = 'String has a URL';
};
<p>Please enter a string and test it has any url or not</p>
<input type="text" id="url" placeholder="url" onkeyup="hasURL(document.getElementById('url').value)">
<p id="demo"></p>
A: If you would like to apply a more strict rule, here is what I have developed:
isValidUrl(input) {
var regex = /^(((H|h)(T|t)(T|t)(P|p)(S|s)?):\/\/)?[-a-zA-Z0-9@:%._\+~#=]{2,100}\.[a-zA-Z]{2,10}(\/([-a-zA-Z0-9@:%_\+.~#?&//=]*))?/
return regex.test(input)
}
A: Regardless the broad question asked, I post this for anyone in the future who is looking for something simple... as I think validating a URL has no perfect regular expression that fit all needs, it depends on your requirements, i.e: in my case, I just needed to verify if a URL is in the form of domain.extension and I wanted to allow the www or any other subdomain like blog.domain.extension I don't care about http(s) as in my app I have a field which says "enter the URL" so it's obvious what that entered string is.
so here is the regEx:
/^(www\.|[a-zA-Z0-9](.*[a-zA-Z0-9])?\.)?((?!www)[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9])\.[a-z]{2,5}(:[0-9]{1,5})?$/i
The first block in this regExp is:
(www\.|[a-zA-Z0-9](.*[a-zA-Z0-9])?\.)? ---> we start to check if the URL start with www. or [a-zA-Z0-9](.*[a-zA-Z0-9])? which means a letterOrNumber + (anyCharacter(0 or multiple times) + another letterOrNumber) followed with a dot
Note that the (.*[a-zA-Z0-9])?\.)? we translated by (anyCharacter(0 or multiple times) + another letterOrNumber)
is optional (can be or not) that's why we grouped it between parentheses and followed with the question mark ?
the whole block we discussed so far is also put between parentheses and followed by ? which means both www or any other word (that represents a subdomain) is optional.
The second part is: ((?!www)[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9])\. ---> which represents the "domain" part, it can be any word (except www) starting with an alphabet or a number + any other alphabet (including dash "-") repeated one or more time, and ending with any alphabet or number followed with a dot.
The final part is [a-z]{2,} ---> which represent the "extension", it can be any alphabet repeated 2 or more times, so it can be com, net, org, art basically any extension
A: A simple check for URL is
^(ftp|http|https):\/\/[^ "]+$
A: The following Regex works for me:
(http(s)?:\/\/.)?(ftp(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{0,256}\.[a-z]
{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)
matches:
https://google.com t.me https://t.me ftp://google.com http://sm.tj http://bro.tj t.me/rshss https:google.com www.cool.com.au http://www.cool.com.au http://www.cool.com.au/ersdfs http://www.cool.com.au/ersdfs?dfd=dfgd@s=1 http://www.cool.com:81/index.html
A: Javascript now has a URL Constructor called new URL(). It allows you to skip REGEX completely.
/**
*
* The URL() constructor returns a newly created URL object representing
* the URL defined by the parameters.
*
* https://developer.mozilla.org/en-US/docs/Web/API/URL/URL
*
*/
let requestUrl = new URL('https://username:password@developer.mozilla.org:8080/en-US/docs/search.html?par1=abc&par2=123&par3=true#Recent');
let urlParts = {
origin: requestUrl.origin,
href: requestUrl.href,
protocol: requestUrl.protocol,
username: requestUrl.username,
password: requestUrl.password,
host: requestUrl.host,
hostname: requestUrl.hostname,
port: requestUrl.port,
pathname: requestUrl.pathname,
search: requestUrl.search,
searchParams: {
par1: String(requestUrl.searchParams.get('par1')),
par2: Number(requestUrl.searchParams.get('par2')),
par3: Boolean(requestUrl.searchParams.get('par3')),
},
hash: requestUrl.hash
};
console.log(urlParts);
A: Thank you to @eyelidlessness for the extremely thorough (albeit long) RFC based regular expression.
For those of us using EICMAScript / JavaScript / Apps Script it doesn't work, however. Here is an otherwise exact replica of his answer that will work with these (along with a snippet to run for example - neat new feature!):
regEx_valid_URL = /^[a-z](?:[-a-z0-9\+\.])*:(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0}-\uD7FF}\uF900-\uFDCF}\uFDF0}-\uFFEF}\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0}-\uD7FF}\uF900-\uFDCF}\uFDF0}-\uFFEF}\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0}-\uD7FF}\uF900-\uFDCF}\uFDF0}-\uFFEF}\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0}-\uD7FF}\uF900-\uFDCF}\uFDF0}-\uFFEF}\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0}-\uD7FF}\uF900-\uFDCF}\uFDF0}-\uFFEF}\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0}-\uD7FF}\uF900-\uFDCF}\uFDF0}-\uFFEF}\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0}-\uD7FF}\uF900-\uFDCF}\uFDF0}-\uFFEF}\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0}-\uD7FF}\uF900-\uFDCF}\uFDF0}-\uFFEF}\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@])|[\uE000-\uF8FF}\uF0000-\uFFFFD\u100000-\u10FFFD\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0}-\uD7FF}\uF900-\uFDCF}\uFDF0}-\uFFEF}\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@])|[\/\?])*)?$/i;
checkedURL = RegExp(regEx_valid_URL).exec('gopher://example.somewhere.university/');
if (checkedURL != null) {
console.log('The URL ' + checkedURL + ' is valid');
}
A: I use this: /((https?:\/\/|ftp:\/\/|www\.)\S+\.[^()\n ]+((?:\([^)]*\))|[^.,;:?!"'\n\)\]<* ])+)/
It's short, but it handles edge cases like certain Wikipedia links (https://en.wikipedia.org/wiki/Sally_(name)) that ends in a bracket, which the most voted answers here don't seem to cover.
A:
[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)
A: URL regexes from Android Open Source Project
Introduction
The Android Open Source Project (AOSP) contains multiple code blocks with URL regular expressions in Patterns.java. It can be difficult for non-Java users to extract the regex patterns out of it because of unicode, so I wrote some code to do it. Because the regex patterns contain unicode, which literal string syntax can differ per programming language, I've added two formats of each regex pattern.
For example, Java uses \uUNICODE_NUMBER format, whereas PHP uses \u{UNICODE_NUMBER}.
Pattern called "WEB_URL"
Description from API doc:
Regular expression pattern to match most part of RFC 3987 Internationalized URLs, aka IRIs.
Regex in unicode \uUNICODE_NUMBER (Java, Python, Ruby) format:
(((?:(?i:http|https|rtsp|ftp)://(?:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,64}(?:\:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,25})?\@)?)?(?:(([a-zA-Z0-9[\u00a0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\ud800\udc00-\ud83f\udffd\ud840\udc00-\ud87f\udffd\ud880\udc00-\ud8bf\udffd\ud8c0\udc00-\ud8ff\udffd\ud900\udc00-\ud93f\udffd\ud940\udc00-\ud97f\udffd\ud980\udc00-\ud9bf\udffd\ud9c0\udc00-\ud9ff\udffd\uda00\udc00-\uda3f\udffd\uda40\udc00-\uda7f\udffd\uda80\udc00-\udabf\udffd\udac0\udc00-\udaff\udffd\udb00\udc00-\udb3f\udffd\udb44\udc00-\udb7f\udffd&&[^\u00a0[\u2000-\u200a]\u2028\u2029\u202f\u3000]]](?:[a-zA-Z0-9[\u00a0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\ud800\udc00-\ud83f\udffd\ud840\udc00-\ud87f\udffd\ud880\udc00-\ud8bf\udffd\ud8c0\udc00-\ud8ff\udffd\ud900\udc00-\ud93f\udffd\ud940\udc00-\ud97f\udffd\ud980\udc00-\ud9bf\udffd\ud9c0\udc00-\ud9ff\udffd\uda00\udc00-\uda3f\udffd\uda40\udc00-\uda7f\udffd\uda80\udc00-\udabf\udffd\udac0\udc00-\udaff\udffd\udb00\udc00-\udb3f\udffd\udb44\udc00-\udb7f\udffd&&[^\u00a0[\u2000-\u200a]\u2028\u2029\u202f\u3000]]_\-]{0,61}[a-zA-Z0-9[\u00a0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\ud800\udc00-\ud83f\udffd\ud840\udc00-\ud87f\udffd\ud880\udc00-\ud8bf\udffd\ud8c0\udc00-\ud8ff\udffd\ud900\udc00-\ud93f\udffd\ud940\udc00-\ud97f\udffd\ud980\udc00-\ud9bf\udffd\ud9c0\udc00-\ud9ff\udffd\uda00\udc00-\uda3f\udffd\uda40\udc00-\uda7f\udffd\uda80\udc00-\udabf\udffd\udac0\udc00-\udaff\udffd\udb00\udc00-\udb3f\udffd\udb44\udc00-\udb7f\udffd&&[^\u00a0[\u2000-\u200a]\u2028\u2029\u202f\u3000]]]){0,1}\.)+(xn\-\-[\w\-]{0,58}\w|[a-zA-Z[\u00a0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\ud800\udc00-\ud83f\udffd\ud840\udc00-\ud87f\udffd\ud880\udc00-\ud8bf\udffd\ud8c0\udc00-\ud8ff\udffd\ud900\udc00-\ud93f\udffd\ud940\udc00-\ud97f\udffd\ud980\udc00-\ud9bf\udffd\ud9c0\udc00-\ud9ff\udffd\uda00\udc00-\uda3f\udffd\uda40\udc00-\uda7f\udffd\uda80\udc00-\udabf\udffd\udac0\udc00-\udaff\udffd\udb00\udc00-\udb3f\udffd\udb44\udc00-\udb7f\udffd&&[^\u00a0[\u2000-\u200a]\u2028\u2029\u202f\u3000]]]{2,63})|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\:\d{1,5})?)([/\?](?:(?:[a-zA-Z0-9[\u00a0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\ud800\udc00-\ud83f\udffd\ud840\udc00-\ud87f\udffd\ud880\udc00-\ud8bf\udffd\ud8c0\udc00-\ud8ff\udffd\ud900\udc00-\ud93f\udffd\ud940\udc00-\ud97f\udffd\ud980\udc00-\ud9bf\udffd\ud9c0\udc00-\ud9ff\udffd\uda00\udc00-\uda3f\udffd\uda40\udc00-\uda7f\udffd\uda80\udc00-\udabf\udffd\udac0\udc00-\udaff\udffd\udb00\udc00-\udb3f\udffd\udb44\udc00-\udb7f\udffd&&[^\u00a0[\u2000-\u200a]\u2028\u2029\u202f\u3000]];/\?:@&=#~\-\.\+!\*'\(\),_\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\b|$|^))```
Regex in unicode \u{UNICODE_NUMBER} (PHP) format:
(((?:(?i:http|https|rtsp|ftp)://(?:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,64}(?:\:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,25})?\@)?)?(?:(([a-zA-Z0-9[\u{00a0}-\u{d7ff}\u{f900}-\u{fdcf}\u{fdf0}-\u{ffef}\u{d800}\u{dc00}-\u{d83f}\u{dffd}\u{d840}\u{dc00}-\u{d87f}\u{dffd}\u{d880}\u{dc00}-\u{d8bf}\u{dffd}\u{d8c0}\u{dc00}-\u{d8ff}\u{dffd}\u{d900}\u{dc00}-\u{d93f}\u{dffd}\u{d940}\u{dc00}-\u{d97f}\u{dffd}\u{d980}\u{dc00}-\u{d9bf}\u{dffd}\u{d9c0}\u{dc00}-\u{d9ff}\u{dffd}\u{da00}\u{dc00}-\u{da3f}\u{dffd}\u{da40}\u{dc00}-\u{da7f}\u{dffd}\u{da80}\u{dc00}-\u{dabf}\u{dffd}\u{dac0}\u{dc00}-\u{daff}\u{dffd}\u{db00}\u{dc00}-\u{db3f}\u{dffd}\u{db44}\u{dc00}-\u{db7f}\u{dffd}&&[^\u{00a0}[\u{2000}-\u{200a}]\u{2028}\u{2029}\u{202f}\u{3000}]]](?:[a-zA-Z0-9[\u{00a0}-\u{d7ff}\u{f900}-\u{fdcf}\u{fdf0}-\u{ffef}\u{d800}\u{dc00}-\u{d83f}\u{dffd}\u{d840}\u{dc00}-\u{d87f}\u{dffd}\u{d880}\u{dc00}-\u{d8bf}\u{dffd}\u{d8c0}\u{dc00}-\u{d8ff}\u{dffd}\u{d900}\u{dc00}-\u{d93f}\u{dffd}\u{d940}\u{dc00}-\u{d97f}\u{dffd}\u{d980}\u{dc00}-\u{d9bf}\u{dffd}\u{d9c0}\u{dc00}-\u{d9ff}\u{dffd}\u{da00}\u{dc00}-\u{da3f}\u{dffd}\u{da40}\u{dc00}-\u{da7f}\u{dffd}\u{da80}\u{dc00}-\u{dabf}\u{dffd}\u{dac0}\u{dc00}-\u{daff}\u{dffd}\u{db00}\u{dc00}-\u{db3f}\u{dffd}\u{db44}\u{dc00}-\u{db7f}\u{dffd}&&[^\u{00a0}[\u{2000}-\u{200a}]\u{2028}\u{2029}\u{202f}\u{3000}]]_\-]{0,61}[a-zA-Z0-9[\u{00a0}-\u{d7ff}\u{f900}-\u{fdcf}\u{fdf0}-\u{ffef}\u{d800}\u{dc00}-\u{d83f}\u{dffd}\u{d840}\u{dc00}-\u{d87f}\u{dffd}\u{d880}\u{dc00}-\u{d8bf}\u{dffd}\u{d8c0}\u{dc00}-\u{d8ff}\u{dffd}\u{d900}\u{dc00}-\u{d93f}\u{dffd}\u{d940}\u{dc00}-\u{d97f}\u{dffd}\u{d980}\u{dc00}-\u{d9bf}\u{dffd}\u{d9c0}\u{dc00}-\u{d9ff}\u{dffd}\u{da00}\u{dc00}-\u{da3f}\u{dffd}\u{da40}\u{dc00}-\u{da7f}\u{dffd}\u{da80}\u{dc00}-\u{dabf}\u{dffd}\u{dac0}\u{dc00}-\u{daff}\u{dffd}\u{db00}\u{dc00}-\u{db3f}\u{dffd}\u{db44}\u{dc00}-\u{db7f}\u{dffd}&&[^\u{00a0}[\u{2000}-\u{200a}]\u{2028}\u{2029}\u{202f}\u{3000}]]]){0,1}\.)+(xn\-\-[\w\-]{0,58}\w|[a-zA-Z[\u{00a0}-\u{d7ff}\u{f900}-\u{fdcf}\u{fdf0}-\u{ffef}\u{d800}\u{dc00}-\u{d83f}\u{dffd}\u{d840}\u{dc00}-\u{d87f}\u{dffd}\u{d880}\u{dc00}-\u{d8bf}\u{dffd}\u{d8c0}\u{dc00}-\u{d8ff}\u{dffd}\u{d900}\u{dc00}-\u{d93f}\u{dffd}\u{d940}\u{dc00}-\u{d97f}\u{dffd}\u{d980}\u{dc00}-\u{d9bf}\u{dffd}\u{d9c0}\u{dc00}-\u{d9ff}\u{dffd}\u{da00}\u{dc00}-\u{da3f}\u{dffd}\u{da40}\u{dc00}-\u{da7f}\u{dffd}\u{da80}\u{dc00}-\u{dabf}\u{dffd}\u{dac0}\u{dc00}-\u{daff}\u{dffd}\u{db00}\u{dc00}-\u{db3f}\u{dffd}\u{db44}\u{dc00}-\u{db7f}\u{dffd}&&[^\u{00a0}[\u{2000}-\u{200a}]\u{2028}\u{2029}\u{202f}\u{3000}]]]{2,63})|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\:\d{1,5})?)([/\?](?:(?:[a-zA-Z0-9[\u{00a0}-\u{d7ff}\u{f900}-\u{fdcf}\u{fdf0}-\u{ffef}\u{d800}\u{dc00}-\u{d83f}\u{dffd}\u{d840}\u{dc00}-\u{d87f}\u{dffd}\u{d880}\u{dc00}-\u{d8bf}\u{dffd}\u{d8c0}\u{dc00}-\u{d8ff}\u{dffd}\u{d900}\u{dc00}-\u{d93f}\u{dffd}\u{d940}\u{dc00}-\u{d97f}\u{dffd}\u{d980}\u{dc00}-\u{d9bf}\u{dffd}\u{d9c0}\u{dc00}-\u{d9ff}\u{dffd}\u{da00}\u{dc00}-\u{da3f}\u{dffd}\u{da40}\u{dc00}-\u{da7f}\u{dffd}\u{da80}\u{dc00}-\u{dabf}\u{dffd}\u{dac0}\u{dc00}-\u{daff}\u{dffd}\u{db00}\u{dc00}-\u{db3f}\u{dffd}\u{db44}\u{dc00}-\u{db7f}\u{dffd}&&[^\u{00a0}[\u{2000}-\u{200a}]\u{2028}\u{2029}\u{202f}\u{3000}]];/\?:@&=#~\-\.\+!\*'\(\),_\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\b|$|^))
Other patterns
Patterns.java contains more patterns, but posting them will hit the Stackoverflow post length limit. But I'll post the API descriptions of them here, so that you know about their existence and purpose. I've also added code below to output these patterns using Kotlin.
Pattern called "WEB_URL_WITHOUT_PROTOCOL"
Description:
Regular expression to match strings that do not start with a supported protocol. The TLDs are expected to be one of the known TLDs.
Definition:
"("
+ WORD_BOUNDARY
+ "(?<!:\\/\\/)"
+ "("
+ "(?:" + STRICT_DOMAIN_NAME + ")"
+ "(?:" + PORT_NUMBER + ")?"
+ ")"
+ "(?:" + PATH_AND_QUERY + ")?"
+ WORD_BOUNDARY
+ ")";
Pattern called "WEB_URL_WITH_PROTOCOL"
Description:
Regular expression to match strings that start with a supported protocol. Rules for domain names and TLDs are more relaxed. TLDs are optional.
Definition:
"("
+ WORD_BOUNDARY
+ "(?:"
+ "(?:" + PROTOCOL + "(?:" + USER_INFO + ")?" + ")"
+ "(?:" + RELAXED_DOMAIN_NAME + ")?"
+ "(?:" + PORT_NUMBER + ")?"
+ ")"
+ "(?:" + PATH_AND_QUERY + ")?"
+ WORD_BOUNDARY
+ ")";
Pattern called "AUTOLINK_WEB_URL"
Description:
Regular expression pattern to match IRIs. If a string starts with
http(s):// the expression tries to match the URL structure with a
relaxed rule for TLDs. If the string does not start with http(s)://
the TLDs are expected to be one of the known TLDs.
Definition:
"(" + WEB_URL_WITH_PROTOCOL + "|" + WEB_URL_WITHOUT_PROTOCOL + ")")
Code to output the patterns from AOSP Patterns.java
This code is written in language Kotlin (a Java JVM based language). If converts the regex patterns from AOSP Patterns.java to a readable format:
import java.util.regex.Pattern
fun createPattern(pattern: Pattern, unicodeStringFormat: String): String =
pattern.toString().flatMap {
val charCode = it.code
if (charCode > 126) {
unicodeStringFormat.format(charCode).toList()
} else {
listOf(it)
}
}.joinToString("")
fun main() {
val unicodeStringFormatJava = "\\u%04x"
val unicodeStringFormatPHP = "\\u{%04x}"
// Pattern: WEB_URL
println(createPattern(Patterns.WEB_URL, unicodeStringFormatJava))
println(createPattern(Patterns.WEB_URL, unicodeStringFormatPHP))
// Pattern: AUTOLINK_WEB_URL
println(createPattern(Patterns.AUTOLINK_WEB_URL, unicodeStringFormatJava))
println(createPattern(Patterns.AUTOLINK_WEB_URL, unicodeStringFormatPHP))
// Pattern: WEB_URL_WITH_PROTOCOL (variable modified to public visibility)
println(createPattern(Patterns.WEB_URL_WITH_PROTOCOL.toPattern(), unicodeStringFormatJava))
println(createPattern(Patterns.WEB_URL_WITH_PROTOCOL.toPattern(), unicodeStringFormatPHP))
// Pattern: WEB_URL_WITHOUT_PROTOCOL (variable modified to public visibility)
println(createPattern(Patterns.WEB_URL_WITHOUT_PROTOCOL.toPattern(), unicodeStringFormatJava))
println(createPattern(Patterns.WEB_URL_WITHOUT_PROTOCOL.toPattern(), unicodeStringFormatPHP))
}
A: /^(http|HTTP)+(s|S)?:\/\/[\w.-]+(?:\.[\w\.-]+)+[\w\-\._\$\(\)/]+$/g
check demo with tests:
https://regexr.com/5cedu
A: The best regex is a combination of the best answers here! hahaha! I have just tested them all, and put the best together! I changed it a little to only have one capture group! I was able to find 637 URLs in the source code of this page! Only a few false positives!
((?:(?:https?|ftp)://)(?:\S+(?::\S*)?@|\d{1,3}(?:\.\d{1,3}){3}|(?:(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)(?:\.(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)*(?:\.[a-z\x{00a1}-\x{ffff}]{2,6}))(?::\d+)?(?:[^\s]*)|(?:(?:(?:[A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::[0-9]+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)(?:(?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)|(?:(?:(?:(?:[A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)(?:(?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?))|(?:(?:(?:[\\w]+:)?//)?(?:(?:[\\d\\w]|%[a-fA-f\\d]{2,2})+(?::(?:[\\d\\w]|%[a-fA-f\\d]{2,2})+)?@)?(?:[\\d\\w][-\\d\\w]{0,253}[\\d\\w]\\.)+[\\w]{2,4}(?::[\\d]+)?(?:/(?:[-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})*)*(?:\\?(?:&?(?:[-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})=?)*)?(?:#(?:[-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})*)?)|(?:https?:\/\/(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9])(?::?\d*)\/?(?:[a-z_\/0-9\-#.]*)\??(?:[a-z_\/0-9\-#=&]*)|(?:(?:(?:https?:)?(?:\/?\/))(?:(?:[\d\w]|%[a-fA-f\d]{2,2})+(?::(?:[\d\w]|%[a-fA-f\d]{2,2})+)?@)?(?:[\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,63}(?::[\d]+)?(?:/(?:[-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(?:\?(?:&?(?:[-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(?:#(?:[-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?)|(?:(?:https?|ftp)://(?:www\d?|[a-zA-Z0-9]+)?\.[a-zA-Z0-9-]+(?:\:|\.)(?:[a-zA-Z0-9.]+|(?:\d+)?)(?:[/?:].*)?)|(?:\b(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?\b))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1019"
} |
Q: How to allow MediaWiki logged user to edit Common.css? I would like to allow the logged user to edit MediaWiki/Common.css without adding them to the sysop group.
I understand that this will allow user to change it to harful ways but it is a closed wiki so that is not a problem.
Any solution is acceptable even changing php code :)
A: Create a new group, add give it "editinterface" privilege. In LocalSettings.php it's done like this:
$wgGroupPermissions['mynewgroup']['editinterface'] = true;
Then add the user to you new group.
Or if you want to give that right to all logged-in users, do it like this:
$wgGroupPermissions['user']['editinterface'] = true;
// user is the default group for all logged-in users
For details see MediaWiki manual.
A: Probably safer to use;
$wgAllowUserCss = true;
See Mediawiki Manual for the complete details.
"When enabled, users are able to make personalised customisations over and above the normal choice of skins within the 'preferences' display."
A similar setting is available for Javascript.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How would you implement ant-style patternsets in python to select groups of files? Ant has a nice way to select groups of files, most handily using ** to indicate a directory tree. E.g.
**/CVS/* # All files immediately under a CVS directory.
mydir/mysubdir/** # All files recursively under mysubdir
More examples can be seen here:
http://ant.apache.org/manual/dirtasks.html
How would you implement this in python, so that you could do something like:
files = get_files("**/CVS/*")
for file in files:
print file
=>
CVS/Repository
mydir/mysubdir/CVS/Entries
mydir/mysubdir/foo/bar/CVS/Entries
A: Sorry, this is quite a long time after your OP. I have just released a Python package which does exactly this - it's called Formic and it's available at the PyPI Cheeseshop. With Formic, your problem is solved with:
import formic
fileset = formic.FileSet(include="**/CVS/*", default_excludes=False)
for file_name in fileset.qualified_files():
print file_name
There is one slight complexity: default_excludes. Formic, just like Ant, excludes CVS directories by default (as for the most part collecting files from them for a build is dangerous), the default answer to the question would result in no files. Setting default_excludes=False disables this behaviour.
A: As soon as you come across a **, you're going to have to recurse through the whole directory structure, so I think at that point, the easiest method is to iterate through the directory with os.walk, construct a path, and then check if it matches the pattern. You can probably convert to a regex by something like:
def glob_to_regex(pat, dirsep=os.sep):
dirsep = re.escape(dirsep)
print re.escape(pat)
regex = (re.escape(pat).replace("\\*\\*"+dirsep,".*")
.replace("\\*\\*",".*")
.replace("\\*","[^%s]*" % dirsep)
.replace("\\?","[^%s]" % dirsep))
return re.compile(regex+"$")
(Though note that this isn't that fully featured - it doesn't support [a-z] style glob patterns for instance, though this could probably be added). (The first \*\*/ match is to cover cases like \*\*/CVS matching ./CVS, as well as having just \*\* to match at the tail.)
However, obviously you don't want to recurse through everything below the current dir when not processing a ** pattern, so I think you'll need a two-phase approach. I haven't tried implementing the below, and there are probably a few corner cases, but I think it should work:
*
*Split the pattern on your directory seperator. ie pat.split('/') -> ['**','CVS','*']
*Recurse through the directories, and look at the relevant part of the pattern for this level. ie. n levels deep -> look at pat[n].
*If pat[n] == '**' switch to the above strategy:
*
*Reconstruct the pattern with dirsep.join(pat[n:])
*Convert to a regex with glob\_to\_regex()
*Recursively os.walk through the current directory, building up the path relative to the level you started at. If the path matches the regex, yield it.
*If pat doesn't match "**", and it is the last element in the pattern, then yield all files/dirs matching glob.glob(os.path.join(curpath,pat[n]))
*If pat doesn't match "**", and it is NOT the last element in the pattern, then for each directory, check if it matches (with glob) pat[n]. If so, recurse down through it, incrementing depth (so it will look at pat[n+1])
A: os.walk is your friend. Look at the example in the Python manual
(https://docs.python.org/2/library/os.html#os.walk) and try to build something from that.
To match "**/CVS/*" against a file name you get, you can do something like this:
def match(pattern, filename):
if pattern.startswith("**"):
return fnmatch.fnmatch(file, pattern[1:])
else:
return fnmatch.fnmatch(file, pattern)
In fnmatch.fnmatch, "*" matches anything (including slashes).
A: There's an implementation in the 'waf' build system source code.
http://code.google.com/p/waf/source/browse/trunk/waflib/Node.py?r=10755#471
May be this should be wrapped up in a library of its own?
A: Yup. Your best bet is, as has already been suggested, to work with 'os.walk'. Or, write wrappers around 'glob' and 'fnmatch' modules, perhaps.
A: os.walk is your best bet for this. I did the example below with .svn because I had that handy, and it worked great:
import re
for (dirpath, dirnames, filenames) in os.walk("."):
if re.search(r'\.svn$', dirpath):
for file in filenames:
print file
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Putting configuration information in a DLL In my project I have functionality that is being used as a web application and as a console application (to be started from the task scheduler). To do that I put the common code in a DLL that is being used by both the web application and the console application. This works fine.
However, the console and web applications now have an App.config and Web.config that are mostly the same. Is it possible to put this configuration in the DLL as well and make it available to both applications?
A: Yes, you can and should put the common configuration settings in the config file for your DLL. Just add an app.config file to the DLL project, and make sure you read the configuration settings from inside the DLL. When deployed, your config file needs to have the name "MyDLL.dll.config" (assuming your DLL is named "MyDLL.dll") and be in the same folder as the DLL.
A: I'd suggest that you move the configuration loading to the dll rather than the entire configuration, and then call it from the different apps. This is so that:
*
*You don't need to recompile to change config data (always useful)
*If you need to split the config again in the future, this will already be possible with the dll.
A: you could put the common configuration under the windows registry, accessible wherever you like
A: Assuming you are using .Net, you can set up a .settings file to store your configuration data - the data contained there will be stored as default values for those config entries so even if there is no app.config file, your application will run with those defaults.
I'm not saying that's a good thing... 8)
So, if you build a project that references your DLL, you would add the same .settings file to that project and those settings would appear in the app.config file for the app and the DLL would be able to read those values. IF those values aren't in the app.config, the dll will fall back on the defaults.
Most people will think that's a bad thing and I tend to agree but there you are.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: php - imap - moving emails on antoher account I am working on a script that downloads emails and stores them in a db, I usually receive thousands of emails on this account, once downloaded the mails are deleted.
Being paranoic, I want to have at least one month backup of my emails, but I cannot clutter my main mailbox address leaving them in there.
So i need to move the mails (via php code) from one mailbox to another. I came up with this solution that uses imap_append(). This solution, however recreates the email, and does not really move it.
Do you have any suggestions or alternative ways of doing this?
Remember: it must be done in php, because I need to integrate it in my readmail script.
I have already seen this thread where a fetchmail solution was proposed
Here follows the code I wrote for this task
<?php
/**
* Conn params
*/
$fromMboxServerPath = "{imap.from.server/notls/imap:143}";
$fromMboxMailboxPath = "INBOX";
$fromMboxMailAddress = "login";
$fromMboxMailPass = "pass";
$toMboxServerPath = "{imap.to.server/notls/imap:143}";
$toMboxMailboxPath = "INBOX";
$toMboxMailAddress = "login";
$toMboxMailPass = "pass";
$fromMboxConnStr = $fromMboxServerPath.$fromMboxMailboxPath;
$toMboxConnStr = $toMboxServerPath.$toMboxMailboxPath;
$fetchStartSeq = 1;
$fetchEndSeq = 10;
function myLog($str)
{
echo "Log [".date('Y-m-d H:i:s')."]: $str\n";
}
myLog("Connecting to mailbox");
function mboxConn($connstr,$addr,$pass)
{
if(!($mbox = @imap_open($connstr, $addr, $pass)))
{
myLog("Error: ".imap_last_error());
die;
}
else
{
myLog("Connected to: $addr $connstr");
return $mbox;
}
}
function mboxCheck($mbox)
{
if(!($mbox_data = imap_check($mbox)))
{
myLog("Error: ".imap_last_error());
die;
}
else
{
myLog("Mailbox check ".$mbox_data->Mailbox." OK");
myLog($mbox_data->Nmsgs." messages present");
return $mbox_data->Nmsgs;
}
}
$fromMbox = mboxConn($fromMboxConnStr, $fromMboxMailAddress, $fromMboxMailPass);
$toMbox = mboxConn($toMboxConnStr, $toMboxMailAddress, $toMboxMailPass);
$fromMboxCount = mboxCheck($fromMbox);
$toMboxCount = mboxCheck($toMbox);
/**
* Loop on mails
*/
$fetchStartUID = imap_uid($fromMbox,$fetchStartSeq);
if ($fromMboxCount < $fetchEndSeq)
{
$fetchEndSeq = $fromMboxCount;
}
$fetchEndUID = imap_uid($fromMbox,$fetchEndSeq);
/**
* Loop on mails
*/
myLog("Do stuff and backup from UID [$fetchStartUID] to UID [$fetchEndUID]");
for ($i=$fetchStartSeq;$i<=$fetchEndSeq;$i++)
{
$pfx = "Msg #$i : ";
$h = imap_header($fromMbox, $i);
$fh = imap_fetchheader($fromMbox, $i);
$fb = imap_body($fromMbox, $i);
$message = $fh.$fb;
$msgUID = imap_uid($fromMbox,$i);
$struct = imap_fetchstructure ($fromMbox, $i);
/**
* We do some logging
*/
myLog($pfx."UID [".$msgUID."] SEQ [".imap_msgno($fromMbox,$msgUID)."] Flags: [". $h->Unseen . $h->Recent . $h->Deleted . $h->Answered . $h->Draft . $h->Flagged."]");
myLog($pfx."From: [". htmlspecialchars($h->fromaddress) . "] To: [".htmlspecialchars($h->toaddress)."]");
myLog($pfx."Subject: [$h->subject]");
/**
* Here you do whaterver you need with your email
*/
/**
* Backup email
*/
if (!($ret = imap_append($toMbox,$toMboxServerPath.$toMboxMailboxPath,$message)))
{
myLog("Error: ".imap_last_error());
die;
}
else
{
myLog("everything ok, mail [$fetchStartUID:$fetchEndUID] downloaded and moved in $newMailboxNameMOVE");
}
}
/**
* End
*/
imap_close($fromMbox);
imap_close($toMbox);
myLog("Connection closed");
?>
A: First, IMAP does not have a MOVE command only copy but even if it did you can copy from one IMAP server to another directly.
Why not use a subfolder in the account for backups. Download them to your local machine then COPY them to the subfolder and then DELETE them from the INBOX.
COPY and DELETE are imap server side commands so they don't have to leave the server to do the "move"
If both accounts are on the same server there is another option, allow access to the backup account's INBOX to the primary account user. Then you can use server side copy/delete to move it to the backup folder.
Not all IMAP servers allow for shared folders.
php does have a imap_move function but I assume it does a copy/delete.
A: I don't know any other solution like PHP.
But for your code and testing you should use:
$fromMboxServerPath = "{imap.from.server/notls/imap/readonly:143}"; //ReadOnly
in imap_append() you should give the date from emailheader. see PHP Manual: http://php.net/manual/en/function.imap-append.php
after that you will have a 1to1 copy of your mail in the target IMAP-Server.
A: Why separate account and all the hassle that will be involved? Can't you either
a) backup the mail account using standard backup tools like, eg. rdiff-backup?
b) back them up in the db?
or even
c) create an alias so that emails go to both accounts and you have different criteria for removing mails from both accounts (ie. keep them for one more month in the backup account)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the best MemCache solution for ASP.NET applications? What is the best MemCache solution for ASP.NET applications running in a windows server environment? Why?
A: You could also check out Microsoft Velocity, especially if you're at a place that prefers Microsoft products.
A: My sentiments exactly - My Question
From what I've gathered, memcacheddotnet is the best free options,
scaleout if you want to pay
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is JavaScript single threaded? If not, how do I get synchronized access to shared data? I have a web page with DIVs with a mouseover handler that is intended to show a pop-up information bubble. I don't want more than one info bubble to be visible at a time. But when the user moves the mouse rapidly over two items, I sometimes get two bubbles. This should not happen, because the code for showing a pop-up cancels the previous pop-up.
If this were a multi-threaded system then the problem would be obvious: there are two threads trying to show a pop-up, and they both cancel existing pop-ups then pop up their own pop-ups. But I assumed JavaScript is always run single-threaded, which would prevent this. Am I wrong? Are event handlers running asynchronously, in which case I need synchronized access to shared data, or should I instead be looking for bugs in the library code for cancelling pop-ups?
Edited to add:
*
*The library in question is SIMILE Timeline and its Ajax library;
*The event handler does call SimileAjax.DOM.cancelEvent(domEvt), which I assume based on the name cancels the bubbling of events;
*Just to make thing s more complicated, what I am actually doing is starting a timeout that if not cancelled by a moustout shows the pop-up, this being intended to prevent pop-ups flickering annoyingly but annoyingly having the reverse effect.
I'll have another poke at it and see if I can work out where I am going wrong. :-)
A: I don't know the library you are using, but if you are only trying to display one tooltip of somesort at a time... use a flyweight object. Basically a flyweight is something that is made once and used over and over again. Think of a singleton class. So you call a class statically that when first invoked automatically creates an object of itself and stores it. One this happens every static all references the same object and because of this you don't get multiple tooltips or conflicts.
I use ExtJS and they do tooltips, and message boxes as both flyweight elements. I'm hoping that your frameworks had flyweight elements as well, otherwise you will just have to make your own singleton and call it.
A: Yes, Javascript is single-threaded. Even with browsers like Google Chrome, there is one thread per tab.
Without knowing how you are trying to cancel one pop-up from another, it's hard to say what is the cause of your problem.
If your DIVs are nested within one another, you may have an event propagation issue.
A: It is single threaded in browsers. Event handlers are running asynchroniously in one thread, non blocking doesn't allways mean multithreaded. Is one of your divs a child of the other? Because events spread like bubbles in the dom tree from child to parent.
A: Similar to what pkaeding said, it's hard to guess the problem without seeing your markup and script; however, I'd venture to say that you're not properly stopping the event propagation and/or you're not properly hiding the existing element. I don't know if you're using a framework or not, but here's a possible solution using Prototype:
// maintain a reference to the active div bubble
this.oActiveDivBubble = null;
// event handler for the first div
$('exampleDiv1').observe('mouseover', function(evt) {
evt.stop();
if(this.oActiveDivBubble ) {
this.oActiveDivBubble .hide();
}
this.oActiveDivBubble = $('exampleDiv1Bubble');
this.oActiveDivBubble .show();
}.bind(this));
// event handler for the second div
$('exampleDiv2').observe('mouseover'), function(evt) {
evt.stop();
if(this.oActiveDivBubble) {
this.oActiveDivBubble.hide();
}
this.oActiveDivBubble = $('exampleDiv2Bubble');
this.oActiveDivBubble .show();
}.bind(this));
Of course, this could be generalized further by getting all of the elements with, say, the same class, iterating through them, and applying the same event handling function to each of them.
Either way, hopefully this helps.
A: FYI: As of Firefox 3 there is a change pretty much relevant to this discussion: execution threads causing synchronous XMLHttpRequest requests get detached (this is why the interface doesn't freeze there during synchronous requests) and the execution continues. Upon synchronous request completion, its thread continues as well. They won't be executed at the same time, however relying on the assumption that single thread stops while a synchronous procedure (request) happening is not applicable any more.
A: It could be that the display isn't refreshing fast enough. Depending on the JS library you are using, you might be able to put a tiny delay on the pop-up "show" effect.
A: Here's the working version, more or less. When creating items we attach a mouseover event:
var self = this;
SimileAjax.DOM.registerEvent(labelElmtData.elmt, "mouseover", function (elt, domEvt, target) {
return self._onHover(labelElmtData.elmt, domEvt, evt);
});
This calls a function that sets a timeout (pre-existing timeouts for a different item is cancelled first):
MyPlan.EventPainter.prototype._onHover = function(target, domEvt, evt) {
... calculate x and y ...
domEvt.cancelBubble = true;
SimileAjax.DOM.cancelEvent(domEvt);
this._futureShowBubble(x, y, evt);
return false;
}
MyPlan.EventPainter.prototype._futureShowBubble = function (x, y, evt) {
if (this._futurePopup) {
if (evt.getID() == this._futurePopup.evt.getID()) {
return;
} else {
/* We had queued a different event's pop-up; this must now be cancelled. */
window.clearTimeout(this._futurePopup.timeoutID);
}
}
this._futurePopup = {
x: x,
y: y,
evt: evt
};
var self = this;
this._futurePopup.timeoutID = window.setTimeout(function () {
self._onTimeout();
}, this._popupTimeout);
}
This in turn shows the bubble if it fires before being cancelled:
MyPlan.EventPainter.prototype._onTimeout = function () {
this._showBubble(this._futurePopup.x, this._futurePopup.y, this._futurePopup.evt);
};
MyPlan.EventPainter.prototype._showBubble = function(x, y, evt) {
if (this._futurePopup) {
window.clearTimeout(this._futurePopup.timeoutID);
this._futurePopup = null;
}
...
SimileAjax.WindowManager.cancelPopups();
SimileAjax.Graphics.createBubbleForContentAndPoint(...);
};
This seems to work now I have set the timeout to 200 ms rather than 100 ms. Not sure why too short a timeout causes the multi-bubble thing to happen, but I guess queuing of window events or something might still be happening while the newly added elements are being laid out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Are there any downsides to passing structs by value in C, rather than passing a pointer? Are there any downsides to passing structs by value in C, rather than passing a pointer?
If the struct is large, there is obviously the performance aspect of copying lots of data, but for a smaller struct, it should basically be the same as passing several values to a function.
It is maybe even more interesting when used as return values. C only has single return values from functions, but you often need several. So a simple solution is to put them in a struct and return that.
Are there any reasons for or against this?
Since it might not be obvious to everyone what I'm talking about here, I'll give a simple example.
If you're programming in C, you'll sooner or later start writing functions that look like this:
void examine_data(const char *ptr, size_t len)
{
...
}
char *p = ...;
size_t l = ...;
examine_data(p, l);
This isn't a problem. The only issue is that you have to agree with your coworker in which the order the parameters should be so you use the same convention in all functions.
But what happens when you want to return the same kind of information? You typically get something like this:
char *get_data(size_t *len);
{
...
*len = ...datalen...;
return ...data...;
}
size_t len;
char *p = get_data(&len);
This works fine, but is much more problematic. A return value is a return value, except that in this implementation it isn't. There is no way to tell from the above that the function get_data isn't allowed to look at what len points to. And there is nothing that makes the compiler check that a value is actually returned through that pointer. So next month, when someone else modifies the code without understanding it properly (because he didn't read the documentation?) it gets broken without anyone noticing, or it starts crashing randomly.
So, the solution I propose is the simple struct
struct blob { char *ptr; size_t len; }
The examples can be rewritten like this:
void examine_data(const struct blob data)
{
... use data.tr and data.len ...
}
struct blob = { .ptr = ..., .len = ... };
examine_data(blob);
struct blob get_data(void);
{
...
return (struct blob){ .ptr = ...data..., .len = ...len... };
}
struct blob data = get_data();
For some reason, I think that most people would instinctively make examine_data take a pointer to a struct blob, but I don't see why. It still gets a pointer and an integer, it's just much clearer that they go together. And in the get_data case it is impossible to mess up in the way I described before, since there is no input value for the length, and there must be a returned length.
A: I'd say passing (not-too-large) structs by value, both as parameters and as return values, is a perfectly legitimate technique. One has to take care, of course, that the struct is either a POD type, or the copy semantics are well-specified.
Update: Sorry, I had my C++ thinking cap on. I recall a time when it was not legal in C to return a struct from a function, but this has probably changed since then. I would still say it's valid as long as all the compilers you expect to use support the practice.
A: I think that your question has summed things up pretty well.
One other advantage of passing structs by value is that memory ownership is explicit. There is no wondering about if the struct is from the heap, and who has the responsibility for freeing it.
A: One reason not to do this which has not been mentioned is that this can cause an issue where binary compatibility matters.
Depending on the compiler used, structures can be passed via the stack or registers depending on compiler options/implementation
See: http://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html
-fpcc-struct-return
-freg-struct-return
If two compilers disagree, things can blow up. Needless to say the main reasons not to do this are illustrated are stack consumption and performance reasons.
A: Page 150 of PC Assembly Tutorial on http://www.drpaulcarter.com/pcasm/ has a clear explanation about how C allows a function to return a struct:
C also allows a structure type to be
used as the return value of a func-
tion. Obviously a structure can not be
returned in the EAX register.
Different compilers handle this
situation differently. A common
solution that compilers use is to
internally rewrite the function as one
that takes a structure pointer as a
parameter. The pointer is used to put
the return value into a structure
defined outside of the routine called.
I use the following C code to verify the above statement:
struct person {
int no;
int age;
};
struct person create() {
struct person jingguo = { .no = 1, .age = 2};
return jingguo;
}
int main(int argc, const char *argv[]) {
struct person result;
result = create();
return 0;
}
Use "gcc -S" to generate assembly for this piece of C code:
.file "foo.c"
.text
.globl create
.type create, @function
create:
pushl %ebp
movl %esp, %ebp
subl $16, %esp
movl 8(%ebp), %ecx
movl $1, -8(%ebp)
movl $2, -4(%ebp)
movl -8(%ebp), %eax
movl -4(%ebp), %edx
movl %eax, (%ecx)
movl %edx, 4(%ecx)
movl %ecx, %eax
leave
ret $4
.size create, .-create
.globl main
.type main, @function
main:
pushl %ebp
movl %esp, %ebp
subl $20, %esp
leal -8(%ebp), %eax
movl %eax, (%esp)
call create
subl $4, %esp
movl $0, %eax
leave
ret
.size main, .-main
.ident "GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3"
.section .note.GNU-stack,"",@progbits
The stack before call create:
+---------------------------+
ebp | saved ebp |
+---------------------------+
ebp-4 | age part of struct person |
+---------------------------+
ebp-8 | no part of struct person |
+---------------------------+
ebp-12 | |
+---------------------------+
ebp-16 | |
+---------------------------+
ebp-20 | ebp-8 (address) |
+---------------------------+
The stack right after calling create:
+---------------------------+
| ebp-8 (address) |
+---------------------------+
| return address |
+---------------------------+
ebp,esp | saved ebp |
+---------------------------+
A: For small structs (eg point, rect) passing by value is perfectly acceptable. But, apart from speed, there is one other reason why you should be careful passing/returning large structs by value: Stack space.
A lot of C programming is for embedded systems, where memory is at a premium, and stack sizes may be measured in KB or even Bytes... If you're passing or returning structs by value, copies of those structs will get placed on the stack, potentially causing the situation that this site is named after...
If I see an application that seems to have excessive stack usage, structs passed by value is one of the things I look for first.
A: To really answer this question, one needs to dig deep into the assembly land:
(The following example uses gcc on x86_64. Anyone is welcome to add other architectures like MSVC, ARM, etc.)
Let's have our example program:
// foo.c
typedef struct
{
double x, y;
} point;
void give_two_doubles(double * x, double * y)
{
*x = 1.0;
*y = 2.0;
}
point give_point()
{
point a = {1.0, 2.0};
return a;
}
int main()
{
return 0;
}
Compile it with full optimizations
gcc -Wall -O3 foo.c -o foo
Look at the assembly:
objdump -d foo | vim -
This is what we get:
0000000000400480 <give_two_doubles>:
400480: 48 ba 00 00 00 00 00 mov $0x3ff0000000000000,%rdx
400487: 00 f0 3f
40048a: 48 b8 00 00 00 00 00 mov $0x4000000000000000,%rax
400491: 00 00 40
400494: 48 89 17 mov %rdx,(%rdi)
400497: 48 89 06 mov %rax,(%rsi)
40049a: c3 retq
40049b: 0f 1f 44 00 00 nopl 0x0(%rax,%rax,1)
00000000004004a0 <give_point>:
4004a0: 66 0f 28 05 28 01 00 movapd 0x128(%rip),%xmm0
4004a7: 00
4004a8: 66 0f 29 44 24 e8 movapd %xmm0,-0x18(%rsp)
4004ae: f2 0f 10 05 12 01 00 movsd 0x112(%rip),%xmm0
4004b5: 00
4004b6: f2 0f 10 4c 24 f0 movsd -0x10(%rsp),%xmm1
4004bc: c3 retq
4004bd: 0f 1f 00 nopl (%rax)
Excluding the nopl pads, give_two_doubles() has 27 bytes while give_point() has 29 bytes. On the other hand, give_point() yields one fewer instruction than give_two_doubles()
What's interesting is that we notice the compiler has been able to optimize mov into the faster SSE2 variants movapd and movsd. Furthermore, give_two_doubles() actually moves data in and out from memory, which makes things slow.
Apparently much of this may not be applicable in embedded environments (which is where the playing field for C is most of the time nowdays). I'm not an assembly wizard so any comments would be welcome!
A: One thing people here have forgotten to mention so far (or I overlooked it) is that structs usually have a padding!
struct {
short a;
char b;
short c;
char d;
}
Every char is 1 byte, every short is 2 bytes. How large is the struct? Nope, it's not 6 bytes. At least not on any more commonly used systems. On most systems it will be 8. The problem is, the alignment is not constant, it's system dependent, so the same struct will have different alignment and different sizes on different systems.
Not only that padding will further eat up your stack, it also adds the uncertainty of not being able to predict the padding in advance, unless you know how your system pads and then look at every single struct you have in your app and calculate the size for it. Passing a pointer takes a predictable amount of space -- there is no uncertainty. The size of a pointer is known for the system, it is always equal, regardless of what the struct looks like and pointer sizes are always chosen in a way that they are aligned and need no padding.
A: Simple solution will be return an error code as a return value and everything else as a parameter in the function,
This parameter can be a struct of course but don't see any particular advantage passing this by value, just sent a pointer.
Passing structure by value is dangerous, you need to be very careful what are you passing are, remember there is no copy constructor in C, if one of structure parameters is a pointer the pointer value will be copied it might be very confusing and hard to maintain.
Just to complete the answer (full credit to Roddy ) the stack usage is another reason not pass structure by value, believe me debugging stack overflow is real PITA.
Replay to comment:
Passing struct by pointer meaning that some entity has an ownership on this object and have a full knowledge of what and when should be released. Passing struct by value create a hidden references to the internal data of struct (pointers to another structures etc .. ) at this is hard to maintain (possible but why ?) .
A: Here's something no one mentioned:
void examine_data(const char *c, size_t l)
{
c[0] = 'l'; // compiler error
}
void examine_data(const struct blob blob)
{
blob.ptr[0] = 'l'; // perfectly legal, quite likely to blow up at runtime
}
Members of a const struct are const, but if that member is a pointer (like char *), it becomes char *const rather than the const char * we really want. Of course, we could assume that the const is documentation of intent, and that anyone who violates this is writing bad code (which they are), but that's not good enough for some (especially those who just spent four hours tracking down the cause of a crash).
The alternative might be to make a struct const_blob { const char *c; size_t l } and use that, but that's rather messy - it gets into the same naming-scheme problem I have with typedefing pointers. Thus, most people stick to just having two parameters (or, more likely for this case, using a string library).
A: I just want to point one advantage of passing your structs by value is that an optimizing compiler may better optimize your code.
A: Taking into account all of the things people have said...
*
*Returning a struct was not always allowed in C. Now it is.
*Returning a struct can be done in three ways...
a. Returning each member in a register (probably optimal, but unlikely to be the actual...)
b. Returning the struct in the stack (slower than registers, but still better than a cold access of heap ram... yay caching!)
c. Returning the struct in a pointer to the heap (It only hurts you when you read or write to it? A Good compiler will pass the pointers it read just once and tried to access, did instruction reordering and accesses it much earlier than needed so it was ready when you were? to make life better? (shiver))
*Different compiler settings can cause different problems when the code interfaces because of this. (Different size registers, different amounts of padding, different optimizations turned on)
*const-ness or volatile-ness doesn't permeate through a struct, and can result in some miserably un-efficient or possibly lead to broken code (E.G. a const struct foo does not result in foo->bar being const.)
Some simple measures I will take after reading this...
*
*Make your functions accept parameters rather than structs. It allows fine grained control over const-ness and volatile-ness etc, it also ensures that all the variables passed are relevant to the function using them. If the parameters are all the same kind, use some other method to enforce ordering. (Make type defs to make your function calls more strongly typed, which an OS does routinely.)
*Instead of allowing the final base function to return a pointer to a structure made in the heap, provide a pointer to a struct to put the results into. that struct still might be in the heap, but it is possible that the struct is actually in the stack - and will get better runtime performance. It also means that you do not need to rely on compilers providing you a struct return type.
*By passing the parameters as pieces and being clear about the const-ness, volatile-ness, or the restrict-ness, you better convey your intentions to the complier and that will allow it to make better optimizations.
I am not sure where 'too big' and 'too small' is at, but I guess the answer is between 2 and register count + 1 members.
If I made a struct that holds 1 member that is an int, then clearly we should not pass the struct. (Not only is it inefficient, it also makes intention VERY murky... I suppose it has a use somewhere, but not common)
If I make a struct that holds two items, it might have value in clarity, as well as compliers might optimize it into two variables that travel as pairs. (risc-v specifies that a struct with two members returns both members in registers, assuming they are ints or smaller...)
If I make a structure that holds as many ints and double as there are in the registers for in the processor, it is TECHNICALLY a possible optimization.
The instance I surpass the register amounts though, it probably would have been worth it to keep the result struct in a pointer, and pass in only the parameters that were relevant. (That, and probably make the struct smaller and the function do less, because we have a LOT of registers on systems nowadays, even in the embedded world...)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "185"
} |
Q: initialize a const array in a class initializer in C++ I have the following class in C++:
class a {
const int b[2];
// other stuff follows
// and here's the constructor
a(void);
}
The question is, how do I initialize b in the initialization list, given that I can't initialize it inside the body of the function of the constructor, because b is const?
This doesn't work:
a::a(void) :
b([2,3])
{
// other initialization stuff
}
Edit: The case in point is when I can have different values for b for different instances, but the values are known to be constant for the lifetime of the instance.
A: With C++11 the answer to this question has now changed and you can in fact do:
struct a {
const int b[2];
// other bits follow
// and here's the constructor
a();
};
a::a() :
b{2,3}
{
// other constructor work
}
int main() {
a a;
}
A: You can't do that from the initialization list,
Have a look at this:
http://www.cprogramming.com/tutorial/initialization-lists-c++.html
:)
A: Where I've a constant array, it's always been done as static. If you can accept that, this code should compile and run.
#include <stdio.h>
#include <stdlib.h>
class a {
static const int b[2];
public:
a(void) {
for(int i = 0; i < 2; i++) {
printf("b[%d] = [%d]\n", i, b[i]);
}
}
};
const int a::b[2] = { 4, 2 };
int main(int argc, char **argv)
{
a foo;
return 0;
}
A: Like the others said, ISO C++ doesn't support that. But you can workaround it. Just use std::vector instead.
int* a = new int[N];
// fill a
class C {
const std::vector<int> v;
public:
C():v(a, a+N) {}
};
A: A solution without using the heap with std::vector is to use boost::array, though you can't initialize array members directly in the constructor.
#include <boost/array.hpp>
const boost::array<int, 2> aa={ { 2, 3} };
class A {
const boost::array<int, 2> b;
A():b(aa){};
};
A: How about emulating a const array via an accessor function? It's non-static (as you requested), and it doesn't require stl or any other library:
class a {
int privateB[2];
public:
a(int b0,b1) { privateB[0]=b0; privateB[1]=b1; }
int b(const int idx) { return privateB[idx]; }
}
Because a::privateB is private, it is effectively constant outside a::, and you can access it similar to an array, e.g.
a aobj(2,3); // initialize "constant array" b[]
n = aobj.b(1); // read b[1] (write impossible from here)
If you are willing to use a pair of classes, you could additionally protect privateB from member functions. This could be done by inheriting a; but I think I prefer John Harrison's comp.lang.c++ post using a const class.
A: It is not possible in the current standard. I believe you'll be able to do this in C++0x using initializer lists (see A Brief Look at C++0x, by Bjarne Stroustrup, for more information about initializer lists and other nice C++0x features).
A: interestingly, in C# you have the keyword const that translates to C++'s static const, as opposed to readonly which can be only set at constructors and initializations, even by non-constants, ex:
readonly DateTime a = DateTime.Now;
I agree, if you have a const pre-defined array you might as well make it static.
At that point you can use this interesting syntax:
//in header file
class a{
static const int SIZE;
static const char array[][10];
};
//in cpp file:
const int a::SIZE = 5;
const char array[SIZE][10] = {"hello", "cruel","world","goodbye", "!"};
however, I did not find a way around the constant '10'. The reason is clear though, it needs it to know how to perform accessing to the array. A possible alternative is to use #define, but I dislike that method and I #undef at the end of the header, with a comment to edit there at CPP as well in case if a change.
A: std::vector uses the heap. Geez, what a waste that would be just for the sake of a const sanity-check. The point of std::vector is dynamic growth at run-time, not any old syntax checking that should be done at compile-time. If you're not going to grow then create a class to wrap a normal array.
#include <stdio.h>
template <class Type, size_t MaxLength>
class ConstFixedSizeArrayFiller {
private:
size_t length;
public:
ConstFixedSizeArrayFiller() : length(0) {
}
virtual ~ConstFixedSizeArrayFiller() {
}
virtual void Fill(Type *array) = 0;
protected:
void add_element(Type *array, const Type & element)
{
if(length >= MaxLength) {
// todo: throw more appropriate out-of-bounds exception
throw 0;
}
array[length] = element;
length++;
}
};
template <class Type, size_t Length>
class ConstFixedSizeArray {
private:
Type array[Length];
public:
explicit ConstFixedSizeArray(
ConstFixedSizeArrayFiller<Type, Length> & filler
) {
filler.Fill(array);
}
const Type *Array() const {
return array;
}
size_t ArrayLength() const {
return Length;
}
};
class a {
private:
class b_filler : public ConstFixedSizeArrayFiller<int, 2> {
public:
virtual ~b_filler() {
}
virtual void Fill(int *array) {
add_element(array, 87);
add_element(array, 96);
}
};
const ConstFixedSizeArray<int, 2> b;
public:
a(void) : b(b_filler()) {
}
void print_items() {
size_t i;
for(i = 0; i < b.ArrayLength(); i++)
{
printf("%d\n", b.Array()[i]);
}
}
};
int main()
{
a x;
x.print_items();
return 0;
}
ConstFixedSizeArrayFiller and ConstFixedSizeArray are reusable.
The first allows run-time bounds checking while initializing the array (same as a vector might), which can later become const after this initialization.
The second allows the array to be allocated inside another object, which could be on the heap or simply the stack if that's where the object is. There's no waste of time allocating from the heap. It also performs compile-time const checking on the array.
b_filler is a tiny private class to provide the initialization values. The size of the array is checked at compile-time with the template arguments, so there's no chance of going out of bounds.
I'm sure there are more exotic ways to modify this. This is an initial stab. I think you can pretty much make up for any of the compiler's shortcoming with classes.
A: ISO standard C++ doesn't let you do this. If it did, the syntax would probably be:
a::a(void) :
b({2,3})
{
// other initialization stuff
}
Or something along those lines. From your question it actually sounds like what you want is a constant class (aka static) member that is the array. C++ does let you do this. Like so:
#include <iostream>
class A
{
public:
A();
static const int a[2];
};
const int A::a[2] = {0, 1};
A::A()
{
}
int main (int argc, char * const argv[])
{
std::cout << "A::a => " << A::a[0] << ", " << A::a[1] << "\n";
return 0;
}
The output being:
A::a => 0, 1
Now of course since this is a static class member it is the same for every instance of class A. If that is not what you want, ie you want each instance of A to have different element values in the array a then you're making the mistake of trying to make the array const to begin with. You should just be doing this:
#include <iostream>
class A
{
public:
A();
int a[2];
};
A::A()
{
a[0] = 9; // or some calculation
a[1] = 10; // or some calculation
}
int main (int argc, char * const argv[])
{
A v;
std::cout << "v.a => " << v.a[0] << ", " << v.a[1] << "\n";
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "81"
} |
Q: How do I send arrays between views in CakePHP I am not sure if I formulated the question right, but still ...
I have a view that shows a flash embed and this flash take as parameter a /controller/action URL that generates a XML. I nee to send, from this view, an array to the XML generator action. How is the best way ? Is there some helper->set() method like or I have to create an specific URL to send this array to that action ?
Here goes my structure:
my_controller.php
function player() {}
player.ctp
<div id="myDiv">Here it Goes</div>
<script type="text/javascript">
var so = new SWFObject('player.swf','test','50','50','8');
so.addVariable('file','/xml/generate'); // need to pass an array here
so.write('myDiv');
</script>
xml_controller.php
public function generate() {
// I need to read an array here
}
generate.ctp
echo "<xml><data>" . $array['contents'] . "</data>";
A: If the array is small enough, serialize then urlencode it and add it as a paramter to the url to your generate action:
player.ctp
so.addVariable('file','/xml/generate/<?php echo urlencode(serialize($array)); ?>');
then read it back:
public function generate($array) {
$array = unserialize($array);
}
A: Save the array in the session then in the next request to the XML generator action, read it back from the session.
my_controller.php
function player() {
$this->Session->write('key', $array);
}
xml_controller.php
public function generate() {
$array = $this->Session->read('key');
}
However, I have heard of some problems where flash sometimes doesn't send session cookies, in which case, append the session id to the url of the action:
so.addVariable('file','/xml/generate/<?php echo $session->id(); ?>');
and to get the session back:
public function generate($sessionId) {
CakeSession::id($sessionId);
$array = $this->Session->read('key');
}
A: First of all you cannot send data from one view to another in the manner you are speaking. Each of those calls would be a separate request and this means that it goes out of the framework and then in again. This means that the framework will be built and tear down between calls, making impossible to pass the data between views.
Now in regards to the array that has to be sent to your action, I'm utterly confused. I don't think you are looking at the problem the right way. If that action needs an array of data and then produce XML so the Flash Object can get it, then it makes even less sense. Are you sure that the Flash Object isn't the one responsible to sending that array of data to the Param you mentioned?
Well, even if all you are saying has to be done quite like that, I'll suggest you drop that array on the file system and then pick it up when the action is called by the Flash.
Or another suggestion would be to use AJAX to send that array to the action.
Both suggestions imply my utter "cluelessness" on your predicate.
I still have to ask, isn't the Flash Object gonna do something in all this?
A: You can send an array with data from a view to a controller in CakePHP like this.
To the link you can pass arguments:
www.site.com/model/action/param1:foo/param2:test
You can then retrieve them in the controller action in the following way:
$yourarray = $this->params['named'];
Of course the array shouldn't be too large then.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is one's complement a real-world issue, or just a historical one? Another question asked about determining odd/evenness in C, and the idiomatic (x & 1) approach was correctly flagged as broken for one's complement-based systems, which the C standard allows for.
Do systems really exist in the 'real world' outside of computer museums? I've been coding since the 1970's and I'm pretty sure I've never met such a beast.
Is anyone actually developing or testing code for such a system? And, if not, should we worry about such things or should we put them into Room 101 along with paper tape and punch cards...?
A: I decided to find one. The Unisys ClearPath systems have an ANSI C compiler (yes they call it "American National Standard C" for which even the PDF documentation was last updated in 2013. The documentation is available online;
There the signed types are all using one's complement representation, with the following properties:
Type | Bits | Range
---------------------+------+-----------------
signed char | 9 | -2⁸+1 ... 2⁸-1
signed short | 18 | -2¹⁷+1 ... 2¹⁷-1
signed int | 36 | -2³⁵+1 ... 2³⁵-1
signed long int | 36 | -2³⁵+1 ... 2³⁵-1
signed long long int | 72 | -2⁷¹+1 ... 2⁷¹-1
Remarkably, it also by default supports non-conforming unsigned int and unsigned long, which range from 0 ... 2³⁶ - 2, but can be changed to 0 ... 2³⁶ - 1 with a pragma.
A: I've never encountered a one's complement system, and I've been coding as long as you have.
But I did encounter a 9's complement system -- the machine language of a HP-41c calculator. I'll admit that this can be considered obsolete, and I don't think they ever had a C compiler for those.
A: We got off our last 1960's Honeyboxen sometime last year, which made it our oldest machine on site. It was two's complement. This isn't to say knowing or being aware of one's complement is a bad thing. Just, You will probably never run into one's complement issues today, no matter how much computer archeology they have you do at work.
The issues you are more likely to run into on the integer side are endian issues (I'm looking at you PDP). Also, you'll run into more "real world" (i.e. today) issues with floating point formats than you will integer formats.
A: Funny thing, people asked that same question on comp.std.c in 1993, and nobody could point to a one's complement machine that had been used back then.
So yes, I think we can confidently say that one's complement belongs to a dark corner of our history, practically dead, and is not a concern anymore.
A: I work in the telemetry field and we have some of our customers have old analog-to-digital converters that still use 1's complement. I just had to write code the other day to convert from 1's complement to 2's complement in order to compensate.
So yes, it's still out there (but you're not going to run into it very often).
A: This all comes down to knowing your roots.
Yes, this is technically an old technique and I would probably do what other people suggested in that question and use the modulo (%) operator to determine odd or even.
But understanding what a 1s complement (or 2s complement) is always a good thing to know. Whether or not you ever use them, your CPU is dealing with those things all of the time. So it can never hurt to understand the concept. Now, modern systems make it so you generally never have to worry about things like that so it has become a topic for Programming 101 courses in a way. But you have to remember that some people actually would still use this in the "real world"... for example, contrary to popular belief there are people who still use assembly! Not many, but until CPUs can understand raw C# and Java, someone is going to still have to understand this stuff.
And heck, you never know when you might find your self doing something where you actually need to perform binary math and that 1s complement could come in handy.
A: The CDC Cyber 18 I used back in the '80 was a 1s complement machine, but that's nearly 30 years ago, and I haven't seen one since (however, that was also the last time I worked on a non-PC)
A: RFC 791 p.14 defines the IP header checksum as:
The checksum field is the 16 bit one's complement of the one's complement sum of all 16 bit words in the header. For purposes of computing the checksum, the value of the checksum field is zero.
So one's complement is still heavily used in the real world, in every single IP packet that is sent. :)
A:
Is one's complement a real-world issue, or just a historical one?
Yes, it still used. Its even used in modern Intel processors. From Intel® 64 and IA-32 Architectures Software Developer’s Manual 2A, page 3-8:
3.1.1.8 Description Section
Each instruction is then described by number of information sections. The “Description” section describes the purpose of the instructions and required operands in more detail.
Summary of terms that may be used in the description section:
* Legacy SSE: Refers to SSE, SSE2, SSE3, SSSE3, SSE4, AESNI, PCLMULQDQ and any future instruction sets referencing XMM registers and encoded without a VEX prefix.
* VEX.vvvv. The VEX bitfield specifying a source or destination register (in 1’s complement form).
* rm_field: shorthand for the ModR/M r/m field and any REX.B
* reg_field: shorthand for the ModR/M reg field and any REX.R
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
} |
Q: How do I resolve merge conflicts in a Git repository? How do I resolve merge conflicts in my Git repository?
A: If you're making frequent small commits, then start by looking at the commit comments with git log --merge. Then git diff will show you the conflicts.
For conflicts that involve more than a few lines, it's easier to see what's going on in an external GUI tool. I like opendiff -- Git also supports vimdiff, gvimdiff, kdiff3, tkdiff, meld, xxdiff, emerge out of the box and you can install others: git config merge.tool "your.tool" will set your chosen tool and then git mergetool after a failed merge will show you the diffs in context.
Each time you edit a file to resolve a conflict, git add filename will update the index and your diff will no longer show it. When all the conflicts are handled and their files have been git add-ed, git commit will complete your merge.
A: This answer is to add an alternative for those Vim users like me that prefers to do everything within the editor.
TL;DR
Tpope came up with this great plugin for Vim called fugitive. Once installed, you can run :Gstatus to check the files that have conflict and :Gdiff to open Git in a three-way merge.
Once in the three-way merge, fugitive will let you get the changes of any of the branches you are merging in the following fashion:
*
*:diffget //2, get changes from original (HEAD) branch:
*:diffget //3, get changes from merging branch:
Once you are finished merging the file, type :Gwrite in the merged buffer.
Vimcasts released a great video explaining these steps in detail.
A: I find merge tools rarely help me understand the conflict or the resolution. I'm usually more successful looking at the conflict markers in a text editor and using git log as a supplement.
Here are a few tips:
Tip One
The best thing I have found is to use the "diff3" merge conflict style:
git config merge.conflictstyle diff3
This produces conflict markers like this:
<<<<<<<
Changes made on the branch that is being merged into. In most cases,
this is the branch that I have currently checked out (i.e. HEAD).
|||||||
The common ancestor version.
=======
Changes made on the branch that is being merged in. This is often a
feature/topic branch.
>>>>>>>
The middle section is what the common ancestor looked like. This is useful because you can compare it to the top and bottom versions to get a better sense of what was changed on each branch, which gives you a better idea for what the purpose of each change was.
If the conflict is only a few lines, this generally makes the conflict very obvious. (Knowing how to fix a conflict is very different; you need to be aware of what other people are working on. If you're confused, it's probably best to just call that person into your room so they can see what you're looking at.)
If the conflict is longer, then I will cut and paste each of the three sections into three separate files, such as "mine", "common" and "theirs".
Then I can run the following commands to see the two diff hunks that caused the conflict:
diff common mine
diff common theirs
This is not the same as using a merge tool, since a merge tool will include all of the non-conflicting diff hunks too. I find that to be distracting.
Tip Two
Somebody already mentioned this, but understanding the intention behind each diff hunk is generally very helpful for understanding where a conflict came from and how to handle it.
git log --merge -p <name of file>
This shows all of the commits that touched that file in between the common ancestor and the two heads you are merging. (So it doesn't include commits that already exist in both branches before merging.) This helps you ignore diff hunks that clearly are not a factor in your current conflict.
Tip Three
Verify your changes with automated tools.
If you have automated tests, run those. If you have a lint, run that. If it's a buildable project, then build it before you commit, etc. In all cases, you need to do a bit of testing to make sure your changes didn't break anything. (Heck, even a merge without conflicts can break working code.)
Tip Four
Plan ahead; communicate with co-workers.
Planning ahead and being aware of what others are working on can help prevent merge conflicts and/or help resolve them earlier -- while the details are still fresh in mind.
For example, if you know that you and another person are both working on different refactoring that will both affect the same set of files, you should talk to each other ahead of time and get a better sense for what types of changes each of you is making. You might save considerable time and effort if you conduct your planned changes serially rather than in parallel.
For major refactorings that cut across a large swath of code, you should strongly consider working serially: everybody stops working on that area of the code while one person performs the complete refactoring.
If you can't work serially (due to time pressure, maybe), then communicating about expected merge conflicts at least helps you solve the problems sooner while the details are still fresh in mind. For example, if a co-worker is making a disruptive series of commits over the course of a one-week period, you may choose to merge/rebase on that co-workers branch once or twice each day during that week. That way, if you do find merge/rebase conflicts, you can solve them more quickly than if you wait a few weeks to merge everything together in one big lump.
Tip Five
If you're unsure of a merge, don't force it.
Merging can feel overwhelming, especially when there are a lot of conflicting files and the conflict markers cover hundreds of lines. Often times when estimating software projects we don't include enough time for overhead items like handling a gnarly merge, so it feels like a real drag to spend several hours dissecting each conflict.
In the long run, planning ahead and being aware of what others are working on are the best tools for anticipating merge conflicts and prepare yourself to resolve them correctly in less time.
A: I am using Microsoft's Visual Studio Code for resolving conflicts. It's very simple to use. I keep my project open in the workspace. It detects and highlights conflicts. Moreover, it gives GUI options to select whatever change I want to keep from HEAD or incoming.
A: I either want my or their version in full, or want to review individual changes and decide for each of them.
Fully accept my or theirs version:
Accept my version (local, ours):
git checkout --ours -- <filename>
git add <filename> # Marks conflict as resolved
git commit -m "merged bla bla" # An "empty" commit
Accept their version (remote, theirs):
git checkout --theirs -- <filename>
git add <filename>
git commit -m "merged bla bla"
If you want to do for all conflict files run:
git merge --strategy-option ours
or
git merge --strategy-option theirs
Review all changes and accept them individually
*
*git mergetool
*Review changes and accept either version for each of them.
*git add <filename>
*git commit -m "merged bla bla"
Default mergetool works in command line. How to use a command line mergetool should be a separate question.
You can also install visual tool for this, e.g. meld and run
git mergetool -t meld
It will open local version (ours), "base" or "merged" version (the current result of the merge) and remote version (theirs). Save the merged version when you are finished, run git mergetool -t meld again until you get "No files need merging", then go to Steps 3. and 4.
A: See How Conflicts Are Presented or, in Git, the git merge documentation to understand what merge conflict markers are.
Also, the How to Resolve Conflicts section explains how to resolve the conflicts:
After seeing a conflict, you can do two things:
*
*Decide not to merge. The only clean-ups you need are to reset the index file to the HEAD commit to reverse 2. and to clean up working tree changes made by 2. and 3.; git merge --abort can be used for this.
*Resolve the conflicts. Git will mark the conflicts in the working tree. Edit the files into shape and git add them to the index. Use git commit to seal the deal.
You can work through the conflict with a number of tools:
*
*Use a mergetool. git mergetool to launch a graphical mergetool which will work you through the merge.
*Look at the diffs. git diff will show a three-way diff, highlighting changes from both the HEAD and MERGE_HEAD versions.
*Look at the diffs from each branch. git log --merge -p <path> will show diffs first for the HEAD version and then the MERGE_HEAD version.
*Look at the originals. git show :1:filename shows the common ancestor, git show :2:filename shows the HEAD version, and git show :3:filename shows the MERGE_HEAD version.
You can also read about merge conflict markers and how to resolve them in the Pro Git book section Basic Merge Conflicts.
A: git fetch <br>
git checkout **your branch**<br>
git rebase master<br>
In this step you will try to fix the conflict using your preferred IDE.
You can follow this link to check how to fix the conflict in the file.
git add<br>
git rebase --continue<br>
git commit --amend<br>
git push origin HEAD:refs/drafts/master (push like a drafts)<br>
Now everything is fine and you will find your commit in Gerrit.
A: For Emacs users which want to resolve merge conflicts semi-manually:
git diff --name-status --diff-filter=U
shows all files which require conflict resolution.
Open each of those files one by one, or all at once by:
emacs $(git diff --name-only --diff-filter=U)
When visiting a buffer requiring edits in Emacs, type
ALT+x vc-resolve-conflicts
This will open three buffers (mine, theirs, and the output buffer). Navigate by pressing 'n' (next region), 'p' (prevision region). Press 'a' and 'b' to copy mine or theirs region to the output buffer, respectively. And/or edit the output buffer directly.
When finished: Press 'q'. Emacs asks you if you want to save this buffer: yes.
After finishing a buffer mark it as resolved by running from the teriminal:
git add FILENAME
When finished with all buffers type
git commit
to finish the merge.
A: Try Visual Studio Code for editing if you aren't already.
After you try merging (and land up in merge conflicts), Visual Studio Code automatically detects the merge conflicts.
It can help you very well by showing the changes made to the original one and if you should accept incoming or
current change (meaning original one before merging)'.
It helped me and it can work for you too!
PS: It will work only if you've configured Git with with your code and Visual Studio Code.
A: Bonus:
In speaking of pull/fetch/merge in the previous answers, I would like to share an interesting and productive trick,
git pull --rebase
This above command is the most useful command in my Git life which saved a lot of time.
Before pushing your newly committed change to remote server, try git pull --rebase rather git pull and manual merge and it will automatically sync the latest remote server changes (with a fetch + merge) and will put your local latest commit at the top in the Git log. No need to worry about manual pull/merge.
In case of a conflict, just use
git mergetool
git add conflict_file
git rebase --continue
Find details at: What does “git pull –rebase” do?
A: *
*Identify which files are in conflict (Git should tell you this).
*Open each file and examine the diffs; Git demarcates them. Hopefully it will be obvious which version of each block to keep. You may need to discuss it with fellow developers who committed the code.
*Once you've resolved the conflict in a file git add the_file.
*Once you've resolved all conflicts, do git rebase --continue or whatever command
Git said to do when you completed.
A: Simply, if you know well that changes in one of the repositories is not important, and want to resolve all changes in favor of the other one, use:
git checkout . --ours
to resolve changes in the favor of your repository, or
git checkout . --theirs
to resolve changes in favor of the other or the main repository.
Or else you will have to use a GUI merge tool to step through files one by one, say the merge tool is p4merge, or write any one's name you've already installed
git mergetool -t p4merge
and after finishing a file, you will have to save and close, so the next one will open.
A: There are three steps:
*
*Find which files cause conflicts by the command
git status
*Check the files, in which you would find the conflicts marked like
<<<<<<<<head
blablabla
*Change it to the way you want it, and then commit with the commands
git add solved_conflicts_files
git commit -m 'merge msg'
A: Try:
git mergetool
It opens a GUI that steps you through each conflict, and you get to choose how to merge. Sometimes it requires a bit of hand editing afterwards, but usually it's enough by itself. It is much better than doing the whole thing by hand certainly.
As per Josh Glover's comment:
[This command]
doesn't necessarily open a GUI unless you install one. Running git mergetool for me resulted in vimdiff being used. You can install
one of the following tools to use it instead: meld, opendiff,
kdiff3, tkdiff, xxdiff, tortoisemerge, gvimdiff, diffuse,
ecmerge, p4merge, araxis, vimdiff, emerge.
Below is a sample procedure using vimdiff to resolve merge conflicts, based on this link.
*
*Run the following commands in your terminal
git config merge.tool vimdiff
git config merge.conflictstyle diff3
git config mergetool.prompt false
This will set vimdiff as the default merge tool.
*Run the following command in your terminal
git mergetool
*You will see a vimdiff display in the following format:
╔═══════╦══════╦════════╗
║ ║ ║ ║
║ LOCAL ║ BASE ║ REMOTE ║
║ ║ ║ ║
╠═══════╩══════╩════════╣
║ ║
║ MERGED ║
║ ║
╚═══════════════════════╝
These 4 views are
*
*LOCAL: this is the file from the current branch
*BASE: the common ancestor, how this file looked before both changes
*REMOTE: the file you are merging into your branch
*MERGED: the merge result; this is what gets saved in the merge commit and used in the future
You can navigate among these views using ctrl+w. You can directly reach the MERGED view using ctrl+w followed by j.
More information about vimdiff navigation is here and here.
*You can edit the MERGED view like this:
*
*If you want to get changes from REMOTE
:diffg RE
*If you want to get changes from BASE
:diffg BA
*If you want to get changes from LOCAL
:diffg LO
*Save, Exit, Commit, and Clean up
:wqa save and exit from vi
git commit -m "message"
git clean Remove extra files (e.g. *.orig). Warning: It will remove all untracked files, if you won't pass any arguments.
A: Please follow the following steps to fix merge conflicts in Git:
*
*Check the Git status:
git status
*Get the patchset:
git fetch (checkout the right patch from your Git commit)
*Checkout a local branch (temp1 in my example here):
git checkout -b temp1
*Pull the recent contents from master:
git pull --rebase origin master
*Start the mergetool and check the conflicts and fix them...and check the changes in the remote branch with your current branch:
git mergetool
*Check the status again:
git status
*Delete the unwanted files locally created by mergetool, usually mergetool creates extra file with *.orig extension. Please delete that file as that is just the duplicate and fix changes locally and add the correct version of your files.
git add #your_changed_correct_files
*Check the status again:
git status
*Commit the changes to the same commit id (this avoids a new separate patch set):
git commit --amend
*Push to the master branch:
git push (to your Git repository)
A: CoolAJ86's answer sums up pretty much everything. In case you have changes in both branches in the same piece of code you will have to do a manual merge. Open the file in conflict in any text editor and you should see following structure.
(Code not in Conflict)
>>>>>>>>>>>
(first alternative for conflict starts here)
Multiple code lines here
===========
(second alternative for conflict starts here)
Multiple code lines here too
<<<<<<<<<<<
(Code not in conflict here)
Choose one of the alternatives or a combination of both in a way that you want new code to be, while removing equal signs and angle brackets.
git commit -a -m "commit message"
git push origin master
A: A safer way to resolve conflicts is to use git-mediate (the common solutions suggested here are quite error prone imho).
See this post for a quick intro on how to use it.
A: For those who are using Visual Studio (Visual Studio 2015 in my case)
*
*Close your project in Visual Studio. Especially in big projects, Visual Studio tends to freak out when merging using the UI.
*Do the merge in a command prompt.
git checkout target_branch
git merge source_branch
*Then open the project in Visual Studio and go to Team Explorer → Branch. Now there is a message that says Merge is pending and conflicting files are listed right below the message.
*Click the conflicting file and you will have the option to Merge, Compare, Take Source, and Take Target. The merge tool in Visual Studio is very easy to use.
A: If you are using IntelliJ IDEA as the IDE, try to merge the parent to your branch by:
git checkout <localbranch>
git merge origin/<remotebranch>
It will show all conflicts like this:
A_MBPro:test anu$ git merge origin/ Auto-merging
src/test/java/com/.../TestClass.java CONFLICT
(content): Merge conflict in
src/test/java/com/.../TestClass.java
Now note that the file TestClass.java is shown in red in IntelliJ IDEA.
Also git status will show:
Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: src/test/java/com/.../TestClass.java
Open the file in IntelliJ IDEA. It will have sections with
<<<<<<< HEAD
public void testMethod() {
}
=======
public void testMethod() { ...
}
>>>>>>> origin/<remotebranch>
where HEAD is changes on your local branch and origin/<remotebranch> is changes from the remote branch. Here keep the stuff that you need and remove the stuff you don't need. After that, the normal steps should do. That is
git add TestClass.java
git commit -m "commit message"
git push
A: You could fix merge conflicts in a number of ways as other have detailed.
I think the real key is knowing how changes flow with local and remote repositories. The key to this is understanding tracking branches. I have found that I think of the tracking branch as the 'missing piece in the middle' between me my local, actual files directory and the remote defined as origin.
I've personally got into the habit of 2 things to help avoid this.
Instead of:
git add .
git commit -m"some msg"
Which has two drawbacks -
a) All new/changed files get added and that might include some unwanted changes.
b) You don't get to review the file list first.
So instead I do:
git add file,file2,file3...
git commit # Then type the files in the editor and save-quit.
This way you are more deliberate about which files get added and you also get to review the list and think a bit more while using the editor for the message. I find it also improves my commit messages when I use a full screen editor rather than the -m option.
[Update - as time has passed I've switched more to:
git status # Make sure I know whats going on
git add .
git commit # Then use the editor
]
Also (and more relevant to your situation), I try to avoid:
git pull
or
git pull origin master.
because pull implies a merge and if you have changes locally that you didn't want merged you can easily end up with merged code and/or merge conflicts for code that shouldn't have been merged.
Instead I try to do
git checkout master
git fetch
git rebase --hard origin/master # or whatever branch I want.
You may also find this helpful:
git branch, fork, fetch, merge, rebase and clone, what are the differences?
A: If you want to merge from branch test to master, you can follow these steps:
Step 1: Go to the branch
git checkout test
Step 2:
git pull --rebase origin master
Step 3: If there are some conflicts, go to these files to modify it.
Step 4: Add these changes
git add #your_changes_files
Step 5:
git rebase --continue
Step 6: If there is still conflict, go back to step 3 again. If there is no conflict, do following:
git push origin +test
Step 7: And then there is no conflict between test and master. You can use merge directly.
A: Using patience
For a big merge conflict, using patience provided good results for me. It will try to match blocks rather than individual lines.
If you change the indentation of your program for instance, the default Git merge strategy sometimes matches single braces { which belongs to different functions. This is avoided with patience:
git merge -s recursive -X patience other-branch
From the documentation:
With this option, merge-recursive spends a little extra time to avoid
mismerges that sometimes occur due to unimportant matching lines
(e.g., braces from distinct functions). Use this when the branches to
be merged have diverged wildly.
Comparison with the common ancestor
If you have a merge conflict and want to see what others had in mind when modifying their branch, it's sometimes easier to compare their branch directly with the common ancestor (instead of our branch). For that you can use merge-base:
git diff $(git merge-base <our-branch> <their-branch>) <their-branch>
Usually, you only want to see the changes for a particular file:
git diff $(git merge-base <our-branch> <their-branch>) <their-branch> <file>
A: git log --merge -p [[--] path]
Does not seem to always work for me and usually ends up displaying every commit that was different between the two branches, this happens even when using -- to separate the path from the command.
What I do to work around this issue is open up two command lines and in one run
git log ..$MERGED_IN_BRANCH --pretty=full -p [path]
and in the other
git log $MERGED_IN_BRANCH.. --pretty=full -p [path]
Replacing $MERGED_IN_BRANCH with the branch I merged in and [path] with the file that is conflicting. This command will log all the commits, in patch form, between (..) two commits. If you leave one side empty like in the commands above git will automatically use HEAD (the branch you are merging into in this case).
This will allow you to see what commits went into the file in the two branches after they diverged. It usually makes it much easier to solve conflicts.
A: Here's a probable use case, from the top:
You're going to pull some changes, but oops, you're not up to date:
git fetch origin
git pull origin master
From ssh://gitosis@example.com:22/projectname
* branch master -> FETCH_HEAD
Updating a030c3a..ee25213
error: Entry 'filename.c' not uptodate. Cannot merge.
So you get up-to-date and try again, but have a conflict:
git add filename.c
git commit -m "made some wild and crazy changes"
git pull origin master
From ssh://gitosis@example.com:22/projectname
* branch master -> FETCH_HEAD
Auto-merging filename.c
CONFLICT (content): Merge conflict in filename.c
Automatic merge failed; fix conflicts and then commit the result.
So you decide to take a look at the changes:
git mergetool
Oh my, oh my, upstream changed some things, but just to use my changes...no...their changes...
git checkout --ours filename.c
git checkout --theirs filename.c
git add filename.c
git commit -m "using theirs"
And then we try a final time
git pull origin master
From ssh://gitosis@example.com:22/projectname
* branch master -> FETCH_HEAD
Already up-to-date.
Ta-da!
A: As of December 12th 2016, you can merge branches and resolve conflicts on github.com
Thus, if you don't want to use the command-line or any 3rd party tools that are offered here from older answers, go with GitHub's native tool.
This blog post explains in detail, but the basics are that upon 'merging' two branches via the UI, you will now see a 'resolve conflicts' option that will take you to an editor allowing you to deal with these merge conflicts.
A: Merge conflicts could occur in different situations:
*
*When running git fetch and then git merge
*When running git fetch and then git rebase
*When running git pull (which is actually equal to one of the above-mentioned conditions)
*When running git stash pop
*When you're applying git patches (commits that are exported to files to be transferred, for example, by email)
You need to install a merge tool which is compatible with Git to resolve the conflicts. I personally use KDiff3, and I've found it nice and handy. You can download its Windows version here:
https://sourceforge.net/projects/kdiff3/files/
BTW, if you install Git Extensions there is an option in its setup wizard to install Kdiff3.
Then setup the Git configuration to use KDiff3 as its mergetool:
$ git config --global --add merge.tool kdiff3
$ git config --global --add mergetool.kdiff3.path "C:/Program Files/KDiff3/kdiff3.exe"
$ git config --global --add mergetool.kdiff3.trustExitCode false
$ git config --global --add diff.guitool kdiff3
$ git config --global --add difftool.kdiff3.path "C:/Program Files/KDiff3/kdiff3.exe"
$ git config --global --add difftool.kdiff3.trustExitCode false
(Remember to replace the path with the actual path of the KDiff3 EXE file.)
Then every time you come across a merge conflict, you just need to run this command:
$ git mergetool
Then it opens Kdiff3, and first tries to resolve the merge conflicts automatically. Most of the conflicts would be resolved spontaneously and you need to fix the rest manually.
Here's what Kdiff3 looks like:
Then once you're done, save the file and it goes to the next file with a conflict and you do the same thing again until all the conflicts are resolved.
To check if everything is merged successfully, just run the mergetool command again. You should get this result:
$ git mergetool
No files need merging
A: I always follow the below steps to avoid conflicts.
*
*git checkout master (Come to the master branch)
*git pull (Update your master to get the latest code)
*git checkout -b mybranch (Check out a new a branch and start working on that branch so that your master always remains top of trunk.)
*git add . and git commit and git push (on your local branch after your changes)
*git checkout master (Come back to your master)
Now you can do the same and maintain as many local branches you want and work simultaneous by just doing a git checkout to your branch whenever necessary.
A: I understood what a merge conflict was, but when I saw the output of git diff, it looked like nonsense to me at first:
git diff
++<<<<<<< HEAD
+ display full last name boolean in star table
++=======
+ users viewer.id/star.id, and conversation uses user.id
+
++>>>>>>> feat/rspec-tests-for-cancancan
But here is what helped me:
*
*Everything between <<<<<<< and ======= is what was in one file, and
*Everything between ======= and >>>>>>> is what was in the other file
*So literally all you have to do is open the file with the merge conflicts and remove those lines from either branch (or just make them the same), and the merge will immediately succeed. Problem solved!
A: Merge conflicts happens when changes are made to a file at the same time. Here is how to solve it.
git CLI
Here are simple steps what to do when you get into conflicted state:
*
*Note the list of conflicted files with: git status (under Unmerged paths section).
*Solve the conflicts separately for each file by one of the following approaches:
*
*Use GUI to solve the conflicts: git mergetool (the easiest way).
*To accept remote/other version, use: git checkout --theirs path/file. This will reject any local changes you did for that file.
*To accept local/our version, use: git checkout --ours path/file
However you've to be careful, as remote changes that conflicts were done for some reason.
Related: What is the precise meaning of "ours" and "theirs" in git?
*Edit the conflicted files manually and look for the code block between <<<<</>>>>> then choose the version either from above or below =====. See: How conflicts are presented.
*Path and filename conflicts can be solved by git add/git rm.
*Finally, review the files ready for commit using: git status.
If you still have any files under Unmerged paths, and you did solve the conflict manually, then let Git know that you solved it by: git add path/file.
*If all conflicts were solved successfully, commit the changes by: git commit -a and push to remote as usual.
See also: Resolving a merge conflict from the command line at GitHub
For practical tutorial, check: Scenario 5 - Fixing Merge Conflicts by Katacoda.
DiffMerge
I've successfully used DiffMerge which can visually compare and merge files on Windows, macOS and Linux/Unix.
It graphically can show the changes between 3 files and it allows automatic merging (when safe to do so) and full control over editing the resulting file.
Image source: DiffMerge (Linux screenshot)
Simply download it and run in repo as:
git mergetool -t diffmerge .
macOS
On macOS you can install via:
brew install caskroom/cask/brew-cask
brew cask install diffmerge
And probably (if not provided) you need the following extra simple wrapper placed in your PATH (e.g. /usr/bin):
#!/bin/sh
DIFFMERGE_PATH=/Applications/DiffMerge.app
DIFFMERGE_EXE=${DIFFMERGE_PATH}/Contents/MacOS/DiffMerge
exec ${DIFFMERGE_EXE} --nosplash "$@"
Then you can use the following keyboard shortcuts:
*
*⌘-Alt-Up/Down to jump to previous/next changes.
*⌘-Alt-Left/Right to accept change from left or right
Alternatively you can use opendiff (part of Xcode Tools) which lets you merge two files or directories together to create a third file or directory.
A: GitLens for Visual Studio Code
You can try GitLens for Visual Studio Code. The key features are:
3. Easily resolve conflicts
I already like this feature:
2. Current Line Blame.
3. Gutter Blame
4. Status Bar Blame
And there are many features. You can check them here.
A: Check out the answers in Stack Overflow question Aborting a merge in Git, especially Charles Bailey's answer which shows how to view the different versions of the file with problems, for example,
# Common base version of the file.
git show :1:some_file.cpp
# 'Ours' version of the file.
git show :2:some_file.cpp
# 'Theirs' version of the file.
git show :3:some_file.cpp
A: I follow the below process.
The process to fix a merge conflict:
*
*First, pull the latest from the destination branch to which you want to merge git pull origin develop
*As you get the latest from the destination, now resolve the conflict manually in an IDE by deleting those extra characters.
*Do a git add to add these edited files to the Git queue so that it can be commit and push to the same branch you are working on.
*As git add is done, do a git commit to commit the changes.
*Now push the changes to your working branch by git push origin HEAD
This is it and you will see it resolved in your pull request if you are using Bitbucket or GitHub.
A: I like using WinMerge (free tool) that does both full entire directory tree comparison/merge and also individual file(s) comparison/merge of the full directory tree compare.
The Git merge conflict is telling you that your pull request will undo/lose/overwrite a coworker's changes, typically because your copy of the content wasn't recent enough.
Steps to resolve can be:
*
*Take another new clone of the source to a newly named folder,
*Use WinMerge to compare your content and the most recent content to understand the conflict,
*For the file(s) changed by both yourself and your coworker that are causing the Git Merge conflict, look at the lines that your co-worker has added/changed/deleted as per compared to the code lines that you have added/changed/deleted.
*Use the WinMerge left / right code section move arrows to ensure your coworker's work is in your copy of the file and you aren't clobbering their work.
I.e., no magic way to resolve Git merge conflicts other than manually looking at what each person has done to the same source file(s).
That is what I'm thinking.
Note: WinMerge creates .bak files .. and you don't want them copied to source control AzOps, TFS, etc., so if you are sure you have done the edit correctly, remove the .bak files.
A: Well, all the answers already given seem to explain which tools you can use to detect merge conflicts or how to initiate a merge request...
The answer to your question however is both simple and frustrating. Merge conflicts are almost always to solve by hand manually. If you use a tool like e.g. GitLab, the GUI might help you to find differences in two code versions, but at the end of the day, you have to decide which line should be kept and which should be erased.
A simple example: Programmer A and programmer B both push the same - differently modified - file to a remote repository. Programmer A opens a merge request and GitLab highlights several lines of code where conflicts occur between the two versions. Now it is up to Programmer A and B to decide, who wrote better code in these specific lines. They have to make compromises.
A: If you do not use a tool to merge, first copy your code outside:
- `checkout master`
- `git pull` / get new commit
- `git checkout` to your branch
- `git rebase master`
It resolve conflict and you can copy your code.
A: If you simply want to restore the remote master, then
git reset --hard origin/master
WARNING: All local changes will be lost,
see https://stackoverflow.com/a/8476004/11769765.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5296"
} |
Q: What are main/best Maven respositories to use? What are the main/best Maven repositories to use that will include the majority of your open source Java package dependencies.
Also in what order should these be included? Does it matter?
A: I would suggest using a Maven proxy like Archiva, Artifactory or Nexus and defining your repo list on the server side. The order matters only to the extent that the proxy server tries the proxied repos one by one and specifying a fringe repository as first will slow down the resolution of uncached artifacts (Artifactory allows you to specify whitelist and blacklist expressions for each proxied repo, which solves this problem)
Overall using your own repo gives you more control and reliable builds ('central' is often painfully slow). It also gives you a place to put your own artifacts and any non-free 3rd party artifacts.
A: This is the current setup in the project we are building:
*
*MavenCentral
*ObjectWeb
*JBoss Maven2
*and some snapshots (see below)
<repository>
<id>MavenCentral</id>
<name>Maven repository</name>
<url>http://repo1.maven.org/maven2</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>objectweb</id>
<name>Objectweb repository</name>
<url>http://maven.objectweb.org/maven2</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>jboss</id>
<name>JBoss Maven2 repository</name>
<url>http://repository.jboss.com/maven2/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
<repository>
<id>glassfish</id>
<name>Glassfish repository</name>
<url>http://download.java.net/maven/1</url>
<layout>legacy</layout>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>apache.snapshots</id>
<name>Apache Snapshot Repository</name>
<url>
http://people.apache.org/repo/m2-snapshot-repository
</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>ops4j.repository</id>
<name>OPS4J Repository</name>
<url>http://repository.ops4j.org/maven2</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>Codehaus Snapshots</id>
<url>http://snapshots.repository.codehaus.org/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: How to indicate that a method was unsuccessful I have several similar methods, say eg. CalculatePoint(...) and CalculateListOfPoints(...). Occasionally, they may not succeed, and need to indicate this to the caller. For CalculateListOfPoints, which returns a generic List, I could return an empty list and require the caller to check this; however Point is a value type and so I can't return null there.
Ideally I would like the methods to 'look' similar; one solution could be to define them as
public Point CalculatePoint(... out Boolean boSuccess);
public List<Point> CalculateListOfPoints(... out Boolean boSuccess);
or alternatively to return a Point? for CalculatePoint, and return null to indicate failure. That would mean having to cast back to the non-nullable type though, which seems excessive.
Another route would be to return the Boolean boSuccess, have the result (Point or List) as an 'out' parameter, and call them TryToCalculatePoint or something...
What is best practice?
Edit: I do not want to use Exceptions for flow control! Failure is sometimes expected.
A: Why would they fail? If it's because of something the caller has done (i.e. the arguments provided) then throwing ArgumentException is entirely appropriate. A Try[...] method which avoids the exception is fine.
I think it's a good idea to provide the version which throws an exception though, so that callers who expect that they will always provide good data will receive a suitably strong message (i.e. an exception) if they're ever wrong.
A: Another alternative is to throw an exception. However, you generally only want to throw exceptions in "exceptional cases".
If the failure cases are common (and not exceptional), then you've already listed out your two options. EDIT: There may be a convention in your project as how to handle such non-exceptional cases (whether one should return success or the object). If there is no existing convention, then I agree with lucasbfr and suggest you return success (which agrees with how TryParse(...) is designed).
A: Personally, I think I'd use the same idea as TryParse() : using an out parameter to output the real value, and returning a boolean indicating whether the call was successful or not
public bool CalculatePoint(... out Point result);
I am not a fan of using exception for "normal" behaviors (if you expect the function not to work for some entries).
A: If the failure is for a specific reason then I think its ok to return null, or bool and have an out parameter. If however you return null regardless of the failure then I don't recommend it. Exceptions provide a rich set of information including the reason WHY something failed, if all you get back is a null then how do you know if its because the data is wrong, you've ran out of memory or some other weird behavior.
Even in .net the TryParse has a Parse brother so that you can get the exception if you want to.
If I provided a TrySomething method I would also provide a Something method that threw an exception in the event of failure. Then it's up to the caller.
A: The model I've used is the same one MS uses with the TryParse methods of various classes.
Your original code:
public Point CalculatePoint(... out Boolean boSuccess);
public List CalculateListOfPoints(... out Boolean boSuccess);
Would turn into
public bool CalculatePoint(... out (or ref) Point CalculatedValue);
public bool CalculateListOfPoints(... out (or ref) List CalculatedValues);
Basically you make the success/failure the return value.
A: To summarise there are a couple of approaches you can take:
*
*When the return type is a value-type, like Point, use the Nullable feature of C# and return a Point? (aka Nullable), that way you can still return null on a failure
*Throw an exception when there's a failure. The whole argument/discussion regarding what is and isn't "exceptional" is a moot point, it's your API, you decide what's exceptional behaviour.
*Adopt a model similar to that implemented by Microsoft in the base types like Int32, provide a CalculatePoint and TryCalculatePoint (int32.Parse and int32.TryParse) and have one throw and one return a bool.
*Return a generic struct from your methods that has two properties, bool Success and GenericType Value.
Dependent on the scenario I tend to use a combination of returning null or throwing an exception as they seem "cleanest" to me and fit best with the existing codebase at the company I work for. So my personal best practice would be approaches 1 and 2.
A: It mostly depends on the behavior of your methods and their usage.
If failure is common and non-critical, then have your methods return a boolean indicating their success and use an out parameter to convey the result. Looking up a key in a hash, attempting to read data on a non-blocking socket when no data is available, all these examples fall in that category.
If failure is unexpected, return directly the result and convey errors with exceptions. Opening a file read-only, connecting to a TCP server, are good candidates.
And sometimes both ways make sense...
A: Return Point.Empty. It's a .NET design patter to return a special field when you want to check if structure creation was successful. Avoid out parameters when you can.
public static readonly Point Empty
A: A pattern that I'm experimenting with is returning a Maybe. It has the semantics of the TryParse pattern, but a similar signature to the null-return-on-error pattern.
I'm not yet convinced one way or the other, but I offer it for your collective consideration. It does have the benefit of not requiring a variable to defined before the method call to hold the out parameter at the call site of the method. It could also be extended with an Errors or Messages collection to indicate the reason for the failure.
The Maybe class looks something like this:
/// <summary>
/// Represents the return value from an operation that might fail
/// </summary>
/// <typeparam name="T"></typeparam>
public struct Maybe<T>
{
T _value;
bool _hasValue;
public Maybe(T value)
{
_value = value;
_hasValue = true;
}
public Maybe()
{
_hasValue = false;
_value = default(T);
}
public bool Success
{
get { return _hasValue; }
}
public T Value
{
get
{ // could throw an exception if _hasValue is false
return _value;
}
}
}
A: I would say best practice is a return value means success, and an exception means failure.
I see no reason in the examples you provided that you shouldn't be using exceptions in the event of a failure.
A: Using an exception is a bad idea in some cases (especially when writing a server). You would need two flavors of the method. Also look at the dictionary class for an indication of what you should do.
// NB: A bool is the return value.
// This makes it possible to put this beast in if statements.
public bool TryCalculatePoint(... out Point result) { }
public Point CalculatePoint(...)
{
Point result;
if(!TryCalculatePoint(... out result))
throw new BogusPointException();
return result;
}
Best of both worlds!
A: The bool TrySomething() is at least a practice, which works ok for .net's parse methods, but I don't think I like it in general.
Throwing an exception is often a good thing, though it should not be used for situations you would expect to happen in many normal situations, and it has an associated performance cost.
Returning null when possible is in most cases ok, when you don't want an exception.
However - your approach is a bit procedural - what about creating something like a PointCalculator class - taking the required data as parameters in the constructor? Then you call CalculatePoint on it, and access the result through properties (separate properties for Point and for Success).
A: You don't want to be throwing exceptions when there is something expected happening, as @Kevin stated exceptions are for exceptional cases.
You should return something that is expected for the 'failure', generally null is my choice of bad return.
The documentation for your method should inform the users of what to expect when the data does not compute.
A: We once wrote an entire Framework where all the public methods either returned true (executed successfully) or false (an error occurred). If we needed to return a value we used output parameters. Contrary to popular belief, this way of programming actually simplified a lot of our code.
A: Well with Point, you can send back Point.Empty as a return value in case of failure. Now all this really does is return a point with 0 for the X and Y value, so if that can be a valid return value, I'd stay away from that, but if your method will never return a (0,0) point, then you can use that.
A: Sorry, I just remembered the Nullable type, you should look at that. I am not too sure what the overhead is though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Setting data type when reading XML data in SAS I need to control the data type when reading XML data in SAS. The XML data are written and accessed using the XML libname engine in SAS.
SAS seems to guess the data type based on the contents of a column: If I write "20081002" to my XML data in a character column, it will be read back in as a numerical variable.
An example:
filename my_xml '/tmp/my.xml'; * Yes, I use SAS on Unix *;
libname my_xml XML;
data my_xml.data_type_test;
text_char="This is obviously text";
date_char="20081002";
num_char="42";
genuine_num=42;
run;
proc copy inlib=my_xml outlib=WORK;
run;
libname my_xml;
filename my_xml CLEAR;
Only the last column is defined as numerical data type in the XML data, but when I copy it into my WORK library, only the column text_char is character. The other 3 are now numeric.
How can I control the data type when reading XML data in SAS?
A: Take a look at the SAS XML Mapper.
It allows you to create a map to read (and wrte in 9.2) XML files and specifying column attributes.
If this is your XML file:
This is obviously text
20081002
42
42
You could create a MAP like this:
<!-- ############################################################ -->
<TABLE name="DATA_TYPE_TEST">
<TABLE-PATH syntax="XPath">/TABLE/DATA_TYPE_TEST</TABLE-PATH>
<COLUMN name="text_char">
<PATH syntax="XPath">/TABLE/DATA_TYPE_TEST/text_char</PATH>
<TYPE>character</TYPE>
<DATATYPE>string</DATATYPE>
<LENGTH>22</LENGTH>
</COLUMN>
<COLUMN name="date_char">
<PATH syntax="XPath">/TABLE/DATA_TYPE_TEST/date_char</PATH>
<TYPE>numeric</TYPE>
<DATATYPE>integer</DATATYPE>
<FORMAT width="9">DATE</FORMAT>
<INFORMAT width="8">ND8601DA</INFORMAT>
</COLUMN>
<COLUMN name="num_char">
<PATH syntax="XPath">/TABLE/DATA_TYPE_TEST/num_char</PATH>
<TYPE>character</TYPE>
<DATATYPE>string</DATATYPE>
<LENGTH>2</LENGTH>
</COLUMN>
<COLUMN name="genuine_num">
<PATH syntax="XPath">/TABLE/DATA_TYPE_TEST/genuine_num</PATH>
<TYPE>numeric</TYPE>
<DATATYPE>integer</DATATYPE>
</COLUMN>
</TABLE>
And then read the XML file:
filename my 'C:\temp\my.xml';
filename SXLEMAP 'C:\temp\MyMap.map';
libname my xml xmlmap=SXLEMAP access=READONLY;
title 'Table DATA_TYPE_TEST';
proc contents data=my.DATA_TYPE_TEST varnum;
run;
proc print data=my.DATA_TYPE_TEST(obs=10);
run;
Result:
Table DATA_TYPE_TEST
The CONTENTS Procedure
Data Set Name MY.DATA_TYPE_TEST Observations
Member Type DATA Variables 4
Engine XML Indexes 0
Created . Observation Length 0
Last Modified . Deleted Observations 0
Protection Compressed NO
Data Set Type Sorted NO
Label
Data Representation Default
Encoding Default
Variables in Creation Order
# Variable Type Len Format Informat Label
1 text_char Char 22 $22. $22. text_char
2 date_char Num 8 DATE9. ND8601DA8. date_char
3 num_char Char 2 $2. $2. num_char
4 genuine_num Num 8 F8. F8. genuine_num
Table DATA_TYPE_TEST
genuine_
Obs text_char date_char num_char num
1 This is obviously text 02OCT2008 42 42
A: I think you need to define some xml specific options whith your libname XML statement for export go:
libname my_xml_out XML XMLMETA=SCHEMADATA;
To include the data schema. Also, you might want to save the XML schema to a separate file for later import:
libname my_xml_in XML XMLSCHEMA='external-file'
after you exported the schema using XMLMETA=SCHEMA of course.
I think this is the documentation you need.
Apart from that liberal use of format statements on original dataset creation is recommended.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is it possible to unlisten on a socket? Is it possible to unlisten on a socket after you have called listen(fd, backlog)?
Edit: My mistake for not making myself clear. I'd like to be able to temporarily unlisten on the socket. Calling close() will leave the socket in the M2LS state and prevent me from reopening it (or worse, some nefarious program could bind to that socket)
Temporarily unlistening would be a way (maybe not the best way) to signal to an upstream load balancer that this app couldn't accept any more requests for the moment
A: After closing the socket, your programs may still tell you that the socket is "in use", this is because of some weirdiness I don't know exactly about. But the manpage about sockets shows you there is a flag to re-use the same socket, lazily called: "SO_REUSEADDR". Set it using "setsockopt()".
A: Some socket libraries allow you to specifically reject incoming connections. For example: GNU's CommonC++: TCPsocket Class has a reject method.
BSD Sockets doesn't have this functionality. You can accept the connection and then immediately close it, while leaving the socket open:
while (running) {
int i32ConnectFD = accept(i32SocketFD, NULL, NULL);
while (noConnectionsPlease) {
shutdown(i32ConnectFD, 2);
close(i32ConnectFD);
break;
}
}
A: Close it. As I recall;
close(fd);
A: Based on your edited version of the question, I'm not sure you have to "unlisten" or close(). Two options come to mind:
1) After you invoke listen(), connections are not actually accepted until (logically enough) you call accept(). You can "unlisten" by simply ignoring socket activity and deferring any accept()'s until you are ready for them. Any inbound connection attempts backlog onto the queue that was created when the port was opened in listen mode. Once the backlog queue is full in the stack, further connection attempts are simply dropped on the floor. When you resume with accepts(), you'll quickly dequeue the backlog and be ready for more connections.
2) If you really want the port to appear completely closed temporarily, you might dynamically apply the kernel level packet filter to the port to prevent the inbound connection attempts from reaching the network stack. For example, you could use Berkeley Packet Filter (BPF) on most *nix platforms. That is you want to drop inbound packets coming in to the port of interest using the platform's firewall features. This, of course, varies by platform, but is a possible approach.
A: I don't think it's a good way to signal an upstream load-balancer. It would have to actually send some connections to your server before the message got through - those connections would probably get rejected.
Likewise, any connections which were pending when you closed the listening socket will get closed with no data.
If you want to signal the upstream load balancer, you should have a protocol for doing that. Don't try to abuse TCP to do it.
Fortunately if the clients are normal web browsers, you can get away with an awful lot - simply closing sockets generally results in them retrying transparently to the user (to a point).
A: There is no explicit method to unlisten!
You can either close(fd) or shutdown(fd, how)
fd is the socket file descriptor you want to shutdown, and how is one of the following:
0 Further receives are disallowed
1 Further sends are disallowed
2 Further sends and receives are disallowed (like close())
A: At a basic level, sockets are either open or closed (we'll ignore the niceties of the TCP/IP state diagram here).
If your socket is closed, then nothing can send data to it. If it's open, then incoming data will be accepted and acknowledged by the TCP/IP stack until it's buffering algorithm cries "enough!". At that point, further data will not be acknowledged.
You have two choices that I can see. Either close() the socket when you want to "unlisten", and reopen it later - Use setsockopt() with the SO_REUSEADDR flag to allow you to rebind to the well-known port before TIME_WAIT2 expires.
The other choice is to keep the socket open but simply not accept() from it while you're 'busy'. Assuming you have an application-level acknowledge to requests, You load balancer would realise it's not getting a response and act accordingly.
A: Here's a rather ugly approach based on your edited question:
Open a socket for listening with a normal backlog. Proceed.
When you want to "shut down", open a 2nd one with a backlog of 1 and SO_REUSEADDR. Close the first one. When ready to resume, do another socket juggle to one with a normal backlog.
Picky details around draining the accept queue from the socket that you're closing will be the killer here. Probably enough of a killer to make this approach nonviable.
A: I don't necessarily think this is a good idea, but...
You might be able to call listen a second time. The POSIX spec doesn't say not to. Perhaps you could call it a second time with a backlog parameter of 0 when you want to "unlisten".
What happens when listen is called with a backlog of 0 seems to be implementation defined. The POSIX spec says it may allow connections to be accepted, which implies some implementations may choose to reject all connections if the backlog parameter is 0. More likely though, your implementation will choose some positive value when you pass in 0 (probably either 1 or SOMAXCONN).
A: The question didn't say what kind of socket. If it is a unix socket, you can stop and start listening with rename(2). You can also permanently stop listening with unlink(2), and since the socket remains open you can continue to service your backlog. This approach seems quite handy, though I have not seen used before and am just exploring it myself.
A: You already got some answers on the impossibility to do this via the socket API.
You can use other OS methods (i.e. Host firwewall/iptables/ipfilter) to set up a temporary reject rule.
I found that most load balancers are a bit limited in the possibilities they offer to recognize connection problems (most of them recognize a RST only in the connect probe, not as answer to a legit connection attempt.)
Anyway, if you are limited by the probes detecting the inavailability, you set up an application level probe which does a HTTP request or FTP login or similiar things it will recognize if you simply close after accept. It could even interpret error messages like "500 service not available", which seems cleaner to me anyway. With SNMP some load balancers can also use the result as a load hint.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: How can I read binary data from wfstream? I have a slight problem reading data from file. I want to be able to read wstring's, aswell as a chunk of raw data of arbitrary size (size is in bytes).
std::wfstream stream(file.c_str());
std::wstring comType;
stream >> comType;
int comSize;
stream >> comSize;
char *comData = new char[comSize];
memset(comData, 0, comSize);
stream.read(comData, comSize);
//error C2664 : 'std::basic_istream<_Elem,_Traits>::read'
// : cannot convert parameter 1 from 'char *' to 'wchar_t *'
Perhaps I am using wrong streams, or something along those lines. Basically, I want to read a wstring, size of the data followed (which could be any number of bytes), followed by that many bytes of component data. Obviously, I can't read char's because the template assumes wchar_t's.
I can read wchar_t's but then I have to make sure the data is stored as aligned by sizeof(wchar_t). Otherwise, I could end up corrupting the stream. A scenario would be when the data is 15 bytes. I would have to read 16 bytes, then mask the unwanted byte, seek the stream to 15 bytes offset (if possible with wchar_t templated?) to be able to read the next data chunk.
Clearly, there should be a nicer way of achieving what I am trying to do.
A: Considering your requirements I do not think wfstream is the way to go. Considerer using something like the following code snippet.
#include "stdafx.h"
#include <fstream>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
std::wstring str(L"hello");
size_t size1 = str.length();
char data[] = { 0x10, 0x20, 0x30 };
size_t size2 = 3;
FILE* output = NULL;
if (_wfopen_s(&output, L"c:\\test.bin", L"wb") == 0) {
fwrite(&size1, sizeof(size_t), 1, output);
fwrite(str.c_str(), size1 * sizeof(wchar_t), 1, output);
fwrite(&size2, sizeof(size_t), 1, output);
fwrite(data, size2, 1, output);
fclose(output);
}
FILE* input = NULL;
if (_wfopen_s(&input, L"c:\\test.bin", L"rb") == 0) {
fread(&size1, sizeof(size_t), 1, input);
wchar_t* wstr = new wchar_t[size1 + 1];
fread(wstr, size1 * sizeof(wchar_t), 1, input);
std::wstring str(wstr, size1);
delete[] wstr;
fread(&size2, sizeof(size_t), 1, input);
char* data1 = new char[size2];
fread(data1, size2, 1, input);
std::wcout << str.c_str() << std::endl;
for (size_t i = 0; i < size2; ++i) {
std::wcout << std::hex << "0x" << int(data1[i]) << std::endl;
}
delete[] data1;
fclose(input);
}
return 0;
}
This outputs:
hello
0x10
0x20
0x30
A: the problem with the stream.read is that it uses wchar_t as "character unit" with wfstream. If you use fstream it uses char as "character unit".
This would work if you want to read wide characters:
wchar_t *comData = new wchar_t[comSize];
stream.read(comData, comSize);
Also 15 bytes of data can't be read with a wide stream, because the smallest unit is at least 2bytes (see below), so you can only read chunks of sizwof(wchar_t) * n.
But if you are concerned about portability of the application wfstream/wchar_t is maybe not the best solution because there is no standard how wide wchar_t is (e.g. on windows wchar_t is 16bit on many unix/linux systems it is 32bit).
The second problem with storing text as wide characters is endianess, i would suggest to use UTF-8 for text storage.
A: # ifdef UNICODE
# define tfstream wfstream
# else
# define tfstream fstream
# endif
tfstream fs( _T("filename.bin"), tfstream::binary );
byte buffer[1023];
fs.read( buffer, sizeof(buffer) )
I think, the _T("filename.bin") and tfstream are the UI expression; the buffer and the read() is DATA LOGIC expression. wfstream must NOT restrict the buffer to the type wchar_t. The UI must NOT mix with DATA LOGIC ! wfstream do the wrong thing here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Using Quotes within getRuntime().exec I'd like to invoke bash using a string as input. Something like:
sh -l -c "./foo"
I'd like to do this from Java. Unfortunately, when I try to invoke the command using getRuntime().exec, I get the following error:
foo": -c: line 0: unexpected EOF while looking for matching `"'
foo": -c: line 1: syntax error: unexpected end of file
It seems to be related to my string not being terminated with an EOF.
Is there a way to insert a platform specific EOF into a Java string? Or should I be looking for another approach, like writing to a temp script before invoking "sh" ?
A: Use this:
Runtime.getRuntime().exec(new String[] {"sh", "-l", "-c", "./foo"});
Main point: don't put the double quotes in. That's only used when writing a command-line in the shell!
e.g., echo "Hello, world!" (as typed in the shell) gets translated to:
Runtime.getRuntime().exec(new String[] {"echo", "Hello, world!"});
(Just forget for the moment that the shell normally has a builtin for echo, and is calling /bin/echo instead. :-))
A: EOF is NOT a character, so there's no way to write an EOF.
You've forgotten to close a quoted string.
A: Windows command lines behave differently from UNIX, Mac OS X and GNU/Linux.
On Windows the process receives the input text verbatim after the executable name (and space). It's then up to the program to parse the command line (which is usually done implicitly, the programmer is often clueless about the process).
In GNU/Linux the shell processes the command line, guaranteeing the familiar array of strings passed to C's main function. You don't have that shell. The best approach (even on Windows) is to use one of the form of exec where you pass each command line argument individually in its own String.
Process exec(String[] cmdarray)
Process exec(String[] cmdarray, String[] envp)
Process exec(String[] cmdarray, String[] envp, File dir)
Or better, java.lang.ProcessBuilder.
You can get a shell to do the parsing for you if you really want. This would make your example look something like (untested):
Runtime.getRuntime().exec(new String[] {
"sh", "-c", "sh -l -c \"echo foo; echo bar;\""
});
A: The cause for this error is most likely a missing syntax token that bash expects but the string you pass ends before bash encountered it. Look for ifs, fors etc. that have no closing fi or done.
A: Quotes need to be escaped when inside a string.
Instead of writing " write \".
E.g.
strcpy(c, "This is a string \"with\" quotes");
A: if I were you, I would write the contents of the string to a temp bashfile and see if bash executes that without any error. If that executes without an error, then I would consider debugging further;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: Hidden features of Perl? What are some really useful but esoteric language features in Perl that you've actually been able to employ to do useful work?
Guidelines:
*
*Try to limit answers to the Perl core and not CPAN
*Please give an example and a short description
Hidden Features also found in other languages' Hidden Features:
(These are all from Corion's answer)
*
*C
*
*Duff's Device
*Portability and Standardness
*C#
*
*Quotes for whitespace delimited lists and strings
*Aliasable namespaces
*Java
*
*Static Initalizers
*JavaScript
*
*Functions are First Class citizens
*Block scope and closure
*Calling methods and accessors indirectly through a variable
*Ruby
*
*Defining methods through code
*PHP
*
*Pervasive online documentation
*Magic methods
*Symbolic references
*Python
*
*One line value swapping
*Ability to replace even core functions with your own functionality
Other Hidden Features:
Operators:
*
*The bool quasi-operator
*The flip-flop operator
*
*Also used for list construction
*The ++ and unary - operators work on strings
*The repetition operator
*The spaceship operator
*The || operator (and // operator) to select from a set of choices
*The diamond operator
*Special cases of the m// operator
*The tilde-tilde "operator"
Quoting constructs:
*
*The qw operator
*Letters can be used as quote delimiters in q{}-like constructs
*Quoting mechanisms
Syntax and Names:
*
*There can be a space after a sigil
*You can give subs numeric names with symbolic references
*Legal trailing commas
*Grouped Integer Literals
*hash slices
*Populating keys of a hash from an array
Modules, Pragmas, and command-line options:
*
*use strict and use warnings
*Taint checking
*Esoteric use of -n and -p
*CPAN
*overload::constant
*IO::Handle module
*Safe compartments
*Attributes
Variables:
*
*Autovivification
*The $[ variable
*tie
*Dynamic Scoping
*Variable swapping with a single statement
Loops and flow control:
*
*Magic goto
*for on a single variable
*continue clause
*Desperation mode
Regular expressions:
*
*The \G anchor
*(?{}) and '(??{})` in regexes
Other features:
*
*The debugger
*Special code blocks such as BEGIN, CHECK, and END
*The DATA block
*New Block Operations
*Source Filters
*Signal Hooks
*map (twice)
*Wrapping built-in functions
*The eof function
*The dbmopen function
*Turning warnings into errors
Other tricks, and meta-answers:
*
*cat files, decompressing gzips if needed
*Perl Tips
See Also:
*
*Hidden features of C
*Hidden features of C#
*Hidden features of C++
*Hidden features of Java
*Hidden features of JavaScript
*Hidden features of Ruby
*Hidden features of PHP
*Hidden features of Python
*Hidden features of Clojure
A: tie, the variable tying interface.
A: The "desperation mode" of Perl's loop control constructs which causes them to look up the stack to find a matching label allows some curious behaviors which Test::More takes advantage of, for better or worse.
SKIP: {
skip() if $something;
print "Never printed";
}
sub skip {
no warnings "exiting";
last SKIP;
}
There's the little known .pmc file. "use Foo" will look for Foo.pmc in @INC before Foo.pm. This was intended to allow compiled bytecode to be loaded first, but Module::Compile takes advantage of this to cache source filtered modules for faster load times and easier debugging.
The ability to turn warnings into errors.
local $SIG{__WARN__} = sub { die @_ };
$num = "two";
$sum = 1 + $num;
print "Never reached";
That's what I can think of off the top of my head that hasn't been mentioned.
A: The goatse operator*:
$_ = "foo bar";
my $count =()= /[aeiou]/g; #3
or
sub foo {
return @_;
}
$count =()= foo(qw/a b c d/); #4
It works because list assignment in scalar context yields the number of elements in the list being assigned.
* Note, not really an operator
A: The input record separator can be set to a reference to a number to read fixed length records:
$/ = \3; print $_,"\n" while <>; # output three chars on each line
A: I don't know how esoteric it is, but one of my favorites is the hash slice. I use it for all kinds of things. For example to merge two hashes:
my %number_for = (one => 1, two => 2, three => 3);
my %your_numbers = (two => 2, four => 4, six => 6);
@number_for{keys %your_numbers} = values %your_numbers;
print sort values %number_for; # 12346
A: This one isn't particularly useful, but it's extremely esoteric. I stumbled on this while digging around in the Perl parser.
Before there was POD, perl4 had a trick to allow you to embed the man page, as nroff, straight into your program so it wouldn't get lost. perl4 used a program called wrapman (see Pink Camel page 319 for some details) to cleverly embed an nroff man page into your script.
It worked by telling nroff to ignore all the code, and then put the meat of the man page after an END tag which tells Perl to stop processing code. Looked something like this:
#!/usr/bin/perl
'di';
'ig00';
...Perl code goes here, ignored by nroff...
.00; # finish .ig
'di \" finish the diversion
.nr nl 0-1 \" fake up transition to first page
.nr % 0 \" start at page 1
'; __END__
...man page goes here, ignored by Perl...
The details of the roff magic escape me, but you'll notice that the roff commands are strings or numbers in void context. Normally a constant in void context produces a warning. There are special exceptions in op.c to allow void context strings which start with certain roff commands.
/* perl4's way of mixing documentation and code
(before the invention of POD) was based on a
trick to mix nroff and perl code. The trick was
built upon these three nroff macros being used in
void context. The pink camel has the details in
the script wrapman near page 319. */
const char * const maybe_macro = SvPVX_const(sv);
if (strnEQ(maybe_macro, "di", 2) ||
strnEQ(maybe_macro, "ds", 2) ||
strnEQ(maybe_macro, "ig", 2))
useless = NULL;
This means that 'di'; doesn't produce a warning, but neither does 'die'; 'did you get that thing I sentcha?'; or 'ignore this line';.
In addition, there are exceptions for the numeric constants 0 and 1 which allows the bare .00;. The code claims this was for more general purposes.
/* the constants 0 and 1 are permitted as they are
conventionally used as dummies in constructs like
1 while some_condition_with_side_effects; */
else if (SvNIOK(sv) && (SvNV(sv) == 0.0 || SvNV(sv) == 1.0))
useless = NULL;
And what do you know, 2 while condition does warn!
A: You can use @{[...]} to get an interpolated result of complex perl expressions
$a = 3;
$b = 4;
print "$a * $b = @{[$a * $b]}";
prints: 3 * 4 = 12
A: sub load_file
{
local(@ARGV, $/) = shift;
<>;
}
and a version that returns an array as appropriate:
sub load_file
{
local @ARGV = shift;
local $/ = wantarray? $/: undef;
<>;
}
A: use diagnostics;
If you are starting to work with Perl and have never done so before, this module will save you tons of time and hassle. For almost every basic error message you can get, this module will give you a lengthy explanation as to why your code is breaking, including some helpful hints as to how to fix it. For example:
use strict;
use diagnostics;
$var = "foo";
gives you this helpful message:
Global symbol "$var" requires explicit package name at - line 4.
Execution of - aborted due to compilation errors (#1)
(F) You've said "use strict vars", which indicates that all variables
must either be lexically scoped (using "my"), declared beforehand using
"our", or explicitly qualified to say which package the global variable
is in (using "::").
Uncaught exception from user code:
Global symbol "$var" requires explicit package name at - line 4.
Execution of - aborted due to compilation errors.
at - line 5
use diagnostics;
use strict;
sub myname {
print { " Some Error " };
};
you get this large, helpful chunk of text:
syntax error at - line 5, near "};"
Execution of - aborted due to compilation errors (#1)
(F) Probably means you had a syntax error. Common reasons include:
A keyword is misspelled.
A semicolon is missing.
A comma is missing.
An opening or closing parenthesis is missing.
An opening or closing brace is missing.
A closing quote is missing.
Often there will be another error message associated with the syntax
error giving more information. (Sometimes it helps to turn on -w.)
The error message itself often tells you where it was in the line when
it decided to give up. Sometimes the actual error is several tokens
before this, because Perl is good at understanding random input.
Occasionally the line number may be misleading, and once in a blue moon
the only way to figure out what's triggering the error is to call
perl -c repeatedly, chopping away half the program each time to see
if the error went away. Sort of the cybernetic version of S.
Uncaught exception from user code:
syntax error at - line 5, near "};"
Execution of - aborted due to compilation errors.
at - line 7
From there you can go about deducing what might be wrong with your program (in this case, print is formatted entirely wrong). There's a large number of known errors with diagnostics. Now, while this would not be a good thing to use in production, it can serve as a great learning aid for those who are new to Perl.
A: The flip-flop operator is useful for skipping the first iteration when looping through the records (usually lines) returned by a file handle, without using a flag variable:
while(<$fh>)
{
next if 1..1; # skip first record
...
}
Run perldoc perlop and search for "flip-flop" for more information and examples.
A: There also is $[ the variable which decides at which index an array starts.
Default is 0 so an array is starting at 0.
By setting
$[=1;
You can make Perl behave more like AWK (or Fortran) if you really want to.
A: ($x, $y) = ($y, $x) is what made me want to learn Perl.
The list constructor 1..99 or 'a'..'zz' is also very nice.
A: @Schwern mentioned turning warnings into errors by localizing $SIG{__WARN__}. You can do also do this (lexically) with use warnings FATAL => "all";. See perldoc lexwarn.
On that note, since Perl 5.12, you've been able to say perldoc foo instead of the full perldoc perlfoo. Finally! :)
A: There are many non-obvious features in Perl.
For example, did you know that there can be a space after a sigil?
$ perl -wle 'my $x = 3; print $ x'
3
Or that you can give subs numeric names if you use symbolic references?
$ perl -lwe '*4 = sub { print "yes" }; 4->()'
yes
There's also the "bool" quasi operator, that return 1 for true expressions and the empty string for false:
$ perl -wle 'print !!4'
1
$ perl -wle 'print !!"0 but true"'
1
$ perl -wle 'print !!0'
(empty line)
Other interesting stuff: with use overload you can overload string literals and numbers (and for example make them BigInts or whatever).
Many of these things are actually documented somewhere, or follow logically from the documented features, but nonetheless some are not very well known.
Update: Another nice one. Below the q{...} quoting constructs were mentioned, but did you know that you can use letters as delimiters?
$ perl -Mstrict -wle 'print q bJet another perl hacker.b'
Jet another perl hacker.
Likewise you can write regular expressions:
m xabcx
# same as m/abc/
A: Add support for compressed files via magic ARGV:
s{
^ # make sure to get whole filename
(
[^'] + # at least one non-quote
\. # extension dot
(?: # now either suffix
gz
| Z
)
)
\z # through the end
}{gzcat '$1' |}xs for @ARGV;
(quotes around $_ necessary to handle filenames with shell metacharacters in)
Now the <> feature will decompress any @ARGV files that end with ".gz" or ".Z":
while (<>) {
print;
}
A: One of my favourite features in Perl is using the boolean || operator to select between a set of choices.
$x = $a || $b;
# $x = $a, if $a is true.
# $x = $b, otherwise
This means one can write:
$x = $a || $b || $c || 0;
to take the first true value from $a, $b, and $c, or a default of 0 otherwise.
In Perl 5.10, there's also the // operator, which returns the left hand side if it's defined, and the right hand side otherwise. The following selects the first defined value from $a, $b, $c, or 0 otherwise:
$x = $a // $b // $c // 0;
These can also be used with their short-hand forms, which are very useful for providing defaults:
$x ||= 0; # If $x was false, it now has a value of 0.
$x //= 0; # If $x was undefined, it now has a value of zero.
Cheerio,
Paul
A: Safe compartments.
With the Safe module you can build your own sandbox-style environment using nothing but perl. You would then be able to load perl scripts into the sandbox.
Best regards,
A: Core IO::Handle module. Most important thing for me is that it allows autoflush on filehandles. Example:
use IO::Handle;
$log->autoflush(1);
A: How about the ability to use
my @symbols = map { +{ 'key' => $_ } } @things;
to generate an array of hashrefs from an array -- the + in front of the hashref disambiguates the block so the interpreter knows that it's a hashref and not a code block. Awesome.
(Thanks to Dave Doyle for explaining this to me at the last Toronto Perlmongers meeting.)
A: All right. Here is another. Dynamic Scoping. It was talked about a little in a different post, but I didn't see it here on the hidden features.
Dynamic Scoping like Autovivification has a very limited amount of languages that use it. Perl and Common Lisp are the only two I know of that use Dynamic Scoping.
A: Use lvalues to make your code really confusing:
my $foo = undef ;
sub bar:lvalue{ return $foo ;}
# Then later
bar = 5 ;
print bar ;
A: The Schwartzian Transform is a technique that allows you to efficiently sort by a computed, secondary index. Let's say that you wanted to sort a list of strings by their md5 sum. The comments below are best read backwards (that's the order I always end up writing these anyways):
my @strings = ('one', 'two', 'three', 'four');
my $md5sorted_strings =
map { $_->[0] } # 4) map back to the original value
sort { $a->[1] cmp $b->[1] } # 3) sort by the correct element of the list
map { [$_, md5sum_func($_)] } # 2) create a list of anonymous lists
@strings # 1) take strings
This way, you only have to do the expensive md5 computation N times, rather than N log N times.
A: One useful composite operator for conditionally adding strings or lists into other lists is the x!!operator:
print 'the meaning of ', join ' ' =>
'life,' x!! $self->alive,
'the universe,' x!! ($location ~~ Universe),
('and', 'everything.') x!! 42; # this is added as a list
this operator allows for a reversed syntax similar to
do_something() if test();
A: This one-liner illustrates how to use glob to generate all word combinations of an alphabet (A, T, C, and G -> DNA) for words of a specified length (4):
perl -MData::Dumper -e '@CONV = glob( "{A,T,C,G}" x 4 ); print Dumper( \@CONV )'
A: The operators ++ and unary - don't only work on numbers, but also on strings.
my $_ = "a"
print -$_
prints -a
print ++$_
prints b
$_ = 'z'
print ++$_
prints aa
A: As Perl has almost all "esoteric" parts from the other lists, I'll tell you the one thing that Perl can't:
The one thing Perl can't do is have bare arbitrary URLs in your code, because the // operator is used for regular expressions.
Just in case it wasn't obvious to you what features Perl offers, here's a selective list of the maybe not totally obvious entries:
Duff's Device - in Perl
Portability and Standardness - There are likely more computers with Perl than with a C compiler
A file/path manipulation class - File::Find works on even more operating systems than .Net does
Quotes for whitespace delimited lists and strings - Perl allows you to choose almost arbitrary quotes for your list and string delimiters
Aliasable namespaces - Perl has these through glob assignments:
*My::Namespace:: = \%Your::Namespace
Static initializers - Perl can run code in almost every phase of compilation and object instantiation, from BEGIN (code parse) to CHECK (after code parse) to import (at module import) to new (object instantiation) to DESTROY (object destruction) to END (program exit)
Functions are First Class citizens - just like in Perl
Block scope and closure - Perl has both
Calling methods and accessors indirectly through a variable - Perl does that too:
my $method = 'foo';
my $obj = My::Class->new();
$obj->$method( 'baz' ); # calls $obj->foo( 'baz' )
Defining methods through code - Perl allows that too:
*foo = sub { print "Hello world" };
Pervasive online documentation - Perl documentation is online and likely on your system too
Magic methods that get called whenever you call a "nonexisting" function - Perl implements that in the AUTOLOAD function
Symbolic references - you are well advised to stay away from these. They will eat your children. But of course, Perl allows you to offer your children to blood-thirsty demons.
One line value swapping - Perl allows list assignment
Ability to replace even core functions with your own functionality
use subs 'unlink';
sub unlink { print 'No.' }
or
BEGIN{
*CORE::GLOBAL::unlink = sub {print 'no'}
};
unlink($_) for @ARGV
A: Autovivification. AFAIK no other language has it.
A: It's simple to quote almost any kind of strange string in Perl.
my $url = q{http://my.url.com/any/arbitrary/path/in/the/url.html};
In fact, the various quoting mechanisms in Perl are quite interesting. The Perl regex-like quoting mechanisms allow you to quote anything, specifying the delimiters. You can use almost any special character like #, /, or open/close characters like (), [], or {}. Examples:
my $var = q#some string where the pound is the final escape.#;
my $var2 = q{A more pleasant way of escaping.};
my $var3 = q(Others prefer parens as the quote mechanism.);
Quoting mechanisms:
q : literal quote; only character that needs to be escaped is the end character.
qq : an interpreted quote; processes variables and escape characters. Great for strings that you need to quote:
my $var4 = qq{This "$mechanism" is broken. Please inform "$user" at "$email" about it.};
qx : Works like qq, but then executes it as a system command, non interactively. Returns all the text generated from the standard out. (Redirection, if supported in the OS, also comes out) Also done with back quotes (the ` character).
my $output = qx{type "$path"}; # get just the output
my $moreout = qx{type "$path" 2>&1}; # get stuff on stderr too
qr : Interprets like qq, but then compiles it as a regular expression. Works with the various options on the regex as well. You can now pass the regex around as a variable:
sub MyRegexCheck {
my ($string, $regex) = @_;
if ($string)
{
return ($string =~ $regex);
}
return; # returns 'null' or 'empty' in every context
}
my $regex = qr{http://[\w]\.com/([\w]+/)+};
@results = MyRegexCheck(q{http://myurl.com/subpath1/subpath2/}, $regex);
qw : A very, very useful quote operator. Turns a quoted set of whitespace separated words into a list. Great for filling in data in a unit test.
my @allowed = qw(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z { });
my @badwords = qw(WORD1 word2 word3 word4);
my @numbers = qw(one two three four 5 six seven); # works with numbers too
my @list = ('string with space', qw(eight nine), "a $var"); # works in other lists
my $arrayref = [ qw(and it works in arrays too) ];
They're great to use them whenever it makes things clearer. For qx, qq, and q, I most likely use the {} operators. The most common habit of people using qw is usually the () operator, but sometimes you also see qw//.
A: My favorite semi-hidden feature of Perl is the eof function. Here's an example pretty much directly from perldoc -f eof that shows how you can use it to reset the file name and $. (the current line number) easily across multiple files loaded up at the command line:
while (<>) {
print "$ARGV:$.\t$_";
}
continue {
close ARGV if eof
}
A: You can replace the delimiter in regexes and strings with just about anything else. This is particularly useful for "leaning toothpick syndrome", exemplified here:
$url =~ /http:\/\/www\.stackoverflow\.com\//;
You can eliminate most of the back-whacking by changing the delimiter. /bar/ is shorthand for m/bar/ which is the same as m!bar!.
$url =~ m!http://www\.stackoverflow\.com/!;
You can even use balanced delimiters like {} and []. I personally love these. q{foo} is the same as 'foo'.
$code = q{
if( this is awesome ) {
print "Look ma, no escaping!";
}
};
To confuse your friends (and your syntax highlighter) try this:
$string = qq'You owe me $1,000 dollars!';
A: Very late to the party, but: attributes.
Attributes essentially let you define arbitrary code to be associated with the declaration of a variable or subroutine. The best way to use these is with Attribute::Handlers; this makes it easy to define attributes (in terms of, what else, attributes!).
I did a presentation on using them to declaratively assemble a pluggable class and its plugins at YAPC::2006, online here. This is a pretty unique feature.
A: I personally love the /e modifier to the s/// operation:
while(<>) {
s/(\w{0,4})/reverse($1);/e; # reverses all words between 0 and 4 letters
print;
}
Input:
This is a test of regular expressions
^D
Output (I think):
sihT si a tset fo regular expressions
A: Quantum::Superpositions
use Quantum::Superpositions;
if ($x == any($a, $b, $c)) { ... }
A: There is a more powerful way to check program for syntax errors:
perl -w -MO=Lint,no-context myscript.pl
The most important thing that it can do is reporting for 'unexistant subroutine' errors.
A: use re debug
Doc on use re debug
and
perl -MO=Concise[,OPTIONS]
Doc on Concise
Besides being exquisitely flexible, expressive and amenable to programing in the style of C, Pascal, Python and other languages, there are several pragmas command switches that make Perl my 'goto' language for initial kanoodling on an algorithm, regex, or quick problems that needs to be solved. These two are unique to Perl I believe, and are among my favorites.
use re debug:
Most modern flavors of regular expressions owe their current form and function to Perl. While there are many Perl forms of regex that cannot be expressed in other languages, there are almost no forms of other languages' flavor of regex that cannot be expressed in Perl. Additionally, Perl has a wonderful regex debugger built in to show how the regex engine is interpreting your regex and matching against the target string.
Example: I recently was trying to write a simple CSV routine. (Yes, yes, I know, I should have been using Text::CSV...) but the CSV values were not quoted and simple.
My first take was /^(^(?:(.*?),){$i}/ to extract the i record on n CSV records. That works fine -- except for the last record or n of n. I could see that without the debugger.
Next I tried /^(?:(.*?),|$){$i}/ This did not work, and I could not see immediately why. I thought I was saying (.*?) followed by a comma or EOL. Then I added use re debug at the top of a small test script. Ahh yes, the alteration between ,|$ was not being interpreted that way; it was being interpreted as ((.*?),) | ($) -- not what I wanted.
A new grouping was needed. So I arrived at the working /^(?:(.*?)(?:,|$)){$i}/. While I was in the regex debugger, I was surprised how many loops it took for a match towards the end of the string. It is the .*? term that is quite ambiguous and requires excessive backtracking to satisfy. So I tried /^(?:(?:^|,)([^,]*)){$i}/ This does two things: 1) reduces backtracking because of the greedy match of all but a comma 2) allowed the regex optimizer to only use the alteration once on the first field. Using Benchmark, this is 35% faster than the first regex. The regex debugger is wonderful and few use it.
perl -MO=Concise[,OPTIONS]:
The B and Concise frameworks are tremendous tools to see how Perl is interpreting your masterpiece. Using the -MO=Concise prints the result of the Perl interpreters translation of your source code. There are many options to Concise and in B, you can write your own presentation of the OP codes.
As in this post, you can use Concise to compare different code structures. You can interleave your source lines with the OP codes those lines generate. Check it out.
A: You can use different quotes on HEREDOCS to get different behaviors.
my $interpolation = "We will interpolated variables";
print <<"END";
With double quotes, $interpolation, just like normal HEREDOCS.
END
print <<'END';
With single quotes, the variable $foo will *not* be interpolated.
(You have probably seen this in other languages.)
END
## this is the fun and "hidden" one
my $shell_output = <<`END`;
echo With backticks, these commands will be executed in shell.
echo The output is returned.
ls | wc -l
END
print "shell output: $shell_output\n";
A: The "for" statement can be used the same way "with" is used in Pascal:
for ($item)
{
s/ / /g;
s/<.*?>/ /g;
$_ = join(" ", split(" ", $_));
}
You can apply a sequence of s/// operations, etc. to the same variable without having to repeat the variable name.
NOTE: the non-breaking space above ( ) has hidden Unicode in it to circumvent the Markdown. Don't copy paste it :)
A: Not really hidden, but many every day Perl programmers don't know about CPAN. This especially applies to people who aren't full time programmers or don't program in Perl full time.
A: The quoteword operator is one of my favourite things. Compare:
my @list = ('abc', 'def', 'ghi', 'jkl');
and
my @list = qw(abc def ghi jkl);
Much less noise, easier on the eye. Another really nice thing about Perl, that one really misses when writing SQL, is that a trailing comma is legal:
print 1, 2, 3, ;
That looks odd, but not if you indent the code another way:
print
results_of_foo(),
results_of_xyzzy(),
results_of_quux(),
;
Adding an additional argument to the function call does not require you to fiddle around with commas on previous or trailing lines. The single line change has no impact on its surrounding lines.
This makes it very pleasant to work with variadic functions. This is perhaps one of the most under-rated features of Perl.
A: The ability to parse data directly pasted into a DATA block. No need to save to a test file to be opened in the program or similar. For example:
my @lines = <DATA>;
for (@lines) {
print if /bad/;
}
__DATA__
some good data
some bad data
more good data
more good data
A: Binary "x" is the repetition operator:
print '-' x 80; # print row of dashes
It also works with lists:
print for (1, 4, 9) x 3; # print 149149149
A: New Block Operations
I'd say the ability to expand the language, creating pseudo block operations is one.
*
*You declare the prototype for a sub indicating that it takes a code reference first:
sub do_stuff_with_a_hash (&\%) {
my ( $block_of_code, $hash_ref ) = @_;
while ( my ( $k, $v ) = each %$hash_ref ) {
$block_of_code->( $k, $v );
}
}
*You can then call it in the body like so
use Data::Dumper;
do_stuff_with_a_hash {
local $Data::Dumper::Terse = 1;
my ( $k, $v ) = @_;
say qq(Hey, the key is "$k"!);
say sprintf qq(Hey, the value is "%v"!), Dumper( $v );
} %stuff_for
;
(Data::Dumper::Dumper is another semi-hidden gem.) Notice how you don't need the sub keyword in front of the block, or the comma before the hash. It ends up looking a lot like: map { } @list
Source Filters
Also, there are source filters. Where Perl will pass you the code so you can manipulate it. Both this, and the block operations, are pretty much don't-try-this-at-home type of things.
I have done some neat things with source filters, for example like creating a very simple language to check the time, allowing short Perl one-liners for some decision making:
perl -MLib::DB -MLib::TL -e 'run_expensive_database_delete() if $hour_of_day < AM_7';
Lib::TL would just scan for both the "variables" and the constants, create them and substitute them as needed.
Again, source filters can be messy, but are powerful. But they can mess debuggers up something terrible--and even warnings can be printed with the wrong line numbers. I stopped using Damian's Switch because the debugger would lose all ability to tell me where I really was. But I've found that you can minimize the damage by modifying small sections of code, keeping them on the same line.
Signal Hooks
It's often enough done, but it's not all that obvious. Here's a die handler that piggy backs on the old one.
my $old_die_handler = $SIG{__DIE__};
$SIG{__DIE__}
= sub { say q(Hey! I'm DYIN' over here!); goto &$old_die_handler; }
;
That means whenever some other module in the code wants to die, they gotta come to you (unless someone else does a destructive overwrite on $SIG{__DIE__}). And you can be notified that somebody things something is an error.
Of course, for enough things you can just use an END { } block, if all you want to do is clean up.
overload::constant
You can inspect literals of a certain type in packages that include your module. For example, if you use this in your import sub:
overload::constant
integer => sub {
my $lit = shift;
return $lit > 2_000_000_000 ? Math::BigInt->new( $lit ) : $lit
};
it will mean that every integer greater than 2 billion in the calling packages will get changed to a Math::BigInt object. (See overload::constant).
Grouped Integer Literals
While we're at it. Perl allows you to break up large numbers into groups of three digits and still get a parsable integer out of it. Note 2_000_000_000 above for 2 billion.
A: Taint checking. With taint checking enabled, perl will die (or warn, with -t) if you try to pass tainted data (roughly speaking, data from outside the program) to an unsafe function (opening a file, running an external command, etc.). It is very helpful when writing setuid scripts or CGIs or anything where the script has greater privileges than the person feeding it data.
Magic goto. goto &sub does an optimized tail call.
The debugger.
use strict and use warnings. These can save you from a bunch of typos.
A: Based on the way the "-n" and "-p" switches are implemented in Perl 5, you can write a seemingly incorrect program including }{:
ls |perl -lne 'print $_; }{ print "$. Files"'
which is converted internally to this code:
LINE: while (defined($_ = <ARGV>)) {
print $_; }{ print "$. Files";
}
A: Axeman reminded me of how easy it is to wrap some of the built-in functions.
Before Perl 5.10 Perl didn't have a pretty print(say) like Python.
So in your local program you could do something like:
sub print {
print @_, "\n";
}
or add in some debug.
sub print {
exists $ENV{DEVELOPER} ?
print Dumper(@_) :
print @_;
}
A: The following are just as short but more meaningful than "~~" since they indicate what is returned, and there's no confusion with the smart match operator:
print "".localtime; # Request a string
print 0+@array; # Request a number
A: Two things that work well together: IO handles on in-core strings, and using function prototypes to enable you to write your own functions with grep/map-like syntax.
sub with_output_to_string(&) { # allows compiler to accept "yoursub {}" syntax.
my $function = shift;
my $string = '';
my $handle = IO::Handle->new();
open($handle, '>', \$string) || die $!; # IO handle on a plain scalar string ref
my $old_handle = select $handle;
eval { $function->() };
select $old_handle;
die $@ if $@;
return $string;
}
my $greeting = with_output_to_string {
print "Hello, world!";
};
print $greeting, "\n";
A: The ability to use a hash as a seen filter in a loop. I have yet to see something quite as nice in a different language. For example, I have not been able to duplicate this in python.
For example, I want to print a line if it has not been seen before.
my %seen;
for (<LINE>) {
print $_ unless $seen{$_}++;
}
A: The new -E option on the command line:
> perl -e "say 'hello"" # does not work
String found where operator expected at -e line 1, near "say 'hello'"
(Do you need to predeclare say?)
syntax error at -e line 1, near "say 'hello'"
Execution of -e aborted due to compilation errors.
> perl -E "say 'hello'"
hello
A: You can expand function calls in a string, for example;
print my $foo = "foo @{[scalar(localtime)]} bar";
foo Wed May 26 15:50:30 2010 bar
A: The feature I like the best is statement modifiers.
Don't know how many times I've wanted to do:
say 'This will output' if 1;
say 'This will not output' unless 1;
say 'Will say this 3 times. The first Time: '.$_ for 1..3;
in other languages.
etc...
The 'etc' reminded me of another 5.12 feature, the Yada Yada operator.
This is great, for the times when you just want a place holder.
sub something_really_important_to_implement_later {
...
}
Check it out: Perl Docs on Yada Yada Operator.
A: Let's start easy with the Spaceship Operator.
$a = 5 <=> 7; # $a is set to -1
$a = 7 <=> 5; # $a is set to 1
$a = 6 <=> 6; # $a is set to 0
A: This is a meta-answer, but the Perl Tips archives contain all sorts of interesting tricks that can be done with Perl. The archive of previous tips is on-line for browsing, and can be subscribed to via mailing list or atom feed.
Some of my favourite tips include building executables with PAR, using autodie to throw exceptions automatically, and the use of the switch and smart-match constructs in Perl 5.10.
Disclosure: I'm one of the authors and maintainers of Perl Tips, so I obviously think very highly of them. ;)
A: map - not only because it makes one's code more expressive, but because it gave me an impulse to read a little bit more about this "functional programming".
A: My vote would go for the (?{}) and (??{}) groups in Perl's regular expressions. The first executes Perl code, ignoring the return value, the second executes code, using the return value as a regular expression.
A: The continue clause on loops. It will be executed at the bottom of every loop, even those which are next'ed.
while( <> ){
print "top of loop\n";
chomp;
next if /next/i;
last if /last/i;
print "bottom of loop\n";
}continue{
print "continue\n";
}
A: The m// operator has some obscure special cases:
*
*If you use ? as the delimiter it only matches once unless you call reset.
*If you use ' as the delimiter the pattern is not interpolated.
*If the pattern is empty it uses the pattern from the last successful match.
A: while(/\G(\b\w*\b)/g) {
print "$1\n";
}
the \G anchor. It's hot.
A: The null filehandle diamond operator <> has its place in building command line tools. It acts like <FH> to read from a handle, except that it magically selects whichever is found first: command line filenames or STDIN. Taken from perlop:
while (<>) {
... # code for each line
}
A: Special code blocks such as BEGIN, CHECK and END. They come from Awk, but work differently in Perl, because it is not record-based.
The BEGIN block can be used to specify some code for the parsing phase; it is also executed when you do the syntax-and-variable-check perl -c. For example, to load in configuration variables:
BEGIN {
eval {
require 'config.local.pl';
};
if ($@) {
require 'config.default.pl';
}
}
A: rename("$_.part", $_) for "data.txt";
renames data.txt.part to data.txt without having to repeat myself.
A: A bit obscure is the tilde-tilde "operator" which forces scalar context.
print ~~ localtime;
is the same as
print scalar localtime;
and different from
print localtime;
A: I'm a bit late to the party, but a vote for the built-in tied-hash function dbmopen() -- it's helped me a lot. It's not exactly a database, but if you need to save data to disk it takes away a lot of the problems and Just Works. It helped me get started when I didn't have a database, didn't understand Storable.pm, but I knew I wanted to progress beyond reading and writing to text files.
A: You might think you can do this to save memory:
@is_month{qw(jan feb mar apr may jun jul aug sep oct nov dec)} = undef;
print "It's a month" if exists $is_month{lc $mon};
but it doesn't do that. Perl still assigns a different scalar value to each key. Devel::Peek shows this. PVHV is the hash. Elt is a key and the SV that follows is its value. Note that each SV has a different memory address indicating they're not being shared.
Dump \%is_month, 12;
SV = RV(0x81c1bc) at 0x81c1b0
REFCNT = 1
FLAGS = (TEMP,ROK)
RV = 0x812480
SV = PVHV(0x80917c) at 0x812480
REFCNT = 2
FLAGS = (SHAREKEYS)
ARRAY = 0x206f20 (0:8, 1:4, 2:4)
hash quality = 101.2%
KEYS = 12
FILL = 8
MAX = 15
RITER = -1
EITER = 0x0
Elt "feb" HASH = 0xeb0d8580
SV = NULL(0x0) at 0x804b40
REFCNT = 1
FLAGS = ()
Elt "may" HASH = 0xf2290c53
SV = NULL(0x0) at 0x812420
REFCNT = 1
FLAGS = ()
An undef scalar takes as much memory as an integer scalar, so you might ask well just assign them all to 1 and avoid the trap of forgetting to check with exists.
my %is_month = map { $_ => 1 } qw(jan feb mar apr may jun jul aug sep oct nov dec);
print "It's a month" if $is_month{lc $mon});
A: The expression defined &DB::DB returns true if the program is running from within the debugger.
A: Interpolation of match regular expressions. A useful application of this is when matching on a blacklist. Without using interpolation it is written like so:
#detecting blacklist words in the current line
/foo|bar|baz/;
Can instead be written
@blacklistWords = ("foo", "bar", "baz");
$anyOfBlacklist = join "|", (@blacklistWords);
/$anyOfBlacklist/;
This is more verbose, but allows for population from a datafile. Also if the list is maintained in the source for whatever reason, it is easier to maintain the array then the RegExp.
A: Using hashes (where keys are unique) to obtain the unique elements of a list:
my %unique = map { $_ => 1 } @list;
my @unique = keys %unique;
A: Add one for the unpack() and pack() functions, which are great if you need to import and/or export data in a format which is used by other programs.
Of course these days most programs will allow you to export data in XML, and many commonly used proprietary document formats have associated Perl modules written for them. But this is one of those features that is incredibly useful when you need it, and pack()/unpack() are probably the reason that people have been able to write CPAN modules for so many proprietary data formats.
A: Next time you're at a geek party pull out this one-liner in a bash shell and the women will swarm you and your friends will worship you:
find . -name "*.txt"|xargs perl -pi -e 's/1:(\S+)/uc($1)/ge'
Process all *.txt files and do an in-place find and replace using perl's regex. This one converts text after a '1:' to upper case and removes the '1:'. Uses Perl's 'e' modifier to treat the second part of the find/replace regex as executable code. Instant one-line template system. Using xargs lets you process a huge number of files without running into bash's command line length limit.
A: @Corion - Bare URLs in Perl? Of course you can, even in interpolated strings. The only time it would matter is in a string that you were actually USING as a regular expression.
A: Showing progress in the script by printing on the same line:
$| = 1; # flush the buffer on the next output
for $i(1..100) {
print "Progress $i %\r"
}
A: One more...
Perl cache:
my $processed_input = $records || process_inputs($records_file);
On Elpeleg
Open Source, Perl CMS
http://www.web-app.net/
A: $0 is the name of the perl script being executed. It can be used to get the context from which a module is being run.
# MyUsefulRoutines.pl
sub doSomethingUseful {
my @args = @_;
# ...
}
if ($0 =~ /MyUsefulRoutines.pl/) {
# someone is running perl MyUsefulRoutines.pl [args] from the command line
&doSomethingUseful (@ARGV);
} else {
# someone is calling require "MyUsefulRoutines.pl" from another script
1;
}
This idiom is helpful for treating a standalone script with some useful subroutines into a library that can be imported into other scripts. Python has similar functionality with the object.__name__ == "__main__" idiom.
A: using bare blocks with redo or other control words to create custom looping constructs.
traverse a linked list of objects returning the first ->can('print') method:
sub get_printer {
my $self = shift;
{$self->can('print') or $self = $self->next and redo}
}
A: Perl is great as a flexible awk/sed.
For example lets use a simple replacement for ls | xargs stat, naively done like:
$ ls | perl -pe 'print "stat "' | sh
This doesn't work well when the input (filenames) have spaces or shell special characters like |$\. So single quotes are frequently required in the Perl output.
One complication with calling perl via the command line -ne is that the shell gets first nibble at your one-liner. This often leads to torturous escaping to satisfy it.
One 'hidden' feature that I use all the time is \x27 to include a single quote instead of trying to use shell escaping '\''
So:
$ ls | perl -nle 'chomp; print "stat '\''$_'\''"' | sh
can be more safely written:
$ ls | perl -pe 's/(.*)/stat \x27$1\x27/' | sh
That won't work with funny characters in the filenames, even quoted like that. But this will:
$ ls | perl -pe 's/\n/\0/' | xargs -0 stat
A: "now"
sub _now {
my ($now) = localtime() =~ /([:\d]{8})/;
return $now;
}
print _now(), "\n"; # 15:10:33
A: B::Deparse - Perl compiler backend to produce perl code. Not something you'd use in your daily Perl coding, but could be useful in special circumstances.
If you come across some piece of code that is obfuscated, or a complex expression, pass it through Deparse. Useful to figure out a JAPH or a Perl code that is golfed.
$ perl -e '$"=$,;*{;qq{@{[(A..Z)[qq[0020191411140003]=~m[..]g]]}}}=*_=sub{print/::(.*)/};$\=$/;q<Just another Perl Hacker>->();'
Just another Perl Hacker
$ perl -MO=Deparse -e '$"=$,;*{;qq{@{[(A..Z)[qq[0020191411140003]=~m[..]g]]}}}=*_=sub{print/::(.*)/};$\=$/;q<Just another Perl Hacker>->();'
$" = $,;
*{"@{[('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z')['0020191411140003' =~ /../g]];}";} = *_ = sub {
print /::(.*)/;
}
;
$\ = $/;
'Just another Perl Hacker'->();
-e syntax OK
A more useful example is to use deparse to find out the code behind a coderef, that you might have received from another module, or
use B::Deparse;
my $deparse = B::Deparse->new;
$code = $deparse->coderef2text($coderef);
print $code;
A: I like the way we can insert a element in any place in the array, such as
=> Insert $x in position $i in array @a
@a = ( 11, 22, 33, 44, 55, 66, 77 );
$x = 10;
$i = 3;
@a = ( @a[0..$i-1], $x, @a[$i..$#a] );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "143"
} |
Q: K & R Exercise: My Code Works, But Feels Stinky; Advice for Cleanup? I'm working on the K&R book. I've read farther ahead than I've done exercises, mostly for lack of time. I'm catching up, and have done almost all the exercises from chapter 1, which is the tutorial.
My issue was exercise 1-18. The exercise is to:
Write a program to remove trailing blanks and
tabs from line of input, and to delete entirely blank lines
My code (below) does that, and works. My problem with it is the trim method I implemented. It feels ... wrong ... somehow. Like if I saw similar code in C# in a code review, I'd probably go nuts. (C# being one of my specialties.)
Can anyone offer some advice on cleaning this up -- with the catch that said advice has to only use knowledge from Chapter 1 of K & R. (I know there are a zillion ways to clean this up using the full C library; we're just talking Chapter 1 and basic stdio.h here.) Also, when giving the advice, can you explain why it will help? (I am, after all, trying to learn! And who better to learn from than the experts here?)
#include <stdio.h>
#define MAXLINE 1000
int getline(char line[], int max);
void trim(char line[], char ret[]);
int main()
{
char line[MAXLINE];
char out[MAXLINE];
int length;
while ((length = getline(line, MAXLINE)) > 0)
{
trim(line, out);
printf("%s", out);
}
return 0;
}
int getline(char line[], int max)
{
int c, i;
for (i = 0; i < max - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
line[i] = c;
if (c == '\n')
{
line[i] = c;
++i;
}
line[i] = '\0';
return i;
}
void trim(char line[], char ret[])
{
int i = 0;
while ((ret[i] = line[i]) != '\0')
++i;
if (i == 1)
{
// Special case to remove entirely blank line
ret[0] = '\0';
return;
}
for ( ; i >= 0; --i)
{
if (ret[i] == ' ' || ret[i] == '\t')
ret[i] = '\0';
else if (ret[i] != '\0' && ret[i] != '\r' && ret[i] != '\n')
break;
}
for (i = 0; i < MAXLINE; ++i)
{
if (ret[i] == '\n')
{
break;
}
else if (ret[i] == '\0')
{
ret[i] = '\n';
ret[i + 1] = '\0';
break;
}
}
}
EDIT: I appreciate all the helpful tips I'm seeing here. I would like to remind folks that I'm still a n00b with C, and specifically haven't gotten up to pointers yet. (Remember the bit about Ch.1 of K&R -- Ch.1 doesn't do pointers.) I "kinda" get some of those solutions, but they're still a touch advanced for where I'm at ...
And most of what I'm looking for is the trim method itself -- specifically the fact that I'm looping through 3 times (which feels so dirty). I feel like if I were just a touch more clever (even without the advanced knowledge of C), this could have been cleaner.
A: If you are sticking with chapter 1, that looks pretty good to me. Here's what I would recommend from a code-review standpoint:
When checking equality in C, always put the constant first
if (1 == myvar)
That way you will never accidentally do something like this:
if (myvar = 1)
You can't get away with that in C#, but it compiles fine in C and can be a real devil to debug.
A: There is no reason to have two buffers, you can trim the input line in place
int trim(char line[])
{
int len = 0;
for (len = 0; line[len] != 0; ++len)
;
while (len > 0 &&
line[len-1] == ' ' && line[len-1] == '\t' && line[len-1] == '\n')
line[--len] = 0;
return len;
}
By returning the line length, you can eliminate blank lines by testing for non-zero length lines
if (trim(line) != 0)
printf("%s\n", line);
EDIT: You can make the while loop even simpler, assuming ASCII encoding.
while (len > 0 && line[len-1] <= ' ')
line[--len] = 0;
A: Personally for while constructs:
I prefer the following:
while( (ret[i] = line[i]) )
i++;
to:
while ((ret[i] = line[i]) != '\0')
++i;
They both check against != 0 but the first looks a little cleaner. If the char is anything other thah 0, then the loop body will execute else it will break out of the loop.
Also for 'for' statements, whilst being syntatically valid, I find that the following:
for ( ; i >= 0; --i)
just looks 'odd' to me and indeed is a potential nightmare solution for potential bugs. If I was reviewing this code, it would be like a glowing red warning like. Typically you want to use for loops for iterating a known number of times, otherwise cosider a while loop. (as always there are exceptions to the rule but Ive found that this generally holds true). The above for statement could become:
while (i)
{
if (ret[i] == ' ' || ret[i] == '\t')
{
ret[i--] = '\0';
}
else if (ret[i] != '\0' && ret[i] != '\r' && ret[i] != '\n')
{
break;
}
}
A: trim() is too big.
What I think you need is a strlen-ish function (go ahead and write it int stringlength(const char *s)).
Then you need a function called int scanback(const char *s, const char *matches, int start) which starts at start, goes down to z as long as the character being scanned at s id contained in matches, return the last index where a match is found.
Then you need a function called int scanfront(const char *s, const char *matches) which starts at 0 and scans forward as long as the character being scanned at s is contained in matches, returning the last index where a match is found.
Then you need a function called int charinstring(char c, const char *s) which returns non-zero if c is contained in s, 0 otherwise.
You should be able to write trim in terms of these.
A: First of all:
int main(void)
You know the parameters to main(). They're nothing. (Or argc&argv, but I don't think that's Chapter 1 material.)
Stylewise, you might want to try K&R-style brackets. They're much easier on the vertical space:
void trim(char line[], char ret[])
{
int i = 0;
while ((ret[i] = line[i]) != '\0')
++i;
if (i == 1) { // Special case to remove entirely blank line
ret[0] = '\0';
return;
}
for (; i>=0; --i) { //continue backwards from the end of the line
if ((ret[i] == ' ') || (ret[i] == '\t')) //remove trailing whitespace
ret[i] = '\0';
else if ((ret[i] != '\0') && (ret[i] != '\r') && (ret[i] != '\n')) //...until we hit a word character
break;
}
for (i=0; i<MAXLINE-1; ++i) { //-1 because we might need to add a character to the line
if (ret[i] == '\n') //break on newline
break;
if (ret[i] == '\0') { //line doesn't have a \n -- add it
ret[i] = '\n';
ret[i+1] = '\0';
break;
}
}
}
(Also added comments and fixed one bug.)
A big issue is the usage of the MAXLINE constant -- main() exclusively uses it for the line and out variables; trim(), which is only working on them doesn't need to use the constant. You should pass the size(s) as a parameter just like you did in getline().
A: Here's my stab at the exercise without knowing what is in Chapter 1 or K & R. I assume pointers?
#include "stdio.h"
size_t StrLen(const char* s)
{
// this will crash if you pass NULL
size_t l = 0;
const char* p = s;
while(*p)
{
l++;
++p;
}
return l;
}
const char* Trim(char* s)
{
size_t l = StrLen(s);
if(l < 1)
return 0;
char* end = s + l -1;
while(s < end && (*end == ' ' || *end == '\t'))
{
*end = 0;
--end;
}
return s;
}
int Getline(char* out, size_t max)
{
size_t l = 0;
char c;
while(c = getchar())
{
++l;
if(c == EOF) return 0;
if(c == '\n') break;
if(l < max-1)
{
out[l-1] = c;
out[l] = 0;
}
}
return l;
}
#define MAXLINE 1024
int main (int argc, char * const argv[])
{
char line[MAXLINE];
while (Getline(line, MAXLINE) > 0)
{
const char* trimmed = Trim(line);
if(trimmed)
printf("|%s|\n", trimmed);
line[0] = 0;
}
return 0;
}
A: Personally I'd put code like this:
ret[i] != '\0' && ret[i] != '\r' && ret[i] != '\n'
into a separate function (or even a define macro)
A: *
*trim should indeed use 1 buffer only (as @Ferruccio says).
*trim needs to be broken up, as @plinth says
*trim needs not return any value (if you want to check for empty string, test line[0] == 0)
*for extra C flavor, use pointers rather than indexes
-go to end of line (terminating 0;
-while not at the start of line and current character is space, replace it with 0.
-back off one char
char *findEndOfString(char *string) {
while (*string) ++string;
return string; // string is now pointing to the terminating 0
}
void trim(char *line) {
char *end = findEndOfString(line);
// note that we start at the first real character, not at terminating 0
for (end = end-1; end >= line; end--) {
if (isWhitespace(*end)) *end = 0;
else return;
}
}
A: Another example of doing the same thing. Did some minor violation by using C99-specific stuff. that will not be found in K&R. also used the assert() function which is part of the starndard library, but is probably not covered in chapter one of K&R.
#include <stdbool.h> /* needed when using bool, false and true. C99 specific. */
#include <assert.h> /* needed for calling assert() */
typedef enum {
TAB = '\t',
BLANK = ' '
} WhiteSpace_e;
typedef enum {
ENDOFLINE = '\n',
ENDOFSTRING = '\0'
} EndofLine_e;
bool isWhiteSpace(
char character
) {
if ( (BLANK == character) || (TAB == character ) ) {
return true;
} else {
return false;
}
}
bool isEndOfLine(
char character
) {
if ( (ENDOFLINE == character) || (ENDOFSTRING == character ) ) {
return true;
} else {
return false;
}
}
/* remove blanks and tabs (i.e. whitespace) from line-string */
void removeWhiteSpace(
char string[]
) {
int i;
int indexOutput;
/* copy all non-whitespace character in sequential order from the first to the last.
whitespace characters are not copied */
i = 0;
indexOutput = 0;
while ( false == isEndOfLine( string[i] ) ) {
if ( false == isWhiteSpace( string[i] ) ) {
assert ( indexOutput <= i );
string[ indexOutput ] = string[ i ];
indexOutput++;
}
i++; /* proceed to next character in the input string */
}
assert( isEndOfLine( string[ i ] ) );
string[ indexOutput ] = ENDOFSTRING;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Parenthesis surrounding return values in C Quite often in ANSI C code I can see parenthesis sorrounding a single return value.
Like this:-
int foo(int x) {
if (x)
return (-1);
else
return (0);
}
Why use () around the return value in those cases? Any ideas? I can see no reason for that.
A: When returning -1 as in your excample, I think it's more readable with the parenthesis because the minus is more visible:
return 1
or
return -1
or
return (-1)
A: There really isn't a reason...it's just old convention.
To save space, programmers would often do the final math in the return line instead of on it's own line and the parens ensure are mostly there to make it easier to see that it is a single statement that is returned, like this:
return (x+i*2);
instead of
int y = x+i*2;
return y;
The parenthesis became a habit and it stuck.
A: A practical, but unlikely, motive is if you put parenthesis around the value, you can define return as a macro, and then insert some logging code to watch all your returns.
A: Perhaps it's custom--after all, the folks who brought us Unix and C came from the Multics project. Multics was written in PL/I, and in PL/I the parentheses are mandatory.
A: In the original C specification, parentheses were required around the return value. While modern C compilers and the ANSI C standard do not require them, the presence of parentheses does not affect the return value, and programmers sometimes still include them out of habit, unfamiliarity with the standards, for consistency with a stylistic convention that requires them, or possibly for backward compatibility.
I should add, for people that are thinking about C++: This question is about C and C is not C++; these are two different languages with different standards, capabilities, levels of difficulty, and different styles of usage that emerge -- whatever they have in common, it is wise to treat them as two totally separate things. For a similar question that covers C++, see Are parentheses around the result significant in a return statement?.
A: I've worked with at least one programmer who thought return was some special sort of function call, and was suprised when he saw that my code complied without the parens.
A: My personal style is to use parentheses if there is a complex expression; e.g.,
return (a + b);
but to not use them if the expression is a simple term
return a;
I can't say why I do it that way; just something I picked up long ago.
By the way, I think that making it look like a function call, like this:
return(a); // ugh
is incredibly ugly and just wrong.
A: As often the case when using parenthesis, I think that's just for readability (e.g., Ruby supports method calls w/o parenthesis enclosing the arguments but recent books and articles advise otherwise).
A: There are a few reasons:
*
*if/while/for/etc. are all control keywords which must have parens. So it often seems natural to always put them on return too.
*sizeof is the only other keyword that can either have them or not, except that in some cases you must use parens. So it's easier to get into the habit of always using parens. for sizeof, which implies a logic of: if you can, always do.
*case/goto are the only keywords where you never use parens. ... and people tend to think of those as special cases (and like them both to stand out from other control keywords, esp. goto).
A: Using parentheses in a return statement shows a deficient grasp of C/C++ syntax. It's as simple as that. But it's not as bad as putting everything in curly braces:
int foo(int x) {
if (x) {
return (-1);
}
else {
return (0);
}
}
So many programmers do this. If one of you reads this, perhaps you might like to explain.
A: The Parenthesis in a return statement indicate to the compiler that you intend for this value to be returned on the stack instead of in memory.
In the old days this was rigorously enforced(typically), but today most compilers only take it as a hint.
This is something I do frequently, since an error could corrupt anything being returned via a memory reference, but typically wont effect a variable being returned on the stack.
Using the stack for transient variables also cuts down on memory usage and typically makes the function call/return quicker because that's what the stack is designed for, transient data/variables.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "85"
} |
Q: WPF Bind to a Collection of objects, sorted by IDs stored in order in another Collection in C# For those of you that like puzzles: I had this problem recently and am sure there must be a nicer solution.
Consider :
*
*an ObservableCollection of Foo objects called foos.
*Foo contains a string ID field
*I have no control over foos
*foos will be changing
Then:
*
*I have another collection called sortLikeThis
*sortListThis contains strings
*The strings are the IDs in the order in which the foos are to be shown
Plus:
*
*There may be objects in foos with an ID that is not in sortLikeThis. These need to go at the end.
*Likewise, there may be strings in sortLikeThis that do not appear in foos.
Is there a nice way to bind to and show in wpf the Foo objects in foos in the order defined by IDs in sortLikeThis ?
A: Sounds like a job for a custom observable collection that implements IEnumerable and has a pretty little enumerator (aaah, yield) that handles the logic of the custom sort.
public class SortFoosLolThx : ObservableCollection<Foo> {
public IList<string> SortList {/*...*/}
/*...*/
public override IEnumerator<Foo> GetEnumerator() { /*...*/ yield foo; /*...*/}
}
A: Have you looked at Bindable LINQ? It allows you to define LINQ queries on top of an observable collection, and makes sure that the LINQ query is performed each time the underlying collection is changed. In your case, you could add an Orderby query on top of the collection.
You can pass the Orderby method a delegate to do the comparison. To set this up you would
*
*Prepare by creating a Dictionary mapping each id in sortLikeThis to an ascending int
*Within the comparison delegate, lookup in the dictionary the ids of the two foos that are passed for comparison. Do the appropriate thing if an item cannot be found.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to evict file from system cache on Linux? When running performance tests file system cache hit or miss can significantly influence test results. Therefore generally before running such tests used files are evicted from system cache. How to do that on Linux?
Clarification: If possible, the solution should not require root privileges.
A: There is a command line utility by Eric Wong that makes it easy to invoke posix_fadvise:
http://git.bogomips.org/cgit/pcu.git/tree/README
It's then as simple as
$ pcu-fadvise -a dontneed filename-to-evict
A: As a superuser you can do the following:
To free pagecache:
*
*echo 1 > /proc/sys/vm/drop_caches
To free dentries and inodes:
*
*echo 2 > /proc/sys/vm/drop_caches
To free pagecache, dentries and inodes:
*
*echo 3 > /proc/sys/vm/drop_caches
This operation will not "lose" any data (caches are written out to disk before their data is dropped), however, to really make sure all cache is cleaned, you should sync first. E.g. all caches should be cleared if you run
sync; echo 3 > /proc/sys/vm/drop_caches
As I said, only a superuser (root) may do so.
A: Ha, I have the answer:
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char *argv[]) {
int fd;
fd = open(argv[1], O_RDONLY);
fdatasync(fd);
posix_fadvise(fd, 0,0,POSIX_FADV_DONTNEED);
close(fd);
return 0;
}
This is from http://insights.oetiker.ch/linux/fadvise.html
A: Regarding use of O_DIRECT: that would perturb the results in another way. The kernel will attempt to DMA the filesystem data directly into your read() buffer, so it can be handed up to your application without any additional copy being done. Without O_DIRECT the kernel DMAs the file data into the page cache, and copies it from the page cache to your read() buffer.
This is fine if your app is really going to use O_DIRECT in production. If you run performance tests with O_DIRECT and then remove O_DIRECT for production, your performance test will be unrealistic.
A: If you can put the test data in a separate filesystem then mounting the filesystem afresh for the test will give you empty caches.
If you list the test fileystem in /etc/fstab with the "user" option then you can mount it for the test without being superuser
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How do you track the time of replicated rows for Subscribers in SQL Server 2005? The basic problem is like this:
A subscriber has successfully replicated a row from the publisher, using transactional replication. Now, how do we keep track the time of this row being last successfully replicated?
A friend has suggested the following solution, which he used for his SQL Server 2000:
1) Add a datetime column.
2) Change the replication stored procedure to update the datetime column (!).
The step #2 sets off all sorts of warning bells within me, so I'm asking if there are better solutions for SQL Server 2005 in this situation, before I even go into detail with his solution.
A: I had this exact problem a few weeks ago trying to find records that have changed recently.
Create a new column and set the data type to TIMESTAMP. SS2005 automatically updates this type when the row is updated. The only problem is that this 'timestamp' has nothing at all to do with a date or time, it is just a number that reflects the last successful update of that row (any update, not just via replication). If that is all you need, then you should be fine.
If you need the last replication update, things might get a bit tricky, and you need get your hands dirty with triggers and stored procs.
http://www.sqlteam.com/article/timestamps-vs-datetime-data-types
Hope that helps~
A: I'd do exactly what your friend suggested. That way, only calls to the replication procedure would update the timestamp.
The problem with this approach is that you need a write lock, but I don' see any other practical way.
You could otherwise use a trigger that fires when you fetch the row (don't quote me on that, I very seldom used triggers), but that doesn't seem right (you might end with false positives)
A: If you are working with transactional replication, why don't you just record time of primary data update and consider it was replicated to the other databases on next replication job?
A: @Philippe: The main problem with that approach is the replication may take awhile to reach some of the more remote database, due to bad network connection. So, the update time of the main record will not reflect the time of the record actually replicated in the remote database.
Anyway, I have tested out my friend's method, and it worked fine for our requirement.
If anyone wants to do this as well, here's an important note: be careful about initializing the subscription and future schema changes.
For my case, we decided to initialize the snapshot manually in order to keep the added datetime column in the Subscriber database. Another possible approach might be to allow initialization, but modify the existing stored procedures to ignore replicating the added datetime column.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Can I run ASP and ASP.NET pages in the same web app simultaneously? In the process of updating a web app from ASP to ASP.NET, I want to insert one of the new files into the old app to test something - is this an offence against reason?
A: Yes but they will not share the session memory. I have an old ASP website and have replaced the main page with a asp.net page with a masterpage/content page setup. I use asp.net to send emails instead of the old asp/com components.
One work-a-round the session sharing issue is to create a bridge page that does an exchange of session data using form post or querystring. http://msdn.microsoft.com/en-us/library/aa479313.aspx
Also if you just add an asp page in your existing asp.net application it will not run. You'll need to set up the entire app in IIS so that both the ASP and ASP.NET pages will run like it will on the server.
A: ASP and ASP.NET work fine side by side. I'm surprised by how important people seem to thing session state is. Most new ASP.NET I've grafted into an existing ASP site has no need of any session state stored by the ASP app. Having said that I avoid using session state for most part anyway in either ASP or ASP.NET.
The only tricky thing is to find a common logon mechanism, I do that using a custom session cookie and a database entry.
A: Yes.
It's just not a very good way of doing things. But it will work quite well until you'll try to share the session states and so on. Then you'll have to do some extra work.
A: No, you can't put an ASP.NET file into a classic ASP application - it will not run.
You can go the other way, and put a classic ASP file into an ASP.NET application.
A: You could have your ASP application post to a ASP.NET page.
A: The short answer is 'Yes', but it's a very painful experience. The ASP pages and the ASP.Net pages will not share a common session, and hooking the two up is not as easy as it could be.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Determining the height of an HTML table that is dynamically filled I would like to draw a diagram in HTML. The positioning structure looks like this:
<div id='hostDiv'>
<div id='backgroundDiv'>
... drawing the background ...
</div>
<div id='foregroundDiv' style='position: absolute;'>
... drawing the foreground ...
</div>
</div>
The foreground contains a Table element that is dynamically populated with text, hence the row heights might alter depending on the amount of text going into a cell.
How can I predict the final height of the Table element in the foregroun? I need this information to set the correct height of the background. Is there a way to pre-render the Table from Javascript and read out its height? Or some other trick?
PS. The size of the hostDiv may vary as the browser resizes.
A: There isn't any way to predict the height without actually rendering it in the target browser.
Once you do that, you can use (for example) jQuery to get the height of the element:
var height = $('#myTable').height();
A: While using jquery, you can actually find out the height of the table before it is rendered to the user. Use a construct like this (liberally borrowing code from the person above me):
$(document).ready(function () { var height = $('#myTable').height(); });
A: You can't predict the overall height of the element until after load as the browser will render and position elements depending on the adjacent elements and the size of the viewing window.
That said, you can use most any js library to find what you are looking for. In Prototype, it's:
$('navlist-main').offsetHeight
This will recursively add up the rendered height (not just the styled height) for each child element and any associated margin and padding and return an accurate figure for element height.
A: If you simply don't want to display the table before resizing the foregorund div:
Set style.visibility="hidden" on the table. Unlike display:none, this does not remove the div from the document flow and so the foreground div will still be properly sized (the table will simply not be visible).
Of course, if acceptable, you could move foregroundDiv into backgroundDiv and remove absolute positioning. backgroundDiv will then automatically resize to contain foregroundDiv (and the table).
A: I think you can use one of DOM attributes: clientHeight, offsetHeight, and scrollHeight as defined in w3 here
This is the usage of clientHeight:
document.getElementById("#Table").clientHeight;
document.getElementById("#Table").clientWidth;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Unequal Html textbox and dropdown width with XHTML 1.0 strict I'm trying to have two inputs (one textbox, one drop down) to have the same width.
You can set the width through css, but for some reason, the select box is always a few pixels smaller.
It seems this only happens with the xhtml 1.0 strict doctype
Any suggestions/ideas about the reason/work around?
Having the following HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<style>
.searchInput{
width: 1000px;
overflow: hidden;
}
</style>
</head>
<body>
<form action="theAction" method="post" class="searchForm" >
<fieldset>
<legend>Search</legend>
<p>
<!--<label for="name">Product name</label>-->
<input class="searchInput" type="text" name="name" id="name" value="" />
</p>
<p>
<!--<label for="ml2">Product Group</label>-->
<select class="searchInput" name="ml2" id="ml2">
<option value="158">INDUSTRIAL PRIMERS/FILLERS</option>
<option value="168">CV CLEAR COATS</option>
<option value="171">CV PRIMERS/FILLERS</option>
<option value="" selected="selected">All</option>
</select>
</p>
<input type="submit" class="search" value="Show" name="Show" id="Show" />
<input type="reset" value="Reset" name="reset" id="reset" class="reset"/>
</fieldset>
</form>
</body
</html>
A: You could try resetting the margins, padding and borders to see if that helps:
.searchInput {
margin:0;
padding:0;
border-width:1px;
width:1000px;
}
A: This seems to have something to do with the box model. More specifically, it seems to have something to do with the border. If you're using firebug, check out the layout tab...
The select shows a 2px border, 0 padding and a width of 996px and height of 18px.
The input shows a 2px border, 1px 0 padding and a width of 1000px and height of 16px.
If you set the border to zero (and give them a background color), you can see they'll be the same size, which shows them both with a width of 1000px in the layout tab.
.searchInput{
width: 1000px;
border: 0;
background-color: #CCC;
overflow: hidden;
}
A: You're right, there is a 4px difference. The input is coming out at 103px wide, while the select is coming at 99px wide. I have no idea why this occurs, but you could work around it like this:
<style type="text/css">
.searchInput {
overflow: hidden;
}
select.searchInput {
width: 101px;
}
input.searchInput {
width: 97px;
}
</style>
It's really quite silly, and I would be really interested if someone knew why this was happening, and a way to prevent it.
The work-around works on Webkit and Firefox. The pixel difference is different in IE.
The funny thing is, they would normally be the same size using an HTML doctype.
A: I had this issue in Firefox 2, but it seems to be resolved in Firefox 3 and IE7.
My fix was to add the missing pixels to a seperate width for select.
A: Browsers tend to do their own thing with regard to form elements and styles. The CSS standard doesn’t specify how browsers should display form widgets, nor which CSS properties it should let users change. It varies between browsers, and between different form widgets in the same browser.
You could try adjusting the padding and borders to help different form widgets match up.
A: @Paul D. Waite - Got to agree with you there
This isn't what CSS is meant for. Look at input boxes in Safari, for example. They're elliptical. CSS properties just don't apply in some cases.
Pad around your elements to line them up.
A: It is ndeed due to the Box Model that #IE supports when it finds the "strict" in the doctype. If u change it to "traditional" doctype everything behaves normally...but not normally as per CSS standard.
CSS Box Model states that in the width/height of an element the padding and border withs are not included. So they are additional on top of the mentioned width of the element, and thus are bigger than desired actually.
A: It seems only with the doctype added this happens.
Corrected the example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Corner desks vs straight desks The company I work for are currently undergoing a site wide renovation and I'm involved in the 'consultation' on what the R&D work spaces are going to be like.
There is no scope for individual private offices - so lets not start on that topic.
One big requirement is that the office layout can be flexible (i.e. team areas can be created and changed as necessary).
In order to allow this one of the most significant changes is that we will be losing our corner facing desks. The rationale being that since no one has big CRT monitors any more we don't need to waste the space in the corner.
People are reluctant about this change but I'm not sure if thats just because people don't like change or if there is a real reason behind it. I've moved my setup out of the corner onto a straight edge to see how much impact it has on myself.
We've also been told that this is now happening across the industry... that people are being moved out of their corners into more bench-like arrangement.
So my the question is twofold:
*
*Is it really important to have a corner?
*Is there really an industry-wide move 'out of the corners'?
I know there are a lot of questions already on here about conditions for developers but nothing about this specific question I don't think.
A: Straight desks for pair programming will work great with this type of chair:
http://www.cenqua.com/pairon/
A: If you're gonna be doing any pair-programming then I would recommend you avoid corner desks as they hamper the ability for 2 people to work side by side.
What about curved desks? A team of four with curved desks (curving away from you, not around you) would form a circular formation ideal for group discussions and pair programming.
A: My personal preference is corner desks, they have better support for your arms while typing or moving your mouse. You can reach a free space for notes taking in the table without moving the chair and also can talk to people over the desk without having to standup or lean to the side of the monitor.
About pair-programming you can always move your monitor a little to your side (as you would do in a straight table) and have the same facility as any other table.
You can also grow your belly and it will fit perfectly in the inner round part of the table without keeping you far away from computer ;)
A: I think a bigger question is how it will be perceived by your coworkers. If they feel that they're losing prestige or being treated like automatons because they're losing corner desks, that could be more important than any actual difference in productivity. (Which I feel would be tiny if there even is one, having worked at both.)
A: I have a corner desk, and whie my overal working area is fairly small it's useful. I can image a corner desk with 'wings' would be better as this would give you a greater working area.
A: I currently work on an L shaped desk, with the corner as my primary work area for my computers. The short part is where my phone and notepads are. The longer part is for my books and things that I must read or review. I find it useful to have the L desk, but we don't use the cubes (or even offices) for intense team meetings - for those, we go to the conference rooms with our laptops (we don't use desktops here).
A: I like my corner. It gives me a familiar sense of security. So far I've evolved from standing in a corner in school to sitting in a a corner at work. I'm waiting anxiously for the next phase, laying in a corner at home :)
To be a bit more serious: I like the L-shaped desk wether in corner or not because the both sides of the desk ar "closer" and I can easily change focus by turning the chair. Beeing in the corner has an advantage in an open office with less distractive codemonkeys in sight...
A: I may be a bit strange, but I actually prefer using a straight, rectangular, desk. The simple reason for this is that I like to have as little space as possible between the edge og my keyboard (or laptop) and the edge of the desk. I shift things around a bit from time to time—for variation;—but my keyboard is rarely more than 5-10cm away from the edge of the desk. Because of this, cornered desks or desks without stragiht edges just annoy me.
My ideal work desk is a 160x80cm wooden "sheet" with four simple, adjustable, legs and no "fancies"—as they just tend to get in the way (if you have ever crashed your legs into one of those metal bars crossing under your desk for "stabilization", you know what I am talking about).
If you need more space, you can always combine two desks to make a nice large surface you can easily "slide" along without fear of crashing into any corners or edges "sticking out". Also, as others have mentioned, straight desks are much better for pair programming or any other form of group activity involving more than one person sitting in front of the desk/monitor.
A: I see that lot's of people have already mentioned it, but as Joel Spolsky says in his blog entry about the new Fog Creek Offices , L-Shaped desks aren't good for Pair Programming:
Pair Programming. When you make typical L-shaped desks many developers set themselves up in the corner. When they need to collaborate temporarily, or pair program, or even just show something to someone on their screen, the second person has to either lean all the way across the desk or look over the first person's shoulder. To avoid this we designed all the desks to be long and straight so that wherever a software developer sits, there's always room for another person to pull up a chair and sit next to them.
A: An island of four desks grouped together is my preference - perfect for four people teams. They are corner desks, but not used in a corner. They are also oblong, making it possible to pair-program.
A: I have an L-shaped corner desk. As mentioned by others, it makes things slightly tricky if pair programming, but even when I'm by myself I find it a little subconsciously taxing.
With screens oriented around one of the straight bits, sitting with one elbow on the "L" section, with the other floating in free space, feels "unbalanced"; with screens in the corner, there's no hope of pairing whatsoever and I feel wedged into my hideyhole.
All things considered, I'd much rather have a straight desk.
A: I am currently working at a straight desk. However i much prefer the corner desks. With the straight desk it seems like I have much less desk real estate to put papers that are easily reachable. With a L desk I have much more reachable area to put things.
A: All of our cube/offices have desk lining 2 adjacent walls, so there is always a corner that can be used if a person so desires. That said however, I can't say I've ever seen someone here with their setup in the corner. I personally think it's way more comfortable not in a corner.
A: I have a corner desk, but the actual front of it is curved, so it's like a hybrid of straight and corner.
A: Our shop doesn't use desks per se. We have these industrial work tables with heavy duty racks overhead where the boxes can sit, providing lots of desk space - the only thing on my desk are four flat screen monitors, a couple of keyboards and mice. I like a straight desk if I have my own office (which I do) but when I've worked in a large room with multiple folks, I actually prefer the corner style or cube so there are a few less distractions.
A: I would take a corner desk over straight any day. I deal with a lot of tangible items on my desk (folders, time log, calculator, coffee, etc) and I don't know where I would put it all, within reach, without a corner desk.
A: The overall floorplan determines what works best for people.
My previous employer used cubes with wraparound desks that can be used either corner facing or straight. Most used as corner facing for extra legroom.
I agree with Sam Wessel, the pair programming concept would work best with straight desks to quickly share workspace and view each other's monitors.
I've also spent some time working in the German branch of my previous employer and their model is to separate the floor into rooms with high partition walls and stick 4 desks in the middle so that everyone faces each other, instead of away. The high partition walls blocked idle conversations but you can still shout to neighbors if needed. This allows you to develop a close work group relationship you wouldn't have otherwise. I liked this layout.
My current employer uses nothing but desks lined up against the walls or half-height partitions. They believe in the clean desk policy and minimal storage. Forget your coding book collection or office decorations, privacy, etc. I end up whispering to my wife on the phone because everyone hears you. I'm not a fan. They can squeeze us together like sardines to reduce office space footprint. Because of growth, they're now pushing people's desks into conference and storage rooms. Pretty soon I expect to be relocated to the basement with no stapler.
A: I used to have a corner desk, but recently, I moved to a straight desk (it was my decision). Wrong decision. I have 2 24in. wide-screen monitors hooked to my desktop, plus my laptop, which is a 19in wide-screen. I use a single mouse and keyboard through Synergy. There is no good way to place the monitors and the laptop in a way that you can face all the screens straight. Facing a corner and a keyboar tray, you can place your-self around so you can look at each of the screens straight, or with minimal turning of your head.
I'm really considering swithching.
A: The corner desk with it's ability to support your arms while typing and using a mouse are incredibly beneficial for your health (I guess)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: What are .git/info/grafts for? I am trying to figure out what is the 'grafts' in the Git.
For example, in one of the latest comments here, Tobu suppose to use git-filter-branch and .git/info/grafts to join two repositories.
But I don't understand why I need these grafts? It seems, that all work without last two commands.
A: When working with git-svn:
git grafts are very useful to import a Git tree into a Subversion repository.
E.g. I created a local Git repository as a start. After working on it several days, creating lots of commits, I had to publish it into the central Subversion repository and I didn't want to lose the history.
I found the following How-to article:
http://eikke.com/importing-a-git-tree-into-a-subversion-repository/
A: From Git Wiki:
Graft points or grafts enable two
otherwise different lines of
development to be joined together. It
works by letting users record fake
ancestry information for commits. This
way you can make git pretend the set
of parents a commit has is different
from what was recorded when the commit
was created.
Reasons for Using Grafts
Grafts can be useful when moving
development to git, since it allows
you to make cloning of the old history
imported from another SCM optional.
This keeps the initial clone for users
who just wants to follow the latest
version down while developers can have
the full development history
available.
When Linus started using git for
maintaining his kernel tree there
didn't exist any tools to convert the
old kernel history. Later, when the
old kernel history was imported into
git from the bkcvs gateway, grafts was
created as a method for making it
possible to tie the two different
repositories together.
A: The grafts approach mentioned by Chris Johnsen for joining two repositories is no longer fully valid (with grafts alone).
With Git 2.18 (Q2 2018), the functionality of "$GIT_DIR/info/grafts" has been superseded by the "refs/replace/" mechanism (for some time now).
The internal code had support for it in many places, which has been cleaned up
in order to drop support of the "grafts" mechanism.
See commit a3694d9, commit f42fa47, commit 8d0d81a, commit e2d65c1, commit f9f99b3, commit 0115e03, commit fb40429, commit 041c98e, commit e24e871 (28 Apr 2018), and commit d398f2e, commit fef461e, commit c5aa6db (25 Apr 2018) by Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 352cf6c, 23 May 2018)
So instead of
echo "$commit-id $graft-id" >> .git/info/grafts
You now do:
git replace --graft $commit-id $graft-id
git filter-branch $graft-id..HEAD
Deprecate support for .git/info/grafts
The grafts feature was a convenient way to "stitch together" ancient
history to the fresh start of linux.git.
Its implementation is, however, not up to Git's standards, as there are
too many ways where it can lead to surprising and unwelcome behavior.
For example, when pushing from a repository with active grafts, it is
possible to miss commits that have been "grafted out", resulting in a
broken state on the other side.
Also, the grafts feature is limited to "rewriting" commits' list of
parents, it cannot replace anything else.
The much younger feature implemented as git replace set out to remedy
those limitations and dangerous bugs.
Seeing as git replace is pretty mature by now (since 4228e8b
(replace: add --graft option, 2014-07-19, Git 2.1.0) it can perform the graft
file's duties), it is time to deprecate support for the graft file, and
to retire it eventually.
Now (again, Git 2.18, Q2 2018), you have:
replace: add --graft option
The usage string for this option is:
git replace [-f] --graft <commit> [<parent>...]
First we create a new commit that is the same as <commit>
except that its parents are [<parents>...]
Then we create a replace ref that replace with
the commit we just created.
With this new option, it should be straightforward to
convert grafts to replace refs.
And before Git 2.20 (Q4 2018), the recently introduced commit-graph auxiliary data is incompatible with mechanisms such as replace & grafts that "breaks" immutable nature of the object reference relationship.
Disable optimizations based on its use (and updating existing commit-graph) when these incompatible features are in use in the repository.
See commit 829a321, commit 5cef295, commit 20fd6d5, commit d653824, commit b775896, commit 950c62b (20 Aug 2018) by Derrick Stolee (derrickstolee).
See commit 212e0f7, commit 4a6067c (20 Aug 2018) by Stefan Beller (stefanbeller).
(Merged by Junio C Hamano -- gitster -- in commit 6d8f8eb, 16 Oct 2018)
With Git 2.24 (Q4 2019), the "upload-pack" (the counterpart of "git fetch"), which needs to disable commit-graph when responding to a shallow clone/fetch request, does not panic anymore.
See commit 6abada1, commit fbab552 (12 Sep 2019) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 098e8c6, 07 Oct 2019)
## upload-pack: disable commit graph more gently for shallow traversal
When the client has asked for certain shallow options like "deepen-since", we do a custom rev-list walk that pretends to be shallow.
Before doing so, we have to disable the commit-graph, since it is not compatible with the shallow view of the repository. That's handled by 829a321 (commit-graph: close_commit_graph before shallow walk, 2018-08-20, Git v2.19.2).
That commit literally closes and frees our repo->objects->commit_graph struct.
That creates an interesting problem for commits that have already been
parsed using the commit graph.
Their commit->object.parsed flag is set, their commit->graph_pos is set, but their commit->maybe_tree may still be NULL.
When somebody later calls repo_get_commit_tree(), we see that we haven't loaded the tree oid yet and try to get it from the commit graph.
But since it has been freed, we segfault!
So the root of the issue is a data dependency between the commit's
lazy-load of the tree oid and the fact that the commit graph can go
away mid-process.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "53"
} |
Q: Howto deactivate caching inside a jsp page I understand there is a HTTP response header directive to disable page caching:
Cache-Control:no-cache
I can modify the header by "hand":
<%response.addHeader("Cache-Control","no-cache");%>
But is there a "nice" way to make the JSP interpreter return this header line in the server response?
(I checked the <%@page ...%> directive. It seems there is nothing like that.)
A: Also add
response.addHeader("Expires","-1");
response.addHeader("Pragma","no-cache");
to your headers and give that a shot.
A: If you were using a servlet, then I believe what you posted in the question would be the correct approach. I'm not aware of any way to do this in the JSP.
A: <?xml version="1.0"?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
<jsp:scriptlet><![CDATA[
response.setHeader("Cache-Control", "no-cache");
]]></jsp:scriptlet>
</jsp:root>
You must put the response header inside <jsp:root />. Also, I would instead recommend it sending this from your servlet instead of JSP page.
A: IIRC some browsers may ignore the cache control settings in some contexts. The 'safe' workaround for this was to always get a page (even an AJAX chunk) with a new query string variable (like the time.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How slow are .NET exceptions? I don't want a discussion about when to and not to throw exceptions. I wish to resolve a simple issue. 99% of the time the argument for not throwing exceptions revolves around them being slow while the other side claims (with benchmark test) that the speed is not the issue. I've read numerous blogs, articles, and posts pertaining one side or the other. So which is it?
Some links from the answers: Skeet, Mariani, Brumme.
A: I have no idea what people are talking about when they say they are slow only if they are thrown.
EDIT: If Exceptions aren't thrown, then that means you are doing new Exception() or something like that. Otherwise the exception is going to cause the thread to be suspended, and the stack to be walked. This may be Ok in smaller situations, but in high-traffic websites, relying on exceptions as a workflow or execution path mechanism will certainly cause you performance problems. Exceptions, per se, aren't bad, and are useful for expressing exceptional conditions
The exception workflow in a .NET app uses first and second chance exceptions. For all exceptions, even if you are catching and handling them, the exception object is still created and the framework still has to walk the stack to look for a handler. If you catch and rethrow of course that is going to take longer - you are going to get a first-chance exception, catch it, rethrow it, causing another first-chance exception, which then doesn't find a handler, which then causes a second-chance exception.
Exceptions are also objects on the heap - so if you are throwing tons of exceptions, then you are causing both performance and memory issues.
Furthermore, according to my copy of "Performance Testing Microsoft .NET Web Applications" written by the ACE team:
"Exception handling is expensive. Execution of the involved thread is suspended while CLR recurses through the call stack in search of the right exception handler, and when it is found, the exception handler and some number of finally blocks must all have their chance to execute before regular processing can be performed."
My own experience in the field showed that reducing exceptions significantly helped performance. Of course, there are other things you take into account when performance testing - for example, if your Disk I/O is shot, or your queries are in the seconds, then that should be your focus. But finding and removing exceptions should be a vital part of that strategy.
A: The argument as I understand it is not that throwing exceptions are bad they are slow per se. Instead, it is about using the throw/catch construct as a first class way of controlling normal application logic, instead of more traditional conditional constructs.
Often in normal application logic you perform looping where the same action is repeated thousands/millions of times. In this case, with some very simple profiling (see the Stopwatch class), you can see for yourself that throwing an exception instead of say a simple if statement can turn out to be substantially slower.
In fact I once read that the .NET team at Microsoft introduced the TryXXXXX methods in .NET 2.0 to many of the base FCL types specifically because customers were complaining that performance of their applications was so slow.
It turns out in many cases this was because customers were attempting type conversion of values in a loop, and each attempt failed. An conversion exception was thrown and then caught by an exception handler that then swallowed the exception and continued the loop.
Microsoft now recommend the TryXXX methods should be used particularly in this situation to avoid such possible performance issues.
I could be wrong, but it sounds like you are not certain about the veracity of the "benchmarks" you have read about. Simple solution: Try it out for yourself.
A: My XMPP server gained a major speed boost (sorry, no actual numbers, purely observational) after I consistently tried to prevent them from happening (such as checking if a socket is connected before try to read more data) and giving myself ways to avoid them (the mentioned TryX methods). That was with only about 50 active (chatting) virtual users.
A: There is the definitive answer to this from the guy who implemented them - Chris Brumme. He wrote an excellent blog article about the subject (warning - its very long)(warning2 - its very well written, if you're a techie you'll read it to the end and then have to make up your hours after work :) )
The executive summary: they are slow. They are implemented as Win32 SEH exceptions, so some will even pass the ring 0 CPU boundary!
Obviously in the real world, you'll be doing a lot of other work so the odd exception will not be noticed at all, but if you use them for program flow expect your app to be hammered. This is another example of the MS marketing machine doing us a disservice. I recall one microsoftie telling us how they incurred absolutely zero overhead, which is complete tosh.
Chris gives a pertinent quote:
In fact, the CLR internally uses
exceptions even in the unmanaged
portions of the engine. However,
there is a serious long term
performance problem with exceptions
and this must be factored into your
decision.
A: Just to add my own recent experience to this discussion: in line with most of what is written above, I found throwing exceptions to be extremely slow when done on a repeated basis, even without the debugger running. I just increased the performance of a large program I'm writing by 60% by changing about five lines of code: switching to a return-code model instead of throwing exceptions. Granted, the code in question was running thousands of times and potentially throwing thousands of exceptions before I changed it. So I agree with the statement above: throw exceptions when something important actually goes wrong, not as a way of controlling application flow in any "expected" situations.
A: But mono throws exception 10x faster than .net standalone mode,
and .net standalone mode throws exception 60x faster than .net debugger mode.
(Testing machines have same CPU model)
int c = 1000000;
int s = Environment.TickCount;
for (int i = 0; i < c; i++)
{
try { throw new Exception(); }
catch { }
}
int d = Environment.TickCount - s;
Console.WriteLine(d + "ms / " + c + " exceptions");
A: I'm on the "not slow" side - or more precisely "not slow enough to make it worth avoiding them in normal use". I've written two short articles about this. There are criticisms of the benchmark aspect, which are mostly down to "in real life there'd be more stack to go through, so you'd blow the cache etc" - but using error codes to work your way up the stack would also blow the cache, so I don't see that as a particularly good argument.
Just to make it clear - I don't support using exceptions where they're not logical. For instance, int.TryParse is entirely appropriate for converting data from a user. It's inappropriate when reading a machine-generated file, where failure means "The file isn't in the format it's meant to be, I really don't want to try to handle this as I don't know what else might be wrong."
When using exceptions in "only reasonable circumstances" I've never seen an application whose performance was significantly impaired by exceptions. Basically, exceptions shouldn't happen often unless you've got significant correctness issues, and if you've got significant correctness issues then performance isn't the biggest problem you face.
A: I have never had any performance problem with exceptions. I use exceptions a lot -- I never use return codes if I can. They are a bad practice, and in my opinion, smell like spaghetti code.
I think it all boils down to how you use exceptions: if you use them like return codes (each method call in the stack catches and rethrows) then, yeah, they will be slow, because you have overhead each single catch/throw.
But if you throw at the bottom of the stack and catch at the top (you substitute a whole chain of return codes with one throw/catch), all costly operations are done once.
At the end of the day, they are a valid language feature.
Just to prove my point
Please run the code at this link (too big for an answer).
Results on my computer:
marco@sklivvz:~/develop/test$ mono Exceptions.exe | grep PM
10/2/2008 2:53:32 PM
10/2/2008 2:53:42 PM
10/2/2008 2:53:52 PM
Timestamps are output at the beginning, between return codes and exceptions, at the end. It takes the same time in both cases. Note that you have to compile with optimizations.
A: If you compare them to return codes they are slow as hell. However as previous posters stated you don't want to throw in normal program operation so you only get the perf hit when a problem occurs and in the vast majority of cases performance no longer matters (as the exception implies a road-block anyway).
They're definately worth using over error codes, the advantages are vast IMO.
A: On the Windows CLR, for a depth-8 call chain, throwing an exception is 750-times slower than checking and propagating a return value. (see below for benchmarks)
This high cost for exceptions is because the windows CLR integrates with something called Windows Structured Exception Handling. This enables exceptions to be properly caught and thrown across different runtimes and languages. However, it's very very slow.
Exceptions in the Mono runtime (on any platform) are much faster, because it does not integrate with SEH. However, there is functionality loss when passing exceptions across multiple runtimes because it doesn't use anything like SEH.
Here are abbreviated results from my benchmark of exceptions vs return values for the Windows CLR.
baseline: recurse_depth 8, error_freqeuncy 0 (0), time elapsed 13.0007 ms
baseline: recurse_depth 8, error_freqeuncy 0.25 (0), time elapsed 13.0007 ms
baseline: recurse_depth 8, error_freqeuncy 0.5 (0), time elapsed 13.0008 ms
baseline: recurse_depth 8, error_freqeuncy 0.75 (0), time elapsed 13.0008 ms
baseline: recurse_depth 8, error_freqeuncy 1 (0), time elapsed 14.0008 ms
retval_error: recurse_depth 5, error_freqeuncy 0 (0), time elapsed 13.0008 ms
retval_error: recurse_depth 5, error_freqeuncy 0.25 (249999), time elapsed 14.0008 ms
retval_error: recurse_depth 5, error_freqeuncy 0.5 (499999), time elapsed 16.0009 ms
retval_error: recurse_depth 5, error_freqeuncy 0.75 (999999), time elapsed 16.001 ms
retval_error: recurse_depth 5, error_freqeuncy 1 (999999), time elapsed 16.0009 ms
retval_error: recurse_depth 8, error_freqeuncy 0 (0), time elapsed 20.0011 ms
retval_error: recurse_depth 8, error_freqeuncy 0.25 (249999), time elapsed 21.0012 ms
retval_error: recurse_depth 8, error_freqeuncy 0.5 (499999), time elapsed 24.0014 ms
retval_error: recurse_depth 8, error_freqeuncy 0.75 (999999), time elapsed 24.0014 ms
retval_error: recurse_depth 8, error_freqeuncy 1 (999999), time elapsed 24.0013 ms
exception_error: recurse_depth 8, error_freqeuncy 0 (0), time elapsed 31.0017 ms
exception_error: recurse_depth 8, error_freqeuncy 0.25 (249999), time elapsed 5607.3208 ms
exception_error: recurse_depth 8, error_freqeuncy 0.5 (499999), time elapsed 11172.639 ms
exception_error: recurse_depth 8, error_freqeuncy 0.75 (999999), time elapsed 22297.2753 ms
exception_error: recurse_depth 8, error_freqeuncy 1 (999999), time elapsed 22102.2641 ms
And here is the code..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1 {
public class TestIt {
int value;
public class TestException : Exception { }
public int getValue() {
return value;
}
public void reset() {
value = 0;
}
public bool baseline_null(bool shouldfail, int recurse_depth) {
if (recurse_depth <= 0) {
return shouldfail;
} else {
return baseline_null(shouldfail,recurse_depth-1);
}
}
public bool retval_error(bool shouldfail, int recurse_depth) {
if (recurse_depth <= 0) {
if (shouldfail) {
return false;
} else {
return true;
}
} else {
bool nested_error = retval_error(shouldfail,recurse_depth-1);
if (nested_error) {
return true;
} else {
return false;
}
}
}
public void exception_error(bool shouldfail, int recurse_depth) {
if (recurse_depth <= 0) {
if (shouldfail) {
throw new TestException();
}
} else {
exception_error(shouldfail,recurse_depth-1);
}
}
public static void Main(String[] args) {
int i;
long l;
TestIt t = new TestIt();
int failures;
int ITERATION_COUNT = 1000000;
// (0) baseline null workload
for (int recurse_depth = 2; recurse_depth <= 10; recurse_depth+=3) {
for (float exception_freq = 0.0f; exception_freq <= 1.0f; exception_freq += 0.25f) {
int EXCEPTION_MOD = (exception_freq == 0.0f) ? ITERATION_COUNT+1 : (int)(1.0f / exception_freq);
failures = 0;
DateTime start_time = DateTime.Now;
t.reset();
for (i = 1; i < ITERATION_COUNT; i++) {
bool shoulderror = (i % EXCEPTION_MOD) == 0;
t.baseline_null(shoulderror,recurse_depth);
}
double elapsed_time = (DateTime.Now - start_time).TotalMilliseconds;
Console.WriteLine(
String.Format(
"baseline: recurse_depth {0}, error_freqeuncy {1} ({2}), time elapsed {3} ms",
recurse_depth, exception_freq, failures,elapsed_time));
}
}
// (1) retval_error
for (int recurse_depth = 2; recurse_depth <= 10; recurse_depth+=3) {
for (float exception_freq = 0.0f; exception_freq <= 1.0f; exception_freq += 0.25f) {
int EXCEPTION_MOD = (exception_freq == 0.0f) ? ITERATION_COUNT+1 : (int)(1.0f / exception_freq);
failures = 0;
DateTime start_time = DateTime.Now;
t.reset();
for (i = 1; i < ITERATION_COUNT; i++) {
bool shoulderror = (i % EXCEPTION_MOD) == 0;
if (!t.retval_error(shoulderror,recurse_depth)) {
failures++;
}
}
double elapsed_time = (DateTime.Now - start_time).TotalMilliseconds;
Console.WriteLine(
String.Format(
"retval_error: recurse_depth {0}, error_freqeuncy {1} ({2}), time elapsed {3} ms",
recurse_depth, exception_freq, failures,elapsed_time));
}
}
// (2) exception_error
for (int recurse_depth = 2; recurse_depth <= 10; recurse_depth+=3) {
for (float exception_freq = 0.0f; exception_freq <= 1.0f; exception_freq += 0.25f) {
int EXCEPTION_MOD = (exception_freq == 0.0f) ? ITERATION_COUNT+1 : (int)(1.0f / exception_freq);
failures = 0;
DateTime start_time = DateTime.Now;
t.reset();
for (i = 1; i < ITERATION_COUNT; i++) {
bool shoulderror = (i % EXCEPTION_MOD) == 0;
try {
t.exception_error(shoulderror,recurse_depth);
} catch (TestException e) {
failures++;
}
}
double elapsed_time = (DateTime.Now - start_time).TotalMilliseconds;
Console.WriteLine(
String.Format(
"exception_error: recurse_depth {0}, error_freqeuncy {1} ({2}), time elapsed {3} ms",
recurse_depth, exception_freq, failures,elapsed_time)); }
}
}
}
}
A: In release mode the overhead is minimal.
Unless you are going to be using exceptions for flow-control (example, non-local exits) in a recursive fashion, I doubt you will be able to notice the difference.
A: You pretty much answered your own question I think. You, and pretty much everyone that has an understanding of them, know they're slow. It's a 100% fact, but as many others have pointed out, the context is what matters 100% as to when to use them. Writing a non server application? you'll never notice a difference. Writing a website public API where a malformed client request can trigger an exception on the backend? That's a recipe for disaster on an order of magnitude that is multiplied by the requests/second. Backends are pegged more times than the penny pony at the grocery store. The problem with that, though, is the BCL/other libraries will throw exceptions you have no control over, so you have to middle man/crossing guard things that would trigger those exceptions before they got to the BCL. There are cases where you have absolutely no defense at all. Such as reaching out to a MongoDB database with the MongoClient. All of the MongoCollection.*Async functions will throw exceptions if they dont succeed in certain scenarios, but it doesnt throw many at all, and I'm pretty sure these scenarios are on the rare end of the spectrum(which shifts this towards the context part of the situation). I could also be wrong, though. I'd just assume they only threw on rare occasions. As you pointed out, you know they're slow, so it's only common sense that you use them in contexts that require things to not be slow. Plain and simple.
A: One quick note here on the performance associated with catching exceptions.
When the execution path enters a 'try' block, nothing magical happens. There is no 'try' instruction, and no cost associated with either entering or exiting the try block. Information about the try block is stored in the method's metadata, and this metadata is used at runtime whenever an exception is raised. The execution engine walks down the stack looking for the first call that was contained in a try block. Any overhead associated with exception handling occurs only when exceptions are thrown.
A: When writing classes/functions for others to use it appears to be difficult to say when exceptions are appropriate. There are some useful parts of BCL that I had to ditch and go for pinvoke because they throw exceptions instead of returning errors. For some cases you can work around it but for others like System.Management and Performance Counters there are usages where you need to do loops in which exceptions are thrown by BCL frequently.
If you are writing a library and there's a remote possibility that your function may be used in a loop and there's a potential for large amount of iterations, use the Try.. pattern or some other way to expose the errors beside exceptions. And even then, it's hard to say how much your function will get called if it's being used by many processes in shared environment.
In my own code, exceptions are only thrown when things are so exceptional that its necessary to go look at the stack trace and see what went wrong and then fix it. So I pretty much have re-written parts of BCL to use error handling based on Try.. pattern instead of exceptions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "149"
} |
Q: If I stop a long running query, does it rollback? A query that is used to loop through 17 millions records to remove duplicates has been running now for about 16 hours and I wanted to know if the query is stopped right now if it will finalize the delete statements or if it has been deleting while running this query? Indeed, if I do stop it, does it finalize the deletes or rolls back?
I have found that when I do a
select count(*) from myTable
That the rows that it returns (while doing this query) is about 5 less than what the starting row count was. Obviously the server resources are extremely poor, so does that mean that this process has taken 16 hours to find 5 duplicates (when there are actually thousands), and this could be running for days?
This query took 6 seconds on 2000 rows of test data, and it works great on that set of data, so I figured it would take 15 hours for the complete set.
Any ideas?
Below is the query:
--Declare the looping variable
DECLARE @LoopVar char(10)
DECLARE
--Set private variables that will be used throughout
@long DECIMAL,
@lat DECIMAL,
@phoneNumber char(10),
@businessname varchar(64),
@winner char(10)
SET @LoopVar = (SELECT MIN(RecordID) FROM MyTable)
WHILE @LoopVar is not null
BEGIN
--initialize the private variables (essentially this is a .ctor)
SELECT
@long = null,
@lat = null,
@businessname = null,
@phoneNumber = null,
@winner = null
-- load data from the row declared when setting @LoopVar
SELECT
@long = longitude,
@lat = latitude,
@businessname = BusinessName,
@phoneNumber = Phone
FROM MyTable
WHERE RecordID = @LoopVar
--find the winning row with that data. The winning row means
SELECT top 1 @Winner = RecordID
FROM MyTable
WHERE @long = longitude
AND @lat = latitude
AND @businessname = BusinessName
AND @phoneNumber = Phone
ORDER BY
CASE WHEN webAddress is not null THEN 1 ELSE 2 END,
CASE WHEN caption1 is not null THEN 1 ELSE 2 END,
CASE WHEN caption2 is not null THEN 1 ELSE 2 END,
RecordID
--delete any losers.
DELETE FROM MyTable
WHERE @long = longitude
AND @lat = latitude
AND @businessname = BusinessName
AND @phoneNumber = Phone
AND @winner != RecordID
-- prep the next loop value to go ahead and perform the next duplicate query.
SET @LoopVar = (SELECT MIN(RecordID)
FROM MyTable
WHERE @LoopVar < RecordID)
END
A: no, sql server will not roll back the deletes it has already performed if you stop query execution. oracle requires an explicit committal of action queries or the data gets rolled back, but not mssql.
with sql server it will not roll back unless you are specifically running in the context of a transaction and you rollback that transaction, or the connection closes without the transaction having been committed. but i don't see a transaction context in your above query.
you could also try re-structuring your query to make the deletes a little more efficient, but essentially if the specs of your box are not up to snuff then you might be stuck waiting it out.
going forward, you should create a unique index on the table to keep yourself from having to go through this again.
A: If you don't do anything explicit about transactions then the connection will be in autocommit transactions mode. In this mode every SQL statement is considered a transaction.
The question is whether this means the individual SQL statements are transactions and are therefore being committed as you go, or whether the outer WHILE loop counts as a transaction.
There doesn't seem to be any discussion of this in the description of the WHILE construct on MSDN. However, since a WHILE statement can't directly modify the database it would seem logical that it doesn't start an auto-commit transaction.
A: Implicit transactions
If no 'Implicit transactions' has been set, then each iteration in your loop committed the changes.
It is possible for any SQL Server to be set with 'Implicit transactions'. This is a database setting (by default is OFF). You can also have implicit transactions in the properties of a particular query inside of Management Studio (right click in query pane>options), by default settings in the client, or a SET statement.
SET IMPLICIT_TRANSACTIONS ON;
Either way, if this was the case, you would still need to execute an explicit COMMIT/ROLLBACK regardless of interruption of the query execution.
Implicit transactions reference:
http://msdn.microsoft.com/en-us/library/ms188317.aspx
http://msdn.microsoft.com/en-us/library/ms190230.aspx
A: Your query is not wrapped in a transaction, so it won't rollback the changes already made by the individual delete statements.
I specifically tested this myself on my own SQL Server using the following query, and the ApplicationLog table was empty even though I cancelled the query:
declare @count int
select @count = 5
WHILE @count > 0
BEGIN
print @count
delete from applicationlog;
waitfor time '20:00';
select @count = @count -1
END
However your query is likely to take many days or weeks, much longer then 15 hours. Your estimate that you can process 2000 records every 6 seconds is wrong because each iteration in your while loop will take significantly longer with 17 million rows then it does with 2000 rows. So unless your query takes significantly less then a second for 2000 rows, it will take days for all 17 million.
You should ask a new question on how you can delete duplicate rows efficiently.
A: I inherited a system which had logic something like yours implemented in SQL. In our case, we were trying to link together rows using fuzzy matching that had similar names/addresses, etc, and that logic was done purely in SQL. At the time I inherited it we had about 300,000 rows in the table and according to the timings, we calculated it would take A YEAR to match them all.
As an experiment to see how much faster I could do it outside of SQL, I wrote a program to dump the db table into flat files, read the flat files into a C++ program, build my own indexes, and do the fuzzy logic there, then reimport the flat files into the database. What took A YEAR in SQL took about 30 seconds in the C++ app.
So, my advice is, don't even try what you are doing in SQL. Export, process, re-import.
A: DELETES that have been performed up to this point will not be rolled back.
As the original author of the code in question, and having issued the caveat that performance will be dependant on indexes, I would propose the following items to speed this up.
RecordId better be PRIMARY KEY. I don't mean IDENTITY, I mean PRIMARY KEY. Confirm this using sp_help
Some index should be used in evaluating this query. Figure out which of these four columns has the least repeats and index that...
SELECT *
FROM MyTable
WHERE @long = longitude
AND @lat = latitude
AND @businessname = BusinessName
AND @phoneNumber = Phone
Before and After adding this index, check the query plan to see if index scanning has been added.
A: As a loop your query will struggle to scale well, even with appropriate indexes. The query should be rewritten to a single statement, as per the suggestions in your previous question on this.
If you're not running it explicitly within a transaction it will only roll back the executing statement.
A: I think this query would be much more efficient if it was re-written using a single-pass algorithm using a cursor. You would order you cursor table by longitude,latitude,BusinessName AND @phoneNumber. You’d step through the rows one at a time. If a row has the same longitude, latitude, businessname, and phonenumber as the previous row, then delete it.
A: I think you need to seriously consider your methodolology.
You need to start thinking in sets (although for performance you may need batch processing, but not row by row against a 17 million record table.)
First do all of your records have duplicates? I suspect not, so the first thing you wan to do is limit your processing to only those records which have duplicates. Since this is a large table and you may need to do the deletes in batches over time depending on what other processing is going on, you first pull the records you want to deal with into a table of their own that you then index. You can also use a temp table if you are going to be able to do this all at the same time without ever stopping it other wise create a table in your database and drop at the end.
Something like (Note I didn't write the create index statments, I figure you can look that up yourself):
SELECT min(m.RecordID), m.longitude, m.latitude, m.businessname, m.phone
into #RecordsToKeep
FROM MyTable m
join
(select longitude, latitude, businessname, phone
from MyTable
group by longitude, latitude, businessname, phone
having count(*) >1) a
on a.longitude = m.longitude and a.latitude = m.latitude and
a.businessname = b.businessname and a.phone = b.phone
group by m.longitude, m.latitude, m.businessname, m.phone
ORDER BY CASE WHEN m.webAddress is not null THEN 1 ELSE 2 END,
CASE WHEN m.caption1 is not null THEN 1 ELSE 2 END,
CASE WHEN m.caption2 is not null THEN 1 ELSE 2 END
while (select count(*) from #RecordsToKeep) > 0
begin
select top 1000 *
into #Batch
from #RecordsToKeep
Delete m
from mytable m
join #Batch b
on b.longitude = m.longitude and b.latitude = m.latitude and
b.businessname = b.businessname and b.phone = b.phone
where r.recordid <> b.recordID
Delete r
from #RecordsToKeep r
join #Batch b on r.recordid = b.recordid
end
Delete m
from mytable m
join #RecordsToKeep r
on r.longitude = m.longitude and r.latitude = m.latitude and
r.businessname = b.businessname and r.phone = b.phone
where r.recordid <> m.recordID
A: Also try thinking another method to remove duplicate rows:
delete t1 from table1 as t1 where exists (
select * from table1 as t2 where
t1.column1=t2.column1 and
t1.column2=t2.column2 and
t1.column3=t2.column3 and
--add other colums if any
t1.id>t2.id
)
I suppose that you have an integer id column in your table.
A: If your machine doesn't have very advanced hardware then it may take sql server a very long time to complete that command. I don't know for sure how this operation is performed under the hood but based on my experience this could be done more efficiently by bringing the records out of the database and into memory for a program that uses a tree structure with a remove duplicate rule for insertion. Try reading the entirety of the table in chuncks (say 10000 rows at a time) into a C++ program using ODBC. Once in the C++ program use and std::map where key is the unique key and struct is a struct that holds the rest of the data in variables. Loop over all the records and perform insertion into the map. The map insert function will handle removing the duplicates. Since search inside a map is lg(n) time far less time to find duplicates than using your while loop. You can then delete the entire table and add the tuples back into the database from the map by forming insert queries and executing them via odbc or building a text file script and running it in management studio.
A: I'm pretty sure that is a negatory. Otherwise what would the point of transactions be?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: Visual Studio 2005: All projects in solution explorer expanded on first opening of solution Is any way to tell the solution explorer of Visual Studio 2005 not to expand all projects on the first opening of the solutio after svn-checkout?
Edit:
Thanks for pointing out the PowerCommands. As I am using Visual Studio 2005 with .Net 2.0 it does not work for me. Are there similar tools available for VS2005?
A: I found this annoying too, so my solution was to install PowerCommands for Visual Studio which is a nice add in, it has "Colapse Project" function which does exactly that.
it also has a dozen of other cool features.
Highly recommended.
A: Re: something like PowerPack: DPack has a solution collapse option too, and it works with 2005.
I configure it to collapse "Top Items Only" because "All Projects and Files" works too slowly and flickery for me.
A: My default (without anyway of changing this as far as I know) VS will expand all the projects like that on first opening of a solution and creation of the solution user options file. as ljubomir mentioned, the best thing to do is create something to collapse all the projects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Refactoring Code: When to do what? Ever since I started using .NET, I've just been creating Helper classes or Partial classes to keep code located and contained in their own little containers, etc.
What I'm looking to know is the best practices for making ones code as clean and polished as it possibly could be.
Obviously clean code is subjective, but I'm talking about when to use things (not how to use them) such as polymorphism, inheritance, interfaces, classes and how to design classes more appropriately (to make them more useful, not just say 'DatabaseHelper', as some considered this bad practice in the code smells wiki).
Are there any resources out there that could possibly help with this kind of decision making?
Bare in mind that I haven't even started a CS or software engineering course, and that a teaching resource is fairly limited in real-life.
A: Here is a review on slash dot of a book called Clean Code.
The book is apparently a little dry but very good.
A: A real eye-opener to me was Refactoring: Improving the Design of Existing Code:
With proper training a skilled system
designer can take a bad design and
rework it into well-designed, robust
code. In this book, Martin Fowler
shows you where opportunities for
refactoring typically can be found,
and how to go about reworking a bad
design into a good one.
Refactoring http://ecx.images-amazon.com/images/I/519XT0DER6L._SL160_PIlitb-dp-arrow,TopRight,21,-23_SH30_OU01_AA115_.jpg
It helped me to efficiently and systematically refactor code. Also it helped me a lot in discussions with other developers, when their holy code has to be changed ...
A: Check out Martin Fowler's comments and book on Refactoring
A: Jeff Atwood made a nice blog post on refactoring and code smells, you might want to check that out.
Refactoring code in .NET takes some time to grok. You need to know some object-oriented design principles (or design techniques) in order to refactor effectively and mercilessly.
In short, you refactor code in order to remove code smells and make changes easier to do. Also, don't overdo it.
A: *
*Re-factor you code when it is causing problems. Any problems will do: performance, scallabillity, integration, maintainance - anything which makes you spend more time on it when you should. It it is not broken do not fix it even if you do not believe it is clean or is up to the modern standards.
*Don't spend too much time making the code perfect. You will never achieve perfection but you could spend lots of time trying to do so. Remember the law of diminishing returns.
*Inside a project only re-factor the code when you are actually working on the functionality which depends on it. I.e. if you have a user story for the iteration calls for a "change the upload mechanism" or "fixing the bug in the file upload" you could re-factor the file uploading code. However if your user story is about "facelifting the file upload UI design" do not go into the business logic.
A: I'd recommend Domain Driven Design. I think both YAGNI and AlwaysRefactor principles are two simplistic. The age old question on the issue is do i refactor "if(someArgument == someValue)" into a function or leave it inline?
There is no yes or no answer. DDD advises to refactor it if the test represents a buisiness rule. The refactoring is not (only) about reuse but about making the intentions clear.
A: Working Effectively with Legacy Code is one of the best books I have seen on this subject.
Don't be put off the title of the book - Rather than treating Refactoring as a formal concept (which has its place), this book has lots and lots of simple "why didn't I think of that" tips. Things like "go through a class and remove any methods not directly realted to that class and put them in a different one".
e.g. You have a grid and some code to persist the layout of that grid to file. You can probably safely move the layout persisting code out to a different class.
A: My rule of thumb is to leave the code in no worse shape than you found it.
The idea is to work towards the better, without trying to achieve the perfect result, or go all the way.
Individual refactorings sometimes have a questionable benefit, and - as an extreme example - it might indeed be argued if m_Pi is a better name than m_PI. However, most often one choice is more consistent, and less surprising even if not obviously "better".
One situation where I regulary find myself refactoring automatically is before implementing a featureon a piece of code.
There are often a few TODO's waiting to be fed, some inconsistencies or sometimes custom functionality that has lately acquired better library support. Doing these changes before I implement the actual feature request gives me some understanding of the code, and I verify the "before" functionality.
Another point is after fixing bugs. After, so the before-repro isn't affected, and the bug fix and the refactoring are two separate commits.
A: I just got a copy of Code Complete, and found that there was a section on this.
Although I will still be reading the accepted answer's book, what Code Complete has taught me has dramatically improved the way I think about designing classes.
Before today, I didn't know what an ADT was (abstract data type), and now I know how to develop classes adhering to the encapsulation.
A: There's a web page dedicated to refactoring at http://www.refactoring.com/. It features many references to further resources on the topic of refactoring code as well as a mailing list to discuss refactoring-related issues.
Last but not least, there's a big (and still growing) catalog of refactorings available which extends well beyond what's written in the (very much recommended) Refactoring book by Martin Fowler.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: Using Selenium IDE with random values Is it possible to create Selenium tests using the Firefox plugin that use randomly generated values to help do regression tests?
The full story:
I would like to help my clients do acceptance testing by providing them with a suite of tests that use some smarts to create random (or at least pseudo-random) values for the database. One of the issues with my Selenium IDE tests at the moment is that they have predefined values - which makes some types of testing problematic.
A: Here's a one-line solution to generating a random string of letters in JS:
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("").filter(function(e, i, a) { return Math.random() > 0.8 }).join("")
Useful for pasting into Selenium IDE.
A: First off, the Selenium IDE is rather limited, you should consider switching to Selenium RC, which can be driven by Java or Perl or Ruby or some other languages.
Using just Selenium IDE, you can embed JavaScript expressions to derive command parameters.
You should be able to type a random number into a text field, for example:
type fieldName javascript{Math.floor(Math.random()*11)}
Update: You can define helper functions in a file called "user-extensions.js". See the Selenium Reference.
A: (Based on Thilo answer)
You can mix literals and random numbers like this:
javascript{"joe+" + Math.floor(Math.random()*11111) + "@gmail.com";}
Gmail makes possible that automatically everything that use aliases, for example, joe+testing@gmail.com will go to your address joe@gmail.com
Multiplying *11111 to give you more random values than 1 to 9 (in Thilo example)
A: You can add user exentions.js to get the random values .
Copy the below code and save it as .js extension (randomgenerator.js) and add it to the Selenium core extensions (SeleniumIDE-->Options--->general tab)
Selenium.prototype.doRandomString = function( options, varName ) {
var length = 8;
var type = 'alphanumeric';
var o = options.split( '|' );
for ( var i = 0 ; i < 2 ; i ++ ) {
if ( o[i] && o[i].match( /^\d+$/ ) )
length = o[i];
if ( o[i] && o[i].match( /^(?:alpha)?(?:numeric)?$/ ) )
type = o[i];
}
switch( type ) {
case 'alpha' : storedVars[ varName ] = randomAlpha( length ); break;
case 'numeric' : storedVars[ varName ] = randomNumeric( length ); break;
case 'alphanumeric' : storedVars[ varName ] = randomAlphaNumeric( length ); break;
default : storedVars[ varName ] = randomAlphaNumeric( length );
};
};
function randomNumeric ( length ) {
return generateRandomString( length, '0123456789'.split( '' ) );
}
function randomAlpha ( length ) {
var alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split( '' );
return generateRandomString( length, alpha );
}
function randomAlphaNumeric ( length ) {
var alphanumeric = '01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split( '' );
return generateRandomString( length, alphanumeric );
}
function generateRandomString( length, chars ) {
var string = '';
for ( var i = 0 ; i < length ; i++ )
string += chars[ Math.floor( Math.random() * chars.length ) ];
return string;
}
Way to use
Command Target Value
----------- --------- ----------
randomString 6 x
type username ${x}
Above code generates 6 charactes string and it assign to the variable x
Code in HTML format looks like below:
<tr>
<td>randomString</td>
<td>6</td>
<td>x</td>
</tr>
<tr>
<td>type</td>
<td>username</td>
<td>${x}</td>
</tr>
A: A one-liner for randomly choosing from a small set of alternatives:
javascript{['brie','cheddar','swiss'][Math.floor(Math.random()*3)]}
A: <tr>
<td>store</td>
<td>javascript{Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 8)}</td>
<td>myRandomString</td>
</tr>
A: I made a little improvment to the function generateRandomString.
When FF crashes, it's good to be able to use the same random number again.
Basically, it will ask you to enter a string yourself. If you don't enter anything, it will generate it.
function generateRandomString( length, chars ) {
var string=prompt("Please today's random string",'');
if (string == '')
{for ( var i = 0 ; i < length ; i++ )
string += chars[ Math.floor( Math.random() * chars.length ) ];
return string;}
else
{
return string;}
}
A: While making sense of RajendraChary's post above, I spent some time writing a new Selenium IDE extension.
My extension will let the user populate a variable with lorem ipsum text. There are a number of configurable options and it's turned into a nice little command. You can do things like "5 words|wordcaps|nomarks" to generate 5 lorem ipsum words, all capitalized, without punctuation.
I've thoroughly explained installation and usage as well as provided the full codebase here
If you take a peek at the code you'll get an idea of how to build similar functionality.
A: Here another variation on the gmail example:
<tr>
<td>runScript</td>
<td>emailRandom=document.getElementById('email');console.log(emailRandom.value);emailRandom.value="myEmail+" + Math.floor(Math.random()*11111)+ "@gmail.com";</td>
<td></td>
</tr>
A: Selenium RC gives you much more freedom than Selenium IDE, in that you can:
*
*(1) Enter any value to a certain field
*(2) Choose any field to test in a certain HTML form
*(3) Choose any execution order/step to test a certain set of fields.
You asked how to enter some random value in a field using Selenium IDE, other people have answered you how to generate and enter random values in a field using Selenium RC. That falls into the testing phase (1): "Enter any value to a certain field".
Using Selenium RC you could easily do the phase (2) and (3): testing any field under any execution step by doing some programming in a supported language like Java, PHP, CSharp, Ruby, Perl, Python.
Following is the steps to do phase (2) and (3):
*
*Create list of your HTML fields so that you could easily iterate through them
*Create a random variable to control the step, say RAND_STEP
*Create a random variable to control the field, say RAND_FIELD
*[Eventually, create a random variable to control the value entered into a certain field, say RAND_VALUE, if you want to do phase (1)]
*Now, inside your fuzzing algorithm, iterate first through the values of RAND_STEP, then with each such iteration, iterate through RAND_FIELD, then finally iterate through RAND_VALUE.
See my other answer about fuzzing test, Selenium and white/black box testing
A: Math.random may be "good enough" but, in practice, the Random class is often preferable to Math.random(). Using Math.random , the numbers you get may not actually be completely random. The book "Effective Java Second Edition" covers this in Item #47.
A: One more solution, which I've copied and pasted into hundreds of tests :
<tr>
<td>store</td>
<td>javascript{var myDate = new Date(); myDate.getFullYear()+"-"+(myDate.getMonth()+1)+"-"+myDate.getDate()+"-"+myDate.getHours()+myDate.getMinutes()+myDate.getSeconds()+myDate.getMilliseconds();}</td>
<td>S_Unique</td>
</tr>
<tr>
<td>store</td>
<td>Selenium Test InternalRefID-${S_Unique}</td>
<td>UniqueInternalRefID</td>
</tr>
<tr>
<td>store</td>
<td>Selenium Test Title-${S_Unique}</td>
<td>UniqueTitle</td>
</tr>
<tr>
<td>store</td>
<td>SeleniumEmail-${G_Unique}@myURL.com</td>
<td>UniqueEmailAddress</td>
</tr>
Each test suite begins by setting a series of variables (if it's a big suite, use a separate file like Set_Variables.html). Those variables can then be used throughout your suite to set, test, and delete test data. And since the variables use the date rather than a random number, you can debug your test suite by looking for the objects which share a date.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "48"
} |
Q: could not read column value from result set ; String index out of range: 0 I'm reading data from a table( from a MySQL Database) with Hibernate SQL Query.
The thing is, the table contains a colum that is mapped to a char in Hibernate Model, and sometimes this column is empty.
And I suppose this is where my exception comes from.
How can I map a colum of char to my hibernate model without getting this error ?
Thanks for your answers !
Thank you for your answer !
My column is not nullable (I 'm using MySQL and this column is NOT NULL)
Then, I don't think that
if (str == null) {
is appropriate.
the error is :
15:30:35,289 INFO CharacterType:178 - could not read column value from result set: LSFUS11_20_; String index out of range: 0
which results in the following exception :
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:558)
I think I may try your solution, but with :
if (str == "") {
since it can't be null, it's just an empty String.
Thanks for your piece code, I'm going to try that !
A: I am assuming from your question that you're mapping this to a primitive character. Next time, please post the stacktrace that you receive (you may leave out where you call it, you could only include the hibernate stuff if your project is too sensitive).
If you do map to a primitive character, and it is null, you will get an exception, because primitives cannot have null assigned to them.
This class will mitigate this, the "null" character is returned as a character representing "0". You can customize this to your liking:
import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.type.CharacterType;
public class NullCharacterType extends CharacterType {
/**
* Serializable ID generated by Eclipse
*/
private static final long serialVersionUID = 1L;
public NullCharacterType() {
super();
}
public Object get(final ResultSet rs, final String name)
throws SQLException {
final String str = rs.getString(name);
if (str == null || str.length() == 0) {
return new Character((char) 0);
} else {
return new Character(str.charAt(0));
}
}
}
To use this new type, in your hibernate mapping, before you had something like:
<property name="theChar" type="character">
Now, you just specify the class name as your type:
<property name="theChar" type="yourpackage.NullCharacterType">
However, the best practice is to not use primitive types for database mapping. If at all possible, use Character instead of char, because that way you won't have an issue with null (null can be assigned to the wrapper types).
A: Search your JBoss (server) whether mysql.jar (mysql-connector-java-5.1.7-bin) is present in lib files or not.
Even I faced the same problem, after adding the mysql.jar file it is working fine.
A: use native function LEFT or RIGHT to change the column datatype in origin
let's suppose this was the SQL query giving the error
select username from Users
change it with:
select LEFT(username,100) from Users
the number should be equal to the size of the field
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Visual Studio 2008: make Ctrl + K, Ctrl + N (next bookmark) stay within the same file In Visual Studio 2003 you could jump to the next bookmark with Ctrl + K, Ctrl + N; it stayed within the same file and wrapped around to the top of the file when there were no furter bookmarks in the file. Now in VS 2008 this seems to have changed, and Ctrl + K, Ctrl + N jumps to other files with bookmarks. How can I change this back to the old behavior?
A: Actually, you have two other commands that by default are not assigned a shortcut:
*
*Previous Bookmark In Document
*Next Bookmark In Document
You'll see them if you go to the Edit->Bookmarks menu. You can bind them to a shortcut if you go to Options->Preferences->Environment->Keyboard and look them up as Edit.PreviousBookmarkInDocument and Edit.NextBookmarkInDocument.
Cheers!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Is there any way to determine the amount of time a client spends on a web page Assuming I have an open source web server or proxy I can enhance, let's say apache or squid.
Is there a way to determine the time each client spends on a web page?
HTTP is of course stateless, so it's not trivial, but maybe someone has an idea on how to approach this problem?
A: With Apache or Squid you hardly can detect the time a user spends on your page.
But with some additional sugar on your webpage you can:
*
*Try Google Analytics.
It's free and has a lot of functions.
But you'll also invite Google to watch the stats of your site ... (but maybe that helps them to decide if you wanna buy you :-))
A: Not without having some javascript constantly hit your server on the client side and then checking when it stops (but of course that assumes the user has javascript enabled). There are also various (ugly) ways to detect windows being closed with javascript, but of course these won't always trigger. eg. browser crash.
I sort of wonder why you want this anyway. What if a person looks at the web page for 3 seconds, gets distracted by another tab/window but leaves your page open for 2 hours? The answer you get is 2 hours, the answer you (probably) want is 3 seconds.
A: You could count the time between when the page was requested to when the next page is requested, however this would only be correct if the user stayed on that page the whole time til he requested the next page. Even then he may still be on the original page (e.g. he opened the new one in a tab), and will only work if they do browse to another page.
The only way to know for sure would be to use Javascript to ping the server from the open page every ten seconds or so, just to say "I'm still being read!"
A: I've actually seen javascript analytics packages where they not only tracked how long you were on the page, by pinging the server every so often, but also kept track of exactly what was on the screen. by measuring the size of your browser window, along with the scroll positions of the document, they were able to determine exactly how long each element was on the screen. By tracking the location of the mouse, can probably get a good guess at what they are looking at too. I can't find the link right now, but here's the short story. If you are really interested in what people are looking at, and for how long, you can do it. There's not much of a limit to how much you can track.
Also, just a thought, If you don't want to ping the server too much, you could keep stuff buffered in memory, and only send to the server when you got a sufficient amount of data, or right before the page closed.
A: This kind of metric was actually pretty popular several years ago, before PCs got more powerful and tabbed browsers became popular, and it became harder to measure as accurately. The standard way to do it in the past was to assume people are usually just loading one page at a time, and just use server log data to determine the time between page views. Your standard analytics vendors like Omniture and Urchin (now Google Analytics) calculate this.
Normally, you set a tracking cookie to be able to identify a specific person/browser over time, but in the short term you can just use an IP address/user-agent combo.
So, basically you just crunch the log data and count the delta between to page views as how long the person was on the page. You set some rules (or your analytics vendor does this behind the curtain) like discarding/truncating times beyond some cutoff (say 10 minutes) where you assume the person wasn't actually reading but left the page open in a window/tab.
Is this data perfect? Obviously not. But you just need enough "good enough" data to do statistical analysis and draw some conclusions.
It's still useful for longitudinal analysis (readers' habits over time) and qualitative comparison between different pages on your site. (i.e. between two 700-word articles, if one has a mean reading time twice as long as the other, then more people are actually reading the first article.) Of course, your site has to be busy enough to have enough data points for statistically sound analysis after you throw out all the "bad" outlier data points.
Yes, you could use Javascript to send keep-alives to improve the data. You could just poll at given intervals after document.onload or set mouseover events on sections of your pages.
Another technique is to use Javascript to add an onclick event to every <a href> that hits your server. Not only do you then know when someone clicks a link to take them off your site, really sophisticated "hotspot" analysis looks at the fact that if someone clicked a link 6 paragraphs down a page, then they must have read that far.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/161994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Making every pixel of an image having a specific color transparent I have an object of the type System.Drawing.Image and want to make every pixel which has some specific color, for example black, transparent (that is, set alpha to 0 for this pixel).
What is the best way to do this?
A: One good approach is to use the ImageAttributes class to setup a list of colors to remap when drawing takes place. The advantage of this is good performance as well as allowing you to alter the remapping colors very easily. Try something like this code...
ImageAttributes attribs = new ImageAttributes();
List<ColorMap> colorMaps = new List<ColorMap>();
//
// Remap black top be transparent
ColorMap remap = new ColorMap();
remap.OldColor = Color.Black;
remap.NewColor = Color.Transparent;
colorMaps.Add(remap);
//
// ...add additional remapping entries here...
//
attribs.SetRemapTable(colorMaps.ToArray(), ColorAdjustType.Bitmap);
context.Graphics.DrawImage(image, imageRect, 0, 0,
imageRect.Width, imageRect.Height,
GraphicsUnit.Pixel, attribs);
A: Construct a Bitmap from the Image, and then call MakeTransparent() on that Bitmap. It allows you to specify a colour that should be rendered as transparent.
A: Do you only know that it's an Image? If it's a Bitmap, you could call LockBits, check/fix every pixel and then unlock the bits again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: CruiseControl.NET view NUnit xml test result when Nant build file executes NUnit I have a Nant build file which executes NUnit after compiling the dll's. I am executing the NAnt build file with a task in CruiseControl. So NAnt is running the tests not CruiseControl.
How do I configure it so that the CruiseControl web dashboard can be used to view the NUnit output ?
This fixed it:
<publishers>
<merge>
<files>
<file>build\*.test-result.xml</file>
</files>
</merge>
<xmllogger />
</publishers>
A: You want to use the merge capabilities of CruiseControl to grab your NUnit XML output. This is the situation my company has going, and it seems to work fairly well. Here is a config snippet (This goes in the <publishers> element in CCNet.config):
<merge>
<files>
<file><path to XML output>\*.xml</file>
</files>
</merge>
Hope this works for you.
A: FWIW I had the same problem (CC.Net fires off Nant which does the compile and NUnit work) and my NUnit output was not appearing on CC.Net either. I already had the <merge> task inside my <publisher> task (and before the <xmllogger> task) and still nothing.
The one thing that I did not have, b/c I didn't explicitly need it, was a <workingDirectory> node in my <project>. As soon as I added that my NUnit output appeared immediately. Looks as if there's a dependency there for whatever reason. Hope this helps some of you.
A: Make sure that in the the dashboard.config file you have a valid xsl file in the section we run nunit with ncover and use this xsl\NCoverExplorer.xsl
I think that the xsl file we took from the ncover install somewhere.
also make sure that this line is correct:
Then make sure in the ccnet.config file that under the section you have the xml output from the nunit test listed.
Also make sure you put the xsl file in the xsl folder under webdashboard.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Fire Async method on page load with AJAX I am using ASP.NET 2.0 with AJAX Extensions (1.0?) and am wondering if it is possible to call a method asynchronously and have the results populate on the page after it has been loaded.
I have a gridview that is populated by a fairly long-running SQL query. I would prefer to have the page come up and the results trickle back in as they are returned from the server instead of forcing the user to stare at a blank page until everything is processed.
A: You can use an asp:UpdatePanel and insert the gridview in there. They just call the AJAX call during load. You use the Sys.Application.load event. Check it out here for more information: http://www.asp.net/ajax/documentation/live/overview/AJAXClientEvents.aspx
A: You can place a hidden button inside your updatepanel and do a PostBack to that button.
Is not an elegant solution but it works fine.
Inside your updatepanel you will write something like this.
<div style="visibility:hidden">
<asp:Button ID="btnLoad" OnClick="btnLoad_Click" runat="server"/>
</div>
On your Page_Load event you must register the script for the PostBack:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "InitialLoad" + this.ClientID, Page.ClientScript.GetPostBackEventReference(btnLoad, "")+";", true);
}
}
Then you can write the code that will be executed on startup in the btnLoad_Click method (OnClick event for the button).
I tried another approach using a AJAX Timer and disabling it on the first Tick but sometimes I receive more than one tick before the code behind is executed, so I discarded that solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Disable Intellisense in XAML Editor in VS2008? Is there a way to disable Intellisense in the XAML editor in Visual Studio 2008? It is often a big performance drain while typing, and sometimes I'll sit for ten or more seconds waiting while the list automatically popups up.
It appears that in Options->Text Editors->XAML, the Intellisense section is section is unavailable (grayed out). We open documents in Full XAML View, and don't use any third party enhancements.
It's so bad that sometimes I'll just open the file elsewhere and edit what I need, but I'd really like to get this solved so I don't have to use an external application.
A: Found my own answer:
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor\XAML\Auto List Members
Setting to 0x00000000 solves it.
The "Auto List Params" Key seems to have no effect. To top it off, you can still use <Ctrl+Space> to open it up on demand (for setting an attribute you can't think of the name of, etc.)
Pretty nifty!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: What does stdole.dll do? We have a large C# (.net 2.0) app which uses our own C++ COM component and a 3rd party fingerprint scanner library also accessed via COM. We ran into an issue where in production some events from the fingerprint library do not get fired into the C# app, although events from our own C++ COM component fired and were received just fine.
Using MSINFO32 to compare the loaded modules on a working system to those on a failing system we determined that this was caused by STDOLE.DLL not being in the GAC and hence not loaded into the faulty process.
Dragging this file into the GAC caused events to come back fine from the fingerprint COM library.
So what does stdole.dll do? It's 16k in size so it can't be much... is it some sort of link to another library like STDOLE32? How come its absence causes such odd behavior?
How do we distribute stdole.dll? This is an XCOPY deploy app and we don't use the GAC. Should we package it as a resource and use the System.EnterpriseServices.Internal.Publish.GacInstall to ensure it's in the GAC?
A: This issue is also discussed over here: Why is Visual Studio 2015 adding stdole.dll and Microsoft.AnalysisServices.AdomdClient.dll to my project?
Upgrading an older project to VS 2015 is what caused stdole.dll to start getting included in the project in this case.
If the library referencing has the option to "Embed Interop Types" in the properies, this is preferred and the stdole.dll may not be needed after that. Just set Embed Interop Types=true in the properties of the reference.
Libraries that allow this include the MS Office libraries such as Office, Excel, Core. An example of one that does not is Crystal Reports.
Hans Passant strongly discourages setting Embed Interop Types=false here: What's the difference setting Embed Interop Types true and false in Visual Studio?
A: I don't think any of the other answers actually answered most of the question "what does stdole.dll do". Here's my understanding.
Summary:
This DLL is near the top of a chain of references leading from your managed application ultimately to unmanaged operating system DLLs which looks like this:
.NET app -->
stdole.dll -->
stdole2.tlb -->
oleaut32.dll
The links in this chain are well defined but obscure. The rest of this answer walks the chain...
Detailed explanation:
stdole.dll itself is an interop DLL. That means that it is a .NET assembly whose purpose is to essentially act as a wrapper around specific unmanaged classes which have COM interfaces. If you look inside stdole.dll with a tool like ILSpy or dotPeek you can see what's there. Here's an example for the StdPicture interface:
using System.Runtime.InteropServices;
namespace stdole
{
[CoClass(typeof (StdPictureClass))]
[Guid("7BF80981-BF32-101A-8BBB-00AA00300CAB")]
[ComImport]
public interface StdPicture : Picture
{
}
}
All this is is an interface with attributes that encode details of the COM classes that really should be used. DLLs like this are generally created automatically with a tool like tlbimp.exe or Visual Studio will do this for you when you add an unmanaged COM DLL directly to your project as a reference.
We can dig a little deeper. A Guid in the example above 7BF80981-BF32-101A-8BBB-00AA00300CAB is generally going to be found in the Windows registry, that's where the runtime is going to look when stole.StdPicture is actually used from managed code.
If you search for that GUID using RegEdit, you'll find:
Computer\HKEY_CLASSES_ROOT\Interface\{7BF80981-BF32-101A-8BBB-00AA00300CAB}\TypeLib
which has the value 00020430-0000-0000-C000-000000000046.
Searching for that value, you'll find:
Computer\HKEY_CLASSES_ROOT\TypeLib\{00020430-0000-0000-C000-000000000046}
(Most of the other GUIDs from the same DLL would probably have a similar entry).
This key has a lot of interesting details, in fact details for several versions of the underlying implementation. For instance under subkey 2.0\0\win32 the default value is:
C:\WINDOWS\SysWow64\stdole2.tlb
for the 32-bit variant of version 2. That's one step closer to where StdPicture actually is implemented.
A TLB file is just a COM "header" of sorts for a DLL. It doesn't have executable code in itself. Opening stdole2.tlb in a tool like OLEViewDotNet or the original OleView, you can read the IDL of the typelib itself. In this case, the first part has the following:
// typelib filename: stdole2.tlb
[
uuid(00020430-0000-0000-C000-000000000046),
version(2.0),
helpstring("OLE Automation")
]
library stdole
{
...
}
Note the uuid has the same value we got from Regedit above. Scrolling down eventually we come to the StdPicture entry, the same example as above:
[
uuid(0BE35204-8F91-11CE-9DE3-00AA004BB851)
]
coclass StdPicture {
...
};
Yet again there's no real code here, just a class definition. Back to RegEdit we can find that uuid:
Computer\HKEY_CLASSES_ROOT\CLSID\{0BE35204-8F91-11CE-9DE3-00AA004BB851}\InprocServer32
whose value is C:\Windows\System32\oleaut32.dll. Now we know that this DLL implements the StdPicture coclass for version 2 of the 32-bit stdole library.
(Though I would have thought this file should be in SysWow64...?)
If you were to follow this chain for some other interface, you might end up at the same DLL or another.
Note that for some languages (like VB6) it is typical for the TLB to be embedded right in the implementing DLL directly. But this is not required for COM and obviously not how Microsoft did it in this case.
A: I had the same problem. I just deleted the reference from the application and recompiled. Ran all the tests which passed. Then redeployed without the dll and it all worked.
I dont know how a reference to this got in the project in the first place. It is a legacy app so must have been a long time ago.
Simon
A: It seems that stdole.dll is a primary interop assembly. See Office 2003 Primary Interop Assemblies on MSDN.
A: In my case, it was an old unused reference to Office Word Interop ... but removing that was not sufficient: The publish profile still had line to copy stdole.dll !
<File Include="bin/stdole.dll"> ...
Deleting that line (found using 'Find in Files') and deleting the stdole.dll from the bin folder on the remote server fixed my problem.
Hope this helps someone else.
A: I had to also add a reference to my project for stdole. Even though I don't have any references to it (it's a simple image app), 2 of our users were getting errors that it was missing. It could be that they were only running .net 2.0 when this is a 3.5 app. I have figured out why.
I also went in to publish on the project properties tab, and selected Application Files, then included the stdole to be deployed. Hopefully that will work.
A: In our project IDispatch couses using stdole.dll. We've change it to object and remove IDispatch, then remove stdole from references.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "46"
} |
Q: New site creation and security/authentication,- should I use ASP.net Membership Provider? There seem to many ways to skin this particular cat - but which is the best and easiest to implement. It would seem that the ASP.net Membership Provider is the one that will save more time, so my questions are:
*
*What are the pros/cons of Membership?
*How do you integrate the auto generated user db with your own custom made db? e.g customers/orders/products db. (We are talking MS Sql here BTW)
*Where can I find a good tutorial thats up do date?
Many thanks.
A: Membership is lightweight and easy to set up. You can also use the various providers to use Active Directory or some other member location.
You shouldn't need to integrate the databases, you can use one to authenticate users and then as long as they are valid, go query another database for the data. This is a good way to keep information seperate for security reasons.
For a good tutorial, I'd suggest: http://msdn.microsoft.com/en-us/library/yh26yfzy.aspx
And if you want to create your own membership provider: http://www.asp.net/learn/videos/video-189.aspx
A: Overall I give it a thumbs up, but there are several minor cons I can think of:
*
*Roles are just strings, there's no way to attach additional information to them without rolling your own code.
*Some of the Login controls don't set their default button properly, so hitting the "enter" key while in an input field does nothing. You can fix this by setting it yourself.
*No default way to require numbers in a password, just symbols.
*Login controls w/ SqlMembershipProvider don't display specific "user is locked out" messages.
Either a con or a pro, depends on your point of view:
*
*User names are case-insensitive in the SqlMembershipProvider
A: Tutorials - there are a series of good tutorials on the ASP.Net site. We have used the membership provider facilities, and have it integrated with our database - we use the "user name" value as a foreign key to our own tables with additional "business" information.
The system works well with minimal coding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Merge two arrays as key value pairs in PHP I've got two arrays of the same size. I'd like to merge the two so the values of one are the key indexes of the new array, and the values of the new array are the values of the other.
Right now I'm just looping through the arrays and creating the new array manually, but I have a feeling there is a much more elegant way to go about this. I don't see any array functions for this purpose, but maybe I missed something? Is there a simple way to this along these lines?
$mapped_array = mapkeys($array_with_keys, $array_with_values);
A: See array_combine() on PHP.net.
A: This should do the trick
function array_merge_keys($ray1, $ray2) {
$keys = array_merge(array_keys($ray1), array_keys($ray2));
$vals = array_merge($ray1, $ray2);
return array_combine($keys, $vals);
}
A: (from the docs for easy reading)
array_combine — Creates an array by using one array for keys and another for its values
Description
array array_combine ( array $keys , array $values )
Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.
Parameters
keys - Array of keys to be used. Illegal values for key will be converted to string.
values - Array of values to be used
Example
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
print_r($c);
?>
The above example will output:
Array
(
[green] => avocado
[red] => apple
[yellow] => banana
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
} |
Q: Unknown Outlook MailItem EntryID My Outlook add-in handles NewInspector event of the Inspector object, in order to display a custom form for the mail item.
I can get EntryID of the CurrentItem of the Inspector object which is passed as a parameter of the event. But, the problem is that the EntryID of the current mail item is shorter than it should be, and is unknown. I know every EntryID of every mail item that was created, and I can see that specific mail item has a wrong EntryID.
What is wrong?
A: The idea is to remember every EntryID of the MailItem that was created by an add-in, so that it can be treated differently later. Problem was that EntryID of the item opened by an Inspector was the short one, and not in the list of remembered ids, although it should be.
Few lines of code where I was creating mail item were:
item.Save();
item.Move(some_folder);
items_list.Add(item.EntryID);
Folder 'some_folder' is inside of external non-default PST, so mail item gets new EntryID. I changed those lines to:
item.Save();
item = (Outlook.MailItem)item.Move(some_folder);
items_list.Add(item.EntryID);
Now, item has a new EntryID, which can be found later.
A: Just in case this helps anyone, all I needed to do is to call MailItem.Save() before fetching EntryID. A newly created MailItem doesn't have any EntryID till it is saved (in Drafts folder in my case).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Are there any viable alternatives to the GOF Singleton Pattern? Let's face it. The Singleton Pattern is highly controversial topic with hordes programmers on both sides of the fence. There are those who feel like the Singleton is nothing more then a glorified global variable, and others who swear by pattern and use it incessantly. I don't want the Singleton Controversy to lie at the heart of my question, however. Everyone can have a tug-of-war and battle it out and see who wins for all I care. What I'm trying to say is, I don't believe there is a single correct answer and I'm not intentionally trying inflame partisan bickering. I am simply interested in singleton-alternatives when I ask the question:
Are their any specific alternatives to the GOF Singleton Pattern?
For example, many times when I have used the singleton pattern in the past, I am simply interested in preserving the state/values of one or several variables. The state/values of variables, however, can be preserved between each instantiation of the class using static variables instead of using the singleton pattern.
What other idea's do you have?
EDIT: I don't really want this to be another post about "how to use the singleton correctly." Again, I'm looking for ways to avoid it. For fun, ok? I guess I'm asking a purely academic question in your best movie trailer voice, "In a parallel universe where there is no singleton, what could we do?"
A: To understand the proper way to workaround Singletons, you need to understand what is wrong with Singletons (and global state in general):
Singletons hide dependencies.
Why is that important?
Because If you hide the dependencies you tend to lose track of the amount of coupling.
You might argue that
void purchaseLaptop(String creditCardNumber, int price){
CreditCardProcessor.getInstance().debit(creditCardNumber, amount);
Cart.getInstance().addLaptop();
}
is simpler than
void purchaseLaptop(CreditCardProcessor creditCardProcessor, Cart cart,
String creditCardNumber, int price){
creditCardProcessor.debit(creditCardNumber, amount);
cart.addLaptop();
}
but at least the second API makes it clear exactly what the method's collaborators are.
So the way to workaround Singletons is not to use static variables or service-locators, but to change the Singleton-classes into instances, which are instantiated in the scope where they make sense and injected into the components and methods that need them. You might use a IoC-framework to handle this, or you might do it manually, but the important thing is to get rid of your global state and make the dependencies and collaborations explicit.
A: You shouldn't have to go out of your way to avoid any pattern. The use of a pattern is either a design decision or a natural fit (it just falls into place). When you are designing a system, you have a choice to either use a pattern or not use the pattern. However, you shouldn't go out of your way to avoid anything that is ultimately a design choice.
I don't avoid the Singleton Pattern. Either it's appropriate and I use it or it's not appropriate and I don't use it. I believe that it is as simple as that.
The appropriateness (or lack thereof) of the Singleton depends on the situation. It's a design decision that must be made and the consequences of that decision must be understood (and documented).
A: Spring or any other IoC-Container does a reasonably good job in that. Since the classes are created and managed outside the app itself, the container can make simple classes singletons and inject them where needed.
A: Alex Miller in "Patterns I Hate" quotes the following:
"When a singleton seems like the answer, I find it is often wiser to:
*
*Create an interface and a default implementation of your singleton
*Construct a single instance of your default implementation at the “top” of your system. This might be in a Spring config, or in code, or defined in a variety of ways depending on your system.
*Pass the single instance into each component that needs it (dependency injection)
A: Monostate (described in Robert C. Martin's Agile Software Development) is an alternative to singleton. In this pattern the class's data are all static but the getters/setters are non-static.
For example:
public class MonoStateExample
{
private static int x;
public int getX()
{
return x;
}
public void setX(int xVal)
{
x = xVal;
}
}
public class MonoDriver
{
public static void main(String args[])
{
MonoStateExample m1 = new MonoStateExample();
m1.setX(10);
MonoStateExample m2 = new MonoStateExample();
if(m1.getX() == m2.getX())
{
//singleton behavior
}
}
}
Monostate has similar behavior to singleton but does so in a way where the programmer is not necessarily aware of the fact that a singleton is being used.
A: The singleton pattern exists because there are situations when a single object is needed to provide a set of services.
Even if this is the case I still consider the approach of creating singletons by using a global static field/property representing the instance, inappropriate. It's inappropriate because it create a dependency in the code between the static field and the object not, the services the object provides.
So instead of the classic, singleton pattern, I recommend to use the service 'like' pattern with serviced containers, where instead of using your singleton through a static field, you obtain a reference to it through a a method requesting the type of service required.
*pseudocode* currentContainer.GetServiceByObjectType(singletonType)
//Under the covers the object might be a singleton, but this is hidden to the consumer.
instead of single global
*pseudocode* singletonType.Instance
This way when you want to change type of an object from singleton to something else, you'll have and easy time doing it. Also as an and added benefit you don't have to pass around allot of object instances to every method.
Also see Inversion of Control, the idea is that by exposing singletons directly to the consumer, you create a dependency between the consumer and the object instance, not the object services provided by the object.
My opinion is to hide the use of the singleton pattern whenever possible, because it is not always possible to avoid it, or desirable.
A: If you're using a Singleton to represent a single data object, you could instead pass a data object around as a method parameter.
(although, I would argue this is the wrong way to use a Singleton in the first place)
A: The finest solution I have came across is using the factory pattern to construct instances of your classes. Using the pattern, you can assure that there is only one instance of a class that is shared among the objects that use it.
I though it would be complicated to manage, but after reading this blog post "Where Have All the Singletons Gone?", it seems so natural. And as an aside, it helps a lot with isolating your unit tests.
In summary, what you need to do? Whenever an object depends on another, it will receive an instance of it only through its constructor (no new keyword in your class).
class NeedyClass {
private ExSingletonClass exSingleton;
public NeedyClass(ExSingletonClass exSingleton){
this.exSingleton = exSingleton;
}
// Here goes some code that uses the exSingleton object
}
And then, the factory.
class FactoryOfNeedy {
private ExSingletonClass exSingleton;
public FactoryOfNeedy() {
this.exSingleton = new ExSingletonClass();
}
public NeedyClass buildNeedy() {
return new NeedyClass(this.exSingleton);
}
}
As you will instantiate your factory only once, there will be a single instantiation of exSingleton. Every time you call buildNeedy, the new instance of NeedyClass will be bundled with exSingleton.
I hope this helps. Please point out any mistakes.
A: If your issue is that you want to keep state, you want a MumbleManager class. Before you start working with a system, your client creates a MumbleManager, where Mumble is the name of the system. State is retained through that. Chances are your MumbleManager will contain a property bag which holds your state.
This type of style feels very C-like and not very object like - you'll find that objects that define your system will all have a reference to the same MumbleManager.
A: Use a plain object and a factory object. The factory is responsible for policing the instance and the plain object details only with the configuration information (it contains for example) and behaviour.
A: Actually if you design right from scratch on avoiding Singeltons, you may not have to work around not using Singletons by using static variables. When using static variables, you are also creating a Singleton more or less, the only difference is you are creating different object instances, however internally they all behave as if they were using a Singleton.
Can you maybe give a detailed example where you use a Singleton or where a Singleton is currently used and you are trying to avoid using it? This could help people to find a more fancy solution how the situation could be handled without a Singleton at all.
BTW, I personally have no problems with Singletons and I can't understand the problems other people have regarding Singletons. I see nothing bad about them. That is, if you are not abusing them. Every useful technique can be abused and if being abused, it will lead to negative results. Another technique that is commonly misused is inheritance. Still nobody would say inheritance is something bad just because some people horribly abuse it.
A: Personally for me а much more sensible way to implement something that behaves like singleton is to use fully static class(static members , static methods , static properties).
Most of the time I implement it in this way (I can not think of any behaviour differences from user point of view)
A: I think the best place to police the singleton is at the class design level. At this stage, you should be able to map out the interactions between classes and see if something absolutely, definitely requires that only 1 instance of this class is ever in existence at any time of the applications life.
If that is the case, then you have a singleton. If you are throwing singletons in as a convenience during coding then you should really be revisiting your design and also stop coding said singletons :)
And yes, 'police' is the word I meant here rather than 'avoid'. The singleton isn't something to be avoided (in the same way that goto and global variables aren't something to be avoided). Instead, you should be monitoring it's use and ensuring that it is the best method to get what you want done effectively.
A: I use singleton mostly as "methods container", with no state at all. If I need to share these methods with many classes and want to avoid the burden of instantiation and initialization I create a context/session and initialize all the classes there; everything which refers to the session has also access to the "singleton" thereby contained.
A: Having not programmed in an intensely object-oriented environment (e.g. Java), I'm not completely up on the intricacies of the discussion. But I have implemented a singleton in PHP 4. I did it as a way of creating a 'black-box' database handler that automatically initialized and didn't have to be passed up and down function calls in an incomplete and somewhat broken framework.
Having read some links of singleton patterns, I'm not completely sure I would implement it in quite the same way again. What was really needed was multiple objects with shared storage (e.g. the actual database handle) and this is pretty much what my call turned into.
Like most patterns and algorithms, using a singleton 'just because it's cool' is The Wrong Thing To Do. I needed a truly 'black-box' call that happened to look a lot like a singleton. And IMO that's the way to tackle the question: be aware of the pattern, but also look at it's wider scope and at what level it's instance needs to be unique.
A: What do you mean, what are my techniques to avoid it?
To "avoid" it, that implies that there are many situations that I come across in which the singleton pattern is a naturally good fit, and hence that I have to take some measures to defuse these situations.
But there are not. I don't have to avoid the singleton pattern. It simply doesn't arise.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "94"
} |
Q: How do you insert email headers with a Thunderbird extension? I'm building a Thunderbird extension and would like to add my own header to all outgoing email (e.g. <myext-version: 1.0> ). Any idea how to do this? I know it's possible since this is done in the OpenPGP Enigmail extension. Thanks!
A: Here is the code from one extension I'm working on:
function SendObserver() {
this.register();
}
SendObserver.prototype = {
observe: function(subject, topic, data) {
/* thunderbird sends a notification even when it's only saving the message as a draft.
* We examine the caller chain to check for valid send notifications
*/
var f = this.observe;
while (f) {
if(/Save/.test(f.name)) {
print("Ignoring send notification because we're probably autosaving or saving as a draft/template");
return;
}
f = f.caller;
}
// add your headers here, separated by \r\n
subject.gMsgCompose.compFields.otherRandomHeaders += "x-test: test\r\n";
}
},
register: function() {
var observerService = Components.classes["@mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
observerService.addObserver(this, "mail:composeOnSend", false);
},
unregister: function() {
var observerService = Components.classes["@mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
observerService.removeObserver(this, "mail:composeOnSend");
}
};
/*
* Register observer for send events. Check for event target to ensure that the
* compose window is loaded/unloaded (and not the content of the editor).
*
* Unregister to prevent memory leaks (as per MDC documentation).
*/
var sendObserver;
window.addEventListener('load', function (e) {if (e.target == document) sendObserver = new SendObserver(); }, true);
window.addEventListener('unload', function (e) { if (e.target == document) sendObserver.unregister();}, true);
Put this inside a .js file that is loaded by the compose window (for example by overlaying chrome://messenger/content/messengercompose/messengercompose.xul).
The check in SendObserver.observe was necessary in my case because I wanted to do a user interaction, but you could probably leave it out.
A: I don't know the answer but just some thoughts...
I think thunderbird extensions are usually just xul and js. From the enigmail site:
Unlike most Mozilla AddOns, Enigmail
contains platform dependent parts: it
depends on the CPU, the compiler,
libraries of the operating system and
the email application it shall
integrate into.
Looking at the Enigmail source code, this might be the relevant section (written in c++)
So you might need to either translate what they've done into js(!) or keep looking for a different example.
Here's another link that might be helpful
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Adjusting the auto-complete dropdown width on a textbox I am using a textbox in a .NET 2 winforms app that is setup with a custom AutoCompleteSource. Is there anyway through code that I can increase the width of the list that appears containing the auto complete suggestions?
Ideally I would like to do this without increasing the width of the textbox as I am short for space in the UI.
A: Not that I know of, but you can auto-size the Textbox so that it is only wide when it needs to be, rather than always as wide as the longest text.
Example from http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3311429&SiteID=1
Public Class Form1
Private WithEvents T As TextBox
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
T = New TextBox
T.SetBounds(20, 20, 100, 30)
T.Font = New Font("Arial", 12, FontStyle.Regular)
T.Multiline = True
T.Text = "Type Here"
T.SelectAll()
Controls.Add(T)
End Sub
Private Sub T_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles T.TextChanged
Dim Width As Integer = TextRenderer.MeasureText(T.Text, T.Font).Width + 10
Dim Height As Integer = TextRenderer.MeasureText(T.Text, T.Font).Height + 10
T.Width = Width
T.Height = Height
End Sub
End Class
A: Hmmm, there's no direct way really. You'd probably have to resort to subclassing (in the Windows API sense) the TextBox to do that, and even then there'd be a lot of guessing to do.
A: As far as I know the TextBox class wraps the complete AutoComplete API that comes with Windows. Alas, this fact is not "portable" to other parts of the .NET framework.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to merge jsp pre-compiled web.xml fragment with main web.xml using Ant We have the usual web.xml for our web application which includes some jsp and jsp tag files. I want to switch to using pre-compiled jsp's. I have the pre-compilation happening in the build ok, and it generates the web.xml fragment and now I want to merge the fragment into the main web.xml.
Is there an include type directive for web.xml that will let me include the fragment.
Ideally I will leave things as is for DEV- as its useful to change jsp's on the fly and see the changes immediately but then for UAT/PROD, the jsp's will be pre-compiled and thus work faster.
A: Doh - there is an option on the jasper2 task to auto-merge the fragment into the main web.xml - addWebXmlMappings
<jasper2
validateXml="false"
uriroot="${web.dir}"
addWebXmlMappings="true"
webXmlFragment="${web.dir}/WEB-INF/classes/jasper_generated_web.xml"
outputDir="${web.dir}/WEB-INF/jsp-src" />
I wonder how good the merge is...
Annoyingly you need to generate the fragment still, even though its not needed after this task.
A: I use the Tomcat jasper ANT tasks in my project, which precompile the JSPs into servlets and add the new servlet mappings to the original web.xml. In the DEV builds, just skip this step and deploy the JSPs without pre-compile and modification of the web.xml.
<?xml version="1.0"?>
<project name="jspc" basedir="." default="all">
<import file="${build.appserver.home}/bin/catalina-tasks.xml"/>
<target name="all" depends="jspc,compile"></target>
<target name="jspc">
<jasper
validateXml="false"
uriroot="${build.war.dir}"
webXmlFragment="${build.war.dir}/WEB-INF/generated_web.xml"
addWebXmlMappings="true"
outputDir="${build.src.dir}" />
</target>
<target name="compile">
<javac destdir="${build.dir}/classes"
srcdir="${build.src.dir}"
optimize="on"
debug="off"
failonerror="true"
source="1.5"
target="1.5"
excludes="**/*.smap">
<classpath>
<fileset dir="${build.war.dir}/WEB-INF/classes">
<include name="*.class" />
</fileset>
<fileset dir="${build.war.lib.dir}">
<include name="*.jar" />
</fileset>
<fileset dir="${build.appserver.home}/lib">
<include name="*.jar" />
</fileset>
<fileset dir="${build.appserver.home}/bin">
<include name="*.jar"/>
</fileset>
</classpath>
<include name="**" />
<exclude name="tags/**"/>
</javac>
</target>
<target name="clean">
<delete>
<fileset dir="${build.src.dir}"/>
<fileset dir="${build.dir}/classes/org/apache/jsp"/>
</delete>
</target>
</project>
If you already have the JSP compilation working and just want to merge the web.xml files, a simple XSLT could be written to add selected elements(such as the servlet mappings) from the newly generated web,xml into your original.
A: Because the generated fragment is not a valid XML file ( it's a fragment after all ), it is not possible to use XSLT directly. On the other hand you don't have to. Here is a simple trick that will give you exactly what you need.
In your web.xml file insert XML comment <!-- @JSPS_MAP@ --> between <servlet> and <servlet-mapping> elements, e.g.
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>my.servlets.MyServlet</servlet-class>
<servlet>
<!-- @JSPS_MAP@ -->
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/my-servlet</url-pattern>
</servlet-mapping>
Then use a token filter to replace @JSPS_MAP@ tag with generated content.
<loadfile
property="generated.web.xml.fragment"
srcFile="${generated.fragment.file}"
/>
<copy file="${orig-web-content.dir}/WEB-INF/web.xml"
toFile="${generated-web-content.dir}/WEB-INF/web.xml"
>
<filterset>
<filter token="JSPS_MAP"
value=" --> ${generated.web.xml.fragment} <!-- "
/>
</filterset>
</copy>
This approach has an advantage that the original web.xml file is completely valid (a tag is hidden in the comment), but gives you total control of where and when the generated fragment will be inserted.
So for DEV build, just copy ${orig-web-content.dir}/WEB-INF/web.xml to ${generated-web-content.dir}/WEB-INF/web.xml without filtering.
A: There is the jasper2 ant task others have noted. I thought I'd mention a couple of other options I've found.
One is cactus' webxmlmerge ant task, which uses org.codehaus.cargo.module.webapp.WebXmlMerger
Another would be to use JAXB to manipulate the web.xml; Sebastien Dionne's dtd-schemas-generator demo does this. Not sure what the license is though.
fwiw having considered these options i think I'm going to use the ant XSLT task.
A: In your web.xml file if you have tags to specify where the merge starts and ends the addWebXmlMappings flag will generate the file correctly for you. The tags are:
<!-- JSPC servlet mappings start -->
and
<!-- JSPC servlet mappings end -->
after doing this to my web.xml everything worked like a charm! (I have to look at the code for org.apcahe.jasper.JspC to see how this was implemented)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: web.xml and relative paths in web.xml i set my welcome file to a jsp within web.xml
<welcome-file>WEB-INF/index.jsp</welcome-file>
inside index.jsp i then forward on to a servlet
<% response.sendRedirect(response.encodeRedirectURL("myServlet/")); %>
however the application tries to find the servlet at the following path
applicationName/WEB-INF/myServlet
the problem is that web-inf should not be in the path. If i move index.jsp out of web-inf then the problem goes but is there another way i can get around this?
A: As I understand it, WEB-INF is a special folder containing configuration and classes used by your JSPs, you shouldn't put code intended for direct serving inside it.
Anyhow, have you tried /myServlet?
A: <% response.sendRedirect(response.encodeRedirectURL("/myServlet/")); %>`
since the jsp is served from the WEB-INF directory the servlet url is also resolved from that relative path. adding a / before will resolve the url from the context root
A: Have you tried to do it with the absolute path ?
response.sendRedirect(response.encodeRedirectURL("/myServlet/"));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does ActiveRecord's serialize randomly corrupt my data? I use serialize in one ActiveRecord model to serialize an Array of simple Hashes into a text database field. I even use the second parameter to coerce deserialization into Arrays.
class Shop < ActiveRecord::Base
serialize : recipients, Array
end
It seems to work fine but, after a few requests, the content of recipients turns to HashOfIndifferentAccess hashes instead of arrays. This only happens after a few reloads of the models and I haven't been able to reproduce it in tests or the console, only in production environment.
A: I had the same problem with some serialized fields in one of my Rails 3.1 apps. After a lot of troubleshooting I narrowed it down to a character encoding issue. I wasn't able to reproduce it locally because I was using SQLite, while my production environment was on Postgres.
Try applying some_field.force_encoding(Encoding::UTF_8) on all values before they are serialized and see what happens.
A: This seems like something you should be able to reproduce locally with enough testing.
Look through your production db and logs and attempt to use the same data in your local tests.
The hashwithindifferentaccess is coming from the controller. Perhaps you are taking data straight from the controller and not massaging it at all.
Create a gist of your page, controller, and model saving code, and update this question.
Depending on how deeply nested your hash, you can convert a HWIA hash to a regular one before saving.
Shouldn't be too hard to debug and resolve.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Best Way To Get Started With Mac Development I just recently got my first mac. I do lots of programming on windows but now I want to get into Mac development. What are some languages i should know or tools i should use to get started with mac development?
A: For desktop apps, cocoa+objective-c are the way to go. XCode is the best editor for that. For webapps, I'd check out Ruby on Rails and Textmate.
If you've done Java development, you can keep on doing that, too. Eclipse will be very familiar.
A: I've joined the Mac Developer Network, and subscribe to the many podcasts there. Not a reference mind, you just a place to keep you motivated on your journey.
A: I second hunterjrj's suggestion of Aaron Hillegass's book.
Another book that I'm reading at the moment which is a good tour of Xcode 3 is Fritz Anderson's Xcode 3 Unleashed.
Apple's development website also has lots of programming guides and video. Sign up at developer.apple.com. If you have an apple.com account already (or iTunes) it is easy to extend that to a developer membership. Note that you don't get all the developer info unless you pay for a full ADC membership. But all the API docs and programming guides are available without paying.
A: Cocoa(R) Programming for Mac(R) OS X (3rd Edition) by Aaron Hillegass:
Fantastic book and the author has alot of credibility - Apple brought him in to train their developers on Cocoa.
A: Check out Apple's Mac Dev Center
A: Are you coming from a Windows environment? If you do I would recommend Mono which is a .Net free implementation or Java, both platforms work well in windows/osx/linux
If you just want to target OSX then Cocoa/Objective-C/XCode is the way to go but im not quite sure how many documentation or examples you will find since there seems to be only one big provider for development tools for OSX and that is Apple itself compared to the myriad of development tools you might find developing for Windows.
Of course there are many other alternatives, remember OSX is a Unix operative system, you could easily develop with Python/Perl/Ruby and many other scripting languages and development technologies just be sure to know what platforms are you going to target.
A: If you have Windows experience but also want to develop Mac software you might consider looking into REALbasic. It doesn't give you complete access to the Mac OS X Cocoa framework, but it can be used to make some slick Mac apps. And it's really easy to get started with.
A: You could try combining f-script and traditional Cocoa (xcode in other words). f-script is great when you want to experiment with the Cocoa API, which is surely different from what you are used to. The more dynamic you stay, the faster you learn. That is my experience.
A: Cocoa is definitely the way to go. If you don't want to pay for a book these websites will help you out:
http://cocoadevcentral.com/
http://cocoadev.com/
http://oreilly.com/pub/ct/37
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: What's the best way to create an etag? What's a good method of programatically generating etag for web pages, and is this practice recommended? Some sites recommend turning etags off, others recommend producing them manually, and some recommend leaving the default settings active - what's the best way here?
A: I recommend generating a hash of the the content, e.g. md5($content).
Additionally, to prevent hash collision, you might want to add e.g. the ID of the content element to it (if this is appropriate).
A: Well ETags make sense when you rely heavily on caching. They are a great indicator for the state of a resource (e.g. a URL).
For example, let's say you use an ajax request to pull the latest comments of a user and you want to know if there are any new comments. Changing the ETag to alert your application of new content is a less expensive way to check on that.
Because if the ETag is the same, you can keep your cache, but otherwise rebuild it.
ETags also make a lot of sense with RESTful APIs.
As for generating it, looking at the spec, I think you can do almost anything you want. A timestamp, a hash, whatever makes sense to you/your application.
A: I just fired up YSlow and it complained about Etags, so I did a little research. The issue, as per the Yahoo blog (see the comments too)is that the default ETags implementations uses the file inode number or ntfs revision number or soemthing else equally server specific as a part of the hash. This, while being fast, basically prevents the same file being served by 2 different servers from having the same etag and screws up both browsers and downstream caches or load balances.
The previous suggestion to use an MD5 Hash is a good one, although you have to prevent that from becoming a performance problem in and of itself. The implementation of that suggestions remains up to the reader, although off-hand it seems to me like this is the sort of thing that your framework might be able to handle for you.
For myself, since I'm in a simple environment where the file timestamp will be more than adequate, I just turned them off in Apache using FileETag none in my .htaccess file. This shuts up YSlow and should make things fall back to the last modified date on the file.
A: Generally, the "sites" that discourage their use is Yahoo, and that's because some default web servers do not automatically create ETAGs that work in server farms. (Which is correct and accurate of Yahoo to claim.)
But, if you have a single web server, than you're fine. If not, you'll want to check up on how your web server handles this and act appropriately.
A: Mufasa,
Yahoo (and YSlow) actually encourage their use, but with the caveat that auto-generated ETags will differ from server to server.
I can't yet vote so I'll just say I agree with the suggestion of a hash of the file path and timestamp (or the table name + primary field value + timestamp if being represented by db content).
A: ETags do help when you use some kind of caching mechanism in front of your website-generator. Browsers themselves do not use them, they listen to "(if) modified since" or "age" header structs, afaik.
Anyway, due to its simple nature it is no problem to provide a http-header with an ETag. I heard that many web servers simply take the location of the file and the timestamp of the file and do a md5-hash over this data.
We, as an example, built a simple but effective etag with our software. Every "content unit" (i.e. html, jpegs, gifs...) in our software has a unique id and a version number (i.e. a jpeg has the id "17" and version "2", this means it was changed once). So the ETag simply is the string "id-version", here: "17-2". With the next change it would be "17-3" so that the cacher recognizes the change, loads the new content part (once) completely and stores it in it's own cache.
But you could probably use the URL and a timestamp (i.e. the timestamp of the file), too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: Events in C# Just how much slower are events? I have written a streaming XML parser (that can handle open-ended and incomplete documents) and by tearing out the events and using an interface instead I got a significant speed boost.
Does any one else have any war stories?
(Let's not open the GC can of worms here, we all know it's broken :))
A: Events are really just delegates. From what I recall, they were made much faster in the 2.0 CLR. I'm surprised that replacing events with an interface made your code significantly faster - in my experience they're pretty fast, and if you're dealing with XML, I wouldn't have expected the event calls to be the bottlenecks.
Did your code constantly subscribe to and unsubscribe from events? Do you have any indication of the number of event calls that were made when parsing a particular document?
A: Events firing are delegate invocations, which are a a bit slower than virtual calls
(source: microsoft.com)
But dealing with interfaces for subscriber/publisher/observer/observable scenario is more painful that using events.
A: Events are definately slower than a straight function call, i can't tell you exactly how much slower, but significantly. You could also pass delegates around for "middle" ground. The .NET event system uses delegates, but calling a method directly through the delegate vs the whole event system is still faster.
A: Delegates have a slight overhead compared to virtual method calls because they're lists of methods and can therefore theoretically invoke multiple handlers.
A: If there's no reflection involved in the calls then I assume the overhead is pretty negligible. Assumption could be wrong of course . Do you have a micro benchmark to demonstrate this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Sorting sets of ordered linked lists I'm looking for an elegant, high performance solution to the following problem.
There are 256 linked lists.
*
*Each list contains the same types of object that among other things holds a whole number that is used to define a sort order.
*All numbers across all lists are unique
*Each individual list is sorted in ascending order by these numbers
How would you create a single ascending ordered list from all the objects from the 256 original linked lists? I'd prefer not to brute force it, and have a few other ideas, but this seems like one of those problems that there's a standard, optimal solution for.
A: You could use a priority queue that holds the “topmost” item of each of the 256 linked lists. This “topmost” item is the one that is scheduled to be inserted into the resulting list. This way, you can just take the smallest element from the priority queue, insert it into your resulting queue, and insert its next element into the priority queue:
# Preprocessing:
result = list.new()
queue = priority_queue.new()
foreach (list in lists):
queue.push(list.first())
# Main loop:
while (not queue.empty()):
node = queue.pop()
result.insert(node)
if (node.next() != null):
queue.push(node.next())
A: if the individual lists are already sorted, then it's a direct application of the merge algorithm. in short: compare all the heads and pick the smallest, take it out of its list and push into your output list. repeat until all source lists are empty.
edit: Konrad's use of a priority queue (a heap) is a far more elegant and scalable solution, but maybe 256 input lists are so few that a simple compare could be faster.
A: Just merge each list with the list 128 above it. (resulting in 128 lists)
Then merge each list with the list 64 above it. (resulting in 64 lists)
Then merge each list with the list 32 above it. (resulting in 32 lists)
Then merge each list with the list 16 above it. (resulting in 16 lists)
Then merge each list with the list 8 above it. (resulting in 8 lists)
Then merge each list with the list 4 above it. (resulting in 4 lists)
Then merge each list with the list 2 above it. (resulting in 2 lists)
Then merge each list with the list 1 above it. (resulting in 1 list)
(You might use a loop for the above).
A: You don't say how long these lists are, but I assume they all fit in RAM at the same time. The first thing I would try is appending them all together, and calling my environment's builtin sort routine, and I'd see if that gave acceptable performance. It's easy to implement and wouldn't take long to test. If that didn't give acceptable performance, I'd go with the priority queue merge given by Konrad Rudolph.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: XMLTextReader in .NET 1.1 I have a process that reads an XML file. It uses the XMLTextReader class to do this as it is supposed to be a fast, forward only XML parser/reader.
Works just great with a 1 megabyte test file but comes to a complete halt when working on a 12 meg file in the live system.
Are there any solutions to this other than writing my own XML reader? That's not the end of the world but I would prefer to use available standard components if possible
A: SAXExpat used to be really good. Expat is the XML parser, almost a reference implementation. I remember using it to read some synchronization XML files sent over a TCP connection, sometimes really big files (around 50mb) without any kind of problem. And that was 3/4 years ago, in .NET 1.1 and really crappy computers.
A: I would be very surprised if the problem were in the XmlTextReader.
If you spend a few minutes to write a test program that creates an XmlTextReader and simply uses Read() to read through each node in the file until it gets to the end of the document, I bet you'll find that it zooms through your 12mb file like a hot knife through butter. That's the first thing I'd try if I were experiencing this problem.
Because once you've eliminated XmlTextReader as the source of the problem, you can focus your attention on what's actually causing it - which is, very probably, the code that processes the nodes that you're reading, not the code that reads the nodes.
A: I have had similar performance issues in the past. I traced it back to trying to remotely resolve against a DTD/schema. Are you doing this? Try setting XmlTextReader.XmlResolver to null if possible.
A: Depends what you do with what you get out of the reader. Are you putting it in an XML DOM, or any object model for that matter? That would make a big memory hit not matter what language or library you use.
Maybe it is flawed in 1.1, thought about trying out 2.0? I never used the XmlTextReader in my 1.1 days, so I can't vouch for it: but since 2.0 it is perfect.
A: Just one thought. Are you opening a database transaction for the length of the entire process? If so try it without the transaction or at least commit more often during the process.
A: I hate to recommend this, but if the software isn't sold or external, you could try bringing in the reader from Mono and see if that fixes your woes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Perforce trigger to deny submission of unchanged files? Perforce allows people to check in unchanged files. Why any version control system would allow this is beyond me, but that's a topic for another question. I want to create a trigger that will deny the submission of unchanged files. However, I have no experience with Perforce triggers. From what I've read, I'm guessing this would be a "Change-content" trigger since the files being submitted would have to be diffed against the respective head revisions they are about to replace. I would need to iterate over the incoming files and make sure they had all indeed changed. The problem is, I have no idea how to go about it.
Can anyone with Perforce trigger experience offer an example or at least point me in the right direction?
A: In recent version of perforce allow a client setting which prevents submitting unchanged files:
SubmitOptions: Flags to change submit behaviour.
submitunchanged All open files are submitted
submitunchanged+reopen (default).
revertunchanged Files that have content or type
revertunchanged+reopen changes are submitted. Unchanged
files are reverted.
leaveunchanged Files that have content or type
leaveunchanged+reopen changes are submitted. Unchanged
files are moved to the default
changelist.
+reopen appended to the submit option flag
will cause submitted files to be
reopened on the default changelist.
This might be an avenue to investigate if the user is just checking unchanged files due to apathy.
EDIT:
Given that you want to enforce the restriction regardless of the user's workspace settings, then you'll need a trigger as suggested in other answers.
You'll need to look at Perforce's documentation to work out the details, but you'll need a change-content trigger.
You'll probably want to pass in %user% as well as %change% plus possibly other variables, so that you can restrict the expensive operations to just the problem user.
A: If you look at the Triggers table in Perforce, you will see that triggers are nothing but scripts that get invoked when some kind of event happens. In your case, the change-content event is triggered.
You have several options to write scripts that interact with Perforce. The Perforce downloads page has libraries and modules for many widely use languages. Any of this will help you and greatly simplify what you need to do. Also, check the Perforce Documentation page and download the administrator's guide. It will explain how to create the trigger, etc.
Basically, you need to write a script that will get the information from the change list that is being submitted and for each file in it run a "diff" command against the server. If you find a file that has not change, you need to invalidate the submission.
The Perforce module on you favorite language and the administrators guide will give you all the answers you need.
A: You'll want to write a change-content trigger. These triggers are run after files are transferred to the server, but before they are committed to the DB. As per the perforce documentation, you can use a command similar to the following
p4 diff //depot/path/...@=<change>
In the change-content trigger the @= (where change is the changelist number sent to the trigger) will get you the contents of the files that were submitted. If you are looking for a way to check against the server version, you might be able to do something like
p4 diff -sr //...@=<change>
The -sr command will report on files that open and are the same as the current depot contents. Since the files haven't been committed yet, I'm going to assume that you will actually get a list of files whose contents that have been transferred to the server are the same as the current head revision in the depot. If p4 diff -sr returns any files that are the same, return a non-zero exit code and the submit will be halted and the user will have to revert his unchanged files manually.
I don't think that you want to actually modify the contents of the changelist by doing the revert for him. That sounds too dangerous.
Note that you can write your trigger in any language that makes sense (as a previous poster suggested). I do think that this kind of trigger is going to be pretty heavyweight though. You will essentially be enforcing a diff on all contents submitted for all users in order to make one developer step in line. Maybe that's an okay price to pay, but depending on the number of users and the sizes of their changelist (and files), this kind of trigger might take a long time to run.
A: Rather than using a trigger, you can edit his workspaces (assuming you have the correct permissions ) to default to a submission strategy that avoids this. By default (again I dont know why) peforce will submit all selected files even if unchanged, but it is possible to change this behaviour. Open his workspaces, and set the SubmitOptions drop down to 'revertunchanged' which will revert any files in the changelist that have not changed, or 'leaveunchanged' which will keep them checked out but not submit them.
It is also possible to do this on an individual changelist submit if he wishes just look at the On Submit Dropdown.
We had this problem in our environment, but once I explained to the offenders what was happening and how easy it was to change the default behaviour they changed without any problems.
A: The script below is done in Linux using a perl script. I'm sure you can adapt it as necessary in Windows and using a scripting language other than Perl.
As the admin user, type
p4 triggers.
Add this under the Triggers: line of your script.
Trigger_name change-content //... "/<path_to_trigger_script>/<script_name> %changelist% %serverhost% %serverport% %user%"
The Trigger_name is arbitrary. The //... means all of your versioned files, but you can modify this as needed. Anything surrounded by % is a special variable name unique to Perforce, and these will be the arguments to your script. These should be all you need. Note that anything surrounded by <> is variable and depends on your environment.
Now, for the script itself. This is what I wrote.
#!/usr/bin/perl
# ----- CHECK 1 : Make sure files NOT identical
# get variables passed in through triggers call 'p4 triggers'
$ChangeNum = $ARGV[0]; #change number
$Server = $ARGV[1];
$Port = $ARGV[2];
$User = $ARGV[3];
$p4 = "<path_to_p4_exec>/p4 -p $Port ";
# get list of files opened under the submitted changelist
@files = `$p4 opened -a -c $ChangeNum | cut -f1 -d"#"`;
# go through each file and compare to predecessor
# although workspace should be configured to not submit unchanged files
# this is an additional check
foreach $file (@files)
{
chomp($file);
# get sum of depot file, the #head version
$depotSum = `$p4 print -q $file\#head | sum`;
# get sum of the recently submitted file, use @=$ChangeNum to do this
$clientSum = `$p4 print -q $file\@=$ChangeNum | sum`;
chomp $depotSum;
chomp $clientSum;
# if 2 sums are same, issue error
if ( $depotSum eq $clientSum )
{
# make sure this file is opened for edit and not for add/delete
if ( `$p4 describe $ChangeNum | grep "edit"` )
{
printf "\nFile $file identical to predecessor!";
exit( 1 );
}
}
}
A: We have a trigger script which begins by checking the SubmitOptions of the client spec for submitunchanged. If that is not present, then the trigger script can exit, since the user could not have submitted an unchanged file. Otherwise, we check all files where the action is edit and the file type has not been changed. We compare such files against the previous revision.
A: Add this to your triggers table:
Triggers:
myTrigger form-in client "sed -i -e s/submitunchanged/leaveunchanged/ %formfile%"
This will prevent anyone from saving a client with the submitunchanged option, which will in turn make it difficult for them to submit unchanged files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Avoid being blocked by web mail companies for mass/bulk emailing? Our company is sending out a lot of emails per day and planning to send even more in future. (thousands) Also there are mass mailouts as well in the ten thousands every now and then.
Anybody has experience with hotmail, yahoo (web.de, gmx.net) and similar webmail companies blocking your emails because "too many from the same source in a period of time" have been sent to them?
What can be done about it? Spreading email mailouts over a whole day/night? At what rate?
(we are talking about legal emailing just to make sure...)
A: If you want to do this you're getting into some of the same techniques spammers use. Spreading email mailouts over a day or night could be a way to do it. I don't think anyone knows the 'right' rate to do this because varies per mail-provider and they probably adjust this over time. You could try spreading the emails sent to a single provider. If you've got a lot of mail for hotmail.com for example then don't send it all at the same time.
Maybe it would be a good idea to look at pull media instead of push media for your application. You could put the content of the mass mailings up on a website and notify interested readers with an rss feed for example. This has a lower risk of irritating potential customer. And your company has a lower risk of being sued for spamming.
You're right, rss is not really accessible for all users. But as you'll probably need to create a webpage-alternative to the mailings anyway for people who can't read html-mail. You might as well provide an rss feed to those pages as an alternative for the users who do want to use it. This might reduce the volumes for the mailings enough to make your job a bit easier.
A: You want to look at the following:
*
*add a bulk-header to your outgoing email (Precedence: bulk)
*look into SPF
*look into SenderID
*look into DomainKeys or DKIM
*look into CAN-SPAM act
*setup and handle email to abuse@
*build relationships with the important providers
*monitor the usual spam lists, work with them when you are on them
Also, most providers have pages setup where they explain how they want "bulk" email to look like when you are sending it to their customers. That general includes requirements for double opt-in, etc..
A: Trying using a service like AuthSMTP. Typically the major free mail providers like Yahoo, Gmail will limit the amount of e-mails you can send per day and people on the receiving end might end up reporting them as spam.
A: I had to send out several thousand a week (all opt in) for a coupon site, I just figured out how many seconds there were in the given time period I needed to send them, and generated a random number of seconds between 0 and that number, added the random number to my "SendAt" date in my queue.
Not perfect but it worked. I do agree that ultimately it's a flawed concept, if you really HAVE to send thousands a day you'll need to contact a mail service.
http://www.streamsend.com/
BTW, you need to be very careful about not getting added to any of the blacklists
http://www.mxtoolbox.com/blacklists.aspx
A: Most of these provider have some form of "white-lists". Contact them directly, and see their requirements to be put on the list.
A: Here is some good advice about the headers for bulk emails, the likes of companies like constant contact use.
http://old.openspf.org/esps.html
To add to the list of good practices least likely to get you blacklisted,
If you follow guidelines for double-opt-in / unsubscribe links on every email / handling abuse reports this will improve the recipients not marking your email as spam - because if enough people within gmail/yahoo/hotmail mark your email as spam, it will go into the spam folder by default sometimes even if other good practices are being followed. So double-opt in makes sure the recipient only gets email they are expecting, reducing the chance of spam reports.
And to add to the managed email queue idea - do not just unintelligently process and send emails as fast as your CPU/memory will allow, create your own queue system as others have suggested that trickle over time and shuffle the order of email provider you are sending to (@gmail.com, @yahoo.com etc).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: C#, Get other application text from TextBox and TextArea? Good morgning,
I would like to be able to analyze text where I am writting whatever the application I am. Example, If I am here, typing in this TextArea, I would like to be able to get the text, same way if I were in the Subject Textbox in my Outlook.
I have search Google without success, maybe it's because it require Win32API call.
The goal would be to start having fun with multiple algorithm like "Bloom Filter" and Markov Chain.
Is it possible with C# and how to start?
A: CodingTheWheels series on building a poker bot goes into detail on how to capture window events from other applications. Its not exactly what your looking for, but it has some good info.
http://www.codingthewheel.com/archives/how-i-built-a-working-poker-bot
A: This tool works perfectly fine even for non-managed processess.
Runtime Object Editor
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: JavaScript: client-side vs. server-side validation Which is better to do client side or server side validation?
In our situation we are using
*
*jQuery and MVC.
*JSON data to pass between our View and Controller.
A lot of the validation I do is validating data as users enter it.
For example I use the the keypress event to prevent letters in a text box, set a max number of characters and that a number is with in a range.
I guess the better question would be, Are there any benefits to doing server side validation over client side?
Awesome answers everyone. The website that we have is password protected and for a small user base(<50). If they are not running JavaScript we will send ninjas. But if we were designing a site for everyone one I'd agree to do validation on both sides.
A: Well, I still find some room to answer.
In addition to answers from Rob and Nathan, I would add that having client-side validations matters. When you are applying validations on your webforms you must follow these guidelines:
Client-Side
*
*Must use client-side validations in order to filter genuine requests coming from genuine users at your website.
*The client-side validation should be used to reduce the errors that might occure during server side processing.
*Client-side validation should be used to minimize the server-side round-trips so that you save bandwidth and the requests per user.
Server-Side
*
*You SHOULD NOT assume the validation successfully done at client side is 100% perfect. No matter even if it serves less than 50 users. You never know which of your user/emplyee turn into an "evil" and do some harmful activity knowing you dont have proper validations in place.
*Even if its perfect in terms of validating email address, phone numbers or checking some valid inputs it might contain very harmful data. Which needs to be filtered at server-side no matter if its correct or incorrect.
*If client-side validation is bypassed, your server-side validations comes to rescue you from any potential damage to your server-side processing. In recent times, we have already heard lot of stories of SQL Injections and other sort of techniques that might be applied in order to gain some evil benefits.
Both types of validations play important roles in their respective scope but the most strongest is the server-side. If you receive 10k users at a single point of time then you would definitely end up filtering the number of requests coming to your webserver. If you find there was a single mistake like invalid email address then they post back the form again and ask your user to correct it which will definitely eat your server resources and bandwidth. So better you apply javascript validation. If javascript is disabled then your server side validation will come to rescue and i bet only a few users might have accidentlly disable it since 99.99% of websites use javascript and its already enabled by default in all modern browsers.
A: You can do Server side validation and send back a JSON object with the validation results for each field, keeping client Javascript to a minimum (just displaying results) and still having a user friendly experience without having to repeat yourself on both client and server.
A: Yes, client side validation can be totally bypassed, always. You need to do both, client side to provide a better user experience, and server side to be sure that the input you get is actually validated and not just supposedly validated by the client.
A: I am just going to repeat it, because it is quite important:
Always validate on the server
and add JavaScript for user-responsiveness.
A: Client side should use a basic validation via HTML5 input types and pattern attributes and as these are only used for progressive enhancements for better user experience (Even if they are not supported on < IE9 and safari, but we don't rely on them). But the main validation should happen on the server side..
A: I will suggest to implement both client and server validation it keeps project more secure......if i have to choose one i will go with server side validation.
You can find some relevant information here
https://web.archive.org/web/20131210085944/http://www.webexpertlabs.com/server-side-form-validation-using-regular-expression/
A: As others have said, you should do both. Here's why:
Client Side
You want to validate input on the client side first because you can give better feedback to the average user. For example, if they enter an invalid email address and move to the next field, you can show an error message immediately. That way the user can correct every field before they submit the form.
If you only validate on the server, they have to submit the form, get an error message, and try to hunt down the problem.
(This pain can be eased by having the server re-render the form with the user's original input filled in, but client-side validation is still faster.)
Server Side
You want to validate on the server side because you can protect against the malicious user, who can easily bypass your JavaScript and submit dangerous input to the server.
It is very dangerous to trust your UI. Not only can they abuse your UI, but they may not be using your UI at all, or even a browser. What if the user manually edits the URL, or runs their own Javascript, or tweaks their HTTP requests with another tool? What if they send custom HTTP requests from curl or from a script, for example?
(This is not theoretical; eg, I worked on a travel search engine that re-submitted the user's search to many partner airlines, bus companies, etc, by sending POST requests as if the user had filled each company's search form, then gathered and sorted all the results. Those companies' form JS was never executed, and it was crucial for us that they provide error messages in the returned HTML. Of course, an API would have been nice, but this was what we had to do.)
Not allowing for that is not only naive from a security standpoint, but also non-standard: a client should be allowed to send HTTP by whatever means they wish, and you should respond correctly. That includes validation.
Server side validation is also important for compatibility - not all users, even if they're using a browser, will have JavaScript enabled.
Addendum - December 2016
There are some validations that can't even be properly done in server-side application code, and are utterly impossible in client-side code, because they depend on the current state of the database. For example, "nobody else has registered that username", or "the blog post you're commenting on still exists", or "no existing reservation overlaps the dates you requested", or "your account balance still has enough to cover that purchase." Only the database can reliably validate data which depends on related data. Developers regularly screw this up, but PostgreSQL provides some good solutions.
A: The benefit of doing server side validation over client side validation is that client side validation can be bypassed/manipulated:
*
*The end user could have javascript switched off
*The data could be sent directly to your server by someone who's not even using your site, with a custom app designed to do so
*A Javascript error on your page (caused by any number of things) could result in some, but not all, of your validation running
In short - always, always validate server-side and then consider client-side validation as an added "extra" to enhance the end user experience.
A: I came across an interesting link that makes a distinction between gross, systematic, random errors.
Client-Side validation suits perfectly for preventing gross and random errors. Typically a max length for any input. Do not mimic the server-side validation rule; provide your own gross, rule of thumb validation rule (ex. 200 characters on client-side; a specific n chars less than 200 on server-side dictated by a strong business rule).
Server-side validation suits perfectly for preventing systematic errors; it will enforce business rules.
In a project I'm involved in, the validation is done on the server through ajax requests. On the client I display error messages accordingly.
Further reading: gross, systematic, random errors:
https://answers.yahoo.com/question/index?qid=20080918203131AAEt6GO
A: JavaScript can be modified at runtime.
I suggest a pattern of creating a validation structure on the server, and sharing this with the client.
You'll need separate validation logic on both ends, ex:
"required" attributes on inputs client-side
field.length > 0 server-side.
But using the same validation specification will eliminate some redundancy (and mistakes) of mirroring validation on both ends.
A: Client side data validation can be useful for a better user experience: for example, I a user who types wrongly his email address, should not wait til his request is processed by a remote server to learn about the typo he did.
Nevertheless, as an attacker can bypass client side validation (and may even not use the browser at all), server side validation is required, and must be the real gate to protect your backend from nefarious users.
A: You must always validate on the server.
Also having validation on the client is nice for users, but is utterly insecure.
A: If you are doing light validation, it is best to do it on the client. It will save the network traffic which will help your server perform better. If if it complicated validation that involves pulling data from a database or something, like passwords, then it best to do it on the server where the data can be securely checked.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "204"
} |
Q: Registering a COM server with WiX I have been trying to determine a best case solution for registering a COM server using WiX to create a Windows Installer package and am struggling.
In this post Deployment Engineering Archive: HOWTO: Use Regsvr32.exe with WIX, there is an open request for the "Setup police" to crack down on using regsvr32 through an exe custom action. I know the evils of using regsvr32 as it registers to the system rather than the user, but I also recall that OleSelfRegister can have issues from a microsoft support bulletin (sorry, can't find the link) - and I believe they recommended using regsvr32.
Any advice?
A: Read "Do not use the SelfReg and TypeLib tables" at:
https://msdn.microsoft.com/en-us/library/bb204770#no_selfreg
For WiX, take a look at the Component element in the schema reference at:
http://wixtoolset.org/documentation/manual/v3/xsd/wix/component.html
Take notice of certain child elements such as AppId, Class, ProgId, Registry and so on. The proper technique is to use COM extraction to reflect the registration information and emit it declaratively into your installer so MSI can take care of it for you without going out of process to some code (like DllRegisterServer()) that could fail and also not provides MSI insight into the footprint of the component from a repair and advertisement perspective.
A: There is a tool "Tallow" included with Wix. You can use it to generate correct registry entries automatically. Then you just configure your wix installation to write those entries. Selfreg should not be used.
A: As @Trampster pointed out, heat.exe does not do a good job of harvesting registry entries from COM servers. I tried but the results were incomplete.
Instead, following the advice at Monitor Registry Accesses (InstallSite Tools: Monitoring), I used InstallShield RegSpyUI. This supposedly ships with versions of Installshield v7 and beyond, including the evaluation version. This information may be out of date; I can confirm that it is not supplied with the pretty-much useless Installshield LE that comes with VS2013.
Luckily I did have a copy of InstallShield 2010 and this did come with RegSpyUI.
Anyway, RegSpyUI was a breeze to use: point it at the COM .exe, extract the registry info to a .reg file. Then use heat to harvest this into a .wxs file you can add to your Wix project
heat reg <some.reg> -gg -o <some.wxs>
Then it's just a matter of modifying any hard coded paths that point to the COM .exe's location so they reflect the intended installation folder.
e.g. if the .wxs file created by RegSpyUI+heat has something like this
<Fragment>
<DirectoryRef Id="TARGETDIR">
<Component Id="blah" Guid="{xxxxxxxxxxxxxxxxxxxxxxxxx}" KeyPath="yes">
<RegistryKey Key="TypeLib\{xxxxxxxxxxxxxxxxxxxxxx}\4.1\0\win32" Root="HKCR">
<RegistryValue Value="C:\Users\you\projects\MyProject\dependencies\installation\COMFOO.exe" Type="string" />
</RegistryKey>
</Component>
</DirectoryRef>
</Fragment>
and you are installing in your main wix file to
<Directory Id="TARGETDIR" Name="SourceDir">
<Directory Id="ProgramFilesFolder" Name="PFiles">
<Directory Id="COMPANY" Name="My Company">
<!--This is the actual installation folder-->
<Directory Name="MyProduct" Id="MYPRODUCT">
then simply edit the RegistryValue@value path to ..."[MYPRODUCT]\COMFOO.exe"
A: There is just one drawback to this: WiX Com registration with heat.exe does not work for .exe COM servers. InstallShield and its tools seem to support it, but RegSpyUI is just a UI tool, not one which I can run on my build machine.
A: Try this:
*
*Create a new .NET project
*Add a project Reference to the candidate COM dll or OOP exe whose wxs you want to gather
*Search for the file Interop.candidate.dll (in the obj\debug folder)
*Run the WiX Heat tool on the interop dll you just found.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: MySQL server goes away in XAMPP I am trying to install xampp 1.6.7 in a Red Hat Enterprise Edition. I followed the installation instructions and after that I started the stack with the command
sudo /opt/lampp/lampp start
And I get te usual response
XAMPP: Starting Apache with SSL (and PHP5)...
XAMPP: Starting MySQL...
XAMPP: Starting ProFTPD...
XAMPP for Linux started.
But when I check the status of the components of the stack MySQL is not running, and I get:
Version: XAMPP for Linux 1.5.5
Apache is running.
MySQL is not running.
ProFTPD is running.
This not always happens immediatly. Some times MySQL runs for a little while before crashing. I checked the logs and found nothing.
Edit:
the mysql log says
081002 10:41:22 mysqld started
libgcc_s.so.1 must be installed for pthread_cancel to work
081002 10:41:24 mysqld ended
mysql status says:
[root@localhost lampp]# bin/mysql status
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/opt/lampp/var/mysql/mysql.sock' (2)
and ps -ef | grep mysql yields nothing
A: When mysqld crashes (I think it just shuts down), you may need to configure log-error in my.cnf to see anything of real use. I am not sure how xampp is setup, but a simple find / -name "my.cnf" should point you to the location of that file.
Edit
You want to install libgcc. It should be available as an RPM for your platform. Let me know if this helps.
A: What do
mysql status
and
ps aux | grep mysql
say?
Also a snippet of the logs might help as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Reading very large files in PHP fopen is failing when I try to read in a very moderately sized file in PHP. A 6 meg file makes it choke, though smaller files around 100k are just fine. i've read that it is sometimes necessary to recompile PHP with the -D_FILE_OFFSET_BITS=64 flag in order to read files over 20 gigs or something ridiculous, but shouldn't I have no problems with a 6 meg file? Eventually we'll want to read in files that are around 100 megs, and it would be nice be able to open them and then read through them line by line with fgets as I'm able to do with smaller files.
What are your tricks/solutions for reading and doing operations on very large files in PHP?
Update: Here's an example of a simple codeblock that fails on my 6 meg file - PHP doesn't seem to throw an error, it just returns false. Maybe I'm doing something extremely dumb?
$rawfile = "mediumfile.csv";
if($file = fopen($rawfile, "r")){
fclose($file);
} else {
echo "fail!";
}
Another update: Thanks all for your help, it did turn out to be something incredibly dumb - a permissions issue. My small file inexplicably had read permissions when the larger file didn't. Doh!
A: • The fgets() function is fine until the text files passed 20 MBytes and the parsing speed is greatly reduced.
• The file_ get_contents() function give good results until 40 MBytes and acceptable results until 100 MBytes, but file_get_contents() loads the entire file into memory, so it's not scalabile.
• The file() function is disastrous with large files of text because this function creates an array containing each line of text, thus this array is stored in memory and the memory used is even larger.
Actually, a 200 MB file I could only manage to parse with memory_limit set at 2 GB which was inappropriate for the 1+ GB files I intended to parse.
When you have to parse files larger than 1 GB and the parsing time exceeded 15 seconds and you want to avoid to load the entire file into memory, you have to find another way.
My solution was to parse data in arbitrary small chunks. The code is:
$filesize = get_file_size($file);
$fp = @fopen($file, "r");
$chunk_size = (1<<24); // 16MB arbitrary
$position = 0;
// if handle $fp to file was created, go ahead
if ($fp) {
while(!feof($fp)){
// move pointer to $position in file
fseek($fp, $position);
// take a slice of $chunk_size bytes
$chunk = fread($fp,$chunk_size);
// searching the end of last full text line (or get remaining chunk)
if ( !($last_lf_pos = strrpos($chunk, "\n")) ) $last_lf_pos = mb_strlen($chunk);
// $buffer will contain full lines of text
// starting from $position to $last_lf_pos
$buffer = mb_substr($chunk,0,$last_lf_pos);
////////////////////////////////////////////////////
//// ... DO SOMETHING WITH THIS BUFFER HERE ... ////
////////////////////////////////////////////////////
// Move $position
$position += $last_lf_pos;
// if remaining is less than $chunk_size, make $chunk_size equal remaining
if(($position+$chunk_size) > $filesize) $chunk_size = $filesize-$position;
$buffer = NULL;
}
fclose($fp);
}
The memory used is only the $chunk_size and the speed is slightly less than the one obtained with file_ get_contents(). I think PHP Group should use my approach in order to optimize it's parsing functions.
*) Find the get_file_size() function here.
A: Are you sure that it's fopen that's failing and not your script's timeout setting? The default is usually around 30 seconds or so, and if your file is taking longer than that to read in, it may be tripping that up.
Another thing to consider may be the memory limit on your script - reading the file into an array may trip over this, so check your error log for memory warnings.
If neither of the above are your problem, you might look into using fgets to read the file in line-by-line, processing as you go.
$handle = fopen("/tmp/uploadfile.txt", "r") or die("Couldn't get handle");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
// Process buffer here..
}
fclose($handle);
}
Edit
PHP doesn't seem to throw an error, it just returns false.
Is the path to $rawfile correct relative to where the script is running? Perhaps try setting an absolute path here for the filename.
A: Did 2 tests with a 1.3GB file and a 9.5GB File.
1.3 GB
Using fopen()
This process used 15555 ms for its computations.
It spent 169 ms in system calls.
Using file()
This process used 6983 ms for its computations.
It spent 4469 ms in system calls.
9.5 GB
Using fopen()
This process used 113559 ms for its computations.
It spent 2532 ms in system calls.
Using file()
This process used 8221 ms for its computations.
It spent 7998 ms in system calls.
Seems file() is faster.
A: Well you could try to use the readfile function if you just want to output the file.
If this is not the case - maybe you should think about the design of the application, why do you want to open such large files on web requests?
A: I used fopen to open video files for streaming, using a php script as a video streaming server, and I had no problem with files of size more than 50/60 MB.
A: for me, fopen() has been very slow with files over 1mb, file() is much faster.
Just trying to read lines 100 at a time and create batch inserts, fopen() takes 37 seconds vs file() takes 4 seconds. Must be that string->array step built into file()
I'd try all of the file handling options to see which will work best in your application.
A: Have you tried file() ?
http://is2.php.net/manual/en/function.file.php
Or file_ get_contents()
http://is2.php.net/manual/en/function.file-get-contents.php
A: If the problem is caused by hitting the memory limit, you can try setting it a higher value (this could work or not depending on php's configuration).
this sets the memory limit to 12 Mb
ini\_set("memory_limit","12M");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: How to transfer data from one database to another with Hibernate? I have an application A with a domain-model which is mapped to a database using Hibernate. I have another application B that uses exactly the same domain-model-classes as A and adds some additional classes.
My goal is to read data from database A in application B and transfer that data into the database of B (to make a copy of it). In addition, some the domain-classes of B have associations (OneToOne) to domain-classes of A (but in the database of B, of course).
What's the best strategy to accomplish this? I thought of two session factories and using Session.replicate() (how does that work?). Or should I better introduce an additional mapping layer between these two domain-models for loose coupling?
A: I've done this before to transfer data between two different database types (in my case DB2 and MS SQL Server). What I did was to create two separate session factories, and give both of them the same list of mapping files. Then I simply read records from one, and saved them to the other.
Of course, this assumed that both data sources were identical.
A: What is the purpose of the copying? Is that part of your application flow or logic? or just straight data copying?
If it is just for the sake of copying data over, there is no need to use hibernate. There are plenty of tools for it.
A: Like others have pointed out, I think we need to know exactly what it is you're trying to accomplish. If you're doing a one time migration, there are better tools out there than Hibernate to do ETL (Extract, Transform, Load).
If you really insist on doing this in Hibernate (this applies to you also, Daniel), I'd do something like:
*
*Open session to database A.
*Read all entities of the type you're trying to copy (make sure lazy loading is disabled)
*Open session to database B.
*Save or update the entities.
I'd do this in a separate tool, rather than in application A or B.
On the other hand, if this is part of the functionality of your applications (e.g., application A is the admin console to the data, while application B consumes the data), you may want to do things a little differently. It's hard to say without knowing what exactly you're looking for.
Finally, something to look into (I don't think this is what you're looking for, but maybe it'll help you look at your problem in a different way) is Hibernate Shards (http://shards.hibernate.org/).
A: Tried other tools and had problems. Here's my home-rolled solution. Might need some cleaning up, but the meat of it is there.
import java.io.Serializable;
import java.util.List;
import java.util.logging.Logger;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.hibernate.Session;
import org.hibernate.Transaction;
import ca.digitalrapids.lang.GeneralException;
import ca.digitalrapids.mediamanager.server.dao.hibernate.GenericDAOHibernate;
import ca.digitalrapids.mediamanager.server.dao.hibernate.GenericDAOHibernate.GenericDAOHibernateFactory;
import ca.digitalrapids.persist.dao.DAOOptions;
import ca.digitalrapids.persist.hibernate.HibernateUtil2;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
@RequiredArgsConstructor
public class DataMigrator
{
private static final Logger logger = Logger
.getLogger(DataMigrator.class.getName());
private final HibernateUtil2 sourceHibernateUtil2;
private final HibernateUtil2 destHibernateUtil2;
private final ImmutableSet<Class<?>> beanClassesToMigrate;
@Setter @Getter
private Integer copyBatchSize = 10;
@Setter
private GenericDAOHibernateFactory sourceDaoFactory =
new GenericDAOHibernate.GenericDAOHibernateFactoryImpl();
@Setter
private GenericDAOHibernateFactory destDaoFactory =
new GenericDAOHibernate.GenericDAOHibernateFactoryImpl();
private final ImmutableMultimap<Class<?>, Class<?>> entityDependencies;
public void run() throws GeneralException
{
migrateData(sourceHibernateUtil2.getSession(),
destHibernateUtil2.getSession());
}
private void migrateData(Session sourceSession, Session destSession)
throws GeneralException
{
logger.info("\nMigrating data from old HSQLDB database.\n");
Transaction destTransaction = null;
try
{
destTransaction = destSession.beginTransaction();
migrateBeans(sourceSession, destSession, beanClassesToMigrate,
entityDependencies);
destTransaction.commit();
} catch (Throwable e) {
if ( destTransaction != null )
destTransaction.rollback();
throw e;
}
logger.info("\nData migration complete!\n");
}
private void migrateBeans(Session sourceSession, Session destSession,
ImmutableSet<Class<?>> beanClasses, ImmutableMultimap<Class<?>, Class<?>> deps)
{
if ( beanClasses.isEmpty() ) return;
Class<?> head = beanClasses.iterator().next();
ImmutableSet<Class<?>> tail =
Sets.difference(beanClasses, ImmutableSet.of(head)).immutableCopy();
ImmutableSet<Class<?>> childrenOfHead = getChildren(head, tail, deps);
migrateBeans(sourceSession, destSession, childrenOfHead, deps);
migrateBean(sourceSession, destSession, head);
migrateBeans(sourceSession, destSession,
Sets.difference(tail, childrenOfHead).immutableCopy(), deps);
}
private ImmutableSet<Class<?>> getChildren(Class<?> parent,
ImmutableSet<Class<?>> possibleChildren,
ImmutableMultimap<Class<?>, Class<?>> deps)
{
ImmutableSet<Class<?>> parentDeps = ImmutableSet.copyOf(deps.get(parent));
return Sets.intersection(possibleChildren, parentDeps).immutableCopy();
}
private void migrateBean(Session sourceSession, Session destSession,
Class<?> beanClass)
{
GenericDAOHibernate<?, Serializable> sourceDao =
sourceDaoFactory.get(beanClass, sourceSession);
logger.info("Migrating "+sourceDao.countAll()+" of "+beanClass);
DAOOptions options = new DAOOptions();
options.setMaxResults(copyBatchSize);
List<?> sourceBeans;
int firstResult = 0;
int sourceBeansSize;
do {
options.setFirstResult(firstResult);
sourceBeans = sourceDao.findAll(options);
sourceBeansSize = sourceBeans.size();
@SuppressWarnings("unchecked")
GenericDAOHibernate<Object, Serializable> destDao =
(GenericDAOHibernate<Object, Serializable>)
destDaoFactory.get(beanClass, destSession);
for (Object sourceBean : sourceBeans)
{
destDao.save(sourceBean);
}
firstResult += copyBatchSize;
sourceSession.clear();/* prevent memory problems */
} while ( sourceBeansSize >= copyBatchSize );
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Building a web crawler - using Webkit packages I'm trying to build a web crawler.
I need 2 things:
*
*Convert the HTML into a DOM object.
*Execute existing JavaScripts on demand.
The result I expect is a DOM Object, where the JavaScript that executes on-load is already executed.
Also, I need an option to execute on demand additional JavaScripts (on events like: onMouseOver, onMouseClick etc.)
First of all, I couldn't find a good documentation source.
I searched through Webkit Main Page but couldn't find much information for users of the package, and no usefull code examples.
Also, in some forums I've seen instructions not to use the Webkit interface for crawlers, but directly the DOM and Javascript inner packages.
I'm searching for Documentation and Code Examples.
Also, any recommendations on proper usage.
Work environment:
*
*OS: Windows
*Lang: C++
A: Check out some of the testing tools packaged alongside the WebKit trunk. Most ports (as far as I know) include DumpRenderTree which instantiates an WebKitView and then spits out a render tree after processing a specified file. It's theoretically one of the simplest examples of WebKit possible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.