instruction
stringlengths 0
30k
⌀ |
---|
The following **C++** code uses a **ifstream** object to read integers from a text file (which has one number per line) until it hits **EOF**. Why does it read the integer on the last line twice? How to fix this?
**Code:**
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream iFile("input.txt"); // input.txt has integers, one per line
while (!iFile.eof())
{
int x;
iFile >> x;
cerr << x << endl;
}
return 0;
}
**input.txt**:
10
20
30
**Output**:
10
20
30
30
**Note**: All unnecessary error checking code not included to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).
|
Customizing Visual Studio |
|c#|asp.net|visual-studio|winforms| |
I have been working with Visual Studio (WinForm and ASP.NET applications using mostly C#) for several months now. For the most part my IDE is set up fairly standard but I have been wondering what are some suggestions in terms of plugins/settings that you find to be the most useful? |
|c#|asp.net|visual-studio|winforms|plugin-development| |
I have been working with Visual Studio (WinForm and ASP.NET applications using mostly C#) for several months now. For the most part my IDE is set up fairly standard but I have been wondering what are some suggestions in terms of plugins/settings that you find to be the most useful?
**Update**: Thanks for all the great suggestions. It looks like a general consensus that I should look into 'Resharper' along with some eye-candy with themes and custom fonts. |
Thanks for the answer, samjudson.
After further experimentation, I found that you can even use just `$(':checkbox')` to select them. It's interesting that you can use the `.slice()` function to get the range, but you also have the option of doing it in the selector with `:gt` and `:lt`. I do find the syntax of `.slice()` to be cleaner than using the selector filters, though.
I'm going to have to say that I don't like Ryan Duffield's solution as much, because it requires changes to the markup, and involves repeating code.
|
> Tag = a defined slice in time, usually used for releases
I think this is what one typically means by "tag". But in Subversion:
> They don't really have any formal meaning. A folder is a folder to SVN.
which I find rather confusing: a revision control system that knows nothing about branches or tags. From an implementation point of view I think the subversion way of creating "copies" is very clever, but me having to know about it is what I'd call a leaky abstraction.
Or perhaps I've just been using CVS far too long. |
@DAC
> In short: SID = the unique name of
> your DB, ServiceName = the alias used
> when connecting
Not strictly true.. SID = unique name of the INSTANCE (eg the oracle process running on the machine). Oracle considers the "Database" to the be files.
Service Name = alias to an INSTANCE (or many instances). The main purpose of this is if you are running a cluster, the client can say "connect me to SALES.acme.com", the DBA can on the fly change the number of instances which are available to SALES.acme.com requests, or even move SALES.acme.com to a completely different database without the client needing to change any settings.
|
As with all development, screen size is paramount so I would suggest the 24" iMac if your golden ticket stretches that far or a mac mini with a large (probably non-Apple) monitor if it doesn't. |
Restrict selection of SELECT option without disabling the field |
|html|select| |
I have a multiple selection SELECT field which I don't want the end user to be able to change the value of.
For UI reasons, I would like to be able to do this without using the disabled="true" attribute. I've tried using onmousedown, onfocus, onclick and setting each to blur or return false but with no success.
Can this be done or am I trying to do the impossible? |
I've come up with a fairly naive recursive algorithm (pseudocode):
Map<Object, List<Object>> source; // map of each object to its dependency list
List<Object> dest; // destination list
function resolve(a):
if (dest.contains(a)) return;
foreach (b in source[a]):
resolve(b);
dest.add(a);
foreach (a in source):
resolve(a);
The biggest problem with this is that it has no ability to detect cyclic dependencies - it can go into infinite recursion (ie stack overflow ;-p). The only way around that that I can see would be to flip the recursive algorithm into an interative one with a manual stack, and manually check the stack for repeated elements.
Anyone have something better? |
AdBlock forum [says][1] this is used to detect AdBlock. After some tweaking you could use this to gather some statistics.
<script language="JavaScript" type="text/JavaScript">
setTimeout('detect_abp()', 10000);
var isFF = (navigator.userAgent.indexOf("Firefox") > -1) ? true : false;
var hasABP = false;
function detect_abp()
{
if(isFF)
{
if(Components.interfaces.nsIAdblockPlus != undefined)
{
hasABP = true;
}
else
{
var AbpImage = document.createElement("IMG");
AbpImage.id = 'abp_detector';
AbpImage.src = '/textlink-ads.jpg';
AbpImage.style.width = '0px';
AbpImage.style.height = '0px';
AbpImage.style.top = '-1000px';
AbpImage.style.left = '-1000px';
document.body.appendChild(AbpImage);
hasABP = (document.getElementById('abp_detector').style.display == 'none');
var e = document.getElementsByTagName("iframe");
for (var i = 0; i < e.length; i++)
{
if(e[i].clientHeight == 0)
{
hasABP = true;
}
}
if(hasABP == true)
{
history.go(1);
location = "http://www.tweaktown.com/supportus.html";
window.location(location);
}
}
}
}
</script>
[1]: http://adblockplus.org/forum/viewtopic.php?t=2107&postdays=0&postorder=asc&start=60 |
Not Java per-se, but you may run into issues where you have written something to a file, but it hasn't been actually written yet - it might be in a cache somewhere, and reading from the same file may not actually give you the new information.
Short version - use flush() or whatever the relevant system call is to ensure that your data is actually written to the file.
Note I am not talking about the OS level disk cache - if your data gets into here, it should appear in a read() after this point. It may be that the language itself caches writes, waiting until a buffer fills up or file is flushed/closed. |
Dare Obasanjo has a [pretty good blog][1] post about this topic. You really need to assess what it is you're caching, why you're caching it and what your needs are before you can make a decision on a caching strategy.
[1]: http://www.25hoursaday.com/weblog/2007/07/05/ASPNETCachingVsMemcachedSeekingEfficientDataPartitioningLookupAndRetrieval.aspx |
> It is the only framework that I've
> ever used where component creation is
> a deep intricate process like this.
> None of the other web frameworks
> (whether in the .net world or not)
> make this so painful, which is
> completely inexplicable to me.
Some of the design decisions behind JSF start to make a little more sense when you consider the goals. JSF was designed to be tooled - it exposes lots of metadata for IDEs. JSF is not a web framework - it is a [MVP][1] framework that can be used as a web framework. JSF is highly extensible and configurable - you can replace 90% of the implementation on a per-application basis.
Most of this stuff just makes your job more complicated if all you want to do is slip in an extra HTML control.
> The component is a composition of
> several inputtext (and other) base
> components, btw.
I'm assuming JSP-includes/tooling-based page fragments don't meet your requirements.
I would consider using your *UIComponentELTag.createComponent* to create a composite control with a UIPanel base and creating all its children from existing implementations. (I'm assuming you're using JSPs/taglibs and making a few other guesses.) You'd probably want a custom renderer if none of the existing UIPanel renderers did the job, but renderers are easy.
[1]: http://en.wikipedia.org/wiki/Model_View_Presenter |
In short, what you are doing is right, you want to move the common code into a class library (DLL) and then reference that in any projects that require its logic.
Where you are going wrong is that you are not _maintaining_ it. If you need to make little "tweaks" _[subclass](http://en.wikipedia.org/wiki/Subclass_(computer_science)_ your existing code and extend it, dont change it.. If there are major changes needed, then re-think the design. |
I like to write all of my generic classes as just that: generics. I keep them as application independent as possible, and try to keep them even type unaware. If I make a fancy Tree class, I'll use generics to create it as Tree<T> so that I can use any type I want with the class. If I need to use the Tree to hold GameCharacter objects, I can instantiate Tree<GameCharacter> but if I'm writing a business application I can use it as Tree<Spreadsheet>.
If you find yourself changing your Reuse Libary to match your projects, try making them less specific and instead deriving from your Library base classes in your actual projects. Put all of the common logic in the library classes, and for the application specific parts, create a derived class and implement their logic in that derived class.
As far as solution organization goes, I keep the Reuse Library as a separate project in a common folder and include the project in any solution that I create, which lets me reference easily into it, but also make any changes from any of my applications' solutions. |
You can use something like this in VBA:
Sub ListIndirectRef()
Dim rRng As Range
Dim oSh As Worksheet
Dim oCell As Range
For Each oSh In ThisWorkbook.Worksheets
Set rRng = oSh.UsedRange
For Each oCell In rRng
If InStr(oCell.Formula, "INDIRECT") Then
Debug.Print oCell.Address, oCell.Formula
End If
Next
Next
End Sub
Instead of Debug.Print you can add code to suit your taste |
I don't use Visual Studio or .NET, but it think this problem is common enough amongst ALL programmers so I guess I'll take a crack at it.
We've run into problems just like this when we try to extract common code into a separate library. It might be OK at first, but eventually 1 client is going to need some new functionality and require a change to the library. Invariably this leads to problems with some of the other clients, creating a huge mess. Unless you've got a good way to version your library file, this is a tough problem to solve.
In the end, you might be better off just copying-and-pasting the source files into your new project. Yes, this violates the DRY (Don't Repeat Yourself) principle, but you avoid a lot of problems related to the dependencies a common library creates. |
In addition to the process management code in the os module that Greg pointed out, you should also take a look at the threading module: <http://docs.python.org/lib/module-threading.html>
from threading import Thread
def separate_computations(x, y):
print sum(x for i in range(y)) # really expensive multiplication
Thread(target=separate_compuations, args=[57, 83]).start()
print "I'm continuing while that other function runs in another thread!" |
This kind of thing is much easier if you use STL containers, or maybe [Boost.MultiArray](http://www.boost.org/libs/multi_array/doc/index.html). But if you must use an array, this might give you a hint:
#include <iostream>
int sum(int x) {
return x;
}
template <class T, unsigned N>
int sum(const T (&x)[N]) {
int r = 0;
for(int i = 0; i < N; ++i) {
r += sum(x[i]);
}
return r;
}
int main() {
int x[][2][2] = {
{ { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } }
};
std::cout<<sum(x)<<"\n";
} |
This kind of thing is much easier if you use STL containers, or maybe [Boost.MultiArray](http://www.boost.org/libs/multi_array/doc/index.html). But if you must use an array:
#include <iostream>
#include <boost/foreach.hpp>
#include <vector>
int sum(int x) {
return x;
}
template <class T, unsigned N>
int sum(const T (&x)[N]) {
int r = 0;
for(int i = 0; i < N; ++i) {
r += sum(x[i]);
}
return r;
}
template <class T, unsigned N>
std::vector<int> reduce(const T (&x)[N]) {
std::vector<int> result;
for(int i = 0; i < N; ++i) {
result.push_back(sum(x[i]));
}
return result;
}
int main() {
int x[][2][2] = {
{ { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } }
};
BOOST_FOREACH(int v, reduce(x)) {
std::cout<<v<<"\n";
}
}
|
Here's when I use it:
* Accessing Private Methods from within the class (to differentiate)
* Passing the current object to another method (or as a sender object, in case of an event)
* When creating extension methods :D
I don't use this for Private fields because I prefix private field variable names with an underscore (_). |
I've done this a fair few times and the solutions out there really depend on the environment (enterprise / mission critical or development). The BEST way would be the ***Oracle AS/400 Gateway***. Here are some important links in that area:
Allow AS/400 apps to access oracle with the Oracle Access Manager:
[Installation Guide for the AS/400 Oracle Access Manager][1]
Allow your Oracle apps to access AS/400 tables and be queried using Oracle:
[Oracle Transparent Gateway for DB/2][2]
^^^Those products are fairly expensive but super powerful.^^^
Alternately, here are some more academic approaches to the situation:
Here's a technical comparison of the two technologies... It's a little propagandaish*.
[Technical comparisons of Oracle and DB/2][3]
Here's a document written from the opposite point of view - Someone moving from Oracle to DB2. I still find it's useful information:
[Leverage your Oracle 10g skills to learn DB2...][4]
And another IBM link that has some really great information all around:
[IBM Developer Network Search Results][5]
Hope this helps!
*Yes, I know propagandaish is not a real word.
[1]: http://download.oracle.com/docs/html/B13951_01/toc.htm
[2]: http://download.oracle.com/docs/html/B13983_01/toc.htm
[3]: http://www.google.com/url?sa=t&ct=res&cd=3&url=http%3A%2F%2Fwww.cgisecurity.com%2Fdatabase%2Foracle%2Fpdf%2FCWP_9IVSDB_SECURITY.PDF&ei=RSuvSLSRDI6usAPE-Yht&usg=AFQjCNFNFGPT9WjTOibt5AmK7oQwTIq_Cg&sig2=34iBQyH401KRnKGQ8sSlKg
[4]: http://www.ibm.com/developerworks/db2/library/techarticle/dm-0401gupta/
[5]: http://www.ibm.com/developerworks/search/searchResults.jsp?searchType=1&pageLang=&displaySearchScope=dW&searchSite=dW&lastUserQuery1=oracle+db2+differences&lastUserQuery2=&lastUserQuery3=&lastUserQuery4=&qa=oracle%2520db2%2520differences&query=oracle+db2+&searchScope=dW&Go.x=0&Go.y=0 |
How to unit test an object with database queries |
|database|unit-testing| |
I've heard that unit testing is "totally awesome", "really cool" and "all manner of good things" but 70% or more of my files involve database access (some read and some write) and I'm not sure how to write a unit test for these files.
I'm using PHP and Python but I think it's a question that applies to most/all languages that use database access. |
@ allain <blockquote>Can you lower your own process' priority without being superuser?</blockquote>
Sure. Be aware, however, that this is a one way street. You can't even get back to where you started. And even fairly small reductions in priority can have startlingly large effects on running time when there is significant load on the system. |
Modern `mysqldump` commands have a couple options to help with setting up consistent replication. Check out `--master-data` which will put the binary log file and position in the dump and automatically set when loaded into slave. Also `--single-transaction` will do the dump inside a transaction so that no write lock is needed to do a consistent dump. |
Ideally, your objects should be persistent ignorant. For instance, you should have a "data access layer", that you would make requests to, that would return objects. This way, you can leave that part out of your unit tests, or test them in isolation.
If your objects are tightly coupled to your data layer, it is difficult to do proper unit testing. the first part of unit test, is "unit". All units should be able to be tested in isolation.
In my c# projects, I use NHibernate with a completely seperate Data layer. My objects live in the core domain model and are accessed from my application layer. The application layer talks to both the data layer and the domain model layer.
The application layer is also sometimes called the "Business Layer".
If you are using PHP, create a specific set of classes for **ONLY** data access. Make sure your objects have no idea how they are persisted and wire up the two in your application classes.
Another option would be to use mocking/stubs. |
You should mock the database access if you want to unit test your classes. After all, you don't want to test the database in a unit test. That would be an integration test.
Abstract the calls away and then insert a mock that just returns the expected data. If your classes don't do more than executing queries, it may not even be worth testing them, though... |
Yes, design patterns are largely used in the real world - and daily by many of the people I work with.
In my opinion the biggest value provided by design patterns is that they provide a universal, high level language for you to convey software design to other programmers.
For instance instead of describing your new class as a "utility that creates one of several other classes based on some combination of input criteria", you can simply say it's an *"abstract factory"* and everyone instantly understands what you're talking about. |
Well I'm still new to rails and I'm not sure exactly what you're going for here, but if you're just going for code reuse why not use a regular class method?
<pre><code>
def self.ab(a, b)
a(a).b(b)
end
</pre></code>
You could make that more flexible by taking *args instead of a and b, and then possibly make one or the other optional. If you're stuck on named_scope, can't you extend it to do much the same thing?
Let me know if I'm totally off base with what you're wanting to do. |
There are three key components (assuming ur using SQL server):
SQLConnection, SqlCommand, SqlDataReader
(if you're using something else, replace "Sql" with "Something", like "MySqlConnection", "OracleCommand"
Everything else is just built on top of that
Example 1:
using (SqlConnection connection = new SqlConnection("CONNECTION STRING"))
using (SqlCommand command = new SqlCommand())
{
command.commandText = "SELECT Name FROM Users WHERE Status = @OnlineStatus";
command.Connection = connection;
command.Parameters.Add("@OnlineStatus", SqlDbType.Int).Value = 1; //replace with enum
connection.Open();
using (SqlDataReader dr = command.ExecuteReader))
{
List<string> onlineUsers = new List<string>();
while (dr.Read())
{
onlineUsers.Add(dr.GetString(0));
}
}
}
Example 2:
using (SqlConnection connection = new SqlConnection("CONNECTION STRING"))
using (SqlCommand command = new SqlCommand())
{
command.commandText = "DELETE FROM Users where Email = @Email";
command.Connection = connection;
command.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = "user@host.com";
connection.Open();
command.ExecuteNonQuery();
} |
I've never tried it, but you should write a test case to see if reading from a stream after you have hit the end will work, regardless of if there is more data written to the file.
Is there a reason you can't use a piped input/output stream? Is the data being written and read from the same application (if so, you have the data, why do you need to read from the file)?
Otherwise, maybe read till end of file, then monitor for changes and seek to where you left off and continue... though watch out for race conditions. |
Check out SQLite, it seems like a good option for this particular scenario. |
I would not use config files for storing user data. Use a db. |
[LittleCms][1] is about as barebones as you can get.
@modesty, I would definitely NOT use SharePoint, as it is anything but barebones.
[1]: http://www.littlecms.com/ |
[tinyCMS][1] is about as barebones as you can get. (**edit**: fixed link, I had gotten a little click happy and linked to the wrong thing)
@modesty, I would definitely NOT use SharePoint, as it is anything **but** barebones. It is a fairly expensive product (especially when compared to the many free alternatives), and it has quite the learning curve to do anything interesting.
[1]: http://tinycms.sourceforge.net/ |
Seconding memcached, does the simple stuff well and can go distributive and all that jazz if you need it too |
C#: Accessing a Dictionary.Keys Key through a numeric index |
|c#|.net| |
I'm using a Dictionary<string, int> where the int is a count of the key.
Now, I need to access the last-inserted Key inside the Dictionary, but i do not know the name of it. The obvious attempt:
int LastCount = mydict[mydict.keys[mydict.keys.Count]];
does not work, because Dictionary.Keys does not implement a []-indexer.
I just wonder if there is any similar class? I thought about using a Stack, but that only stores a string. I could now create my own struct and then use a Stack<MyStruct>, but I wonder if there is another alternative, essentially a Dictionary that implements an []-indexer on the Keys? |
Not 100% sure example what you are asking, but personally, and I use MochiKit, I create JavaScript "classes" (or widgets, if you prefer) for every significant client-side UI structure. These know, of course, how to populate themselves with data.
I don't know what more there is to say - writing UI code for the browser in JavaScript is no different than writing UI code for other types of apps, as far as I am concerned. Build classes and instantiate them as needed, populate them with data, have them throw events, etc. etc.
Am I up in the night on this? :)
----------
EDIT: In other words, yes - do what you are doing, for the most part. I see too many novice JavaScript hackers write a bunch of poorly-cohesive functions that don't appear to be a part of anything specific other than they are all in a single file. Hope that makes sense. |
Here's how I would do it.
I'd obtain a list of common English words with usage frequency and some grammatical information (like is it a noun or a verb?).
Then I'd run a filter on it so obscure words are removed and that words which are too long are excluded.
Then my generation algorithm would pick 2 words from the list and concatenate them and add a random 3 digits number.
I can also randomize word selection pattern between verb/nouns like
**eatCake778 or pickBasket524 or rideFlyer113 etc..**
the case needn't be camel casing, you can randomize that as well. You can also randomize the placement of the number and the verb/noun.
And since that's a lot of randomizing, Jeff's [The Danger of Naïveté][1] is a must-read.
[1]: http://www.codinghorror.com/blog/archives/001015.html |
Here's how I would do it.
I'd obtain a list of common English words with usage frequency and some grammatical information (like is it a noun or a verb?). I think you can look around the intertubes for some copy. Firefox is open-source and it has a spellchecker... so it must be obtainable somehow.
Then I'd run a filter on it so obscure words are removed and that words which are too long are excluded.
Then my generation algorithm would pick 2 words from the list and concatenate them and add a random 3 digits number.
I can also randomize word selection pattern between verb/nouns like
> **eatCake778
pickBasket524
rideFlyer113
etc..**
the case needn't be camel casing, you can randomize that as well. You can also randomize the placement of the number and the verb/noun.
And since that's a lot of randomizing, Jeff's [The Danger of Naïveté][1] is a must-read. Also make sure to study dictionary attacks well in advance.
And after I'd implemented it, I'd run a test to make sure that my algorithms should never collide. If the collision rate was high, then I'd play with the parameters (amount of nouns used, amount of verbs used, length of random number, total number of words, different kinds of casings etc.)
[1]: http://www.codinghorror.com/blog/archives/001015.html |
Best I can give you is a "works for me" on SVN 1.5. You may try adding `--no-auth-cache` to your `svn update` to see if that lets you override more easily.
If you want to permanently switch from user2 to user1, head into ~/.subversion/auth/ on *nix and delete the auth cache file for domain.com (most likely in ~/.subversion/auth/svn.simple/ -- just read through them and you'll find the one you want to drop). While it is possible to update the current auth cache, you have to make sure to update the length tokens as well. Simpler just to get prompted again next time you update. |
The following **C++** code uses a **ifstream** object to read integers from a text file (which has one number per line) until it hits **EOF**. Why does it read the integer on the last line twice? How to fix this?
**Code:**
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream iFile("input.txt"); // input.txt has integers, one per line
while (!iFile.eof())
{
int x;
iFile >> x;
cerr << x << endl;
}
return 0;
}
**input.txt**:
10
20
30
**Output**:
10
20
30
30
**Note**: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).
|
Complexity of Regex substitution |
|regex|complexity-theory| |
I didn't get the answer to this anywhere. What is the runtime complexity of a Regex substitution? |
I didn't get the answer to this anywhere. What is the runtime complexity of a Regex match and substitution?
Edit: I work in python. But would like to know in general about most popular languages/tools (java, perl, sed). |
Have you looked at [as3corelib][1]? It appears to provide an AS3 parser for JSON data, and my hope would be that it doesn't rely upon eval (eval tends to be bad for security as you noted). There are similar libs for Javascript as well, and they tend to be the preferred way to parse json due to the security implications of calling eval on (potentially) evil data.
[1]: http://code.google.com/p/as3corelib/ |
I generally only derive my own collection classes if I need to "add value". Like, if the collection itself needed to have some "metadata" properties tagging along with it. |
If your clients are using SMS then you're in the clear... SMS supports EXE. You enter a command line when creating 'Programs' and clients are probably already calling msiexec to launch the MSI. Also I'm pretty sure SMS predates the MSI file format :)
However if they're using Active Directory / Group Policy Objects.. then you're SOL as that does depend on MSI format for deployment.
If you do want to stick with InstallAnywhere, there are a number of "MSI repackaging" tools available. Assuming you're looking at a basic application (device drivers might be an issue) then repackaging should be a fairly painless process.
|
**6 of 1, half dozen of another**
Either way its the same thing. I only do it when I have reason to add custom code into the BusinessObjectCollection.
With out it having load methods return a list<T> allows me to write more code in a common generic class and have it just work. Such as a Load method.
|
I prefer just to use `List<BusinessObject>`. Typedefing it just adds unnecessary boilerplate to the code. `List<BusinessObject>` is a specific type, it's not just any `List` object, so it's still strongly typed.
More importantly, declaring something `List<BusinessObject>` makes it easier for everyone reading the code to tell what types they are dealing with, they don't have to search through to figure out what a `BusinessObjectCollection` is and then remember that it's just a list. By typedefing, you'll have to require a consistent (re)naming convention that everyone has to follow in order for it to make sense. |
The literal answer is no - there is never anything "inherently wrong" with code, it's a matter of whether it meets the requirements - which may or may not include being maintainable, secure, robust or fast.
The code you are running is actually a JET query purely within Access - the Java code is doing nothing except telling Access to run the query.
On the one hand, if it ain't broke don't fix it. On the other hand, there's a good chance it will break in the near future so you could try fixing it in advance.
The two likely reasons it might break are:
1. SQL injection risk. Depending on where csvDirPath and csvFileName come from (e.g. csvFileName might come from the name of the file uploaded by a user?), and on how clever the Access JDBC driver is, you could be open to someone breaking or deleting your data by inserting a semicolon (or some brackets to make a subquery) and some additional SQL commands into the query.
2. You are relying on the columns of the CSV file being compatible with the columns of the Access table. If you have unchecked CSV being uploaded, or if the CSV generator has a particular way of handling nulls, or if you one day get an unusual date or number format, you may get an error on inserting into the Access table.
Having said all that, we are all about pragmatism here. If the above code is from a utility class which you are going to use by hand a few times a week/month/year/ever, then it isn't really a problem.
If it is a class which forms part of a web application, then the 'official' Java way to do it would be to read records out of the CSV file (either using a CSV parser or a CSV/text JDBC driver), get the columns out of the recordset, do some validation or sanity checking on them, and then use a new PreparedStatement to insert them into the Access database. Much more trouble but much more robust.
You can probably find a combination of tools (e.g. object-relational layers or other data access tools) which will do a lot of that for you, but setting up the tools is going to be as much hassle as writing the code. Then again, you'll learn a lot from either one.
|
I usually try to break up my tests between testing the objects (and ORM, if any) and testing the db. I test the object-side of things by mocking the data access calls whereas I test the db side of things by testing the object interactions with the db which is, in my experience, usually fairly limited.
I used to get frustrated with writing unit tests until I start mocking the data access portion so I didn't have to create a test db or generate test data on the fly. By mocking the data you can generate it all at run time and be sure that your objects work properly with known inputs. |
I'd like to think my issue is "special" here, since I am using a custom form. I chose to use a custom form rather than a custom FormTemplate simply because I'm doing a lot of stuff that's not very SharePoint list-like (making ajax calls to get info from a third-party app then generating some dynamic form elements based on that ajax result, then subsequent processing of that data on postback). I thought it'd be a nightmare to try this within the usual custom rendering template mechanism.
I also don't think I can supply the custom form declarations in the list definition itself, because I have multiple content types associated with this list, and each content type has its own custom form (the other type is thankfully much simpler).
Actually, my simple way of keeping the list guid in my hidden field was a very low impact way to address this specific problem. My main concern is that I'm not sure why the SPContext just loses all its usefulness when I postback here, which makes me think I'm doing something wrong. |
Is there any way that you could *include* the child nant file as opposed to executing it as a full-fledged child nant project? This would prevent the overwrite, but not sure if it's possible in your situation. |
You can find an implementation of md5crypt in the [tcllib package.][1] Download is available from [sourceforge][2].
[1]: http://tcllib.sourceforge.net/doc/md5crypt.html
[2]: http://sourceforge.net/project/showfiles.php?group_id=12883 |
You can find an implementation of md5crypt in the [tcllib package.][1] Download is available from [sourceforge][2].
You can also find an example of an apache-compatible md5crypt in the [source code for the CAS Generic Handler][3]
[1]: http://tcllib.sourceforge.net/doc/md5crypt.html
[2]: http://sourceforge.net/project/showfiles.php?group_id=12883
[3]: http://esup-casgeneric.sourceforge.net/api/src-html/md5/MD5Crypt.html#line.220 |
id:[a* TO z*] id:[0* TO 9*] etc.
I just did this in lukeall on my index and it worked, therefore it should work in Solr which uses the standard query parser. I don't actually use Solr.
In base Lucene there's a fine reason for why you'd never query for every document, it's because to query for a document you must use a `new indexReader("DirectoryName")` and apply a query to it. Therefore you could totally skip applying a query to it and use the `indexReader` methods `numDocs()` to get a count of all the documents, and `document(int n)` to retrieve any of the documents. |
There are a couple of open source plugins on SourceForge,
http://sourceforge.net/tracker/?group_id=103281&atid=738747
(search for image)
The plugin architecture is easy to understand if you know Javascript.
If you have the time you could roll out your own. |
MD5Crypt is basically a replacement for the old-fashioned unix crypt function. It was introduced in freebsd, and has been adopted by other groups as well.
The basic idea is this:
- a hash is a good way to store a password
- you take the user's entered password and hash it
- compare it to the stored hash
- if the hash is the same, the passwords match
But there's a problem:
- Suppose you pick the password "jeff" and I also pick the password "jeff".
- Now both of our password hashes are the same.
- So if I see the stored hash codes, I will know your password is the same as mine, "jeff".
So, we can add a "salt" string to the password.
- This can be any random thing.
- Suppose for your account it is "zuzu" and for my account it is "rjrj".
- Now we hash the string "jeffzuzu" for your password, and "jeffrjrj" for my password.
- Now we have different hash values for our password.
- We can safely store the salt value with the hashed password, since even knowing the salt value won't help to decode the hash.
You mention .net, there's a pointer over in another forum to this:
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new
System.Security.Cryptography.MD5CryptoServiceProvider();
string hash =BitConverter.ToString((md5.ComputeHash(
System.Text.ASCIIEncoding.Default.GetBytes(stringtohash) ) ));
HTH!
[1]: http://tcllib.sourceforge.net/doc/md5crypt.html |
It stops and starts the services that IIS consists of.
You can think of it as closing the relevant program and starting it up again. |
Yes, you just run xcode builds via the command line (xcodebuild) which makes it simple to target from CC via an ant <exec>. I've been using just regular CC, not the ruby version and it works fine. Here's a barebones example:
<project name="cocoathing" default="build">
<target name="build">
<exec executable="xcodebuild" dir="CocoaThing" failonerror="true">
<arg line="-target CocoaThing -buildstyle Deployment build" />
</exec>
</target>
</project>
[More info on xcodebuild][1]
And there does appear to be a standard git object [here][2], but I don't use git so I can't tell you much more than that!
[1]: http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/xcodebuild.1.html
[2]: http://cruisecontrol.sourceforge.net/main/api/net/sourceforge/cruisecontrol/sourcecontrols/Git.html |
Yes, you just run xcode builds via the command line (xcodebuild) which makes it simple to target from CC via an ant `<exec>`. I've been using just regular CC, not the ruby version and it works fine. Here's a barebones example:
<project name="cocoathing" default="build">
<target name="build">
<exec executable="xcodebuild" dir="CocoaThing" failonerror="true">
<arg line="-target CocoaThing -buildstyle Deployment build" />
</exec>
</target>
</project>
[More info on xcodebuild][1]
And there does appear to be a standard git object [here][2], but I don't use git so I can't tell you much more than that!
[1]: http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/xcodebuild.1.html
[2]: http://cruisecontrol.sourceforge.net/main/api/net/sourceforge/cruisecontrol/sourcecontrols/Git.html |
C# Performance For Proxy Server (vs C++) |
|c#|c++|performance|sockets|system.net| |
I want to create a simple http proxy server that does some very basic processing on the http headers (i.e. if header x == y, do z). The server may need to support hundreds of users. I can write the server in C# (pretty easy) or c++ (much harder). However, would a C# version have as good of performance as a C++ version? If not, would the difference in performance be big enough that it would not make sense to write it in C#? |
I've never done this in PHP and I've never used Python, but what you want to do is mock out the calls to the database. To do that you can implement some [IoC][1] whether 3rd party tool or you manage it yourself, then you can implement some mock version of the database caller which is where you will control the outcome of that fake call.
A simple form of IoC can be performed just by coding to Interfaces. This requires some kind of object orientation going on in your code so it may not apply to what your doing (I say that since all I have to go on is your mention of PHP and Python)
Hope that's helpful, if nothing else you've got some terms to search on now.
[1]: http://en.wikipedia.org/wiki/Inversion_of_Control |
I agree with the first post - database access should be stripped away into a DAO layer that implements an interface. Then, you can test your logic against a stub implementation of the DAO layer. |
I misunderstood you. I thought you wanted Nuclear or Deals. The below should give you only Nuclear and Deals.
----------
select p.*
from wp_posts p, wp_terms t, wp_term_taxonomy tt, wp_term_relationship tr,
wp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2
wp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2
where p.id = tr.object_id and t.term_id = tt.term_id and tr.term_taxonomy_id = tt.term_taxonomy_id
and p.id = tr2.object_id and t2.term_id = tt2.term_id and tr2.term_taxonomy_id = tt2.term_taxonomy_id
and p.id = tr3.object_id and t3.term_id = tt3.term_id and tr3.term_taxonomy_id = tt3.term_taxonomy_id
and (tt.taxonomy = 'category' and tt.term_id = t.term_id and t.name = 'Category1')
and (tt2.taxonomy = 'post_tag' and tt2.term_id = t2.term_id and t2.name = 'Nuclear')
and (tt3.taxonomy = 'post_tag' and tt3.term_id = t3.term_id and t3.name = 'Deals') |
What you really need to do is to use some sort of source control software such that:
- Any change that you do in one project will reflect across all projects without loss of referential integrity
- You may have the option to keep more than one version of the library you have and reference a specific version instead of pulling hairs figuring out which version is used by which project
Just make sure that you have unit tests in hand to make sure that your previous projects are unaffected or only minorly affected by any changes you make on your library.
Goodluck! |
If by user friendly, you mean that a user could type the answer in then I think you would want to look in a different direction. I've seen and done implementations for initial random passwords that pick random words and numbers as an easier and less error prone string.
If though you're looking for a way to encode a random code in the URL string which is an issue I've dealt with for awhile then I what I have done is use 64-bit encoded GUIDs. |
You can use the `nm -g` tool from the binutils toolchain. However, their source is not always readily available. and I'm not actually even sure that this information can always be retrieved. Perhaps `objcopy` reveals further information.
/EDIT: The tool's name is of course `nm`. The flag `-g` is used to show only exported symbols. |
@[Outlaw](#34752)<br/>
If you need to copy code and make application-specific changes, then that code isn't generic. it should be refactored so that the common functionality stays in the common library, and the application specific functionality should be added to a subclass in that application's codebase.
Using version control with a branch for each app-specific version can help with integration problems - make your changes in the branch, then test them with your other applications before merging them back to trunk. There are several questions on this site about good free online source control hosts if you don't want to set up your own. |
I have done it both ways that you mentioned. I like the second, but like you said, it is a little tedious for when you make updates to that library.
Another way that I have used, is choosing a central location to keep your libraries. Then add a registry key with a string value to point to that directory. When adding a reference, all your libraries will show up under the .net tab, just like if the libraries were in the GAC. Then you can make a post build command to build the library to that central location.
Here's the registry key, change CompanyName and the directory:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\AssemblyFolders\ComapnyName]
@="C:\\CentralLocation"
|
I think the problem is that when the Grid is drawn, it draws each row from top to bottom, and within each row the items left to right. So the row-spanned <mx:TextArea> item is drawn first extending down into the area of the 2 next rows, which get drawn after and on top.
The quickest way around I can see would be to draw the row borders on the <mx:GridItem>s instead, skipping the left and right edges based on the item's placement in the row. Something like this:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Style>
Grid {
background-color: white;
horizontal-gap: 0;
}
GridItem {
padding-top: 5;
padding-left: 5;
padding-right: 5;
padding-bottom: 5;
background-color: #efefef;
border-style: solid;
border-thickness: 1;
border-color: black;
}
.left {
border-sides: top, bottom, left;
}
.right {
border-sides: top, bottom, right;
}
.center {
border-sides: top, bottom;
}
</mx:Style>
<mx:Grid>
<mx:GridRow>
<mx:GridItem styleName="left">
<mx:Label text="Label"/>
</mx:GridItem>
<mx:GridItem styleName="center">
<mx:ComboBox/>
</mx:GridItem>
<mx:GridItem styleName="center">
<mx:Label text="Label"/>
</mx:GridItem>
<mx:GridItem styleName="right">
<mx:ComboBox/>
</mx:GridItem>
</mx:GridRow>
<mx:GridRow>
<mx:GridItem styleName="left">
<mx:Label text="Label"/>
</mx:GridItem>
<mx:GridItem styleName="center">
<mx:TextInput/>
</mx:GridItem>
<mx:GridItem colSpan="2" rowSpan="3">
<mx:VBox width="100%" height="100%">
<mx:Label text="Label"/>
<mx:TextArea width="100%" height="100%"/>
</mx:VBox>
</mx:GridItem>
</mx:GridRow>
<mx:GridRow>
<mx:GridItem styleName="left">
<mx:Label text="Label"/>
</mx:GridItem>
<mx:GridItem styleName="center">
<mx:TextInput/>
</mx:GridItem>
</mx:GridRow>
<mx:GridRow>
<mx:GridItem styleName="left">
<mx:Label text="Label"/>
</mx:GridItem>
<mx:GridItem styleName="center">
<mx:TextInput/>
</mx:GridItem>
</mx:GridRow>
</mx:Grid>
</mx:Application>
|
|html|user-interface|select| |
How to concatenate strings of a string field in a PostgreSQL 'group by' query? |
|postgresql| |
I am going to answer my own question because I just found the answer, but thought it still worth posting here.
I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table:
ID COMPANY_ID EMPLOYEE
1 1 Anna
2 1 Bill
3 2 Carol
4 2 Dave
and I wanted to group by company_id to get something like:
COMPANY_ID EMPLOYEE
1 Anna, Bill
2 Carol, Dave
|
I am going to answer my own question because I just found the answer, but thought it still worth posting here.
I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table:
ID COMPANY_ID EMPLOYEE
1 1 Anna
2 1 Bill
3 2 Carol
4 2 Dave
and I wanted to group by company_id to get something like:
COMPANY_ID EMPLOYEE
1 Anna, Bill
2 Carol, Dave
|
|sql|postgresql|concat|group-by| |
It's created when it's executed and dropped when the session ends. |
Resources for building a Visual Studio plug-in? |
|visual-studio|plugin-development| |
I'd like to build a pretty simple plug-in for Visual Studio, but I don't really know how this has to be done. Is this doable in (non-managed) C++?
I'd like to know what resources you'd recommend me...
Thanks.
|
|visual-studio|add-in|plugin-development| |
Are you asking about FLV video files or Flash "movies" as in SWF?
*Just to clarify, an FLV is the Flash Video Format (or whatever the acronym is), a regular Flash movie/application/banner would be an SWF. These are very different file formats.* |
try:
ffmpeg -t 30 -i inputfile.mp3 outputfile.mp3 |
You might want to try [Mp3Splt][1].
I've used it before in a C# service that simply wrapped the mp3splt.exe win32 process. I assume something similar could be done in your Linux/PHP scenario.
[1]: http://mp3splt.sourceforge.net/mp3splt_page/home.php |
Be careful not to rely on this mod behavior in C/C++ on all OSes and architectures. If I recall correctly, I tried to rely on C/C++ code like
float x2 = x % n;
to keep x2 in the range from 0 to n-1 but negative numbers crept in when I would compile on one OS, but things would work fine on another OS. This made for an evil time debugging since it only happened half the time! |
I've never tried, so I don't know about doing it in C++, but this website has loads of information: http://msdn.microsoft.com/en-us/vsx/default.aspx |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.