instruction
stringlengths
0
30k
The most common are probably database injection attacks and cross-site scripting attacks; mainly because those are the easiest to accomplish (that's likely because those are the ones programmers are laziest about).
When should I use type abstraction in embedded systems
|c|implementation|decisioms|
I've worked on a number of different embedded systems. They have all used typedefs (or #defines) for types such as UINT32. This is a good technique as it drives home the size of the type to the programmer and makes you more conscious of chances for overflow etc. etc. But on some systems you know that the compiler and processor won't change for the life of the project. So what should influence your decision to create and enforce project-specific types?
|c|decisions|implementation|
|c|implementation|decisions|embedded-programming|
I've worked on a number of different embedded systems. They have all used typedefs (or #defines) for types such as UINT32. This is a good technique as it drives home the size of the type to the programmer and makes you more conscious of chances for overflow etc. But on some systems you know that the compiler and processor won't change for the life of the project. So what should influence your decision to create and enforce project-specific types? EDIT I think I managed to lose the gist of my question, and maybe it's really two. With embedded programming you may need types of specific size for interfaces and also to cope with restricted resources such as RAM. This can't be avoided, but you can choose to use the basic types from the compiler. For everything else the types have less importance. You need to be careful not to cause overflow and may need to watch out for register and stack usage. Which may lead you to UINT16, UCHAR. Using types such as UCHAR can add compiler 'fluff' however. Because registers are typically larger, some compilers may add code to force the result into the type. <PRE> i++;</PRE> can become <PRE> ADD REG,1 AND REG, 0xFF</PRE> which is unecessary. So I think my question should have been :- given the constraints of embedded software what is the best policy to set for a project which will have many people working on it - not all of whom will be of the same level of experience.
bool UserCredentialsOK(User user) { if (user.Name == "modesty") return false; else // perform other checks } ;)
Just to confuse things a bit more, sometimes you have to work with handles instead of pointers. Handles are pointers to pointers, so that the back end can move things in memory to defragment the heap. If the pointer changes in mid-routine, the results are unpredictable, so you first have to lock the handle to make sure nothing goes anywhere. [http://arjay.bc.ca/Modula-2/Text/Ch15/Ch15.8.html#15.8.5][1] talks about it a bit more coherently than me. :-) [1]: http://arjay.bc.ca/Modula-2/Text/Ch15/Ch15.8.html#15.8.5
You can see even on this site that the most damaging things you'll be looking after involve code injection into your application, so XSS (Cross Site Scripting) and SQL injection (@Patrick's suggestions) are your biggest concerns. Basically you're going to want to make sure that if your application allows for a user to inject any code whatsoever, it's regulated and tested to be sure that only things you're sure you want to allow (an html link, image, etc) are passed, and nothing else is executed.
|hacks|file-format|jpeg|steganography|
So, to simplify my life I want to be able to append from 1 to 7 additional characters on the end of some jpg images my program is processing*. These are dummy padding (fillers, etc - probably all 0x00) just to make the file size a multiple of 8 bytes for block encryption. Having tried this out with a few programs, it appears they are fine with the additional characters, which occur after the [FF D9 that specifies the end of the image][1] - so it appears that the file format is well defined enough that the 'corruption' I'm adding at the end shouldn't matter. I can always post process the files later if needed, but my preference is to do the simplest thing possible - which is to let them remain (I'm decrypting other file types and they won't mind, so having a special case is annoying). I figure with all the talk of [Steganography][2] hullaballo years ago, someone has some input here... -Adam * (encryption processing by 8 byte blocks, I don't want to save pre-encrypted file size, so append 0x00 to input data, and leave them there after decoding) [1]: http://en.wikipedia.org/wiki/JPEG#Syntax_and_structure [2]: http://en.wikipedia.org/wiki/Steganography
I think the ideal solution is to find a balance between the extremes. There is no way to write a rule that will fit in all situations; it comes with experience. Declaring each intermediate variable on its own line will make reading the code more difficult, which will also contribute to the difficulty in maintenance. By the same token, debugging is much more difficult if you inline the intermediate values. The 'sweet spot' is somewhere in the middle.
How do I find out if a process is already running using c#?
|c#|winforms|external-process|
I have C# winforms application that needs to start an external exe from time to time, but I do not wish to start another process if one is already running, but rather switch to it. So how in C# would I so this in the example below? using System.Diagnostics; ... Process foo = new Process(); foo.StartInfo.FileName = @"C:\bar\foo.exe"; foo.StartInfo.Arguments = "Username Password"; bool isRunning = //TODO: Check to see if process foo.exe is already running if (isRunning) { //TODO: Switch to foo.exe process } else { foo.Start(); }
This should do it for ya. [Check Processes][1] [1]: http://www.dreamincode.net/code/snippet1541.htm <pre><code>//Namespaces we need to use using System.Diagnostics; public bool IsProcessOpen(string name) { //here we're going to get a list of all running processes on //the computer foreach (Process clsProcess in Process.GetProcesses) { //now we're going to see if any of the running processes //match the currently running processes. Be sure to not //add the .exe to the name you provide, i.e: NOTEPAD, //not NOTEPAD.EXE or false is always returned even if //notepad is running. //Remember, if you have the process running more than once, //say IE open 4 times the loop thr way it is now will close all 4, //if you want it to just close the first one it finds //then add a return; after the Kill if (clsProcess.ProcessName.Contains(name)) { //if the process is found to be running then we //return a true return true; } } //otherwise we return a false return false; } </code> </pre>
Check out the [Library of Free Data Models][1] from DatabaseAnswers.org -- might be a good starting point. I can't vouch for the quality, but there is a lot here... [1]: http://databaseanswers.org/data_models/
Open source? [DB-UML might work for you][1]. EDIT: Oh! The [MySQL Workbench][2] is good. [1]: https://sourceforge.net/projects/dbuml#item3rd-1 [2]: http://dev.mysql.com/workbench/
[The mondial database.][1] Is used for learning about DBMSs. If you need something quick and dirty to bang around. [1]: http://www.dbis.informatik.uni-goettingen.de/Mondial/
There are a couple of ways to handle this, though neither is really all that great. First, add a column to your table that says that `TextField` is really a number. If you could do that and filter, you would have the most performant version. If that's not an option, then you will need to add a further filter. While I haven't extensively tested it, you could add the filter `AND TextField NOT LIKE 'NN%[0-9]%'` The downside is that this would filter out 'NN12NOO' but that may be an edge case not represented by your data.
In general you use the CLR if you have something that doesn't need to interface with the database much. So let's say you are parsing, or decoding a value. This is easier to do in the CLR and then return the value. Trying to do a compelx query in the CLR is just not the way to go. BTW this didn't change in 2008 either.
FDT is a plugin for Eclipse which many say (including myself) is the best editor when it comes to writing actionscript. FDT supports as2 & as3, including the new apis from Flash player 10. I haven't used Visual Studio myself but i'm guessing it's pretty much the same regarding intellisense (all versions of FDT). FDT Enterprise also supports debugging including breakpoints and stepping through your code (= not just trace). [http://fdt.powerflasher.com/][1] [1]: http://fdt.powerflasher.com/
This is bizarre. LocalSystem definitely has the privileges to install applications (that's how Windows Update and software deployment in Active Directory work), so it should be able to uninstall as well. Perhaps the application is initially installed per-user instead of per-machine?
The best option is to disable keyboard navigation shortcuts in the shadowbox by setting the "enableKeys" option to false (see [this page][1]). Alternatively you could do what Robby suggests and modify the shadowbox.js file, **but only do this if you need to have the shadowbox keyboard navigation**. I think that you want to search for this block of code and modify it so that it only cancels the default event if one of the shortcuts is used (I've added some line breaks and indention): var handleKey=function(e){ var code=SL.keyCode(e); SL.preventDefault(e); if(code==81||code==88||code==27){ SB.close() }else{ if(code==37){ SB.previous() }else{ if(code==39){ SB.next() }else{ if(code==32){ SB[(typeof slide_timer=="number"?"pause":"play")]() } } } } }; I think you could change it to look more like this: var handleKey=function(e){ switch(SL.keyCode(e)) { case 81: case 88: case 27: SB.close() SL.preventDefault(e); break; case 37: SB.previous() SL.preventDefault(e); break; case 39: SB.next() SL.preventDefault(e); break; case 32: SB[(typeof slide_timer=="number"?"pause":"play")]() SL.preventDefault(e); break; } }; This should prevent the shadowbox event handler from swallowing any keystrokes that it doesn't care about. [1]: http://mjijackson.com/shadowbox/doc/api.html
How do you set focus to the HTML5 canvas element?
|javascript|focus|canvas|
I'm using the HTML5 `<canvas>` element in Firefox 2.0.0.16 and in Safari 3.1.2, both on my iMac. (I've tried this in Firefox 3.0 on Windows as well, also to no avail.) The tag looks like this: <td> <canvas id="display" width="500px" height="500px"> </canvas> </td> I have a button to "activate" some functionality that interacts with the canvas. That button's onclick() event calls a function. In that function I have the following line: document.getElementById("display").focus(); This does not work. Firebug reports no error. But the focus still remains where it was. I can click on the canvas or tab towards the canvas and focus will be lost from the other elements, but apparently never be gained on by the canvas. (The canvas's onfocus() event never fires.) I find this odd. Is it that the canvas simply cannot get focus, or am I missing something here? Any insight would be appreciated. Thank you.
Implementing the IComparable interface in your object may provide you with the functionality you need. This will provide you a custom way to determine differences between objects without resorting to checksums which really won't help you track what the differences are in usable terms. Otherwise, there's no way to determine equality between two user objects in .NET that I know of. There are some decent examples of the usage of this interface in the help file for Visual Studio, or [here][1]. You might be able to glean some directives from the examples on clean ways to compare the properties and store the values in some usable manner for tracking purposes (perhaps a collection, or dictionary object?). Hope this helps, Greg [1]: http://msdn.microsoft.com/en-us/library/system.icomparable.aspx
Your second example does **not** create a new dataset. It's just a second _reference_ to an existing dataset.
If it's the **last** revision (HEAD) you can (**BACKING UP** your repo beforehand) delete that revision's files in `db\revs` and `db\revprops` and then run the following python script to fix what revision you repo thinks HEAD is. e.g. if head is 522 and the password was commited in 520, you'd have to deleted revisions 520,521 and 522. (This script shouldn't be necessary once [SVN obliterate][1] is implemented) #!/usr/bin/python def dec_to_36(dec): key = '0123456789abcdefghijklmnopqrstuvwxyz' result = '' while 1: div = dec / 36 mod = dec % 36 dec = div result = key[mod] + result if dec == 0: break return result import os, re, sys repo_path = sys.argv[1] rev_path = os.path.join(repo_path, 'db', 'revs') current_path = os.path.join(repo_path, 'db', 'current') id_re = re.compile(r'^id:\ ([a-z0-9]+)\.([a-z0-9]+)\.r([0-9]+).*') max_node_id = 0 max_copy_id = 0 max_rev_id = 0 for rev in os.listdir(rev_path): f = open(os.path.join(rev_path, rev), 'r') for line in f: m = id_re.match(line) if m: node_id = int(m.group(1), 36) copy_id = int(m.group(2), 36) rev_id = int(m.group(3), 10) if copy_id > max_copy_id: max_copy_id = copy_id if node_id > max_node_id: max_node_id = node_id if rev_id > max_rev_id: max_rev_id = rev_id f = open(current_path, 'w+b') f.write("%d %s %s\n" % (max_rev_id, dec_to_36(max_node_id+1), dec_to_36(max_copy_id+1))) f.close() [1]: http://subversion.tigris.org/issues/show_bug.cgi?id=516
You can simply enumerate processes using [Process.GetProcesses][1] method. [1]: http://msdn.microsoft.com/en-us/library/1f3ys1f9.aspx
I tend to err on the side of readability, not necessarily debuggability. The examples you gave should definitely be avoided, but I feel that judicious use of multiple expressions can make the code more concise and comprehensible.
I think the complete answer to your problem requires understanding of what happens when your application determines that an instance of foo.exe is already running i.e what does '//TODO: Switch to foo.exe process' actually mean?
I have used the AppActivate function in VB runtime to activate an existing process. You will have to import Microsoft.VisualBasic dll into the C# project. using System; using System.Diagnostics; using Microsoft.VisualBasic; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { Process[] proc = Process.GetProcessesByName("notepad"); Interaction.AppActivate(proc[0].MainWindowTitle); } } }
@[Lars Truijens](#49540) suggested > Remember that PowerShell can access > .Net objects. The Start-Sleep as > suggested by Blair Conrad can be > replaced by a call to WaitForInputIdle > of the server process so you know when > the server is ready before starting > the client. This is more elegant than sleeping for a fixed (or supplied via parameter) amount of time. However, [WaitForInputIdle][1] > applies only to processes with a user > interface and, therefore, a message > loop. so this may not work, depending on the characteristics of launch-server-application. [1]: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.waitforinputidle.aspx
@[Lars Truijens](#49540) suggested > Remember that PowerShell can access > .Net objects. The Start-Sleep as > suggested by Blair Conrad can be > replaced by a call to WaitForInputIdle > of the server process so you know when > the server is ready before starting > the client. This is more elegant than sleeping for a fixed (or supplied via parameter) amount of time. However, [WaitForInputIdle][1] > applies only to processes with a user > interface and, therefore, a message > loop. so this may not work, depending on the characteristics of launch-server-application. However, as Lars pointed out to me, the question referred to a _windowed_ application (which I missed when I read the question), so his solution is probably best. [1]: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.waitforinputidle.aspx
Is there a way of selecting the last item of a list with CSS?
|css|css-selectors|
Say I have a list as follows: <ul> <li>item1</li> <li>item2</li> <li>item3</li> </ul> Is there a CSS selector that will allow me to directly select the last item of a list? In this case item 3. Cheers!
Can the Weblogic default handler display the list of contexts?
As alternative, log4net, though potentially dangerous, has given me better results than System.Diagnostics. Basically in log4net, you have a method for the various log levels, each with an Exception parameter. So, when you pass the second exception, it will print the stack trace to whichever appender you have configured. example: `Logger.Error("Danger!!!", myException );` The output, depending on configuration, looks something like System.ApplicationException: Something went wrong. at Adapter.WriteToFile(OleDbCommand cmd) in C:\Adapter.vb:line 35 at Adapter.GetDistributionDocument(Int32 id) in C:\Adapter.vb:line 181 ...
Open one of a series of files using a batch file
|command-line|batch-file|dos|cmd|
I have up to 4 files based on this structure (note the prefixes are dates) - 0830filename.txt - 0907filename.txt - 0914filename.txt - 0921filename.txt I want to open the the most recent one (0921filename.txt). how can i do this in a batch file? Thanks.
Typically relationships in XML are shown by the parent/child relationship. XML can handle graph data but not in this manner. To handle graphs in XML you should use the [xs:ID][1] and [xs:IDREF][2] schema types. In an example, assume that node/@id is an xs:ID type and that link/@ref is an xs:IDREF type. The following XML shows the cycle of three nodes 1 -> 2 -> 3 -> 1. <data> <node id="1"> <link ref="2"/> </node> <node id="2"> <link ref="3"/> </node> <node id="3"> <link ref="1"/> </node> </data> Many development tools have support for ID and IDREF too. I have used Java's JAXB (Java XML Binding. It supports these through the [@XmlID][3] and the [@XmlIDREF][4] annotations. You can build your graph using plain Java objects and then use JAXB to handle the actual serialization to XML. [1]: http://www.zvon.org/xxl/xmlSchema2001Reference/Standard/xmlschema-2.html#ID [2]: http://www.zvon.org/xxl/xmlSchema2001Reference/Standard/xmlschema-2.html#IDREF [3]: http://java.sun.com/javase/6/docs/api/javax/xml/bind/annotation/XmlID.html [4]: http://java.sun.com/javase/6/docs/api/javax/xml/bind/annotation/XmlIDREF.html
Out of curiousity, have you considered using an ORM for managing your data access. A lot of the functionality you're trying to implement could already be there. It may be something to look at because its best not to re-invent the wheel.
haXe and arrays Dynamic type
|haxe|array|loops|iterable|for-loop|
I know it's unlikely but maybe there is someone who knows haXe language. I have a variable of Dynamic type and I know for sure one of it's fields, lets call it an 'a' actually is an array. But when I'm writing var d : Dynamic = getDynamic(); for (t in d.a) { } I get a compilation error on line two, saying 'You can't iterate on a Dynamic value, please specify Iterator or Iterable'. How can I make this compilable?
|arrays|for-loop|haxe|iterable|loops|
If it's the **last** revision (HEAD) you can (**BACKING UP** your repo beforehand) delete that revision's files in `db\revs` and `db\revprops` and then run the following python script to fix what revision you repo thinks HEAD is. e.g. if head is 522 and the password was commited in 520, you'd have to deleted revisions 520,521 and 522. (This script shouldn't be necessary once [SVN obliterate][1] is implemented) (I didn't write this script, I got it from [here][2]) #!/usr/bin/python def dec_to_36(dec): key = '0123456789abcdefghijklmnopqrstuvwxyz' result = '' while 1: div = dec / 36 mod = dec % 36 dec = div result = key[mod] + result if dec == 0: break return result import os, re, sys repo_path = sys.argv[1] rev_path = os.path.join(repo_path, 'db', 'revs') current_path = os.path.join(repo_path, 'db', 'current') id_re = re.compile(r'^id:\ ([a-z0-9]+)\.([a-z0-9]+)\.r([0-9]+).*') max_node_id = 0 max_copy_id = 0 max_rev_id = 0 for rev in os.listdir(rev_path): f = open(os.path.join(rev_path, rev), 'r') for line in f: m = id_re.match(line) if m: node_id = int(m.group(1), 36) copy_id = int(m.group(2), 36) rev_id = int(m.group(3), 10) if copy_id > max_copy_id: max_copy_id = copy_id if node_id > max_node_id: max_node_id = node_id if rev_id > max_rev_id: max_rev_id = rev_id f = open(current_path, 'w+b') f.write("%d %s %s\n" % (max_rev_id, dec_to_36(max_node_id+1), dec_to_36(max_copy_id+1))) f.close() [1]: http://subversion.tigris.org/issues/show_bug.cgi?id=516 [2]: http://svn.haxx.se/users/archive-2005-12/0630.shtml
If it's the **last** revision (HEAD) you can (**BACKING UP** your repo beforehand) delete that revision's files in `db\revs` and `db\revprops` and then run the following python script to fix what revision you repo thinks HEAD is. e.g. if head is 522 and the password was commited in 520, you'd have to delete revisions 520,521 and 522. (This script shouldn't be necessary once [SVN obliterate][1] is implemented) (I didn't write this script, I got it from [here][2]) #!/usr/bin/python def dec_to_36(dec): key = '0123456789abcdefghijklmnopqrstuvwxyz' result = '' while 1: div = dec / 36 mod = dec % 36 dec = div result = key[mod] + result if dec == 0: break return result import os, re, sys repo_path = sys.argv[1] rev_path = os.path.join(repo_path, 'db', 'revs') current_path = os.path.join(repo_path, 'db', 'current') id_re = re.compile(r'^id:\ ([a-z0-9]+)\.([a-z0-9]+)\.r([0-9]+).*') max_node_id = 0 max_copy_id = 0 max_rev_id = 0 for rev in os.listdir(rev_path): f = open(os.path.join(rev_path, rev), 'r') for line in f: m = id_re.match(line) if m: node_id = int(m.group(1), 36) copy_id = int(m.group(2), 36) rev_id = int(m.group(3), 10) if copy_id > max_copy_id: max_copy_id = copy_id if node_id > max_node_id: max_node_id = node_id if rev_id > max_rev_id: max_rev_id = rev_id f = open(current_path, 'w+b') f.write("%d %s %s\n" % (max_rev_id, dec_to_36(max_node_id+1), dec_to_36(max_copy_id+1))) f.close() [1]: http://subversion.tigris.org/issues/show_bug.cgi?id=516 [2]: http://svn.haxx.se/users/archive-2005-12/0630.shtml
CLR stored procedures are not meant to replace set-based queries. If you need to query the database, you are still going to need to put SQL into your CLR code, just as if it was embedded in regular code. This would be a waste of effort. CLR stored procedures are for two main things: 1) interaction with the OS, such as reading from a file or dropping a message in MSMQ, and 2) performing complex calculations, especially when you already have the code written in a .NET language to do the calculation.
There are places for both well-written, well-thought-out T-SQL and CLR. If some function is not called frequently and if it required extended procedures in SQL Server 2000, CLR may be an option. Also running things like calculation right next to the data may be appealing. But solving bad programmers by throwing in new technology sounds like a bad idea.
Good Question! One approach I rather like is to create an iterator/generator object that emits instances of objects that are relevant to a specific context. Usually this object wraps some underlying database access stuff, but I don't need to know that when using it. For example, > An AnswerIterator object generates AnswerIterator.Answer objects. Under the hood it's iterating over a SQL Statement to fetch all the answers, and another SQL statement to fetch all related comments. But when using the iterator I just use the Answer object that has the minimum properties for this context. With a little bit of skeleton code this becomes almost trivial to do. I've found that this works well when I have a huge dataset to work on, and when done right, it gives me small, transient objects that are relatively easy to test. It's basically a thin veneer over the Database Access stuff, but it still gives me the flexibility of abstracting it when I need to.
Nij, our difference in thinking comes from our different perspectives. I'm thinking about developing enterprise apps that predominantly use WinForms clients. In this instance the business logic is contained on an application server. Each client would need to know the phone number to dial, but placing it in the App.config of each client poses a problem if that phone number changes. In that case it seems obvious to store application configuration information (or application wide settings) in a database and have each client read the settings from there. The other, .NET way, (I make the distinction because we have, in the pre .NET days, stored application settings in DB tables) is to store application settings in the app.config file and access via way of the generated Settings class. I digress. Your situation sounds different. If all different apps are on the same server, you could place the settings in a web.config at a higher level. However if they are not, you could also have a seperate "configuration service" that all three applications talk to get their shared settings. At least in this solution you're not replicating the code in three places, raising the potential of maintenance problems when adding settings. Sounds a bit over engineered though. My personal preference is to use strong typed settings. I actually generate my own strongly typed settings class based on what it's my settings table in the database. That way I can have the best of both worlds. Intellisense to my settings and settings stored in the db (note: that's in the case where there's no app server). I'm interested in learning other peoples strategies for this too :)
|java|jakarta-ee|weblogic|
In Jetty, if there is no deployment at '/' then the [DefaultHandler](http://www.mortbay.org/jetty/jetty-6/xref/org/mortbay/jetty/handler/DefaultHandler.html) displays a list of known contexts. This is very useful during development. Is it possible to configure BEA Weblogic to provide a similar convenience?
I've never tried it, but it looks like you might be able to use a <a href="http://msdn.microsoft.com/en-us/library/ms141069(SQL.90).aspx">Derived Column transformation</a> to do it: set the expression for attribute1 to <code>"foo"</code> and the expression for attribute2 to <code>"bar"</code>. You'd then transform the original data source, then only use the derived columns in your destination. If you still need the original source, you can Multicast it to create a duplicate. At least I think this will work, based on the documentation. YMMV.
Not that i'm aware of. The traditional solution is to tag the first & last items with class="first" & class="last" so you can identify them. The CSS psudo-class [first-child][1] will get you the first item but not all browsers support it. CSS3 will have [last-child too][2] (this is currently supported by Firefox, Safari but not IE 6/7/beta 8) [1]: http://www.w3.org/TR/CSS2/selector.html#first-child [2]: http://www.w3.org/TR/2001/CR-css3-selectors-20011113/#last-child-pseudo
You'll need to use ADSI objects. The <a href="http://msdn.microsoft.com/en-us/library/ms525753.aspx">IIsComputer.Backup</a> method is what you want. As far as how to access ADSI objects from C#, check out this <a href="http://support.microsoft.com/kb/315716">MSDN page</a>.
You'll need to use ADSI objects. The <a href="http://msdn.microsoft.com/en-us/library/ms525753.aspx">IIsComputer.Backup</a> method is what you want. As far as how to access ADSI objects from C#, check out this <a href="http://support.microsoft.com/kb/315716">MSDN page</a>. **EDIT:** Here's a <a href="http://www.vbforums.com/archive/index.php/t-470587.html">sample implementation in C#</a>.
That's great! I didn't know you could do a comparison of (x, y, z) with the result of a SELECT statement. This works great with Oracle. As a side-note for other readers, the above query is missing a "=" after "(deptno,job,sal)". Maybe the Stack Overflow formatter ate it (?). Again, thanks Mark.
The following is slightly over-engineered, but is a good SQL pattern for "top x" queries. SELECT * FROM scott.emp WHERE (deptno,job,sal) (SELECT deptno, job, max(sal) FROM scott.emp WHERE deptno = 20 and job = 'CLERK' GROUP BY deptno, job ) Also note that this will work in Oracle and Postgress (i think) but not MS SQL. For something similar in MS SQL see question [SQL Query to get latest price][1] [1]: /questions/49404/sql-query-to-get-latest-price
The following is slightly over-engineered, but is a good SQL pattern for "top x" queries. SELECT * FROM scott.emp WHERE (deptno,job,sal) (SELECT deptno, job, max(sal) FROM scott.emp WHERE deptno = 20 and job = 'CLERK' GROUP BY deptno, job ) Also note that this will work in Oracle and Postgress (i think) but not MS SQL. For something similar in MS SQL see question [SQL Query to get latest price][1] [1]: http://stackoverflow.com/questions/49404/sql-query-to-get-latest-price#49424
System::String has a constructor that takes a char*: const char* charstr = "Hello, world!"; String^ clistr = gcnew String(charstr); Console::WriteLine(clistr); Getting a char* back is a bit harder, but not too bad: IntPtr p = Marshal::StringToHGlobalAnsi(clistr); char *pNewCharStr = static_cast<char*>(p.ToPointer()); cout << pNewCharStr << endl; Marshal::FreeHGlobal(p);
While Keith is right, I suppose the example was simply badly chosen. Generally, it is better to initialize to the “right” object from the beginning and *not* construct an intermediate, empty object as in your case. Two reasons: 1. Performance. This should be obvious: Object creation costs time so creating less objects is better. 2. *Much* more important however, it better states your **intent**. You do generally *not* intend to create stateless/empty objects. Rather, you intend to create objects with some state or content. Do it. No need to create a useless (because empty) temporary.
Well, if .net is an option, they have put a lot of effort into [Parallel Computing][1]. [1]: http://msdn.microsoft.com/en-us/concurrency/default.aspx
As Juan mentioned, xDebug is excellent. If you're on Windows, [WinCacheGrind][1] will let you look over the reports. [1]: http://sourceforge.net/projects/wincachegrind/
Custom Counter Creation Through Web Application
|.net|
I have a .NET 3.5 web application for which I have implemented a class called CalculationsCounterManager (code below). This class has some shared/static members that manage the creation and incrementing of two custom performance counters that monitor data calls to a SQL Server database. Execution of these data calls drives the creation of the counters if the don't exist. Of course, everything works fine through the unit tests that are executed through the nUnit GUI for this class. The counters are created and incremented fine. However, when the same code executes through the ASPNET worker process, the following error message occurs: "Requested registry access is not allowed.". This error happens on line 44 in the CalculationsCounterManager class when a read is done to check if the counter category already exists. Does anyone know a way to provide enough priveledges to the worker process account in order to allow it to create the counters in a production environment without opening the server up to security problems? Thanks in advance! Imports eA.Analytics.Interfaces.Common Namespace eA.Analytics.DataLayer.PerformanceMetrics ''' <summary> ''' Manages performance counters for the calculatioins data layer assembly ''' </summary> ''' <remarks>GAJ 09/10/08 - Initial coding and testing</remarks> Public Class CalculationCounterManager Private Shared _AvgRetrieval As PerformanceCounter Private Shared _TotalRequests As PerformanceCounter Private Shared _ManagerInitialized As Boolean Private Shared _SW As Stopwatch ''' <summary> ''' Creates/recreates the perf. counters if they don't exist ''' </summary> ''' <param name="recreate"></param> ''' <remarks></remarks> Public Shared Sub SetupCalculationsCounters(ByVal recreate As Boolean) If PerformanceCounterCategory.Exists(CollectionSettings.CalculationMetricsCollectionName) = False Or recreate = True Then Dim AvgCalcsProductRetrieval As New CounterCreationData(CounterSettings.AvgProductRetrievalTimeCounterName, _ CounterSettings.AvgProductRetrievalTimeCounterHelp, _ CounterSettings.AvgProductRetrievalTimeCounterType) Dim TotalCalcsProductRetrievalRequests As New CounterCreationData(CounterSettings.TotalRequestsCounterName, _ CounterSettings.AvgProductRetrievalTimeCounterHelp, _ CounterSettings.TotalRequestsCounterType) Dim CounterData As New CounterCreationDataCollection() ' Add counters to the collection. CounterData.Add(AvgCalcsProductRetrieval) CounterData.Add(TotalCalcsProductRetrievalRequests) If recreate = True Then If PerformanceCounterCategory.Exists(CollectionSettings.CalculationMetricsCollectionName) = True Then PerformanceCounterCategory.Delete(CollectionSettings.CalculationMetricsCollectionName) End If End If If PerformanceCounterCategory.Exists(CollectionSettings.CalculationMetricsCollectionName) = False Then PerformanceCounterCategory.Create(CollectionSettings.CalculationMetricsCollectionName, CollectionSettings.CalculationMetricsDescription, _ PerformanceCounterCategoryType.SingleInstance, CounterData) End If End If _AvgRetrieval = New PerformanceCounter(CollectionSettings.CalculationMetricsCollectionName, CounterSettings.AvgProductRetrievalTimeCounterName, False) _TotalRequests = New PerformanceCounter(CollectionSettings.CalculationMetricsCollectionName, CounterSettings.TotalRequestsCounterName, False) _ManagerInitialized = True End Sub Public Shared ReadOnly Property CategoryName() As String Get Return CollectionSettings.CalculationMetricsCollectionName End Get End Property ''' <summary> ''' Determines if the performance counters have been initialized ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Shared ReadOnly Property ManagerInitializaed() As Boolean Get Return _ManagerInitialized End Get End Property Public Shared ReadOnly Property AvgRetrieval() As PerformanceCounter Get Return _AvgRetrieval End Get End Property Public Shared ReadOnly Property TotalRequests() As PerformanceCounter Get Return _TotalRequests End Get End Property ''' <summary> ''' Initializes the Average Retrieval Time counter by starting a stopwatch ''' </summary> ''' <remarks></remarks> Public Shared Sub BeginIncrementAvgRetrieval() If _SW Is Nothing Then _SW = New Stopwatch End If _SW.Start() End Sub ''' <summary> ''' Increments the Average Retrieval Time counter by stopping the stopwatch and changing the ''' raw value of the perf counter. ''' </summary> ''' <remarks></remarks> Public Shared Sub EndIncrementAvgRetrieval(ByVal resetStopwatch As Boolean, ByVal outputToTrace As Boolean) _SW.Stop() _AvgRetrieval.RawValue = CLng(_SW.ElapsedMilliseconds) If outPutToTrace = True Then Trace.WriteLine(_AvgRetrieval.NextValue.ToString) End If If resetStopwatch = True Then _SW.Reset() End If End Sub ''' <summary> ''' Increments the total requests counter ''' </summary> ''' <remarks></remarks> Public Shared Sub IncrementTotalRequests() _TotalRequests.IncrementBy(1) End Sub Public Shared Sub DeleteAll() If PerformanceCounterCategory.Exists(CollectionSettings.CalculationMetricsCollectionName) = True Then PerformanceCounterCategory.Delete(CollectionSettings.CalculationMetricsCollectionName) End If End Sub End Class End Namespace
I have a .NET 3.5 web application for which I have implemented a class called CalculationsCounterManager (code below). This class has some shared/static members that manage the creation and incrementing of two custom performance counters that monitor data calls to a SQL Server database. Execution of these data calls drives the creation of the counters if the don't exist. Of course, everything works fine through the unit tests that are executed through the nUnit GUI for this class. The counters are created and incremented fine. However, when the same code executes through the ASPNET worker process, the following error message occurs: "Requested registry access is not allowed.". This error happens on line 44 in the CalculationsCounterManager class when a read is done to check if the counter category already exists. Does anyone know a way to provide enough priveledges to the worker process account in order to allow it to create the counters in a production environment without opening the server up to security problems? Thanks in advance! Namespace eA.Analytics.DataLayer.PerformanceMetrics ''' <summary> ''' Manages performance counters for the calculatioins data layer assembly ''' </summary> ''' <remarks>GAJ 09/10/08 - Initial coding and testing</remarks> Public Class CalculationCounterManager Private Shared _AvgRetrieval As PerformanceCounter Private Shared _TotalRequests As PerformanceCounter Private Shared _ManagerInitialized As Boolean Private Shared _SW As Stopwatch ''' <summary> ''' Creates/recreates the perf. counters if they don't exist ''' </summary> ''' <param name="recreate"></param> ''' <remarks></remarks> Public Shared Sub SetupCalculationsCounters(ByVal recreate As Boolean) If PerformanceCounterCategory.Exists(CollectionSettings.CalculationMetricsCollectionName) = False Or recreate = True Then Dim AvgCalcsProductRetrieval As New CounterCreationData(CounterSettings.AvgProductRetrievalTimeCounterName, _ CounterSettings.AvgProductRetrievalTimeCounterHelp, _ CounterSettings.AvgProductRetrievalTimeCounterType) Dim TotalCalcsProductRetrievalRequests As New CounterCreationData(CounterSettings.TotalRequestsCounterName, _ CounterSettings.AvgProductRetrievalTimeCounterHelp, _ CounterSettings.TotalRequestsCounterType) Dim CounterData As New CounterCreationDataCollection() ' Add counters to the collection. CounterData.Add(AvgCalcsProductRetrieval) CounterData.Add(TotalCalcsProductRetrievalRequests) If recreate = True Then If PerformanceCounterCategory.Exists(CollectionSettings.CalculationMetricsCollectionName) = True Then PerformanceCounterCategory.Delete(CollectionSettings.CalculationMetricsCollectionName) End If End If If PerformanceCounterCategory.Exists(CollectionSettings.CalculationMetricsCollectionName) = False Then PerformanceCounterCategory.Create(CollectionSettings.CalculationMetricsCollectionName, CollectionSettings.CalculationMetricsDescription, _ PerformanceCounterCategoryType.SingleInstance, CounterData) End If End If _AvgRetrieval = New PerformanceCounter(CollectionSettings.CalculationMetricsCollectionName, CounterSettings.AvgProductRetrievalTimeCounterName, False) _TotalRequests = New PerformanceCounter(CollectionSettings.CalculationMetricsCollectionName, CounterSettings.TotalRequestsCounterName, False) _ManagerInitialized = True End Sub Public Shared ReadOnly Property CategoryName() As String Get Return CollectionSettings.CalculationMetricsCollectionName End Get End Property ''' <summary> ''' Determines if the performance counters have been initialized ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Shared ReadOnly Property ManagerInitializaed() As Boolean Get Return _ManagerInitialized End Get End Property Public Shared ReadOnly Property AvgRetrieval() As PerformanceCounter Get Return _AvgRetrieval End Get End Property Public Shared ReadOnly Property TotalRequests() As PerformanceCounter Get Return _TotalRequests End Get End Property ''' <summary> ''' Initializes the Average Retrieval Time counter by starting a stopwatch ''' </summary> ''' <remarks></remarks> Public Shared Sub BeginIncrementAvgRetrieval() If _SW Is Nothing Then _SW = New Stopwatch End If _SW.Start() End Sub ''' <summary> ''' Increments the Average Retrieval Time counter by stopping the stopwatch and changing the ''' raw value of the perf counter. ''' </summary> ''' <remarks></remarks> Public Shared Sub EndIncrementAvgRetrieval(ByVal resetStopwatch As Boolean, ByVal outputToTrace As Boolean) _SW.Stop() _AvgRetrieval.RawValue = CLng(_SW.ElapsedMilliseconds) If outPutToTrace = True Then Trace.WriteLine(_AvgRetrieval.NextValue.ToString) End If If resetStopwatch = True Then _SW.Reset() End If End Sub ''' <summary> ''' Increments the total requests counter ''' </summary> ''' <remarks></remarks> Public Shared Sub IncrementTotalRequests() _TotalRequests.IncrementBy(1) End Sub Public Shared Sub DeleteAll() If PerformanceCounterCategory.Exists(CollectionSettings.CalculationMetricsCollectionName) = True Then PerformanceCounterCategory.Delete(CollectionSettings.CalculationMetricsCollectionName) End If End Sub End Class End Namespace
I've had a few headaches with SVN when I've reorganized the folder layout from within Visual Studio. A folder moved within a solution will literally move the folder in the filesystem, including the hidden `.svn` folder. This causes commit problems because the `.svn` data is associated to the old path and I haven't found a way to reassociate to its new path. SVN `clean up` runs OK but fixes nothing. SVN `switch` doesn't allow you to change it after the folder was moved. I've only been able to fix this by deleting all `.svn` folders within the moved folder and its subfolders, then re-add the folder. The problem I have with this fix is that you lose your version trail on those files because SVN sees it as brand new. Also, it doesn't store the file contents as efficiently by storing the diff from the previous version. Per the SVN documentation, it is recommended to allow the `svn` client to do all your folder move/create/delete to keep everything in sync for the next commit. This isn't always acceptable from Visual Studio. Fortunately, most problem cases are caught during commit-time, particularly if you use TortoiseSVN.
Is DocumentBuilder.parse() thread safe?
|java|
Is the standard Java 1.6 [javax.xml.parsers.DocumentBuilder][1] class thread safe? Is it safe to call the parse() method from several threads in parallel? The JavaDoc doesn't mention the issue, but the [JavaDoc for the same class][2] in Java 1.4 specifically says that it *isn't* meant to be concurrent; so can I assume that in 1.6 it is? [1]: http://java.sun.com/javase/6/docs/api/javax/xml/parsers/DocumentBuilder.html [2]: http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/parsers/DocumentBuilder.html
You will want to use `org.xml.sax.XMLReader` (<http://java.sun.com/j2se/1.4.2/docs/api/org/xml/sax/XMLReader.html>).
This is also a short little presentation on security by one of wordpress's core developers. [Security in wordpress][1] it covers all of the basic security problems in web apps. [1]: http://markjaquith.wordpress.com/2008/08/16/secure-coding-with-wordpress-wordcamp-sf-2008-slides/
Need to test an ajax timeout condition
|asp.net|testing|ajax|
As the title mentions, I have a timeout callback handler on an ajax call, and I want to be able to test that condition but nothing is coming to mind immediately on ways I can force my application to hit that state, any suggestions?
That is true MySQL is $599 (one license is required per database server) for commercial use
I've used PHP/MySQL for a while, and I've used Rails, and I'm getting into ASP.NET right now. My incentive for switching to ASP.NET at the moment is similar to my incentive for digging into Rails--I find C# and Ruby to be much more enjoyable languages to code in. The object models are much more mature, and it feels like I'm fighting with the tool a lot less. I can't really compare MySQL to SQL Server yet, because I haven't done too much with the latter yet.
SQL Injection. Cross Site Scripting.
As mentioned many times elsewhere, Just Do It. I was able to get started from scratch with Subversion under Windows in no time by reading the quick-start guide in the Red Book. Once I pointed TortoiseSVN at the repository, I was in business. It took me a while to get the finer points down, but they were minor humps to get over. I'd suggest installing the Subversion Service instead of using file:// URLs, but that's mostly personal preference. For a repository stored on your development machine, file:// works fine.
> someone said that recompile is a lazy excuse! yeah lets see how lazy you feel when you have to recompile and deploy your app to 1000's of desktops, all because the DBA has told you that your ad-hoc Query is eating up too much Server time! is it good system architecture if you let connect 1000 desctops direcly to database?
> someone said that recompile is a lazy excuse! yeah lets see how lazy you feel when you have to recompile and deploy your app to 1000's of desktops, all because the DBA has told you that your ad-hoc Query is eating up too much Server time! is it good system architecture if you let connect 1000 desktops directly to database?
You could always run a server-side script that keeps running for a period of time. For example: <pre><code> &lt;?php sleep(10); //sleep for 10 seconds. print "This script has finished."; ?&gt; </code></pre>
SQL INJECTION ATTACKS. They are easy to avoid but all too common. NEVER EVER EVER EVER (did I mention "ever"?) trust user information passed to you from form elements. If your data is not vetted before being passed into other logical layers of your application, you might as well give the keys to your site to a stranger on the street. You do not mention what platform you are on but if on ASP.NET get a start with good ol' Scott Guthrie and his article "[Tip/Trick: Guard Against SQL Injection Attacks][1]". After that you need to consider what type of data you will permit users to submit into and eventually out of your database. If you permit HTML to be inserted and then later presented you are wide-open for Cross Site Scripting attacks (known as XSS). Those are the two that come to mind for me, but our very own Jeff Atwood had a good article at [Coding Horror][2] with a review of the book "[19 Deadly Sins of Software Security][3]". [1]: http://weblogs.asp.net/scottgu/archive/2006/09/30/Tip_2F00_Trick_3A00_-Guard-Against-SQL-Injection-Attacks.aspx [2]: http://www.codinghorror.com/blog/archives/000841.html [3]: http://www.amazon.com/exec/obidos/ASIN/0072260858/codinghorror-20
Look into the plugin, [x_send_file][1] too. "The XSendFile plugin provides a simple interface for sending files via the X-Sendfile HTTP header. This enables your web server to serve the file directly from disk, instead of streaming it through your Rails process. This is faster and saves a lot of memory if you‘re using Mongrel. Not every web server supports this header. YMMV." I'm not sure if it's usable with Blobs, it may just be for files on the file system. But you probably need something that doesn't tie up the web server streaming large chunks of data. [1]: http://john.guen.in/rdoc/x_send_file/
You might have more luck in cmd.exe if you opened it in UNICODE mode. Use "cmd /U". Others have proposed using a real programming language. That's fine, especially if you have a language you are very comfortable with. My friend on the C# team says that C# 3.0 (with Linq) is well-suited to whipping up quick, small programs like this. He has stopped writing batch files most of the time. Personally, I would choose PowerShell. This problem can be solved right on the command line, and in a single line. I'll see if I can work something up for you...
You might have more luck in cmd.exe if you opened it in UNICODE mode. Use "cmd /U". Others have proposed using a real programming language. That's fine, especially if you have a language you are very comfortable with. My friend on the C# team says that C# 3.0 (with Linq) is well-suited to whipping up quick, small programs like this. He has stopped writing batch files most of the time. Personally, I would choose PowerShell. This problem can be solved right on the command line, and in a single line. I'll EDIT: it's not one line, but it's not a lot of code, either. Also, it looks like StackOverflow doesn't like the syntax "$_.Name", and renders the _ as &#95. $mapping = @{ "å" = "a" "ä" = "a" "ö" = "o" } Get-ChildItem -Recurse . *.txt | Foreach-Object { $newname = $_.Name foreach ($l in $mapping.Keys) { $newname = $newname.Replace( $l, $mapping[$l] ) $newname = $newname.Replace( $l.ToUpper(), $mapping[$l].ToUpper() ) } Rename-Item -WhatIf $_.FullName $newname # remove the -WhatIf when you're ready to do it for real. }
The answer to your question depends on how your are authoring your installer. For Visual Studio setup projects, create an installer class in one of your deployed assemblies. This is covered in the MSDN documentation, eg [http://msdn.microsoft.com/en-us/library/d9k65z2d(VS.80).aspx][1] For Wix projects, you can use DTF to build managed custom actions which have complete access to the contents of the MSI. Wix is available at [http://wix.sourceforge.net/][2]. [1]: http://msdn.microsoft.com/en-us/library/d9k65z2d(VS.80).aspx [2]: http://wix.sourceforge.net/
The syntax is: ls > `pwd`.txt That is the '`' character up underneath the '~', not the regular single quote.
Eric, No one is stopping you from choosing the framework/approach that you would wish. If you are going to go the "data driven/stored procedure-powered" path, then by all means, go for it! Especially if it really, really helps you deliver your applications on-spec and on-time. The caveat being (a flipside to your question that is), ALL of your business rules should be on stored procedures, and your application is nothing more than a thin client. That being said, same rules apply if you do your application in OOP : be consistent. Follow OOP's tenets, and *that* includes creating entity objects to represent your domain models. The only real rule here is the word *consistency*. Nobody is stopping you from going DB-centric. No one is stopping you from doing old-school structured (aka, functional/procedural) programs. Hell, no one is stopping anybody from doing COBOL-style code. BUT an application has to be very, very consistent once going down this path, if it wishes to attain any degree of success.
The following is slightly over-engineered, but is a good SQL pattern for "top x" queries. SELECT * FROM scott.emp WHERE (deptno,job,sal) IN (SELECT deptno, job, max(sal) FROM scott.emp WHERE deptno = 20 and job = 'CLERK' GROUP BY deptno, job ) Also note that this will work in Oracle and Postgress (i think) but not MS SQL. For something similar in MS SQL see question [SQL Query to get latest price][1] [1]: http://stackoverflow.com/questions/49404/sql-query-to-get-latest-price#49424
How do you do string comparison in javascript?
|javascript|string|basic|