text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Enforce constraint checking only when inserting rows in MSSQL? Is there a way to enforce constraint checking in MSSQL only when inserting new rows? I.e. allow the constraints to be violated when removing/updating rows?
Update: I mean FK constraint.
A: You could create an INSERT TRIGGER that checks that the conditions are met. That way all updates will go straight through.
CREATE TRIGGER employee_insupd
ON employee
FOR INSERT
AS
/* Get the range of level for this job type from the jobs table. */
DECLARE @min_lvl tinyint,
@max_lvl tinyint,
@emp_lvl tinyint,
@job_id smallint
SELECT @min_lvl = min_lvl,
@max_lvl = max_lvl,
@emp_lvl = i.job_lvl,
@job_id = i.job_id
FROM employee e INNER JOIN inserted i ON e.emp_id = i.emp_id
JOIN jobs j ON j.job_id = i.job_id
IF (@job_id = 1) and (@emp_lvl <> 10)
BEGIN
RAISERROR ('Job id 1 expects the default level of 10.', 16, 1)
ROLLBACK TRANSACTION
END
ELSE
IF NOT (@emp_lvl BETWEEN @min_lvl AND @max_lvl)
BEGIN
RAISERROR ('The level for job_id:%d should be between %d and %d.',
16, 1, @job_id, @min_lvl, @max_lvl)
ROLLBACK TRANSACTION
END
A: I think your best bet is to remove the explicit constraint and add a cursor for inserts, so you can perform your checking there and raise an error if the constraint is violated.
A: What sort of constraints? I'm guessing foreign key constraints, since you imply that deleting a row might violate the constraint. If that's the case, it seems like you don't really need a constraint per se, since you're not concerned with referential integrity.
Without knowing more about your specific situation, I would echo the intent of the other posters, which seems to be "enforce the insert requirements in your data access layer". However, I'd quibble with their implementations. A trigger seems like overkill and any competent DBA should sternly rap you on the knuckles with a wooden ruler for trying to use a cursor to perform a simple insert. A stored procedure should suffice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Strange Rails Authentication Issue I'm using the RESTful authentication Rails plugin for an app I'm developing.
I'm having a strange issue I can't get to the bottom of.
Essentially, the first time I log into the app after a period of inactivity (the app is deployed in production, but only being used by me), I will be brought to a 404 page, but if I go back to the home page and log in again, everything works according to plan.
Any ideas?
A: Please check your routes.
Not all routes are created equally. Routes have priority defined by the order of appearance of the routes in the config/routes.rb file. The priority goes from top to bottom. The last route in that file is at the lowest priority and will be applied last. If no route matches, 404 is returned.
More info: http://api.rubyonrails.org/classes/ActionController/Routing.html
A: I'm using a slightly modified version of that plugin so I'm not 100% sure that this will be the same for you, but for me the default is to redirect to the root path, or the page you were trying to get to if there is one. (check your lib/authenticated_system.rb to see your default) If you don't have map.root defined in your routes, I believe that would cause the error you're describing -- it wouldn't find root_path at first but if you tried "from" a page in your app it would redirect to that page.
Let us know what happens with this one if you would, I'm curious to see what this ends up being in case I run into it in the future. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Developing on Eclipse 3.4, running on Eclipse 3.3 I'm developing an Eclipse plug-in, based on a bunch of core Eclipse plug-ins like SWT, JDT, GEF and others.
I need my plug-in to be compatible with Eclipse 3.3, since many potential customers are still using it. However, personally I like the new features in Eclipse 3.4 and would like to use it for my development. This means I need PDE to reference 3.3 code and, when debug, execute a 3.3 instance.
Any tips on how this can be achieved?
Thanks.
A: You can change the 'Target platform' setting to point to the location of an existing set of eclipse 3.3 plugins. This will compile your code against the 3.3 plugins, making sure that they stay compatible no matter which version of eclipse you are using to develop the application.
The setting is under Window->Preferences->Plug-in development->Target Platform
A: What Barak said. See also this topic on Eclipse help:
http://help.eclipse.org/stable/index.jsp?topic=/org.eclipse.pde.doc.user/guide/tools/preference_pages/target_platform.htm
Note also:
*
*the default target platform is your Eclipse install
*your dev environment should be at least as recent as the target platform (i.e. you cannot use 3.3 as dev environment and target 3.4)
*this also allows you to develop against plug-ins you don't have in your development Eclipse install.
A: And is it no way how to develop plugin for newer palfrom? Eg.: develop new plugin for 3.5 into 3.4...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: php mail() not working windows 2003, IIS SMTP I'm getting this problem:
PHP Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable to relay for [email protected] in c:\inetpub\wwwroot\mailtest.php on line 12
from this script:
<?php
$to = "[email protected]";
$subject = "test";
$body = "this is a test";
if (mail($to, $subject, $body)){
echo "mail sent";
}
else {
echo "problem";
}
?>
section from php.ini on the server:
[mail function]
; For Win32 only.
SMTP = server.domain.com; for Win32 only
smtp_port = 25
; For Win32 only.
sendmail_from = [email protected]
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
;sendmail_path =
(note that "server" and "domain" refer accurately to the actual server and domain name)
In IIS, SMTP is running. Under "Access" tab, "Relay" button, the Select which computers may relay through this virtual server is set to checkbox "only the list below" and on the list is "127.0.0.1(xxx.xxx.xxx.xxx)" (x's representing actual server IP address).
Server is running Windows Server 2003 Service Pack 2, fully patched as of 5 PM Sept 1st 2008. I assume it is running IIS7 (how to check?).
Any ideas?
In reponse to Espo: This machine is hosted at a datacenter. We do not want to use a gmail account (were doing it, want to move away from that). Windows server 2003 comes with its own SMTP server.
Update: Per Yaakov Ellis' advice, I dropped all relay restrictions and added the server IP to the allowed list (using the reverse DNS button provided) and the thing started working.
Thanks to both Espo and Yaakov for helping me out.
A: Try removing the IP restrictions for Relaying in the SMTP server, and opening it up to all relays. If it works when this is set, then you know that the problem has to do with the original restrictions. In this case, it may be a DNS issue, or perhaps you had the wrong IP address listed.
A: You are using the wrong SMTP-server. If you you are only going to send emails to your gmail-account, have a look at my answer here.
If you also need to send email to other accounts, ask you ISP for your SMTP-details.
EDIT: I think it is always better to use the ISP SMTP-server as they (should) have people monitoring the mail-queues, checking for exploits and updating the mail-software. If you business is developing web-applications it is almost always best to stick with what you do, and let other people do their stuff (eg running mailservers).
If you still for some reason want to use you local SMTP server, the first thing would be to rule out the php-part. Try folowing KB153119 and then check you SMTPServer IISlog for errors.
EDIT2:
That KB-article says it is for exchange, but the same commands are used for other SMTP-servers (including IIS) as well, so please try and see if you can send mails using the examples from the article.
A: @Espo: I'll do that re KB153119. Thanks.
About the mail server: I hear you.
I'll update when I uncover more.
A: @Espo, the article in question relates to Exchange servers, not IIS7.0 SMTP server.
From the summary: This article describes how to telnet to port 25 on a computer that runs Simple Mail Transfer Protocol (SMTP) services to troubleshoot SMTP communication problems. The information in this article, including error messages, only applies to issues when attempting to resolve SMTP communication issues with Microsoft Exchange-based servers and is not intended for general troubleshooting purposes.
A: I had the same problem, php 5 on iis6, 2003 server. Php always failed when trying to use mail().
I've managed to get it accepting mail from php by changing the Relay Restrictions from 'Only the list below' (which is empty by default) to 'All except the list below' .
The relay restrictions can be found in the Access tab in the smtp servers properties screens.
Of course if the server is open to the internet then one would have to be more sensible about these relaying restrictions but in my case this is on a virtual server on a dev box.
hope that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Running DB Migrations from application I have a rails application where each user has a separate database. (taking Joel Spolsky's advice on this). I want to run DB migrations from the rails application to create a new database and tables for this user.
What is the easiest way to do this?
Maybe the db migration is not the best for this type of thing. Thanks!
It would be nice if it could be a completely automated process. The following process would be ideal.
*
*A user signs up on our site to use this web app
*Migrations are run to create this users database and get tables setup correctly
Is there a way of calling a rake task from a ruby application?
A: We use seperate configuration files for each user. So in the config/ dir we would have roo.database.yml which would connect to my personal database, and I would copy that over the database.yml file that is used by rails.
We were thinking of expanding the rails Rakefile so we could specify the developer as a environment variable, which would then select a specfic datbase configuration, allowing us to only have one database.yml file. We haven't done this though as the above method works well enough.
A: To answer part of your question, here's how you'd run a rake task from inside Rails code:
require 'rake'
load 'path/to/task.rake'
Rake::Task['foo:bar:baz'].invoke
Mind you, I have no idea how (or why) you could have one database per user.
A: Actually I have discovered a good way to run DB migrations from an application:
ActiveRecord::Migrator.migrate("db/migrate/")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to take screenshot in Mac OS X using Cocoa or C++ How to take screenshot programmically of desktop area in Mac OS X ?
A: Qt includes an example screenshot app in examples\desktop\screenshot. Qt works on a range of platforms, including MacOSX.
http://trolltech.com/products/qt/
A: Two interesting options I have seen, but yet to use professionally, are the screencapture utility and a MacFuse demo.
The screencapture utility has been around since 10.2, according to the man page, and could be linked to a Cocoa application by use of NSTask.
The MacFuse demo worked by creating a new screenshot each time a folder was opened, or something like that. The idea being you could write a quick script to access the image when you needed it, without having to have the script actually run on that machine.
But seriously, Apple has some other sample code called "Son of Grab" which uses the new CGWindow API which is pretty awesome.
http://developer.apple.com/samplecode/SonOfGrab/
A: One way of going about doing this would be to use NSTask in conjuction with the 'screencapture' command line command.
For example:
NSTask *theProcess;
theProcess = [[NSTask alloc] init];
[theProcess setLaunchPath:@"/usr/sbin/screencapture"];
// use arguments to set save location
[theProcess setArguments:@"blahblah"];
[theProcess launch];
The you could open up the file wherever you told it to be saved, process it, and then delete it as needed. Obviously stopgap, but it would work.
A: If you're fine with Leopard compatibility, there's a very powerful new CGWindow API that will let you grab screen shots, window shots, or composites of any range of window layers.
http://developer.apple.com/samplecode/SonOfGrab/
A: The following might be helpful if you are attempting to accomplish this with C++ or python. Also, this would be even more helpful in the case that you want your programmatic method to be cross-platform portable. (Windows, Linux, Mac osx, and even beyond)
An earlier response mentions QT.
In the same way that QT will allow you to capture and save a screenshot, so does another "competing" framework, namely wxWidgets. wxWidgets is a C++ framework, but it also provides python bindings via wxPython.
To read more, use the following link, search the book for wxScreenDC and choose "Page 139" from the list of pages that match the search:
http://books.google.com/books?id=CyMsvtgnq0QC&vq="accessing+the+screen+with+wxScreendc"
A: If you consider REALbasic, this is extremely easy to do with RB and the MBS Plugins. I've just written an application that does timed screenshots using RB and the MBS Plugins. You can read about it here: http://tektalkin.blogspot.com/2008/08/screenaudit-for-mac-osx.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Generate field in MySQL SELECT If I've got a table containing Field1 and Field2 can I generate a new field in the select statement? For example, a normal query would be:
SELECT Field1, Field2 FROM Table
And I want to also create Field3 and have that returned in the resultset... something along the lines of this would be ideal:
SELECT Field1, Field2, Field3 = 'Value' FROM Table
Is this possible at all?
A: Yes - it's very possible, in fact you almost had it!
Try:
SELECT Field1, Field2, 'Value' AS `Field3` FROM Table
A: SELECT Field1, Field2, 'Value' Field3 FROM Table
or for clarity
SELECT Field1, Field2, 'Value' AS Field3 FROM Table
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: PHP and Java EE Backend Can I use Struts as a backend and PHP as front end for a web application? If yes, what may be the implications.
A: The first thing to came to mind is Quercus (from the makers of the Resin servlet engine), as Jordi mentioned. It is a Java implementation of the PHP runtime and purportedly allows you to access Java objects directly from your PHP (part of me says "yay, at last").
On the other hand, while I have been itching to try a project this way, I would probably keep the separation between Java EE and PHP unless there was a real reason to integrate on the code-level.
Instead, why don't you try an SOA approach, where your PHP "front-end" calls into the Struts application over a defined REST or SOAP API (strong vote for REST here) over HTTP.
http://mydomain.com/rest/this-is-a-method-call?parameter1=foo
You can use Struts to build your entire "backend" model, dealing only with business logic and data, and completely ignoring presentation. As you expose the API with these URLs, and you are basically building a REST API (which may come in handy later if you ever need to provide greater access to your backend, perhaps by other client apps).
Your PHP application can be built separately (and rather thinly), calling into the REST API (perhaps using Curl) as if it would call into a database or some native PHP class library.
Anyway, that's what I'd do. But, if you do use Quercus, please post how it went.
A: I don't know much about Java, but I remember running into Quercus a while ago. It's a 100% Java interpreter for PHP code.
So yes, you could have PHP templates on your Java app. Update: see Quercus: PHP in Java for more info.
A: What do you mean by backend and and frontend?
If you mean using Java for the admin side of your site and PHP for the part that the public will see then there is nothing stopping you.
The implications are that you will have to maintain two applications in different languages.
A: I think what you mean is you want to use PHP as your templating language and structs as your middleware (actions etc).
I would imaging the answer would be no, not without some kind of bridge between the structs session and the PHP.
If you say change x to 3 in java in a structs action, you couldn't just go <?php echo x ?> or whatever to get the value out, you would need to transfer that information back and forth somehow.
Submitting would be OK though, I would imagine.
Not recommended though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: cross platform unicode support I find that getting Unicode support in my cross-platform apps a real pain in the butt.
I need strings that can go from C code, to a database, to a Java application and into a Perl module. Each of these use a different Unicode encodings (UTF8, UTF16) or some other code page. The biggest thing that I need is a cross-platform way of doing conversions.
What kind of tools, libraries or techniques do people use to make handling these things easier?
A: Have a look at this: http://www.icu-project.org/
A: Perl has Encode as a standard library. It can be used to read/write any encoding you want, so that's not going to be a problem.
A: How are you doing the cross-platform calls? Is it all called from Java?
http://java.sun.com/docs/books/tutorial/i18n/text/string.html might be useful.
I'm a bit confused about exactly what you are trying to do. Is the database essentially interface between all the code? Then it should be easy - just make the DB UTF-8 and each of the clients will need to do their own conversions.
Sounds like an interesting problem, could you share some more details?
A: Well, I guess iconv is sufficient for your needs. Iconv should be available on any POSIX system by default (those include (GNU/)Linux, *BSD, Mac OS X...). On Windows AFAIK it requires separate library but:
*
*you may just install it/bundle with your software/static compile it. (libiconv for windows). (I'd guess I'd recommend to bundle it).
*You may use some native Windows calls as special case.
Of course if you are using Java it has it built-in - but I see that it may not be what you want (JNI calls are expensive).
PS. Cannot you set perl to specific encoding?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Unable to determine guest operating system: Vmware error Ok, here's a very short and to the point question. When trying to import a virtual PC 2004 Windows 2003 Server VM in VM Workstation 6.0.2 I'm getting an error 'unable to determine guest operating system'. Soo how to fix?
A: From here:
*
*Make sure that that the VM is not currently running in VMware Server.
*Make sure that VMware Server does not have a lock on the VM’s files. You have have to stop all VMware Server Services and/or reboot the (VMWare) server.
*Make sure you have appropriate permissions to the VM’s files.
A: This is a fairly generic error from VMware Converter so I would try the following:
Step 1. Make sure you are running the latest version of VMware Converter. Updates seem to come pretty often for this tool.
Step 2. Check the VMware Converter log file. More often than not you will find the source of your problem here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to get the maximum supported resolution of a connected display in os x from java? Assume java 1.6 and leopard. Ideally, it would also be nice to get a list of all supported resolutions and the current resolution. If this isn't possible in java, is there some way to do it that could be called from java?
A: GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getScreenDevices();
for (int i = 0; i < devices.length; i++) {
GraphicsDevice dev = devices[i];
System.out.println("device " + i);
DisplayMode[] modes = dev.getDisplayModes();
for (int j = 0; j < modes.length; j++) {
DisplayMode m = modes[j];
System.out.println(" " + j + ": " + m.getWidth() + " x " + m.getHeight());
}
}
With this code you can determine the current resolution. On my system (SuSE linux) it does NOT output the possible resolutions.
Seems to work an Mac and Windows.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to find out if a file exists in C# / .NET? I would like to test a string containing a path to a file for existence of that file (something like the -e test in Perl or the os.path.exists() in Python) in C#.
A: Give full path as input. Avoid relative paths.
return File.Exists(FinalPath);
A: System.IO.File:
using System.IO;
if (File.Exists(path))
{
Console.WriteLine("file exists");
}
A: Use:
File.Exists(path)
MSDN: http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx
Edit: In System.IO
A: System.IO.File.Exists(path)
msdn
A: I use WinForms and my way to use File.Exists(string path) is the next one:
public bool FileExists(string fileName)
{
var workingDirectory = Environment.CurrentDirectory;
var file = $"{workingDirectory}\{fileName}";
return File.Exists(file);
}
fileName must include the extension like myfile.txt
A: File.Exists(Path.Combine(_workDir, _file));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "236"
} |
Q: How do I merge two dictionaries in a single expression in Python? I want to merge two dictionaries into a new dictionary.
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)
>>> z
{'a': 1, 'b': 3, 'c': 4}
Whenever a key k is present in both dictionaries, only the value y[k] should be kept.
A: x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z = dict(x.items() + y.items())
print z
For items with keys in both dictionaries ('b'), you can control which one ends up in the output by putting that one last.
A: The best version I could think while not using copy would be:
from itertools import chain
x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
dict(chain(x.iteritems(), y.iteritems()))
It's faster than dict(x.items() + y.items()) but not as fast as n = copy(a); n.update(b), at least on CPython. This version also works in Python 3 if you change iteritems() to items(), which is automatically done by the 2to3 tool.
Personally I like this version best because it describes fairly good what I want in a single functional syntax. The only minor problem is that it doesn't make completely obvious that values from y takes precedence over values from x, but I don't believe it's difficult to figure that out.
A: I know this does not really fit the specifics of the questions ("one liner"), but since none of the answers above went into this direction while lots and lots of answers addressed the performance issue, I felt I should contribute my thoughts.
Depending on the use case it might not be necessary to create a "real" merged dictionary of the given input dictionaries. A view which does this might be sufficient in many cases, i. e. an object which acts like the merged dictionary would without computing it completely. A lazy version of the merged dictionary, so to speak.
In Python, this is rather simple and can be done with the code shown at the end of my post. This given, the answer to the original question would be:
z = MergeDict(x, y)
When using this new object, it will behave like a merged dictionary but it will have constant creation time and constant memory footprint while leaving the original dictionaries untouched. Creating it is way cheaper than in the other solutions proposed.
Of course, if you use the result a lot, then you will at some point reach the limit where creating a real merged dictionary would have been the faster solution. As I said, it depends on your use case.
If you ever felt you would prefer to have a real merged dict, then calling dict(z) would produce it (but way more costly than the other solutions of course, so this is just worth mentioning).
You can also use this class to make a kind of copy-on-write dictionary:
a = { 'x': 3, 'y': 4 }
b = MergeDict(a) # we merge just one dict
b['x'] = 5
print b # will print {'x': 5, 'y': 4}
print a # will print {'y': 4, 'x': 3}
Here's the straight-forward code of MergeDict:
class MergeDict(object):
def __init__(self, *originals):
self.originals = ({},) + originals[::-1] # reversed
def __getitem__(self, key):
for original in self.originals:
try:
return original[key]
except KeyError:
pass
raise KeyError(key)
def __setitem__(self, key, value):
self.originals[0][key] = value
def __iter__(self):
return iter(self.keys())
def __repr__(self):
return '%s(%s)' % (
self.__class__.__name__,
', '.join(repr(original)
for original in reversed(self.originals)))
def __str__(self):
return '{%s}' % ', '.join(
'%r: %r' % i for i in self.iteritems())
def iteritems(self):
found = set()
for original in self.originals:
for k, v in original.iteritems():
if k not in found:
yield k, v
found.add(k)
def items(self):
return list(self.iteritems())
def keys(self):
return list(k for k, _ in self.iteritems())
def values(self):
return list(v for _, v in self.iteritems())
A: In Python 3.9
Based on PEP 584, the new version of Python introduces two new operators for dictionaries: union (|) and in-place union (|=). You can use | to merge two dictionaries, while |= will update a dictionary in place:
>>> pycon = {2016: "Portland", 2018: "Cleveland"}
>>> europython = {2017: "Rimini", 2018: "Edinburgh", 2019: "Basel"}
>>> pycon | europython
{2016: 'Portland', 2018: 'Edinburgh', 2017: 'Rimini', 2019: 'Basel'}
>>> pycon |= europython
>>> pycon
{2016: 'Portland', 2018: 'Edinburgh', 2017: 'Rimini', 2019: 'Basel'}
If d1 and d2 are two dictionaries, then d1 | d2 does the same as {**d1, **d2}. The | operator is used for calculating the union of sets, so the notation may already be familiar to you.
One advantage of using | is that it works on different dictionary-like types and keeps the type through the merge:
>>> from collections import defaultdict
>>> europe = defaultdict(lambda: "", {"Norway": "Oslo", "Spain": "Madrid"})
>>> africa = defaultdict(lambda: "", {"Egypt": "Cairo", "Zimbabwe": "Harare"})
>>> europe | africa
defaultdict(<function <lambda> at 0x7f0cb42a6700>,
{'Norway': 'Oslo', 'Spain': 'Madrid', 'Egypt': 'Cairo', 'Zimbabwe': 'Harare'})
>>> {**europe, **africa}
{'Norway': 'Oslo', 'Spain': 'Madrid', 'Egypt': 'Cairo', 'Zimbabwe': 'Harare'}
You can use a defaultdict when you want to effectively handle missing keys. Note that | preserves the defaultdict, while {**europe, **africa} does not.
There are some similarities between how | works for dictionaries and how + works for lists. In fact, the + operator was originally proposed to merge dictionaries as well. This correspondence becomes even more evident when you look at the in-place operator.
The basic use of |= is to update a dictionary in place, similar to .update():
>>> libraries = {
... "collections": "Container datatypes",
... "math": "Mathematical functions",
... }
>>> libraries |= {"zoneinfo": "IANA time zone support"}
>>> libraries
{'collections': 'Container datatypes', 'math': 'Mathematical functions',
'zoneinfo': 'IANA time zone support'}
When you merge dictionaries with |, both dictionaries need to be of a proper dictionary type. On the other hand, the in-place operator (|=) is happy to work with any dictionary-like data structure:
>>> libraries |= [("graphlib", "Functionality for graph-like structures")]
>>> libraries
{'collections': 'Container datatypes', 'math': 'Mathematical functions',
'zoneinfo': 'IANA time zone support',
'graphlib': 'Functionality for graph-like structures'}
A: How can I merge two Python dictionaries in a single expression?
For dictionaries x and y, their shallowly-merged dictionary z takes values from y, replacing those from x.
*
*In Python 3.9.0 or greater (released 17 October 2020, PEP-584, discussed here):
z = x | y
*In Python 3.5 or greater:
z = {**x, **y}
*In Python 2, (or 3.4 or lower) write a function:
def merge_two_dicts(x, y):
z = x.copy() # start with keys and values of x
z.update(y) # modifies z with keys and values of y
return z
and now:
z = merge_two_dicts(x, y)
Explanation
Say you have two dictionaries and you want to merge them into a new dictionary without altering the original dictionaries:
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
The desired result is to get a new dictionary (z) with the values merged, and the second dictionary's values overwriting those from the first.
>>> z
{'a': 1, 'b': 3, 'c': 4}
A new syntax for this, proposed in PEP 448 and available as of Python 3.5, is
z = {**x, **y}
And it is indeed a single expression.
Note that we can merge in with literal notation as well:
z = {**x, 'foo': 1, 'bar': 2, **y}
and now:
>>> z
{'a': 1, 'b': 3, 'foo': 1, 'bar': 2, 'c': 4}
It is now showing as implemented in the release schedule for 3.5, PEP 478, and it has now made its way into the What's New in Python 3.5 document.
However, since many organizations are still on Python 2, you may wish to do this in a backward-compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process:
z = x.copy()
z.update(y) # which returns None since it mutates z
In both approaches, y will come second and its values will replace x's values, thus b will point to 3 in our final result.
Not yet on Python 3.5, but want a single expression
If you are not yet on Python 3.5 or need to write backward-compatible code, and you want this in a single expression, the most performant while the correct approach is to put it in a function:
def merge_two_dicts(x, y):
"""Given two dictionaries, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return z
and then you have a single expression:
z = merge_two_dicts(x, y)
You can also make a function to merge an arbitrary number of dictionaries, from zero to a very large number:
def merge_dicts(*dict_args):
"""
Given any number of dictionaries, shallow copy and merge into a new dict,
precedence goes to key-value pairs in latter dictionaries.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
This function will work in Python 2 and 3 for all dictionaries. e.g. given dictionaries a to g:
z = merge_dicts(a, b, c, d, e, f, g)
and key-value pairs in g will take precedence over dictionaries a to f, and so on.
Critiques of Other Answers
Don't use what you see in the formerly accepted answer:
z = dict(x.items() + y.items())
In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. In Python 3, this will fail because you're adding two dict_items objects together, not two lists -
>>> c = dict(a.items() + b.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'
and you would have to explicitly create them as lists, e.g. z = dict(list(x.items()) + list(y.items())). This is a waste of resources and computation power.
Similarly, taking the union of items() in Python 3 (viewitems() in Python 2.7) will also fail when values are unhashable objects (like lists, for example). Even if your values are hashable, since sets are semantically unordered, the behavior is undefined in regards to precedence. So don't do this:
>>> c = dict(a.items() | b.items())
This example demonstrates what happens when values are unhashable:
>>> x = {'a': []}
>>> y = {'b': []}
>>> dict(x.items() | y.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Here's an example where y should have precedence, but instead the value from x is retained due to the arbitrary order of sets:
>>> x = {'a': 2}
>>> y = {'a': 1}
>>> dict(x.items() | y.items())
{'a': 2}
Another hack you should not use:
z = dict(x, **y)
This uses the dict constructor and is very fast and memory-efficient (even slightly more so than our two-step process) but unless you know precisely what is happening here (that is, the second dict is being passed as keyword arguments to the dict constructor), it's difficult to read, it's not the intended usage, and so it is not Pythonic.
Here's an example of the usage being remediated in django.
Dictionaries are intended to take hashable keys (e.g. frozensets or tuples), but this method fails in Python 3 when keys are not strings.
>>> c = dict(a, **b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: keyword arguments must be strings
From the mailing list, Guido van Rossum, the creator of the language, wrote:
I am fine with
declaring dict({}, **{1:3}) illegal, since after all it is abuse of
the ** mechanism.
and
Apparently dict(x, **y) is going around as "cool hack" for "call
x.update(y) and return x". Personally, I find it more despicable than
cool.
It is my understanding (as well as the understanding of the creator of the language) that the intended usage for dict(**y) is for creating dictionaries for readability purposes, e.g.:
dict(a=1, b=10, c=11)
instead of
{'a': 1, 'b': 10, 'c': 11}
Response to comments
Despite what Guido says, dict(x, **y) is in line with the dict specification, which btw. works for both Python 2 and 3. The fact that this only works for string keys is a direct consequence of how keyword parameters work and not a short-coming of dict. Nor is using the ** operator in this place an abuse of the mechanism, in fact, ** was designed precisely to pass dictionaries as keywords.
Again, it doesn't work for 3 when keys are not strings. The implicit calling contract is that namespaces take ordinary dictionaries, while users must only pass keyword arguments that are strings. All other callables enforced it. dict broke this consistency in Python 2:
>>> foo(**{('a', 'b'): None})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() keywords must be strings
>>> dict(**{('a', 'b'): None})
{('a', 'b'): None}
This inconsistency was bad given other implementations of Python (PyPy, Jython, IronPython). Thus it was fixed in Python 3, as this usage could be a breaking change.
I submit to you that it is malicious incompetence to intentionally write code that only works in one version of a language or that only works given certain arbitrary constraints.
More comments:
dict(x.items() + y.items()) is still the most readable solution for Python 2. Readability counts.
My response: merge_two_dicts(x, y) actually seems much clearer to me, if we're actually concerned about readability. And it is not forward compatible, as Python 2 is increasingly deprecated.
{**x, **y} does not seem to handle nested dictionaries. the contents of nested keys are simply overwritten, not merged [...] I ended up being burnt by these answers that do not merge recursively and I was surprised no one mentioned it. In my interpretation of the word "merging" these answers describe "updating one dict with another", and not merging.
Yes. I must refer you back to the question, which is asking for a shallow merge of two dictionaries, with the first's values being overwritten by the second's - in a single expression.
Assuming two dictionaries of dictionaries, one might recursively merge them in a single function, but you should be careful not to modify the dictionaries from either source, and the surest way to avoid that is to make a copy when assigning values. As keys must be hashable and are usually therefore immutable, it is pointless to copy them:
from copy import deepcopy
def dict_of_dicts_merge(x, y):
z = {}
overlapping_keys = x.keys() & y.keys()
for key in overlapping_keys:
z[key] = dict_of_dicts_merge(x[key], y[key])
for key in x.keys() - overlapping_keys:
z[key] = deepcopy(x[key])
for key in y.keys() - overlapping_keys:
z[key] = deepcopy(y[key])
return z
Usage:
>>> x = {'a':{1:{}}, 'b': {2:{}}}
>>> y = {'b':{10:{}}, 'c': {11:{}}}
>>> dict_of_dicts_merge(x, y)
{'b': {2: {}, 10: {}}, 'a': {1: {}}, 'c': {11: {}}}
Coming up with contingencies for other value types is far beyond the scope of this question, so I will point you at my answer to the canonical question on a "Dictionaries of dictionaries merge".
Less Performant But Correct Ad-hocs
These approaches are less performant, but they will provide correct behavior.
They will be much less performant than copy and update or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they do respect the order of precedence (latter dictionaries have precedence)
You can also chain the dictionaries manually inside a dict comprehension:
{k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7
or in Python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced):
dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2
itertools.chain will chain the iterators over the key-value pairs in the correct order:
from itertools import chain
z = dict(chain(x.items(), y.items())) # iteritems in Python 2
Performance Analysis
I'm only going to do the performance analysis of the usages known to behave correctly. (Self-contained so you can copy and paste yourself.)
from timeit import repeat
from itertools import chain
x = dict.fromkeys('abcdefg')
y = dict.fromkeys('efghijk')
def merge_two_dicts(x, y):
z = x.copy()
z.update(y)
return z
min(repeat(lambda: {**x, **y}))
min(repeat(lambda: merge_two_dicts(x, y)))
min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
min(repeat(lambda: dict(chain(x.items(), y.items()))))
min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))
In Python 3.8.1, NixOS:
>>> min(repeat(lambda: {**x, **y}))
1.0804965235292912
>>> min(repeat(lambda: merge_two_dicts(x, y)))
1.636518670246005
>>> min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
3.1779992282390594
>>> min(repeat(lambda: dict(chain(x.items(), y.items()))))
2.740647904574871
>>> min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))
4.266070580109954
$ uname -a
Linux nixos 4.19.113 #1-NixOS SMP Wed Mar 25 07:06:15 UTC 2020 x86_64 GNU/Linux
Resources on Dictionaries
*
*My explanation of Python's dictionary implementation, updated for 3.6.
*Answer on how to add new keys to a dictionary
*Mapping two lists into a dictionary
*The official Python docs on dictionaries
*The Dictionary Even Mightier - talk by Brandon Rhodes at Pycon 2017
*Modern Python Dictionaries, A Confluence of Great Ideas - talk by Raymond Hettinger at Pycon 2017
A: I benchmarked the suggested with perfplot and found that
x | y # Python 3.9+
is the fastest solution together with the good old
{**x, **y}
and
temp = x.copy()
temp.update(y)
Code to reproduce the plot:
from collections import ChainMap
from itertools import chain
import perfplot
def setup(n):
x = dict(zip(range(n), range(n)))
y = dict(zip(range(n, 2 * n), range(n, 2 * n)))
return x, y
def copy_update(x, y):
temp = x.copy()
temp.update(y)
return temp
def add_items(x, y):
return dict(list(x.items()) + list(y.items()))
def curly_star(x, y):
return {**x, **y}
def chain_map(x, y):
return dict(ChainMap({}, y, x))
def itertools_chain(x, y):
return dict(chain(x.items(), y.items()))
def python39_concat(x, y):
return x | y
b = perfplot.bench(
setup=setup,
kernels=[
copy_update,
add_items,
curly_star,
chain_map,
itertools_chain,
python39_concat,
],
labels=[
"copy_update",
"dict(list(x.items()) + list(y.items()))",
"{**x, **y}",
"chain_map",
"itertools.chain",
"x | y",
],
n_range=[2 ** k for k in range(18)],
xlabel="len(x), len(y)",
equality_check=None,
)
b.save("out.png")
b.show()
A: An alternative:
z = x.copy()
z.update(y)
A: While the question has already been answered several times,
this simple solution to the problem has not been listed yet.
x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z4 = {}
z4.update(x)
z4.update(y)
It is as fast as z0 and the evil z2 mentioned above, but easy to understand and change.
A: def dict_merge(a, b):
c = a.copy()
c.update(b)
return c
new = dict_merge(old, extras)
Among such shady and dubious answers, this shining example is the one and only good way to merge dicts in Python, endorsed by dictator for life Guido van Rossum himself! Someone else suggested half of this, but did not put it in a function.
print dict_merge(
{'color':'red', 'model':'Mini'},
{'model':'Ferrari', 'owner':'Carl'})
gives:
{'color': 'red', 'owner': 'Carl', 'model': 'Ferrari'}
A: Be Pythonic. Use a comprehension:
z={k: v for d in [x,y] for k, v in d.items()}
>>> print z
{'a': 1, 'c': 11, 'b': 10}
A: Using a dict comprehension, you may
x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
dc = {xi:(x[xi] if xi not in list(y.keys())
else y[xi]) for xi in list(x.keys())+(list(y.keys()))}
gives
>>> dc
{'a': 1, 'c': 11, 'b': 10}
Note the syntax for if else in comprehension
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
A: This is an expression for Python 3.5 or greater that merges dictionaries using reduce:
>>> from functools import reduce
>>> l = [{'a': 1}, {'b': 2}, {'a': 100, 'c': 3}]
>>> reduce(lambda x, y: {**x, **y}, l, {})
{'a': 100, 'b': 2, 'c': 3}
Note: this works even if the dictionary list is empty or contains only one element.
For a more efficient merge on Python 3.9 or greater, the lambda can be replaced directly by operator.ior:
>>> from functools import reduce
>>> from operator import ior
>>> l = [{'a': 1}, {'b': 2}, {'a': 100, 'c': 3}]
>>> reduce(ior, l, {})
{'a': 100, 'b': 2, 'c': 3}
For Python 3.8 or less, the following can be used as an alternative to ior:
>>> from functools import reduce
>>> l = [{'a': 1}, {'b': 2}, {'a': 100, 'c': 3}]
>>> reduce(lambda x, y: x.update(y) or x, l, {})
{'a': 100, 'b': 2, 'c': 3}
A: If you think lambdas are evil then read no further.
As requested, you can write the fast and memory-efficient solution with one expression:
x = {'a':1, 'b':2}
y = {'b':10, 'c':11}
z = (lambda a, b: (lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(x, y)
print z
{'a': 1, 'c': 11, 'b': 10}
print x
{'a': 1, 'b': 2}
As suggested above, using two lines or writing a function is probably a better way to go.
A: A union of the OP's two dictionaries would be something like:
{'a': 1, 'b': 2, 10, 'c': 11}
Specifically, the union of two entities(x and y) contains all the elements of x and/or y.
Unfortunately, what the OP asks for is not a union, despite the title of the post.
My code below is neither elegant nor a one-liner, but I believe it is consistent with the meaning of union.
From the OP's example:
x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z = {}
for k, v in x.items():
if not k in z:
z[k] = [(v)]
else:
z[k].append((v))
for k, v in y.items():
if not k in z:
z[k] = [(v)]
else:
z[k].append((v))
{'a': [1], 'b': [2, 10], 'c': [11]}
Whether one wants lists could be changed, but the above will work if a dictionary contains lists (and nested lists) as values in either dictionary.
A: In python3, the items method no longer returns a list, but rather a view, which acts like a set. In this case you'll need to take the set union since concatenating with + won't work:
dict(x.items() | y.items())
For python3-like behavior in version 2.7, the viewitems method should work in place of items:
dict(x.viewitems() | y.viewitems())
I prefer this notation anyways since it seems more natural to think of it as a set union operation rather than concatenation (as the title shows).
Edit:
A couple more points for python 3. First, note that the dict(x, **y) trick won't work in python 3 unless the keys in y are strings.
Also, Raymond Hettinger's Chainmap answer is pretty elegant, since it can take an arbitrary number of dicts as arguments, but from the docs it looks like it sequentially looks through a list of all the dicts for each lookup:
Lookups search the underlying mappings successively until a key is found.
This can slow you down if you have a lot of lookups in your application:
In [1]: from collections import ChainMap
In [2]: from string import ascii_uppercase as up, ascii_lowercase as lo; x = dict(zip(lo, up)); y = dict(zip(up, lo))
In [3]: chainmap_dict = ChainMap(y, x)
In [4]: union_dict = dict(x.items() | y.items())
In [5]: timeit for k in union_dict: union_dict[k]
100000 loops, best of 3: 2.15 µs per loop
In [6]: timeit for k in chainmap_dict: chainmap_dict[k]
10000 loops, best of 3: 27.1 µs per loop
So about an order of magnitude slower for lookups. I'm a fan of Chainmap, but looks less practical where there may be many lookups.
A: Another, more concise, option:
z = dict(x, **y)
Note: this has become a popular answer, but it is important to point out that if y has any non-string keys, the fact that this works at all is an abuse of a CPython implementation detail, and it does not work in Python 3, or in PyPy, IronPython, or Jython. Also, Guido is not a fan. So I can't recommend this technique for forward-compatible or cross-implementation portable code, which really means it should be avoided entirely.
A: You can use toolz.merge([x, y]) for this.
A: I was curious if I could beat the accepted answer's time with a one line stringify approach:
I tried 5 methods, none previously mentioned - all one liner - all producing correct answers - and I couldn't come close.
So... to save you the trouble and perhaps fulfill curiosity:
import json
import yaml
import time
from ast import literal_eval as literal
def merge_two_dicts(x, y):
z = x.copy() # start with x's keys and values
z.update(y) # modifies z with y's keys and values & returns None
return z
x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
start = time.time()
for i in range(10000):
z = yaml.load((str(x)+str(y)).replace('}{',', '))
elapsed = (time.time()-start)
print (elapsed, z, 'stringify yaml')
start = time.time()
for i in range(10000):
z = literal((str(x)+str(y)).replace('}{',', '))
elapsed = (time.time()-start)
print (elapsed, z, 'stringify literal')
start = time.time()
for i in range(10000):
z = eval((str(x)+str(y)).replace('}{',', '))
elapsed = (time.time()-start)
print (elapsed, z, 'stringify eval')
start = time.time()
for i in range(10000):
z = {k:int(v) for k,v in (dict(zip(
((str(x)+str(y))
.replace('}',' ')
.replace('{',' ')
.replace(':',' ')
.replace(',',' ')
.replace("'",'')
.strip()
.split(' '))[::2],
((str(x)+str(y))
.replace('}',' ')
.replace('{',' ').replace(':',' ')
.replace(',',' ')
.replace("'",'')
.strip()
.split(' '))[1::2]
))).items()}
elapsed = (time.time()-start)
print (elapsed, z, 'stringify replace')
start = time.time()
for i in range(10000):
z = json.loads(str((str(x)+str(y)).replace('}{',', ').replace("'",'"')))
elapsed = (time.time()-start)
print (elapsed, z, 'stringify json')
start = time.time()
for i in range(10000):
z = merge_two_dicts(x, y)
elapsed = (time.time()-start)
print (elapsed, z, 'accepted')
results:
7.693928956985474 {'c': 11, 'b': 10, 'a': 1} stringify yaml
0.29134678840637207 {'c': 11, 'b': 10, 'a': 1} stringify literal
0.2208399772644043 {'c': 11, 'b': 10, 'a': 1} stringify eval
0.1106564998626709 {'c': 11, 'b': 10, 'a': 1} stringify replace
0.07989692687988281 {'c': 11, 'b': 10, 'a': 1} stringify json
0.005082368850708008 {'c': 11, 'b': 10, 'a': 1} accepted
What I did learn from this is that JSON approach is the fastest way (of those attempted) to return a dictionary from string-of-dictionary; much faster (about 1/4th of the time) of what I considered to be the normal method using ast. I also learned that, the YAML approach should be avoided at all cost.
Yes, I understand that this is not the best/correct way. I was curious if it was faster, and it isn't; I posted to prove it so.
A: Two dictionaries
def union2(dict1, dict2):
return dict(list(dict1.items()) + list(dict2.items()))
n dictionaries
def union(*dicts):
return dict(itertools.chain.from_iterable(dct.items() for dct in dicts))
sum has bad performance. See https://mathieularose.com/how-not-to-flatten-a-list-of-lists-in-python/
A: Simple solution using itertools that preserves order (latter dicts have precedence)
# py2
from itertools import chain, imap
merge = lambda *args: dict(chain.from_iterable(imap(dict.iteritems, args)))
# py3
from itertools import chain
merge = lambda *args: dict(chain.from_iterable(map(dict.items, args)))
And it's usage:
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> merge(x, y)
{'a': 1, 'b': 10, 'c': 11}
>>> z = {'c': 3, 'd': 4}
>>> merge(x, y, z)
{'a': 1, 'b': 10, 'c': 3, 'd': 4}
A: Abuse leading to a one-expression solution for Matthew's answer:
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = (lambda f=x.copy(): (f.update(y), f)[1])()
>>> z
{'a': 1, 'c': 11, 'b': 10}
You said you wanted one expression, so I abused lambda to bind a name, and tuples to override lambda's one-expression limit. Feel free to cringe.
You could also do this of course if you don't care about copying it:
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = (x.update(y), x)[1]
>>> z
{'a': 1, 'b': 10, 'c': 11}
A: A method is deep merging. Making use of the | operator in 3.9+ for the use case of dict new being a set of default settings, and dict existing being a set of existing settings in use. My goal was to merge in any added settings from new without over writing existing settings in existing. I believe this recursive implementation will allow one to upgrade a dict with new values from another dict.
def merge_dict_recursive(new: dict, existing: dict):
merged = new | existing
for k, v in merged.items():
if isinstance(v, dict):
if k not in existing:
# The key is not in existing dict at all, so add entire value
existing[k] = new[k]
merged[k] = merge_dict_recursive(new[k], existing[k])
return merged
Example test data:
new
{'dashboard': True,
'depth': {'a': 1, 'b': 22222, 'c': {'d': {'e': 69}}},
'intro': 'this is the dashboard',
'newkey': False,
'show_closed_sessions': False,
'version': None,
'visible_sessions_limit': 9999}
existing
{'dashboard': True,
'depth': {'a': 5},
'intro': 'this is the dashboard',
'newkey': True,
'show_closed_sessions': False,
'version': '2021-08-22 12:00:30.531038+00:00'}
merged
{'dashboard': True,
'depth': {'a': 5, 'b': 22222, 'c': {'d': {'e': 69}}},
'intro': 'this is the dashboard',
'newkey': True,
'show_closed_sessions': False,
'version': '2021-08-22 12:00:30.531038+00:00',
'visible_sessions_limit': 9999}
A: This probably won't be a popular answer, but you almost certainly do not want to do this. If you want a copy that's a merge, then use copy (or deepcopy, depending on what you want) and then update. The two lines of code are much more readable - more Pythonic - than the single line creation with .items() + .items(). Explicit is better than implicit.
In addition, when you use .items() (pre Python 3.0), you're creating a new list that contains the items from the dict. If your dictionaries are large, then that is quite a lot of overhead (two large lists that will be thrown away as soon as the merged dict is created). update() can work more efficiently, because it can run through the second dict item-by-item.
In terms of time:
>>> timeit.Timer("dict(x, **y)", "x = dict(zip(range(1000), range(1000)))\ny=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000)
15.52571702003479
>>> timeit.Timer("temp = x.copy()\ntemp.update(y)", "x = dict(zip(range(1000), range(1000)))\ny=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000)
15.694622993469238
>>> timeit.Timer("dict(x.items() + y.items())", "x = dict(zip(range(1000), range(1000)))\ny=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000)
41.484580039978027
IMO the tiny slowdown between the first two is worth it for the readability. In addition, keyword arguments for dictionary creation was only added in Python 2.3, whereas copy() and update() will work in older versions.
A: If you don't mind mutating x,
x.update(y) or x
Simple, readable, performant. You know update() always returns None, which is a false value. So the above expression will always evaluate to x, after updating it.
Most mutating methods in the standard library (like .update()) return None by convention, so this kind of pattern will work on those too. However, if you're using a dict subclass or some other method that doesn't follow this convention, then or may return its left operand, which may not be what you want. Instead, you can use a tuple display and index, which works regardless of what the first element evaluates to (although it's not quite as pretty):
(x.update(y), x)[-1]
If you don't have x in a variable yet, you can use lambda to make a local without using an assignment statement. This amounts to using lambda as a let expression, which is a common technique in functional languages, but is maybe unpythonic.
(lambda x: x.update(y) or x)({'a': 1, 'b': 2})
Although it's not that different from the following use of the new walrus operator (Python 3.8+ only),
(x := {'a': 1, 'b': 2}).update(y) or x
especially if you use a default argument:
(lambda x={'a': 1, 'b': 2}: x.update(y) or x)()
If you do want a copy, PEP 584 style x | y is the most Pythonic on 3.9+. If you must support older versions, PEP 448 style {**x, **y} is easiest for 3.5+. But if that's not available in your (even older) Python version, the let expression pattern works here too.
(lambda z=x.copy(): z.update(y) or z)()
(That is, of course, nearly equivalent to (z := x.copy()).update(y) or z, but if your Python version is new enough for that, then the PEP 448 style will be available.)
A: Drawing on ideas here and elsewhere I've comprehended a function:
def merge(*dicts, **kv):
return { k:v for d in list(dicts) + [kv] for k,v in d.items() }
Usage (tested in python 3):
assert (merge({1:11,'a':'aaa'},{1:99, 'b':'bbb'},foo='bar')==\
{1: 99, 'foo': 'bar', 'b': 'bbb', 'a': 'aaa'})
assert (merge(foo='bar')=={'foo': 'bar'})
assert (merge({1:11},{1:99},foo='bar',baz='quux')==\
{1: 99, 'foo': 'bar', 'baz':'quux'})
assert (merge({1:11},{1:99})=={1: 99})
You could use a lambda instead.
A: New in Python 3.9: Use the union operator (|) to merge dicts similar to sets:
>>> d = {'a': 1, 'b': 2}
>>> e = {'a': 9, 'c': 3}
>>> d | e
{'a': 9, 'b': 2, 'c': 3}
For matching keys, the right dict takes precedence.
This also works for |= to modify a dict in-place:
>>> e |= d # e = e | d
>>> e
{'a': 1, 'c': 3, 'b': 2}
A: I think my ugly one-liners are just necessary here.
z = next(z.update(y) or z for z in [x.copy()])
# or
z = (lambda z: z.update(y) or z)(x.copy())
*
*Dicts are merged.
*Single expression.
*Don't ever dare to use it.
P.S. This is a solution working in both versions of Python. I know that Python 3 has this {**x, **y} thing and it is the right thing to use (as well as moving to Python 3 if you still have Python 2 is the right thing to do).
A: Deep merge of dicts:
from typing import List, Dict
from copy import deepcopy
def merge_dicts(*from_dicts: List[Dict], no_copy: bool=False) -> Dict :
""" no recursion deep merge of two dicts
By default creates fresh Dict and merges all to it.
no_copy = True, will merge all dicts to a fist one in a list without copy.
Why? Sometime I need to combine one dictionary from "layers".
The "layers" are not in use and dropped immediately after merging.
"""
if no_copy:
xerox = lambda x:x
else:
xerox = deepcopy
result = xerox(from_dicts[0])
for _from in from_dicts[1:]:
merge_queue = [(result, _from)]
for _to, _from in merge_queue:
for k, v in _from.items():
if k in _to and isinstance(_to[k], dict) and isinstance(v, dict):
# key collision add both are dicts.
# add to merging queue
merge_queue.append((_to[k], v))
continue
_to[k] = xerox(v)
return result
Usage:
print("=============================")
print("merge all dicts to first one without copy.")
a0 = {"a":{"b":1}}
a1 = {"a":{"c":{"d":4}}}
a2 = {"a":{"c":{"f":5}, "d": 6}}
print(f"a0 id[{id(a0)}] value:{a0}")
print(f"a1 id[{id(a1)}] value:{a1}")
print(f"a2 id[{id(a2)}] value:{a2}")
r = merge_dicts(a0, a1, a2, no_copy=True)
print(f"r id[{id(r)}] value:{r}")
print("=============================")
print("create fresh copy of all")
a0 = {"a":{"b":1}}
a1 = {"a":{"c":{"d":4}}}
a2 = {"a":{"c":{"f":5}, "d": 6}}
print(f"a0 id[{id(a0)}] value:{a0}")
print(f"a1 id[{id(a1)}] value:{a1}")
print(f"a2 id[{id(a2)}] value:{a2}")
r = merge_dicts(a0, a1, a2)
print(f"r id[{id(r)}] value:{r}")
A: In a follow-up answer, you asked about the relative performance of these two alternatives:
z1 = dict(x.items() + y.items())
z2 = dict(x, **y)
On my machine, at least (a fairly ordinary x86_64 running Python 2.5.2), alternative z2 is not only shorter and simpler but also significantly faster. You can verify this for yourself using the timeit module that comes with Python.
Example 1: identical dictionaries mapping 20 consecutive integers to themselves:
% python -m timeit -s 'x=y=dict((i,i) for i in range(20))' 'z1=dict(x.items() + y.items())'
100000 loops, best of 3: 5.67 usec per loop
% python -m timeit -s 'x=y=dict((i,i) for i in range(20))' 'z2=dict(x, **y)'
100000 loops, best of 3: 1.53 usec per loop
z2 wins by a factor of 3.5 or so. Different dictionaries seem to yield quite different results, but z2 always seems to come out ahead. (If you get inconsistent results for the same test, try passing in -r with a number larger than the default 3.)
Example 2: non-overlapping dictionaries mapping 252 short strings to integers and vice versa:
% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z1=dict(x.items() + y.items())'
1000 loops, best of 3: 260 usec per loop
% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z2=dict(x, **y)'
10000 loops, best of 3: 26.9 usec per loop
z2 wins by about a factor of 10. That's a pretty big win in my book!
After comparing those two, I wondered if z1's poor performance could be attributed to the overhead of constructing the two item lists, which in turn led me to wonder if this variation might work better:
from itertools import chain
z3 = dict(chain(x.iteritems(), y.iteritems()))
A few quick tests, e.g.
% python -m timeit -s 'from itertools import chain; from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z3=dict(chain(x.iteritems(), y.iteritems()))'
10000 loops, best of 3: 66 usec per loop
lead me to conclude that z3 is somewhat faster than z1, but not nearly as fast as z2. Definitely not worth all the extra typing.
This discussion is still missing something important, which is a performance comparison of these alternatives with the "obvious" way of merging two lists: using the update method. To try to keep things on an equal footing with the expressions, none of which modify x or y, I'm going to make a copy of x instead of modifying it in-place, as follows:
z0 = dict(x)
z0.update(y)
A typical result:
% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z0=dict(x); z0.update(y)'
10000 loops, best of 3: 26.9 usec per loop
In other words, z0 and z2 seem to have essentially identical performance. Do you think this might be a coincidence? I don't....
In fact, I'd go so far as to claim that it's impossible for pure Python code to do any better than this. And if you can do significantly better in a C extension module, I imagine the Python folks might well be interested in incorporating your code (or a variation on your approach) into the Python core. Python uses dict in lots of places; optimizing its operations is a big deal.
You could also write this as
z0 = x.copy()
z0.update(y)
as Tony does, but (not surprisingly) the difference in notation turns out not to have any measurable effect on performance. Use whichever looks right to you. Of course, he's absolutely correct to point out that the two-statement version is much easier to understand.
A: In Python 3.0 and later, you can use collections.ChainMap which groups multiple dicts or other mappings together to create a single, updateable view:
>>> from collections import ChainMap
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = dict(ChainMap({}, y, x))
>>> for k, v in z.items():
print(k, '-->', v)
a --> 1
b --> 10
c --> 11
Update for Python 3.5 and later: You can use PEP 448 extended dictionary packing and unpacking. This is fast and easy:
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> {**x, **y}
{'a': 1, 'b': 10, 'c': 11}
Update for Python 3.9 and later: You can use the PEP 584 union operator:
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> x | y
{'a': 1, 'b': 10, 'c': 11}
A: It's so silly that .update returns nothing.
I just use a simple helper function to solve the problem:
def merge(dict1,*dicts):
for dict2 in dicts:
dict1.update(dict2)
return dict1
Examples:
merge(dict1,dict2)
merge(dict1,dict2,dict3)
merge(dict1,dict2,dict3,dict4)
merge({},dict1,dict2) # this one returns a new copy
A: (For Python 2.7* only; there are simpler solutions for Python 3*.)
If you're not averse to importing a standard library module, you can do
from functools import reduce
def merge_dicts(*dicts):
return reduce(lambda a, d: a.update(d) or a, dicts, {})
(The or a bit in the lambda is necessary because dict.update always returns None on success.)
A: In your case, you can do:
z = dict(list(x.items()) + list(y.items()))
This will, as you want it, put the final dict in z, and make the value for key b be properly overridden by the second (y) dict's value:
>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 10, 'c': 11}
>>> z = dict(list(x.items()) + list(y.items()))
>>> z
{'a': 1, 'c': 11, 'b': 10}
If you use Python 2, you can even remove the list() calls. To create z:
>>> z = dict(x.items() + y.items())
>>> z
{'a': 1, 'c': 11, 'b': 10}
If you use Python version 3.9.0a4 or greater, you can directly use:
>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 10, 'c': 11}
>>> z = x | y
>>> z
{'a': 1, 'c': 11, 'b': 10}
A: The problem I have with solutions listed to date is that, in the merged dictionary, the value for key "b" is 10 but, to my way of thinking, it should be 12.
In that light, I present the following:
import timeit
n=100000
su = """
x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
"""
def timeMerge(f,su,niter):
print "{:4f} sec for: {:30s}".format(timeit.Timer(f,setup=su).timeit(n),f)
timeMerge("dict(x, **y)",su,n)
timeMerge("x.update(y)",su,n)
timeMerge("dict(x.items() + y.items())",su,n)
timeMerge("for k in y.keys(): x[k] = k in x and x[k]+y[k] or y[k] ",su,n)
#confirm for loop adds b entries together
x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
for k in y.keys(): x[k] = k in x and x[k]+y[k] or y[k]
print "confirm b elements are added:",x
Results:
0.049465 sec for: dict(x, **y)
0.033729 sec for: x.update(y)
0.150380 sec for: dict(x.items() + y.items())
0.083120 sec for: for k in y.keys(): x[k] = k in x and x[k]+y[k] or y[k]
confirm b elements are added: {'a': 1, 'c': 11, 'b': 12}
A: from collections import Counter
dict1 = {'a':1, 'b': 2}
dict2 = {'b':10, 'c': 11}
result = dict(Counter(dict1) + Counter(dict2))
This should solve your problem.
A: There will be a new option when Python 3.8 releases (scheduled for 20 October, 2019), thanks to PEP 572: Assignment Expressions. The new assignment expression operator := allows you to assign the result of the copy and still use it to call update, leaving the combined code a single expression, rather than two statements, changing:
newdict = dict1.copy()
newdict.update(dict2)
to:
(newdict := dict1.copy()).update(dict2)
while behaving identically in every way. If you must also return the resulting dict (you asked for an expression returning the dict; the above creates and assigns to newdict, but doesn't return it, so you couldn't use it to pass an argument to a function as is, a la myfunc((newdict := dict1.copy()).update(dict2))), then just add or newdict to the end (since update returns None, which is falsy, it will then evaluate and return newdict as the result of the expression):
(newdict := dict1.copy()).update(dict2) or newdict
Important caveat: In general, I'd discourage this approach in favor of:
newdict = {**dict1, **dict2}
The unpacking approach is clearer (to anyone who knows about generalized unpacking in the first place, which you should), doesn't require a name for the result at all (so it's much more concise when constructing a temporary that is immediately passed to a function or included in a list/tuple literal or the like), and is almost certainly faster as well, being (on CPython) roughly equivalent to:
newdict = {}
newdict.update(dict1)
newdict.update(dict2)
but done at the C layer, using the concrete dict API, so no dynamic method lookup/binding or function call dispatch overhead is involved (where (newdict := dict1.copy()).update(dict2) is unavoidably identical to the original two-liner in behavior, performing the work in discrete steps, with dynamic lookup/binding/invocation of methods.
It's also more extensible, as merging three dicts is obvious:
newdict = {**dict1, **dict2, **dict3}
where using assignment expressions won't scale like that; the closest you could get would be:
(newdict := dict1.copy()).update(dict2), newdict.update(dict3)
or without the temporary tuple of Nones, but with truthiness testing of each None result:
(newdict := dict1.copy()).update(dict2) or newdict.update(dict3)
either of which is obviously much uglier, and includes further inefficiencies (either a wasted temporary tuple of Nones for comma separation, or pointless truthiness testing of each update's None return for or separation).
The only real advantage to the assignment expression approach occurs if:
*
*You have generic code that needs handle both sets and dicts (both of them support copy and update, so the code works roughly as you'd expect it to)
*You expect to receive arbitrary dict-like objects, not just dict itself, and must preserve the type and semantics of the left hand side (rather than ending up with a plain dict). While myspecialdict({**speciala, **specialb}) might work, it would involve an extra temporary dict, and if myspecialdict has features plain dict can't preserve (e.g. regular dicts now preserve order based on the first appearance of a key, and value based on the last appearance of a key; you might want one that preserves order based on the last appearance of a key so updating a value also moves it to the end), then the semantics would be wrong. Since the assignment expression version uses the named methods (which are presumably overloaded to behave appropriately), it never creates a dict at all (unless dict1 was already a dict), preserving the original type (and original type's semantics), all while avoiding any temporaries.
A: I wanted something similar, but with the ability to specify how the values on duplicate keys were merged, so I hacked this out (but did not heavily test it). Obviously this is not a single expression, but it is a single function call.
def merge(d1, d2, merge_fn=lambda x,y:y):
"""
Merges two dictionaries, non-destructively, combining
values on duplicate keys as defined by the optional merge
function. The default behavior replaces the values in d1
with corresponding values in d2. (There is no other generally
applicable merge strategy, but often you'll have homogeneous
types in your dicts, so specifying a merge technique can be
valuable.)
Examples:
>>> d1
{'a': 1, 'c': 3, 'b': 2}
>>> merge(d1, d1)
{'a': 1, 'c': 3, 'b': 2}
>>> merge(d1, d1, lambda x,y: x+y)
{'a': 2, 'c': 6, 'b': 4}
"""
result = dict(d1)
for k,v in d2.iteritems():
if k in result:
result[k] = merge_fn(result[k], v)
else:
result[k] = v
return result
A: This can be done with a single dict comprehension:
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> { key: y[key] if key in y else x[key]
for key in set(x) + set(y)
}
In my view the best answer for the 'single expression' part as no extra functions are needed, and it is short.
A: Recursively/deep update a dict
def deepupdate(original, update):
"""
Recursively update a dict.
Subdict's won't be overwritten but also updated.
"""
for key, value in original.iteritems():
if key not in update:
update[key] = value
elif isinstance(value, dict):
deepupdate(value, update[key])
return update
Demonstration:
pluto_original = {
'name': 'Pluto',
'details': {
'tail': True,
'color': 'orange'
}
}
pluto_update = {
'name': 'Pluutoo',
'details': {
'color': 'blue'
}
}
print deepupdate(pluto_original, pluto_update)
Outputs:
{
'name': 'Pluutoo',
'details': {
'color': 'blue',
'tail': True
}
}
Thanks rednaw for edits.
A: >>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> x, z = dict(x), x.update(y) or x
>>> x
{'a': 1, 'b': 2}
>>> y
{'c': 11, 'b': 10}
>>> z
{'a': 1, 'c': 11, 'b': 10}
A: Python 3.5 (PEP 448) allows a nicer syntax option:
x = {'a': 1, 'b': 1}
y = {'a': 2, 'c': 2}
final = {**x, **y}
final
# {'a': 2, 'b': 1, 'c': 2}
Or even
final = {'a': 1, 'b': 1, **x, **y}
In Python 3.9 you also use | and |= with the below example from PEP 584
d = {'spam': 1, 'eggs': 2, 'cheese': 3}
e = {'cheese': 'cheddar', 'aardvark': 'Ethel'}
d | e
# {'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
A: Python 3.9+ only
Merge (|) and update (|=) operators have been added to the built-in dict class.
>>> d = {'spam': 1, 'eggs': 2, 'cheese': 3}
>>> e = {'cheese': 'cheddar', 'aardvark': 'Ethel'}
>>> d | e
{'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
The augmented assignment version operates in-place:
>>> d |= e
>>> d
{'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
See PEP 584
A: The question is tagged python-3x but, taking into account that it's a relatively recent addition and that the most voted, accepted answer deals extensively with a Python 2.x solution, I dare add a one liner that draws on an irritating feature of Python 2.x list comprehension, that is name leaking...
$ python2
Python 2.7.13 (default, Jan 19 2017, 14:48:08)
[GCC 6.3.0 20170118] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> [z.update(d) for z in [{}] for d in (x, y)]
[None, None]
>>> z
{'a': 1, 'c': 11, 'b': 10}
>>> ...
I'm happy to say that the above doesn't work any more on any version of Python 3.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6639"
} |
Q: Regex to match unique substrings Here's a basic regex technique that I've never managed to remember. Let's say I'm using a fairly generic regex implementation (e.g., grep or grep -E). If I were to do a list of files and match any that end in either .sty or .cls, how would I do that?
A: ls | grep -E "\.(sty|cls)$"
*
*\. matches literally a "." - an unescaped . matches any character
*(sty|cls) - match "sty" or "cls" - the | is an or and the brackets limit the expression.
*$ forces the match to be at the end of the line
Note, you want grep -E or egrep, not grep -e as that's a different option for lists of patterns.
A: egrep "\.sty$|\.cls$"
A: This regex:
\.(sty|cls)\z
will match any string ends with .sty or .cls
EDIT:
for grep \z should be replaced with $ i.e.
\.(sty|cls)$
as jelovirt suggested.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Can I stop .NET eating IDs? I'm an Information Architect and JavaScript developer by trade nowadays, but recently I've been getting back into back-end coding again. And, whilst trying to get an HTML prototype integrated and working with our C#-based CMS, I've come to blows with our programmers over the HTML ID attributes being arbitrarily rewritten by .NET for form elements.
I can understand the code-behind reasoning for .NET changing IDs, but the fact you can no longer use IDs when trying to develop e.g. jQuery enhanced interfaces is causing some friction. What can I do to work around this?
I've tried using the class attribute instead, but that's really crappy, not what it's meant for and doesn't get around that problem of .NET effectively changing rendered source on the fly. It also means that CSS is less useful now and less efficient to create and maintain.
Any tips or advice greatly appreciated--anything for a few less sleepless nights...
A: Look at ASP.Net MVC - it addresses the over-kill object hierarchies that ASP.Net generates by default.
This site is written in MVC (I think) - look at it's structure. Were I working on a new project right now I would consider it first
If you're stuck with basic ASP.Net then be careful overriding the ClientID and UniqueID - it tends to break many web controls.
The best way I've found is to pass the unreadable ClientID out to the Javascript.
A: You can extend .net controls and make them return actual id's when related properties are called.
ClientID is the id attribute and UniqueID is the name attribute of html elements. So when you create a textbox like the following and using this instead of the textbox in framework, you make id and name attributes render as the same as the server-side id.
public class MyTextBox : TextBox
{
public override string ClientID { get { return ID; } }
public override string UniqueID { get { return ID; } }
}
To use this new user control, basically register this control as you would do for a custom user control (you can do is in web.config so you won't have to do it in all your pages):
<%@ Register Assembly="MyLibrary" NameSpace="MyLibrary.WebControls" TagPrefix="MyPrefix" %>
And use it like you would use a text box:
<MyPrefix:MyTextBox ID="sampleTextBox" runat="server" />
A: The short answer is no, with webforms the id can always be rewritten depending on the nesting of the element. You can get access to the id through the ClientID property, so you could set the ids into variables in a script at the end of the page/control then put them into jQuery.
something like this:
<asp:button id="ImAButton" runat="server">Click Me</asp:button>
<script type="text/javascript">
var buttonId = "<%=ImAButton.ClientId%>";
$("#"+buttonId).bind('click', function() { alert('hi); });
</script>
It's a hack I know, but it will work.
(I should note for the un-initiated, I'm using the Prototype $ get by id method there)
A: One method is to override the ID's manually:
public override string UniqueID
{
get { return this.ID; }
}
public override string ClientID
{
get { return this.ID; }
}
Rick Strahl wrote a blog post with some more information on that approach.
A: Personally, I use a set of methods I have developed for bridging the server-side ASP.NET "magic" (I have yet to use the MS MVC stuff yet) and my client-side code because of the munging of the IDs that happens. Here is just one that may or may not prove useful:
public void RegisterControlClientID(Control control)
{
string variableDeclaration = string.Format("var {0} = \"{1}\";", control.ID, control.ClientID);
ClientScript.RegisterClientScriptBlock(GetType(), control.ID, variableDeclaration, true);
}
So, in your server-side code you simply call this and pass in the instance of a control for which you want to use a friendlier name for. In other words, during design time, you may have a textbox with the ID of "m_SomeTextBox" and you want to be able to write your JavaScript using that same name - you would simply call this method in your server-side code:
RegisterControlClientID(m_SomeTextBox);
And then on the client the following is rendered:
var m_SomeTextBox = "ctl00_m_ContentPlaceHolder_m_SomeTextBox";
That way all of your JavaScript code can be fairly ignorant of what ASP.NET decides to name the variable. Granted, there are some caveats to this, such as when you have multiple instances of a control on a page (because of using multiple instances of user controls that all have an instance of m_SomeTextBox within them, for example), but generally this method may be useful for your most basic needs.
A: What I usually do is create a general function that receives the name of the field. It adds the usual "asp.net" prefix and returns the object.
var elemPrefix = 'ctl00-ContentPlaceHolder-'; //replace the dashes for underscores
var o = function(name)
{
return document.getElementById(elemPrefix + name)
}
With that you can use this kind of calls in jQuery
$(o('buttonId')).bind('click', function() { alert('hi); });
A: You definitely don't want to hard-code the asp.net-generated ID into your CSS, because it can change if you rearrange things on your page in such a way that your control tree changes.
You're right that CSS IDs have their place, so I would ignore the suggestions to just use classes.
The various javascript hacks described here are overkill for a small problem. So is inheriting from a class and overriding the ID property. And it's certainly not helpful to suggest switching to MVC when all you want to do is refactor some CSS.
Just have separate divs and spans that you target with CSS. Don't target the ASP.NET controls directly if you want to use IDs.
<div id="DataGridContainer">
<asp:datagrid runat=server id="DataGrid" >
......
<asp:datagrid>
</div>
A: If you're using jQuery then you have loads of CSS selectors and jQuery custome selectors at your disposal to target elements on your page. So rather than picking out a submit button by it's id, you could do something like:
$('fieldset > input[type="submit"]').click(function() {...});
A: I can see how the .NET system feels less intuitive, but give it a chance. In my experience it actually ends up creating cleaner code. Sure
<asp:button id="ImAButton" runat="server">Click Me</asp:button>
<script type="text/javascript">
var buttonId = <%=ImAButton.ClientId%>
$(buttonId).bind('click', function() { alert('hi); });
</script>
works fine. But this is suffers from not being modular. What you really want is something like this:
<script type="text/javascript">
function MakeAClick(inid)
{
$(inid).bind('click', function() { alert('hi); });
}
</script>
and then later with your code on the java side or the C# side you call MakeAClick. Of course on the C# side it makes more sense, you just ClientID in there.
Maybe this is the real problem with the code you are reviewing.
A: A much better approach would be to use the ClientIDMode and set it to static. You can even set it for a specific page or globally in the web.config file. Then you never have to deal with this issue again and your JQuery is much cleaner.
Top of page:
<%@ Page Title="" ClientIDMode="Static" Language="C#" CodeBehind="..." Inherits="WebApplication1.WebForm2" %>
On control only:
<asp:Panel runat="server" ClientIDMode="Static"></asp:Panel>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: NUnit - How to test all classes that implement a particular interface If I have interface IFoo, and have several classes that implement it, what is the best/most elegant/cleverest way to test all those classes against the interface?
I'd like to reduce test code duplication, but still 'stay true' to the principles of Unit testing.
What would you consider best practice? I'm using NUnit, but I suppose examples from any Unit testing framework would be valid
A: I don't think this is best practice.
The simple truth is that an interface is nothing more than a contract that a method is implemented. It is not a contract on either a.) how the method should be implemented and b.) what that method should be doing exactly (it only guarantees the return type), the two reasons that I glean would be your motive in wanting this kind of test.
If you really want to be in control of your method implementation, you have the option of:
*
*Implementing it as a method in an abstract class, and inherit from that. You will still need to inherit it into a concrete class, but you are sure that unless it is explicitly overriden that method will do that correct thing.
*In .NET 3.5/C# 3.0, implementing the method as an extension method referencing to the Interface
Example:
public static ReturnType MethodName (this IMyinterface myImplementation, SomeObject someParameter)
{
//method body goes here
}
Any implementation properly referencing to that extension method will emit precisely that extension method so you only need to test it once.
A: If you have classes implement any one interface then they all need to implement the methods in that interface. In order to test these classes you need to create a unit test class for each of the classes.
Lets go with a smarter route instead; if your goal is to avoid code and test code duplication you might want to create an abstract class instead that handles the recurring code.
E.g. you have the following interface:
public interface IFoo {
public void CommonCode();
public void SpecificCode();
}
You might want to create an abstract class:
public abstract class AbstractFoo : IFoo {
public void CommonCode() {
SpecificCode();
}
public abstract void SpecificCode();
}
Testing that is easy; implement the abstract class in the test class either as an inner class:
[TestFixture]
public void TestClass {
private class TestFoo : AbstractFoo {
boolean hasCalledSpecificCode = false;
public void SpecificCode() {
hasCalledSpecificCode = true;
}
}
[Test]
public void testCommonCallsSpecificCode() {
TestFoo fooFighter = new TestFoo();
fooFighter.CommonCode();
Assert.That(fooFighter.hasCalledSpecificCode, Is.True());
}
}
...or let the test class extend the abstract class itself if that fits your fancy.
[TestFixture]
public void TestClass : AbstractFoo {
boolean hasCalledSpecificCode;
public void specificCode() {
hasCalledSpecificCode = true;
}
[Test]
public void testCommonCallsSpecificCode() {
AbstractFoo fooFighter = this;
hasCalledSpecificCode = false;
fooFighter.CommonCode();
Assert.That(fooFighter.hasCalledSpecificCode, Is.True());
}
}
Having an abstract class take care of common code that an interface implies gives a much cleaner code design.
I hope this makes sense to you.
As a side note, this is a common design pattern called the Template Method pattern. In the above example, the template method is the CommonCode method and SpecificCode is called a stub or a hook. The idea is that anyone can extend behavior without the need to know the behind the scenes stuff.
A lot of frameworks rely on this behavioral pattern, e.g. ASP.NET where you have to implement the hooks in a page or a user controls such as the generated Page_Load method which is called by the Load event, the template method calls the hooks behind the scenes. There are a lot more examples of this. Basically anything that you have to implement that is using the words "load", "init", or "render" is called by a template method.
A: I disagree with Jon Limjap when he says,
It is not a contract on either a.) how the method should be implemented and b.) what that method should be doing exactly (it only guarantees the return type), the two reasons that I glean would be your motive in wanting this kind of test.
There could be many parts of the contract not specified in the return type. A language-agnostic example:
public interface List {
// adds o and returns the list
public List add(Object o);
// removed the first occurrence of o and returns the list
public List remove(Object o);
}
Your unit tests on LinkedList, ArrayList, CircularlyLinkedList, and all the others should test not only that the lists themselves are returned, but also that they have been properly modified.
There was an earlier question on design-by-contract, which can help point you in the right direction on one way of DRYing up these tests.
If you don't want the overhead of contracts, I recommend test rigs, along the lines of what Spoike recommended:
abstract class BaseListTest {
abstract public List newListInstance();
public void testAddToList() {
// do some adding tests
}
public void testRemoveFromList() {
// do some removing tests
}
}
class ArrayListTest < BaseListTest {
List newListInstance() { new ArrayList(); }
public void arrayListSpecificTest1() {
// test something about ArrayLists beyond the List requirements
}
}
A: When testing an interface or base class contract, I prefer to let the test framework automatically take care of finding all of the implementers. This lets you concentrate on the interface under test and be reasonably sure that all implementations will be tested, without having to do a lot of manual implementation.
*
*For xUnit.net, I created a Type Resolver library to search for all implementations of a particular type (the xUnit.net extensions are just a thin wrapper over the Type Resolver functionality, so it can be adapted for use in other frameworks).
*In MbUnit, you can use a CombinatorialTest with UsingImplementations attributes on the parameters.
*For other frameworks, the base class pattern Spoike mentioned can be useful.
Beyond testing the basics of the interface, you should also test that each individual implementation follows its particular requirements.
A: How about a hierarchy of [TestFixture]s classes? Put the common test code in the base test class and inherit it into child test classes..
A: I don't use NUnit but I have tested C++ interfaces. I would first test a TestFoo class which is a basic implementation of it to make sure the generic stuff works. Then you just need to test the stuff that is unique to each interface.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: Error: "VirtualHost *:80 -- mixing * ports and non-* ports with a NameVirtualHost address is not supported, proceeding with undefined results" I'm running WAMP v2.0 on WindowsXP and I've got a bunch of virtual hosts setup in the http-vhosts.conf file.
This was working, but in the last week whenever I try & start WAMP I get this error in the event logs:
VirtualHost *:80 -- mixing * ports and
non-* ports with a NameVirtualHost
address is not supported, proceeding
with undefined results.
and the server won't start. I can't think of what's changed.
I've copied the conf file below.
NameVirtualHost *
<VirtualHost *:80>
ServerName dev.blog.slaven.net.au
ServerAlias dev.blog.slaven.net.au
ServerAdmin [email protected]
DocumentRoot "c:/Project Data/OtherProjects/slaven.net.au/blog/"
ErrorLog "logs/blog.slaven.localhost-error.log"
CustomLog "logs/blog.slaven.localhost-access.log" common
<Directory "c:/Project Data/OtherProjects/slaven.net.au/blog/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
EDIT: I meant to add, if I change the NameVirtualHosts directive to specify a port, i.e
NameVirtualHost *:80
I get this error:
Only one usage of each socket address (protocol/network address/port) is normally permitted. : make_sock: could not bind to address 0.0.0.0:80
A:
NameVirtualHost *:80
I get this error:
Only one usage of each socket address (protocol/network address/port) is normally >permitted. : make_sock: could not bind to address 0.0.0.0:80
I think this might be because you have somthing else listening to port 80. Do you have any other servers (or for example Skype) running?
(If it was Skype: untick "Tools > Options > Advanced > Connection > Use port 80 and 443 as alternatives for incoming connections")
A: Well, it seems the problem there is the way (and order) in which you assign the ports.
Basically, *:80 means "use port 80 for all hosts in this configuration". When you do this, Apache tries to bind that host to 0.0.0.0:80, which means that host will receive every single packet coming to the machine through port 80, regardless of what virtual host it was intended to go to. That's something you should use only once, and only if you have one host in that configuration.
Thus, if you have the same *:80 directive on two hosts in the configuration file, the server won't load because it will try to bind 0.0.0.0:80 twice, failing on the second try. (which explains the "Only one usage of each socket address (protocol/network address/port) is normally permitted. : make_sock: could not bind to address 0.0.0.0:80" message).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Speeding up XAML editing in VS2008 When editing XAML in VS2008 SP1, the editor is really slow. devenv process seems to be around at 40% CPU (the machine I’m using at the moment is only dual core, so that’s almost maxing out one core) most of the time. It spikes up a bit more when I switch to another XAML file. I do also have ReSharper installed, but I think I’d rather put up with the slowness than remove that :)
Any suggestions on how I can speed things up a bit?
Edited to add:
I'm already using the Xaml only view, which did speed it up from what I remember - but it's still to sluggish. Also, the Xaml files aren't massive - only 100 to 200 lines.
A: You can speed it up a lot by only viewing the XML view. Tools / Options / Text Editor / XAML / Always open documents in full XAML view (check this box).
A: It looks like the slowdown is due to ReSharper. From a bit more Googling I found that pressing Ctrl+8 will turn ReSharper off for the current file (Ctrl+8 again to turn it back on). If I do this for the slow Xaml files, my problems pretty much go away (and I don’t mind not having ReSharper for Xaml)
Update: The 4.1 release of ReSharper seems to have fixed the performance problem, so I no longer need to use the Ctrl+8 shortcut.
A: I found that this hotfix solved a major lagging and stuttering issue I was having.
https://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=10826
Before simply scrolling or editing a tag in my xaml would cause a 5-10 second pause in VS2008. This hotfix seemed to remedy most of it; not it only pauses after save and loading xaml files.
A: Maybe you can edit the XAML file outside Visual Studio. Use tools like:
*
*XamlPadX 4
*Kaxaml
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to convert Word and Excel documents to PDF programmatically? We are developing a little application that given a directory with PDF files creates a unique PDF file containing all the PDF files in the directory. This is a simple task using iTextSharp. The problem appears if in the directory exist some files like Word documents, or Excel documents.
My question is, is there a way to convert word, excel documents into PDF programmatically? And even better, is this possible without having the office suite installed on the computer running the application?
A: Office 2007 allows for this. I have found PDFCreator to be good, the VBA is included in sample files, and have heard that CutePDF is also good. PDFCreator and CutePDF are free.
To work without Office, you would need viewers, as far as I know:
http://www.microsoft.com/downloads/details.aspx?FamilyID=c8378bf4-996c-4569-b547-75edbd03aaf0&displaylang=EN
http://www.microsoft.com/downloads/details.aspx?familyid=95E24C87-8732-48D5-8689-AB826E7B8FDF&displaylang=en
A: I needed to do this myself, but managed to get it done with .Net and without 3rd party tools:
MSDN: Saving Word 2007 Documents to PDF and XPS Formats
Pretty simple, about 50 lines of code. However I think you will need Word 2007 installed on the machine as well as the ability to Save As PDF
A: To convert Word documents to PDF, take a look at jWordConvert, a java library that can do exactly that. This will not work with the Excel files though, only with the Word files. The language is not Sharp, it's Java but you could switch to use IText (which is java) instead of ITextSharp.
A: You can also use a component like activePDF's DocConverter to convert a lot formats to PDF.
A: TallPDF.NET (comes with a hefty price tag) allows you to serve dynamic PDF from any .NET application including ASP.NET pages and web services.
PDFEdit (free and open source) is an editor for manipulating PDF documents. It has a GUI version and a command-line interface. Scripting is used to a great extent in the editor and almost anything can be scripted. It is possible to create your own scripts or plugins.
A: The most common way to convert files to a pdf is to print them to a pdf printer driver. There are a number of such drivers, one that i know of that will do the job is Black Ice.
Another is to use Adobe Acrobat's SDK. from memory its very expensive.
Its been a while since i have actually done any work with converting pdf's and the landscape may have changed.
A: Use PDF maker that comes with adobe 7- 9
I just used this code Covert Doc to PDF
A: I'm surprised Aspose wasn't mentioned here, it's easy, simple, and reliable. Downside is that it is not free.
I've used iTextSharp in the past, it's really good, easy to install (one DLL I believe), the merge takes a bit of tindering so it's not as easy to use as Aspose, but hey, it's free so that is the best part.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Accessing Datasource from Outside A Web Container (through JNDI) I'm trying to access a data source that is defined within a web container (JBoss) from a fat client outside the container.
I've decided to look up the data source through JNDI. Actually, my persistence framework (Ibatis) does this.
When performing queries I always end up getting this error:
java.lang.IllegalAccessException: Method=public abstract java.sql.Connection java.sql.Statement.getConnection() throws java.sql.SQLException does not return Serializable
Stacktrace:
org.jboss.resource.adapter.jdbc.remote.WrapperDataSourceService.doStatementMethod(WrapperDataSourceS
ervice.java:411),
org.jboss.resource.adapter.jdbc.remote.WrapperDataSourceService.invoke(WrapperDataSourceService.java
:223),
sun.reflect.GeneratedMethodAccessor106.invoke(Unknown Source),
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25),
java.lang.reflect.Method.invoke(Method.java:585),
org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155),
org.jboss.mx.server.Invocation.dispatch(Invocation.java:94),
org.jboss.mx.server.Invocation.invoke(Invocation.java:86),
org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264),
org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659),
My Datasource:
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
<local-tx-datasource>
<jndi-name>jdbc/xxxxxDS</jndi-name>
<connection-url>jdbc:oracle:thin:@xxxxxxxxx:1521:xxxxxxx</connection-url>
<use-java-context>false</use-java-context>
<driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
<user-name>xxxxxxxx</user-name>
<password>xxxxxx</password>
<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter</exception-sorter-class-name>
<min-pool-size>5</min-pool-size>
<max-pool-size>20</max-pool-size>
</local-tx-datasource>
</datasources>
Does anyone have a clue where this could come from?
Maybe someone even knows a better way how to achieve this.
Any hints are much appreciated!
Cheers,
Michael
A: Not sure if this is the same issue?
JBoss DataSource config
DataSource wrappers are not usable outside of the server VM
A: @Michael Well, java.sql.Connection is an Interface - it might technically be possible for the concrete implementation you're getting from JBoss to be Serializable - but I don't think you're really going to have any options you can use. If it was possible, it would probably be easy :)
I think @toolkit might have said the right words with useable outside the VM - the JDBC drivers will be talking to native driver code running in the underlying OS I guess, so that might explain why you can't just pass a connection over the network elsewhere.
My advice, (if you don't get any better advice!) would be to find a different approach - if you have access to locate the resource on the JBoss directory, maybe implement a proxy object that you can locate and obtain from the directory that allows you to use the connection remotely from your fat client. That's a design pattern called data transfer object I think Wikipedia entry
A: I think the exception indicates that the SQLConnection object you're trying to retrieve doesn't implement the Serializable interface, so it can't be passed to you the way you asked for it.
From the limited work I've done with JDNI, if you're asking for an object via JNDI it must be serializable. As far as I know, there's no way round that - if I think of a better way I'll post it up...
OK, one obvious option is to provide a serializable object local to the datasource that uses it but doesn't have the datasource as part of its serializable object graph. The fat client could then look up that object and query it instead.
Or create a (web?) service through which to access the datasource is governed - again your fat client would hit the service - this would probably be better encapsulated and more reuseable approach if those are concerns for you.
A: @toolkit:
Well, not exactly. Since I can access the data source over JNDI, it is actually visible and thus usable.
Or am I getting something totally wrong?
@Brabster:
I think you're on the right track. Isn't there a way to make the connection serializable? Maybe it's just a configuration issue...
A: I've read up on Ibatis now - maybe you can make your implementations of Dao etc. Serializable, post them into your directory and so retrieve them and use them in your fat client? You'd get reuse benefits out of that too.
Here's an example of something looks similar for Wicket
A: JBoss wraps up all DataSources with it's own ones.
That lets it play tricks with autocommit to get the specified J2EE behaviour out of a JDBC connection. They are mostly serailizable. But you needn't trust them.
I'd look carefully at it's wrappers. I've written a surrogate for JBoss's J2EE wrappers wrapper for JDBC that works with OOCJNDI to get my DAO code unit test-able standalone.
You just wrap java.sql.Driver, point OOCJNDI at your class, and run in JUnit.
The Driver wrapper can just directly create a SQL Driver and delegate to it.
Return a java.sql.Connection wrapper of your own devising on Connect.
A ConnectionWrapper can just wrap the Connection your Oracle driver gives you,
and all it does special is set Autocommit true.
Don't forget Eclipse can wrt delgates for you. Add a member you need to delegate to , then select it and right click, source -=>add delgage methods.
This is great when you get paid by the line ;-)
Bada-bing, Bada-boom, JUnit out of the box J2EE testing.
Your problem is probably amenable to the same thing, with JUnit crossed out and FatCLient written in an crayon.
My FatClient uses RMI generated with xdoclet to talk to the J2EE server, so I don't have your problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I run my app with large pages in Windows? Large pages are available in Windows Server 2003 and Windows Vista.
But how do I enable large pages for my application?
A: Martin's answer is correct on Windows Server 2003:
You will have to assign the "Lock pages in memory" privilege to any user that runs your > application. This includes administrators
*
*Select Control Panel -> Administrative Tools -> Local Security Policy
*Select Local Policies -> User Rights Assignment
*Double click "Lock pages in memory", add users and/or groups
*Reboot the machine
On Windows Vista you need also make sure that the application is run as Administrator (by right-clicking on the application or the shell and choosing "Run as adminstrator".
In addition, it helps to have a freshly booted machine since the large pages can "run out" due to fragmentation of the heap.
A: You will have to assign the Lock pages in memory privilege to any user that runs your application. This includes administrators.
*
*Select Control Panel -> Administrative Tools -> Local Security Policy
*Select Local Policies -> User Rights Assignment
*Double click "Lock pages in memory", add users and/or groups
*Reboot the machine
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can all RPN expressions be represented such that all operators appear on the left and all operands appear on the right? I've convinced myself that they can't.
Take for example:
4 4 + 4 /
stack: 4
stack: 4 4
4 + 4 = 8
stack: 8
stack: 8 4
8 / 4 = 2
stack: 2
There are two ways that you could write the above expression with the
same operators and operands such that the operands all come first: "4
4 4 + /" and "4 4 4 / +", neither of which evaluate to 2.
"4 4 4 + /"
stack: 4
stack: 4 4
stack: 4 4 4
4 + 4 = 8
stack: 4 8
4 / 8 = 0.5
stack: 0.5
"4 4 4 / +"
stack: 4
stack: 4 4
stack: 4 4 4
4 / 4 = 1
stack: 4 1
4 + 1 = 5
stack: 5
If you have the ability to swap items on the stack then yes, it's possible, otherwise, no.
Thoughts?
A: Consider the algebraic expression:
(a + b) * (c + d)
The obvious translation to RPN would be:
a b + c d + *
Even with a swap operation available, I don't think there is a way to collect all the operators on the right:
a b c d +
a b S
where S is the sum of c and d. At this point, you couldn't use a single swap operation to get both a and b in place for a + operation. Instead, you would need a more sophisticated stack operation (such as roll) to get a and b in the right spot. I don't know whether a roll operation would be sufficient for all cases, either.
A: Actually, you've not only given the answer but a conclusive proof as well, by examining a counter-example which is enough to disprove the assumption implied in the title.
A: I know this is a very old thread, but I just found it today and wanted to say that I believe the answer to the original question is YES. I am confident all RPN expressions can be represented such that all operators appear on the left and all operands appear on the right, if in addition to the normal arithmetic operations, we are allowed to include three additional 'navigational' operators in the representation.
Any arithmetic expression can be represented as a binary tree, with variables and constants at the leaf nodes, binary arithmetic operations at the forks in the tree, and unary operations such as negation, reciprocal, or square root along any branches. The three additional operations I suggest represent building a left branch, building a right branch, or reaching a leaf node in a binary tree. Now if we place all the operands to the left of the input string according to the position of their respective leaves in the tree, we can supply the remainder of the input string with operations telling how to reconstruct the appropriate binary tree in memory and insert the operands and mathematical operations into it at the correct points. Finally a depth-first tree-traversal algorithm is applied to calculate the result.
I don't know if this has any practical application. It's probably too inefficient as way to encode and decode expressions. But as an academic exercise, I am sure it is workable.
A: It is enough to show one that can't in order to tell you the answer to this.
If you can't reorder the stack contents, then the expression (2+4)*(7+8) can't be rearranged.
2 4 + 7 8 + *
No matter how you reorder this, you'll end up with something that needs to be summed before you go on.
At least I believe so.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Very simple C++ DLL that can be called from .net I'm trying to call a 3rd party vendor's C DLL from vb.net 2005 and am getting P/Invoke errors. I'm successfully calling other methods but have hit a bottle-neck on one of the more complex. The structures involved are horrendous and in an attempt to simplify the troubleshooting I'd like to create a C++ DLL to replicate the problem.
Can somebody provide the smallest code snippet for a C++ DLL that can be called from .Net? I'm getting a Unable to find entry point named XXX in DLL error in my C++ dll. It should be simple to resolve but I'm not a C++ programmer.
I'd like to use a .net declaration for the DLL of
Declare Function Multiply Lib "C:\MyDll\Debug\MyDLL.DLL" Alias "Multiply" (ByVal ParOne As Integer, ByVal byvalParTwo As Integer) As Integer
A: Try using the __decspec(dllexport) magic pixie dust in your C++ function declaration. This declaration sets up several things that you need to successfully export a function from a DLL. You may also need to use WINAPI or something similar:
__declspec(dllexport) WINAPI int Multiply(int p1, int p2)
{
return p1 * p2;
}
The WINAPI sets up the function calling convention such that it's suitable for calling from a language such as VB.NET.
A: You can try to look at the exported functions (through DumpBin or Dependency Walker) and see if the names are mangled.
A: Using Greg's suggestion I found the following works. As mentioned I'm not a C++ programmer but just needed something practical.
myclass.cpp
#include "stdafx.h"
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
int _stdcall multiply(int x , int y)
{
return x*y;
}
myclass.def
LIBRARY myclass
EXPORTS
multiply @1
stdafx.cpp
#include "stdafx.h"
stdafx.h
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#if !defined(AFX_STDAFX_H__5DB9057C_BAE6_48D8_8E38_464F6CB80026__INCLUDED_)
#define AFX_STDAFX_H__5DB9057C_BAE6_48D8_8E38_464F6CB80026__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// Insert your headers here
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__5DB9057C_BAE6_48D8_8E38_464F6CB80026__INCLUDED_)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Referencing resource files from multiple projects in a solution I am working on localization for a asp.net application that consists of several projects.
For this, there are some strings that are used in several of these projects. Naturally, I would prefer to have only one copy of the resource file in each project.
Since the resource files don't have an namespace (at least as far as I can tell), they can't be accessed like regular classes.
Is there any way to reference resx files in another project, within the same solution?
A: I have used this solution before to share a assembley info.cs file across all projects in a solution I would presume the same would work fro a resource file.
Create a linked file to each individual project/class library. There will be only one copy and every project will have a reference to the code via a linked file at compile time. Its a very elegant solution to solve shared non public resources without duplicating code.
<Compile Include="path to shared file usually relative">
<Link>filename for Visual Studio To Dispaly.resx</Link>
</Compile>
add that code to the complile item group of a csproj file then replace the paths with your actual paths to the resx files and you sould be able to open them.
Once you have done this for one project file you should be able to employ the copy & paste the linked file to other projects without having to hack the csproj.
A: Some useful advice on how to manage a situation like this is available here:
http://www.codeproject.com/KB/dotnet/Localization.aspx
A: You can just create a class library project, add a resource file there, and then refer to that assembly for common resources.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Move all windows to a single monitor (with two attached) in Mac OS X? Whenever I use my MacBook away from my desk and later plug it into an external display (as primary), I get into the state of having windows deposited in both the notebook monitor and the external one.
To move all windows to a single screen, my current solution is to "Turn on mirroring" in the display preferences and then turn it off again. This is rather tedious, though. Does anyone know of a better way?
I'm afraid the script posted by @erlando does absolutely nothing for me, running Mac OS X 10.5.4. (I.e., with windows on both screens, running the script moves not a single one of them, and it does not return any errors.) I guess I'll just have to stick with using the "mirror/unmirror" method mentioned above.
@Denton: I'm afraid those links provide scripts for getting windows which are orphaned from any screen back onto the display. I ‘just’ want to move all windows from a secondary display onto the primary display.
A: On Lion you can toggle Mirror Displays using fn+Cmd+F1 (provided you are using the media control keys as default).
This also works on Snow Leopard and likely everything in between, also possibly further back.
A: You can click the "Gather Windows" button in the Displays preference pane.
A: Here is a command-line script to do just that: http://zach.in.tu-clausthal.de/software/.
It's a little down the page under "Move Off-Screen Windows to the Main Screen".
-- Source: http://www.jonathanlaliberte.com/2007/10/19/move-all-windows-to-your-main-screen/
-- and: http://www.macosxhints.com/article.php?story=2007102012424539
--
-- Improvements:
-- + code is more efficient and more elegant now
-- + windows are moved also, if they are "almost" completely off-screen
-- (in the orig. version, they would be moved only if they were completely off-screen)
-- + windows are moved (if they are moved) to their closest position on-screen
-- (in the orig. version, they would be moved to a "home position" (0,22) )
-- Gabriel Zachmann, Jan 2008
-- Example list of processes to ignore: {"xGestures"} or {"xGestures", "OtherApp", ...}
property processesToIgnore : {"Typinator"}
-- Get the size of the Display(s), only useful if there is one display
-- otherwise it will grab the total size of both displays
tell application "Finder"
set _b to bounds of window of desktop
set screen_width to item 3 of _b
set screen_height to item 4 of _b
end tell
tell application "System Events"
set allProcesses to application processes
repeat with i from 1 to count allProcesses
--display dialog (name of (process i)) as string
if not (processesToIgnore contains ((name of (process i)) as string)) then
try
tell process i
repeat with x from 1 to (count windows)
set winPos to position of window x
set _x to item 1 of winPos
set _y to item 2 of winPos
set winSize to size of window x
set _w to item 1 of winSize
set _h to item 2 of winSize
--display dialog (name as string) & " - width: " & (_w as string) & " height: " & (_h as string)
if (_x + _w < 40 or _y + _h < 50 or _x > screen_width - 40 or _y > screen_height - 40) then
if (_x + _w < 40) then set _x to 0
if (_y + _h < 50) then set _y to 22
if (_x > screen_width - 40) then
set _x to screen_width - _w
if (_x < 0) then set _x to 0
end if
if (_y > screen_height - 40) then
set _y to screen_height - _h
if (_y < 22) then set _y to 22
end if
set position of window x to {_x, _y}
end if
end repeat
end tell
end try
end if
end repeat
end tell
A: As you said, the best answer seems to be turning "Mirror Displays" on and off again. Afterwards, all windows will have been collected on the main screen, and the secondary screen will be empty.
This is a bit cumbersome, but nothing else has worked for me in Lion.
A: Cmd+F1 appears to be a Mirror Displays shortcut in Snow Leopard. Don't know about Lion, etc, though.
Just tap it twice and see what happens (-:
For the people who prefer to set up their function keys to act in the old-fashioned way (not as brightness/sound controls etc.), it will be Cmd+Fn+F1
A: There is an article on using AppleScript to do this at macosxtips.co.uk, and another at macosxhints.com.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: Programmable, secure FTP replacement We need to move off traditional FTP for security purposes (it transmits it's passwords unencrypted). I am hearing SSH touted as the obvious alternative. However I have been driving FTP from an ASP.NET program interface to automate my web-site development, which is now quite a highly web-enabled process.
Can anyone recommend a secure way to transfer files around which has a program interface that I can drive from ASP.NET?
A: sharpssh implements sending files via scp.
A: the question has three subquestions:
1) choosing the secure transfer protocol
The secure version of old FTP exists - it's called FTP/SSL (plain old FTP over SSL encrypted channel). Maybe you can still use your old deployment infrastructure - just check whether it supports the FTPS or FTP/SSL.
You can check details about FTP, FTP/SSL and SFTP differences at http://www.rebex.net/secure-ftp.net/ page.
2) SFTP or FTP/SSL server for Windows
When you choose whether to use SFTP or FTPS you have to deploy the proper server. For FTP/SSL we use the Gene6 (http://www.g6ftpserver.com/) on several servers without problems. There is plenty of FTP/SSL Windows servers so use whatever you want. The situation is a bit more complicated with SFTP server for Windows - there is only a few working implementations. The Bitvise WinHTTPD looks quite promising (http://www.bitvise.com/winsshd).
3) Internet File Transfer Component for ASP.NET
Last part of the solution is secure file transfer from asp.net. There is several components on the market. I would recommend the Rebex File Transfer Pack - it supports both FTP (and FTP/SSL) and SFTP (SSH File Transfer).
Following code shows how to upload a file to the server via SFTP. The code is taken from our Rebex SFTP tutorial page.
// create client, connect and log in
Sftp client = new Sftp();
client.Connect(hostname);
client.Login(username, password);
// upload the 'test.zip' file to the current directory at the server
client.PutFile(@"c:\data\test.zip", "test.zip");
// upload the 'index.html' file to the specified directory at the server
client.PutFile(@"c:\data\index.html", "/wwwroot/index.html");
// download the 'test.zip' file from the current directory at the server
client.GetFile("test.zip", @"c:\data\test.zip");
// download the 'index.html' file from the specified directory at the server
client.GetFile("/wwwroot/index.html", @"c:\data\index.html");
// upload a text using a MemoryStream
string message = "Hello from Rebex SFTP for .NET!";
byte[] data = System.Text.Encoding.Default.GetBytes(message);
System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
client.PutFile(ms, "message.txt");
Martin
A: We have used a variation of this solution in the past which uses the SSH Factory for .NET
A: The traditional secure replacement for FTP is SFTP, but if you have enough control over both endpoints, you might consider rsync instead: it is highly configurable, secure just by telling it to use ssh, and far more efficient for keeping two locations in sync.
A: G'day,
You might like to look at ProFPD.
Heavily customisable. Based on Apache module structure.
From their web site:
ProFTPD grew out of the desire to have a secure and configurable FTP server, and out of a significant admiration of the Apache web server.
We use our adapted version for large scale transfer of web content. Typically 300,000 updates per day.
HTH
cheers,
Rob
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Search and replace a line in a file in Python I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.
What is the best way to do this, within the following code?
f = open(file)
for line in f:
if line.contains('foo'):
newline = line.replace('foo', 'bar')
# how to write this newline back to the file
A: Here's another example that was tested, and will match search & replace patterns:
import fileinput
import sys
def replaceAll(file,searchExp,replaceExp):
for line in fileinput.input(file, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
Example use:
replaceAll("/fooBar.txt","Hello\sWorld!$","Goodbye\sWorld.")
A: This should work: (inplace editing)
import fileinput
# Does a list of files, and
# redirects STDOUT to the file in question
for line in fileinput.input(files, inplace = 1):
print line.replace("foo", "bar"),
A: Create a new file, copy lines from the old to the new, and do the replacing before you write the lines to the new file.
A: Expanding on @Kiran's answer, which I agree is more succinct and Pythonic, this adds codecs to support the reading and writing of UTF-8:
import codecs
from tempfile import mkstemp
from shutil import move
from os import remove
def replace(source_file_path, pattern, substring):
fh, target_file_path = mkstemp()
with codecs.open(target_file_path, 'w', 'utf-8') as target_file:
with codecs.open(source_file_path, 'r', 'utf-8') as source_file:
for line in source_file:
target_file.write(line.replace(pattern, substring))
remove(source_file_path)
move(target_file_path, source_file_path)
A: The shortest way would probably be to use the fileinput module. For example, the following adds line numbers to a file, in-place:
import fileinput
for line in fileinput.input("test.txt", inplace=True):
print('{} {}'.format(fileinput.filelineno(), line), end='') # for Python 3
# print "%d: %s" % (fileinput.filelineno(), line), # for Python 2
What happens here is:
*
*The original file is moved to a backup file
*The standard output is redirected to the original file within the loop
*Thus any print statements write back into the original file
fileinput has more bells and whistles. For example, it can be used to automatically operate on all files in sys.args[1:], without your having to iterate over them explicitly. Starting with Python 3.2 it also provides a convenient context manager for use in a with statement.
While fileinput is great for throwaway scripts, I would be wary of using it in real code because admittedly it's not very readable or familiar. In real (production) code it's worthwhile to spend just a few more lines of code to make the process explicit and thus make the code readable.
There are two options:
*
*The file is not overly large, and you can just read it wholly to memory. Then close the file, reopen it in writing mode and write the modified contents back.
*The file is too large to be stored in memory; you can move it over to a temporary file and open that, reading it line by line, writing back into the original file. Note that this requires twice the storage.
A: Using hamishmcn's answer as a template I was able to search for a line in a file that match my regex and replacing it with empty string.
import re
fin = open("in.txt", 'r') # in file
fout = open("out.txt", 'w') # out file
for line in fin:
p = re.compile('[-][0-9]*[.][0-9]*[,]|[-][0-9]*[,]') # pattern
newline = p.sub('',line) # replace matching strings with empty string
print newline
fout.write(newline)
fin.close()
fout.close()
A: Based on the answer by Thomas Watnedal.
However, this does not answer the line-to-line part of the original question exactly. The function can still replace on a line-to-line basis
This implementation replaces the file contents without using temporary files, as a consequence file permissions remain unchanged.
Also re.sub instead of replace, allows regex replacement instead of plain text replacement only.
Reading the file as a single string instead of line by line allows for multiline match and replacement.
import re
def replace(file, pattern, subst):
# Read contents from file as a single string
file_handle = open(file, 'r')
file_string = file_handle.read()
file_handle.close()
# Use RE package to allow for replacement (also allowing for (multiline) REGEX)
file_string = (re.sub(pattern, subst, file_string))
# Write contents to file.
# Using mode 'w' truncates the file.
file_handle = open(file, 'w')
file_handle.write(file_string)
file_handle.close()
A: I guess something like this should do it. It basically writes the content to a new file and replaces the old file with the new file:
from tempfile import mkstemp
from shutil import move, copymode
from os import fdopen, remove
def replace(file_path, pattern, subst):
#Create temp file
fh, abs_path = mkstemp()
with fdopen(fh,'w') as new_file:
with open(file_path) as old_file:
for line in old_file:
new_file.write(line.replace(pattern, subst))
#Copy the file permissions from the old file to the new file
copymode(file_path, abs_path)
#Remove original file
remove(file_path)
#Move new file
move(abs_path, file_path)
A: As lassevk suggests, write out the new file as you go, here is some example code:
fin = open("a.txt")
fout = open("b.txt", "wt")
for line in fin:
fout.write( line.replace('foo', 'bar') )
fin.close()
fout.close()
A: A more pythonic way would be to use context managers like the code below:
from tempfile import mkstemp
from shutil import move
from os import remove
def replace(source_file_path, pattern, substring):
fh, target_file_path = mkstemp()
with open(target_file_path, 'w') as target_file:
with open(source_file_path, 'r') as source_file:
for line in source_file:
target_file.write(line.replace(pattern, substring))
remove(source_file_path)
move(target_file_path, source_file_path)
You can find the full snippet here.
A: If you're wanting a generic function that replaces any text with some other text, this is likely the best way to go, particularly if you're a fan of regex's:
import re
def replace( filePath, text, subs, flags=0 ):
with open( filePath, "r+" ) as file:
fileContents = file.read()
textPattern = re.compile( re.escape( text ), flags )
fileContents = textPattern.sub( subs, fileContents )
file.seek( 0 )
file.truncate()
file.write( fileContents )
A: fileinput is quite straightforward as mentioned on previous answers:
import fileinput
def replace_in_file(file_path, search_text, new_text):
with fileinput.input(file_path, inplace=True) as file:
for line in file:
new_line = line.replace(search_text, new_text)
print(new_line, end='')
Explanation:
*
*fileinput can accept multiple files, but I prefer to close each single file as soon as it is being processed. So placed single file_path in with statement.
*print statement does not print anything when inplace=True, because STDOUT is being forwarded to the original file.
*end='' in print statement is to eliminate intermediate blank new lines.
You can used it as follows:
file_path = '/path/to/my/file'
replace_in_file(file_path, 'old-text', 'new-text')
A: if you remove the indent at the like below, it will search and replace in multiple line.
See below for example.
def replace(file, pattern, subst):
#Create temp file
fh, abs_path = mkstemp()
print fh, abs_path
new_file = open(abs_path,'w')
old_file = open(file)
for line in old_file:
new_file.write(line.replace(pattern, subst))
#close temp file
new_file.close()
close(fh)
old_file.close()
#Remove original file
remove(file)
#Move new file
move(abs_path, file)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "356"
} |
Q: OpenGL or Direct3D for a new Windows game project? Or something else? I'm starting a hobby game project on Windows that will make heavy use of 3D graphics effects. It will most likely be written in C++.
Should I use OpenGL or Direct3D for my graphics backend? Why?
Or should I use a ready-made graphics engine such as OGRE 3D? Which one?
Some "how to get started" links would be useful. (On either technology, or both.)
Edit - Yes I really meant Direct3D, not DirectX, thanks to graham.reeds for clarification
Edit - Mihai Lazar pointed out that I could also use a graphics engine such OGRE 3D. Edited the question to reflect this alternative.
A: If you're willing to consider C#, take a good look at XNA. For hobby projects, assuming what you want is to actually get a game up and running instead of tinkering with complex API code, I cannot recommend it highly enough. It is increasingly mature, well-documented, and, compared to D3D/OpenGL, very quick and easy to use. As a bonus, with a $100/year Creators Club membership, you can even use it to develop games for the Xbox 360.
A: You could also base your work on ogre they provide the abstraction themselves and they have really nice tools. Since this is a projects that's been around for over 6 years I think. The base library is not really for beginners since you need to know a bit about software design, but I found a lot of people that have written games using it.
It would be safer and quicker than learning the heavier stuff since it's already been abstracted. Plus after a couple of month you'll be talking 3D jargon anyways. There is also a book to get you started with Ogre, I think it's kinda old by now but a starting point anyways.
A: You must remember that DirectX is a collection of technologies - Input, Audio and Graphics. However to most people DX is synonymous with the renderer.
In my opinion D3D (or DirectGraphics) has not really been that hard since DX8. I have not tried DX9 or DX10.
Bernard is right - try to abstract as much as possible. Try to keep DX or OGL calls outside your object classes.
A: I have no previous OpenGL, DirectX or videogame experience and i have made have an open source race videogame with Ogre3d. Is a very good framework to start in videogames: well done code, plenty of docs and info in the net and very good starting tutorials.
The rendering engine is DirectX/OpenGl agnostic, you can later select to render your game with OpenGL or DirectX (withouth changes in your code)
A: I did my dissertation at uni on a comparison of OpenGL vs Direct3D. The real benefits of Direct3D are that it has a regular release schedule - it's always being updated to take advantage of the latest advances in graphics hardware. How long has it taken between the OpenGL 2.0 and 3.0 releases? Also, a lot of work has been done in extensions for OpenGL, which means only some rendering will work on some cards.
Having said that, OpenGL will be easier to start programming with. As Direct3D is based heavily in COM, it has a steep learning curve.
If it were me, I would be choosing DirectX over OpenGL. That's at the cost of non-platform independance.
A: Best thing to do would be to abstract over your renderer as much as possible, to make porting to the other technology as painless as possible.
A: For the situation that you describe, I would recommend Direct3D.
The primary reason to use Direct3D instead of OpenGL is that often video card vendors only do a good job on the OpenGL drivers for their "high end" cards.
The low end game type cards tend to get poor and generally buggy drivers, causing problems on your end user's machines.
If portability is important, then that would be a big reason to look at OpenGL or Ogre instead.
But if you never plan to port, then focus on Direct3D since it is a more widely stable platform with better IHV driver support.
A: Start with OpenGL because there are good textbooks and other online references on it. Once you get the hang of writing 3D game, you would be able to make the judgment for yourself.
Finishing a game, even if it's really stupid and simple just to get you going, is more important than picking the right library. With glut, you can get some 3D object to show up on your screen in a day. Start with NeHe's tutorials.
A: The thing you should consider is the decision of platform independence. Do you want to tie your game to Windows, or would you like to release it to Mac OS X or Linux at some point. If you decide that you want to support Linux, OS X in the future, you will need to use OpenGL.
There seems to be a lot of goodwill by the Linux community if the game is at least semi-released for Linux.
A: To answer this question well requires more information about you:
*
*what is your programming ability?
If it's high, I would probably start with Ogre (the best strictly rendering open source engine, IMHO) or another open source game engine, such as Delta3D, if you want additional features (sound, physics, etc.) that a game engine brings.
If you don't want to go with an engine, I would go with Direct3D, because it's being updated much quicker than OpenGL. I don't want to get into all the issues, but version 3.0 of OpenGL was announced during SIGGRAPH and most in the community were very disappointed with it. Direct3D puts you in a much better position to take advantage of shaders and other uses of the programmable pipeline.
If your programming ability is not too high, and you are doing this to learn programming, I would start with OpenGL, because it is easier to learn and there are more resources on the web (see http://nehe.gamedev.net for example).
A: It is my understanding that in Direct3D you must handle all resource allocation and management yourself, whereas the OpenGL specification leaves this to the driver/implementation rather than the application.
This allows Direct3D developers to use the best allocation and management methods suitable to the application, but is also extra work.
I have done the typical "Hello World" applications in each, and I prefer OpenGL over Direct3D, but that is just my opinion. You should try out both, spend a day or two learning and playing around with each, and decide for yourself.
A: I really agree with those telling you to learn Ogre3D. You said you'd use C++, so Ogre3D is a great choice. XNA uses C# and you'd have to learn the differences between it and C++, apart from learning the very XNA. Also XNA is neither Open Source nor cross platform, so if you wanna have a wider knowledge about game development, I'd suggest first learning SDL, and then Ogre3D.
A: To start with, we've got the Wikipedia comparison of OpenGL and Direct3D.
But I'd really like to hear some practical viewpoints, especially in the light of recent developments of OpenGL 3.0 and DirectX 10.
A: The suggestions for abstraction of an engine are good, assuming that you know what you are doing. It's difficult to write a good abstraction layer for graphics without having done it already.
I would suggest that you just pick one. You will pick up the concepts from either easily enough -- enough so that you can potentially work on an abstraction layer, or the other library easy enough. But just do it. I really wouldn't worry so much about which is the right one. They are both good, solid performers. DX10 (if you have Vista) may have the slight advantage of more up to date shader models, but for someone starting now, that is pretty irrelevant I think. GL has the advantage that some of the nigglier matrix/vector math operations are either hidden from you, or provided for you (although I think DX has some of these as well.)
A: While OpenGL is by far easy to start with and as some people already wrote - getting a triangle to show on screen and from there move to textures, particles and more can be done within a day.
I do however think that a good question to ask is what is your final goal.
If it is a simple game, no skeletal animation, and simple 3D - OpenGL is definitely the answer. If you aim way higher and don't want to put the time in developing all the technology from scratch (or go hunting for free libraries and putting all together) then DX is a good choice, I would go for DX9c until DX11 comes out.
If you don't mind messing with other languages other than C++ you should also take a look at the XNA development environment - it became quite mature and good.
Just as well, using an already existing engine is good if you know that it'll give you most of what you need, for the right price and will save you the time to develop it yourself, the main problem is that you'd need to go over several game engines (Ogre, Game Studio, Torque, etc..) and then make your choice based on limited experience - read as many reviews from casual developers as you can before you proceed, and try to take a look at the code if you intend to change it.
Hope it helped.
A: You have to think about what you want out of it, as it's a hobby project I'm assuming that "learning stuff" will be a major part of the experience so avoid picking up something that hides things from you and does stuff behind the scenes as this will only give you a fraction of the picture.
I'd go with Direct3D because it's got the better support, I find the docs easy to read and there are decent samples that come with the SDK. You can even use these samples as the base to build on if you want to get a kick start without the initial steep learning curve of getting things set up.
I started with OpenGL for the record, and after about a month went onto Direct3d (version 7 at the time). I found Direct3D forced me to be more aware of what I was wanting to do and how I was setting things up but I preferred this level of understanding.
Importantly IMO, whichever way you choose, take it step by step and get things on screen regularly. There's all sorts of reasons why something isn't on screen (it's transparent, the camera's inside the object, etc...) so by taking baby steps and getting stuff to display regularly you're both verifying things are still moving along and getting a little visual reward.
A: Don't start with Ogre.
Start with OpenGL GLUT (Win32), and a tutorial or two.
As soon as you can move to Win32 and take a look at this site, which is pretty old now, but still, quite good.
A: Clearly from the responses you've been getting, you can reasonably start with either D3D or OpenGL for your 3D graphics API. Triple-A gaming titles have been developed using both technologies, and they both have their strengths and weaknesses.
If you're already reasonably proficient in C++, either one will serve, however there's a number of other considerations to make in your selection:
*
*Portability: OpenGL (and OpenGL ES) is available on Windows, Linux, OS X, iOS, Android, and other systems. D3D/DirectX locks you into MS platforms only.
*Game Input: In DirectX, the DirectInput API gives you access to controllers. OpenGL doesn't have an equivalent here.
*Sounds: DirectAudio supports sounds, OpenGL has no equivalent (however OpenAL is often used)
*Physics: Depending on your game needs, you may need some advanced physics simulation
Typically the actual "gameplay" focus is on the AIs, combat, storyline, etc.
If you're still climbing the C++ learning curve (worthwhile, but takes some time), you might instead use C# and OpenTK. This would provide you with the benefits of a "gaming framework" like Ogre, reasonably direct access to OpenGL, and the significant benefits of using managed code (and IDE) for the game logic. OpenTK is cross-platform via Mono, so your code can run on OS X and Linux as well.
Have fun!
A: My opinion is that OpenGL is best.
OpenGL SuperBible: Comprehensive Tutorial and Reference is a good reference.
A: Ogre3D is great if you want to do cross platform coding and if you want to leave all the rendering to the engine. OpenGL is also great for cross platform coding, but it also makes you do all the boring parts -- however it provides greater control.
I would avoid DirectX in case you want to port your game to other platforms. Plan for the future. DirectX 10 may provide some advantages compared to OpenGL, but I really don't think you'll feel them unless you're a professional development. Otherwise, if you're pro-Microsoft, you should use XNA anyway, since as an amateur developer you won't need control provided by DirectX.
I'm coding with OpenGL for quite some time now and with Ogre3D for a few months now and I can't say I want anything else. I recently got a book on DirectX 7 and I consider it messy. Perhaps things changed, but from what I observed I don't find DirectX, and by extrapolation Direct3D, attractive.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Finding a file in a Python module distribution I've written a Python package that includes a bsddb database of pre-computed values for one of the more time-consuming computations. For simplicity, my setup script installs the database file in the same directory as the code which accesses the database (on Unix, something like /usr/lib/python2.5/site-packages/mypackage/).
How do I store the final location of the database file so my code can access it? Right now, I'm using a hack based on the __file__ variable in the module which accesses the database:
dbname = os.path.join(os.path.dirname(__file__), "database.dat")
It works, but it seems... hackish. Is there a better way to do this? I'd like to have the setup script just grab the final installation location from the distutils module and stuff it into a "dbconfig.py" file that gets installed alongside the code that accesses the database.
A: Try using pkg_resources, which is part of setuptools (and available on all of the pythons I have access to right now):
>>> import pkg_resources
>>> pkg_resources.resource_filename(__name__, "foo.config")
'foo.config'
>>> pkg_resources.resource_filename('tempfile', "foo.config")
'/usr/lib/python2.4/foo.config'
There's more discussion about using pkg_resources to get resources on the eggs page and the pkg_resources page.
Also note, where possible it's probably advisable to use pkg_resources.resource_stream or pkg_resources.resource_string because if the package is part of an egg, resource_filename will copy the file to a temporary directory.
A: That's probably the way to do it, without resorting to something more advanced like using setuptools to install the files where they belong.
Notice there's a problem with that approach, because on OSes with real a security framework (UNIXes, etc.) the user running your script might not have the rights to access the DB in the system directory where it gets installed.
A: Use the standard Python-3.7 library's importlib.resources module,
which is more efficient than setuptools:pkg_resources
(on previous Python versions, use the backported importlib_resources library).
Attention: For this to work, the folder where the data-file resides must be a regular python-package. That means you must add an __init__.py file into it, if not already there.
Then you can access it like this:
try:
import importlib.resources as importlib_resources
except ImportError:
# In PY<3.7 fall-back to backported `importlib_resources`.
import importlib_resources
## Note that the actual package could have been used,
# not just its (string) name, with something like:
# from XXX import YYY as data_pkg
data_pkg = '.'
fname = 'database.dat'
db_bytes = importlib_resources.read_binary(data_pkg, fname)
# or if a file-like stream is needed:
with importlib_resources.open_binary(data_pkg, fname) as db_file:
...
A: Use pkgutil.get_data. It’s the cousin of pkg_resources.resource_stream, but in the standard library, and should work with flat filesystem installs as well as zipped packages and other importers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: Tools for degrading my network connection? I've written some applications than heavily use network, and I would like to test it over a slow network. I'm looking for a tool to simulate these kind of connections.
I'm only interested in Windows tools.
A: I've used Traffic Shaper XP on my XP dev box at work. It seems to handle any connection (not just HTTP). It wasn't perfect, but worked well enough for the tests I was doing. If you're on Windows maybe it'll do enough for you.
A: Try dummynet.
You will find lots of resources on the web, including this tutorial.
A: Throughput, latency, jitter, and packet loss can all impact user experience. Several software solutions that run on a host (or VM) allow these "levers" to be pulled.
Last time I researched I found a few possibilities:
Wanem
dummyet (link1)
dummynet (link2)
nistnet
shunra (link1)
shunra (link2)
tmnetsim
tmnetsim
Cisco WAN-Bridge (CCO Login Required)
If you want something client based maybe try shunra, and if you want something in the infrastructure wanem is pretty easy since their is a VMWare appliance available.
A: What kind of network traffic? If it's HTTP this will work for you:
http://www.charlesproxy.com/
A: How about this tool (network Traffic Generator) ?
A: Clumsy seems to be a promising new tools for testing with degraded network performance.
A: You're right. dummynet works only in FreeBSD, it's actually built into the kernel.
What I did when I used it was grab an older PC nobody used anymore and install the FreeBSD distribution.
A: Fiddler is a(nother) web proxy that can be used to degrade your connection.
A: Dummynet is the way to go, especially if you want to simulate complex scenarios such as ADSL connections (asymmetric uplink and downlink), "Slow connection" (long latency), lossy links, etc. As Christian said, you can find some spare old PCs and install FreeBSD. You can also use VMware but I wouldn't recommand that.
A: If you are trying to do HTTP throttling Charles Web Proxy is absolutely great for this. Please do have a look at it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Drawing animations at the show of a JDialog What would be the best way to draw a simple animation just before showing a modal JDialog? (i.e. expanding borders from the mouse click point to the dialog location). I thought it would be possible to draw on the glasspane of the parent frame on the setVisible method of the dialog.
However, since the JDialog is modal to the parent, I couldn't find a way to pump drawing events into EDT before the JDialog becomes visible, since the current event on the EDT has not been completed yet.
A: Are you trying to show the JDialog indepentently of the annimation? In order to get the order set properly, you may need to bundle those actions in a runnable that is passed to the EDT at once.
eg:
SwingUtilities.invokeLater(new Runnable(){
public void run(){
doAnnimation();
showDialog();
}
}
It may be best to subclass JDialog so that you can just add the doAnnimation() logic to the setVisible(..) or show() method before calling the superclass implementation.
Finally, I imagine you'll need to set the dimensions of the dalog manually -- I don't remember if Java will know the actual size of the dialog before it is shown, so you may get some useless information for your annimation if you query the size before showing it.
A: Maybe you have a look at the SwingWorker Project which is included in JSE 6. (Link to SwingWorker) In the book "Filthy Rich Client" that I am reading at the moment they use this tool a lot. Maybe you can find a hint in the examples on the books website: http://filthyrichclients.org/
A: You may be able to take @rcreswick's answer and expand on it a little to make it work.
void myShowDialog() {
new Thread(new Runnable() {public void run() {
SwingUtilities.invokeAndWait(new Runnable() { public void run() {
doAnimation();
} } );
// Delay to wait for the animation to finish (if needed)
Thread.sleep(500);
SwingUtilities.invokeAndWait(new Runnable() { public void run() {
showDialog();
} } );
} } ).start();
}
It's pretty ugly and would have to be invoked in place of the basic showDialog() call, but it should work.
A: One possibility is to paint your own dialog on the Glass Pane. Then you have full control of the dialog and can paint whatever you want. Here's a tutorial on creating animations on the Glass Pane.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: What is the best way to lock cache in asp.net? I know in certain circumstances, such as long running processes, it is important to lock ASP.NET cache in order to avoid subsequent requests by another user for that resource from executing the long process again instead of hitting the cache.
What is the best way in c# to implement cache locking in ASP.NET?
A: For completeness a full example would look something like this.
private static object ThisLock = new object();
...
object dataObject = Cache["globalData"];
if( dataObject == null )
{
lock( ThisLock )
{
dataObject = Cache["globalData"];
if( dataObject == null )
{
//Get Data from db
dataObject = GlobalObj.GetData();
Cache["globalData"] = dataObject;
}
}
}
return dataObject;
A: There is no need to lock the whole cache instance, rather we only need to lock the specific key that you are inserting for.
I.e. No need to block access to the female toilet while you use the male toilet :)
The implementation below allows for locking of specific cache-keys using a concurrent dictionary. This way you can run GetOrAdd() for two different keys at the same time - but not for the same key at the same time.
using System;
using System.Collections.Concurrent;
using System.Web.Caching;
public static class CacheExtensions
{
private static ConcurrentDictionary<string, object> keyLocks = new ConcurrentDictionary<string, object>();
/// <summary>
/// Get or Add the item to the cache using the given key. Lazily executes the value factory only if/when needed
/// </summary>
public static T GetOrAdd<T>(this Cache cache, string key, int durationInSeconds, Func<T> factory)
where T : class
{
// Try and get value from the cache
var value = cache.Get(key);
if (value == null)
{
// If not yet cached, lock the key value and add to cache
lock (keyLocks.GetOrAdd(key, new object()))
{
// Try and get from cache again in case it has been added in the meantime
value = cache.Get(key);
if (value == null && (value = factory()) != null)
{
// TODO: Some of these parameters could be added to method signature later if required
cache.Insert(
key: key,
value: value,
dependencies: null,
absoluteExpiration: DateTime.Now.AddSeconds(durationInSeconds),
slidingExpiration: Cache.NoSlidingExpiration,
priority: CacheItemPriority.Default,
onRemoveCallback: null);
}
// Remove temporary key lock
keyLocks.TryRemove(key, out object locker);
}
}
return value as T;
}
}
A: Craig Shoemaker has made an excellent show on asp.net caching:
http://polymorphicpodcast.com/shows/webperformance/
A: I have come up with the following extension method:
private static readonly object _lock = new object();
public static TResult GetOrAdd<TResult>(this Cache cache, string key, Func<TResult> action, int duration = 300) {
TResult result;
var data = cache[key]; // Can't cast using as operator as TResult may be an int or bool
if (data == null) {
lock (_lock) {
data = cache[key];
if (data == null) {
result = action();
if (result == null)
return result;
if (duration > 0)
cache.Insert(key, result, null, DateTime.UtcNow.AddSeconds(duration), TimeSpan.Zero);
} else
result = (TResult)data;
}
} else
result = (TResult)data;
return result;
}
I have used both @John Owen and @user378380 answers. My solution allows you to store int and bool values within the cache aswell.
Please correct me if there's any errors or whether it can be written a little better.
A: Just to echo what Pavel said, I believe this is the most thread safe way of writing it
private T GetOrAddToCache<T>(string cacheKey, GenericObjectParamsDelegate<T> creator, params object[] creatorArgs) where T : class, new()
{
T returnValue = HttpContext.Current.Cache[cacheKey] as T;
if (returnValue == null)
{
lock (this)
{
returnValue = HttpContext.Current.Cache[cacheKey] as T;
if (returnValue == null)
{
returnValue = creator(creatorArgs);
if (returnValue == null)
{
throw new Exception("Attempt to cache a null reference");
}
HttpContext.Current.Cache.Add(
cacheKey,
returnValue,
null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
CacheItemPriority.Normal,
null);
}
}
}
return returnValue;
}
A: Here's the basic pattern:
*
*Check the cache for the value, return if its available
*If the value is not in the cache, then implement a lock
*Inside the lock, check the cache again, you might have been blocked
*Perform the value look up and cache it
*Release the lock
In code, it looks like this:
private static object ThisLock = new object();
public string GetFoo()
{
// try to pull from cache here
lock (ThisLock)
{
// cache was empty before we got the lock, check again inside the lock
// cache is still empty, so retreive the value here
// store the value in the cache here
}
// return the cached value here
}
A: I saw one pattern recently called Correct State Bag Access Pattern, which seemed to touch on this.
I modified it a bit to be thread-safe.
http://weblogs.asp.net/craigshoemaker/archive/2008/08/28/asp-net-caching-and-performance.aspx
private static object _listLock = new object();
public List List() {
string cacheKey = "customers";
List myList = Cache[cacheKey] as List;
if(myList == null) {
lock (_listLock) {
myList = Cache[cacheKey] as List;
if (myList == null) {
myList = DAL.ListCustomers();
Cache.Insert(cacheKey, mList, null, SiteConfig.CacheDuration, TimeSpan.Zero);
}
}
}
return myList;
}
A: This article from CodeGuru explains various cache locking scenarios as well as some best practices for ASP.NET cache locking:
Synchronizing Cache Access in ASP.NET
A: I've wrote a library that solves that particular issue: Rocks.Caching
Also I've blogged about this problem in details and explained why it's important here.
A: I modified @user378380's code for more flexibility. Instead of returning TResult now returns object for accepting different types in order. Also adding some parameters for flexibility. All the idea belongs to
@user378380.
private static readonly object _lock = new object();
//If getOnly is true, only get existing cache value, not updating it. If cache value is null then set it first as running action method. So could return old value or action result value.
//If getOnly is false, update the old value with action result. If cache value is null then set it first as running action method. So always return action result value.
//With oldValueReturned boolean we can cast returning object(if it is not null) appropriate type on main code.
public static object GetOrAdd<TResult>(this Cache cache, string key, Func<TResult> action,
DateTime absoluteExpireTime, TimeSpan slidingExpireTime, bool getOnly, out bool oldValueReturned)
{
object result;
var data = cache[key];
if (data == null)
{
lock (_lock)
{
data = cache[key];
if (data == null)
{
oldValueReturned = false;
result = action();
if (result == null)
{
return result;
}
cache.Insert(key, result, null, absoluteExpireTime, slidingExpireTime);
}
else
{
if (getOnly)
{
oldValueReturned = true;
result = data;
}
else
{
oldValueReturned = false;
result = action();
if (result == null)
{
return result;
}
cache.Insert(key, result, null, absoluteExpireTime, slidingExpireTime);
}
}
}
}
else
{
if(getOnly)
{
oldValueReturned = true;
result = data;
}
else
{
oldValueReturned = false;
result = action();
if (result == null)
{
return result;
}
cache.Insert(key, result, null, absoluteExpireTime, slidingExpireTime);
}
}
return result;
}
A: The accepted answer (recommending reading outside of the lock) is very bad advice and is being implemented since 2008. It could work if the cache uses a concurrent dictionary, but that itself has a lock for reads.
Reading outside of the lock means that other threads could be modifying the cache in the middle of read. This means that the read could be inconsistent.
For example, depending on the implementation of the cache (probably a dictionary whose internals are unknown), the item could be checked and found in the cache, at a certain index in the underlying array of the cache, then another thread could modify the cache so that the items from the underlying array are no longer in the same order, and then the actual read from the cache could be from a different index / address.
Another scenario is that the read could be from an index that is now outside of the underlying array (because items were removed), so you can get exceptions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "81"
} |
Q: Linking statically in C# I'm working on a module for a CMS. This module is distributed as a class library DLL.
I have several utility libraries I'd like to use in this module. Is there anyway I can link these libraries statically so I won't have to distribute several DLL's (thereby distributing my utility libraries separately)?
I would like to have only one DLL.
A: The short answer for this is no!
You can not link in a dll during compilation.
I don't know if there is some subtle way to do this, but you would probably have to distribute the dlls along with your cms.
The best way to do this is to make some kind of re-distributable.
A: You can merge your many DLLs with ILMERGE:
http://research.microsoft.com/~mbarnett/ILMerge.aspx
Haven't tried it myself. Hope it helps.
Download here:
http://www.microsoft.com/downloads/details.aspx?familyid=22914587-B4AD-4EAE-87CF-B14AE6A939B0&displaylang=en
Brief Description (from download-page)
ILMerge is a utility for merging multiple .NET assemblies into a single .NET assembly. It works on executables and DLLs alike and comes with several options for controlling the processing and format of the output. See the accompanying documentation for details.
A: If you don't want to use ILMerge, see this page:
http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx
editor's note: Jeffrey Richter advices to put your dlls into exe file as resources (For each DLL file you add, display its properties and change its “Build Action” to “Embedded Resource.”). Then a custom class loader is needed to make the executable work (At runtime, the CLR won’t be able to find the dependent DLL assemblies, which is a problem. To fix this, when your application initializes, register a callback method with the AppDomain’s ResolveAssembly event).
Be sure to change the resourceName string to point to your actual resources. (e.g. change AssemblyLoadingAndReflection to your project name.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: How can I control checkboxes in a .Net Forms.TreeView? I have a .Net desktop application with a TreeView as one of the UI elements.
I want to be able to multi-select that TreeView, only that isn't supported at all.
So I'm adding check-boxes to the tree, My problem is that only some items are selectable, and those that aren't can't consistently cascade selections.
Is there any way to disable or hide some check-boxes while displaying others?
A: The default behavior of TreeView is that when the Checkboxes property is set to true, that checkboxes will be shown for all TreeNodes.
The behavior that you are looking for - to disable or hide some checkboxes - is a custom modification of the normal behavior. You can create a custom implementation of TreeView or TreeNode that overrides the default behavior. One other thing to try would be to use the TreeView.StateImageList property. Some sites to check out for more info:
*
*See this post to the MSDN forums that goes through an implementation similar to what you are attempting.
*CodeProject: Tri-State TreeView
*CodeProject: How to handle custom node state images in a TreeView (e.g. tristate checkboxes)
A: I had a very similar problem in an editor I wrote recently. In the end, I used the TreeNode's BackColor property to determine the selection state of the node. I then wrote a handler for the SelectionChanged event that checked the state of the Shift/Control keys to determine if the selected node was being added to/removed from the selection or creating a new selection. There was also a Generic::List<> of the nodes that were currently selected to eliminate any tree searches.
A: MultiSelectTreeView:
Why doesn't .NET have a multiselect treeview? There are so many uses for one and turning on checkboxes in the treeview is a pretty lousy alternative.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I begin beta testing? I have a project that I would like to start beta testing soon, it is a PHP/MySQL site for programmers. I have beta tested sites before however it was always in-house, and I have never done betas that could/should be seen by someone other then those associated with the project.
How should I go about starting the beta, and what problems, aside from those the beta is supposed to expose, should I be prepared for?
A: First, accept the fact that problems with your app (code, usability, etc.) will be discovered.
Then, make sure you have a clear way for users to communicate with you (form mail, email, uservoice, etc.). The easier you make this the better. For example, there is a uservoice link on every page of SO.
One philosophy I strongly believe in: if it's confusing to your users, it's broken. Be willing to change your app (no matter how "beautiful" the design may be) if your users are confused or not liking it. This doesn't mean you have to cave on your decisions, just that you need to consider revisions to improve the user experience.
A: Check out Jeff's post on it, I think he has recent experience ;-)
A: Hmm, problems related to the people? Are you referring to usability problems?
Also, if you are doing a beta,it means you already did everything you know (in my opinion). One of the goals of a beta is to show you what you didn't knew, besides unexpected code problems, etc.
A: Beta testing is a part of acceptance testing.
This type of testing will ensure the customer about the functionality and quality of the product.
Beta testing is done on customers end in an uncontrolled environment.
In beta testing customer driven test cases are written and he can enter whatever he wants to enter.
Here developer don't have any control over the testing approach.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can a .net class libraries be protected so it cant be referenced by other applications? How can a .net class library project and resulting dll be protected so it cant be referenced by other applications (.net projects) except those projects in my own solution?
A: I think you can't forbid other applications to reference you library.
You can make library's classes internal and provide access to them via InternalVisibleTo attribute but it won't save you from reflection.
A: Yep, aku is right. In reality if you want certain types & methods to only be accessible to one application, you're better off compiling it all into one exe & marking those types all internal. You can then obfuscate the code to avoid the issue with reflection (see here)
A: Forgive my ignorance, but if they're all class libraries, what does the code do? Isn't the purpose of having a dll so that the code can be referenced.
In any case if you mark everything internal it won't be able to be accessed outside its own library
A: I think what deanbates is saying is that he is trying to find a way to keep a DLL public within his own application and private for everything else
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Can you have virtual users using an SFTP server? I've had a FTP server (Mac OS X, but not the server version) set up for a while where the users are virtual, i.e. they are not actual user accounts in the server's OS, but accounts handled by the FTP server software -- to the OS they all look like the ftp user account. I'd like to retire the FTP server software and go SFTP instead.
Is there a way to set up SFTP/SSH so that I can create virtual users and at the same time sandbox them?
The reason I want virtual users is because I add and remove accounts from time to time, and doing that with proper user accounts tend to get messy, and I don't know of a good way to sandbox them. There's always some files left and each user has their own user directory (with a lot of files only relevant if they would actually log on to the machine when sitting in front of it), which is quarantined when the account is removed, so you have to remove it by hand yourself, and so on.
A: The usual generic Unix answer to this is 'PAM'. If you want plain old OpenSSH SSHD to handle your SFTP, you need something plugged in to SSHD's PAM stack (/etc/pam.d/sshd) that does what you need and leaves out what you don't need. This might be a general-purpose directory server (probably LDAP) that maps all your virtual users to one home directory and gives them a restricted or scponly kind of shell.
If you want to look at FTP servers that can also do FTP-ssl (which is not the same as SFTP), good ftp servers like Pure-ftpd or vsftp will do that. FTP-ssl servers have simpler virtual user support.
http://www.bsdguides.org/guides/freebsd/networking/pure-ftpd_virtual_users.php
A: If you're open to commercial products, VShell Server from Van Dyke Software is available on Unix/Linux/Windows, supports virtual users (multiple backends) with SSH and SFTP protocols:
VShell Server
A: JSCAPE SFTP Server is a commercial, cross-platform server that does what you want.
http://www.jscape.com/
I know, sounds like I work for them, but I don't :)
A: There is sftpgo which supports virtual users and much more.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Do you version "derived" files? Using online interfaces to a version control system is a nice way to have a published location for the most recent versions of code. For example, I have a LaTeX package here (which is released to CTAN whenever changes are verified to actually work):
http://github.com/wspr/pstool/tree/master
The package itself is derived from a single file (in this case, pstool.tex) which, when processed, produces the documentation, the readme, the installer file, and the actual files that make up the package as it is used by LaTeX.
In order to make it easy for users who want to download this stuff, I include all of the derived files mentioned above in the repository itself as well as the master file pstool.tex. This means that I'll have double the number of changes every time I commit because the package file pstool.sty is a generated subset of the master file.
Is this a perversion of version control?
@Jon Limjap raised a good point:
Is there another way for you to publish your generated files elsewhere for download, instead of relying on your version control to be your download server?
That's really the crux of the matter in this case. Yes, released versions of the package can be obtained from elsewhere. So it does really make more sense to only version the non-generated files.
On the other hand, @Madir's comment that:
the convenience, which is real and repeated, outweighs cost, which is borne behind the scenes
is also rather pertinent in that if a user finds a bug and I fix it immediately, they can then head over to the repository and grab the file that's necessary for them to continue working without having to run any "installation" steps.
And this, I think, is the more important use case for my particular set of projects.
A: We don't version files that can be automatically generated using scripts included in the repository itself. The reason for this is that after a checkout, these files can be rebuild with a single click or command. In our projects we always try to make this as easy as possible, and thus preventing the need for versioning these files.
One scenario I can imagine where this could be useful if 'tagging' specific releases of a product, for use in a production environment (or any non-development environment) where tools required for generating the output might not be available.
We also use targets in our build scripts that can create and upload archives with a released version of our products. This can be uploaded to a production server, or a HTTP server for downloading by users of your products.
A: I am using Tortoise SVN for small system ASP.NET development. Most code is interpreted ASPX, but there are around a dozen binary DLLs generated by a manual compile step. Whilst it doesn't make a lot of sense to have these source-code versioned in theory, it certainly makes it convenient to ensure they are correctly mirrored from the development environment onto the production system (one click). Also - in case of disaster - the rollback to the previous step is again one click in SVN.
So I bit the bullet and included them in the SVN archive - the convenience, which is real and repeated, outweighs cost, which is borne behind the scenes.
A: Not necessarily, although best practices for source control advise that you do not include generated files, for obvious reasons.
Is there another way for you to publish your generated files elsewhere for download, instead of relying on your version control to be your download server?
A: Normally, derived files should not be stored in version control. In your case, you could build a release procedure that created a tarball that includes the derived files.
As you say, keeping the derived files in version control only increases the amount of noise you have to deal with.
A: In some cases we do, but it's more of a sysadmin type of use case, where the generated files (say, DNS zone files built from a script) have intrinsic interest in their own right, and the revision control is more linear audit trail than branching-and-tagging source control.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I install a color theme for IntelliJ IDEA 7.0.x I prefer dark backgrounds for coding, and I've downloaded a jar file containing an IntelliJ IDEA color theme that has a dark background. How do I tell IntelliJ about it?
A: If you just have the xml file of the color scheme you can:
Go to Preferences -> Editor -> Color and Fonts and use the Import button.
A: Themes downloaded from IntelliJ can be installed as a Plugin.
Follow these steps:
Preferences -> Plugins -> GearIcon -> Install Plugin from disk -> Reset your IDE -> Preferences -> Appearance -> Theme -> Select your theme.
A: Step 1: Do File -> Import Settings... and select the settings jar file
Step 2: Go to Settings -> Editor -> Colors and Fonts to choose the theme you just installed.
A: Interesting I never spent too much time adjusting the colours in IntelliJ although tried once.
See link below with an already defined colour scheme you can import.
Where can I download IntelliJ IDEA 10 Color Schemes?
http://devnet.jetbrains.net/docs/DOC-1154
Download the jar file, file import the jar where you will see a what to import ;)
A: Like nearly everyone else said, go to file -> Import Settings.
But if you don't see the "Import Settings" option under the file menu, you need to disable 2 plugins : IDE Settings Sync and Settings Repository
A: Take a look here: Third Party Add-ons
You may have to extract the jar using a zip application. Hopefully inside you'll find a collection of XML files.
IntelliJ IDEA Plugins
A: Go to File->Import Settings... and select the jar settings file
Update as of IntelliJ 2020:
Go to File -> Manage IDE Settings -> Import Settings...
A: Go to Settings => Plugins => Search Plugins in Marketplace
Search by material theme and download and restart it. it is a good theme.
In the market place, you can also search by theme and it will list all the themes and you can download any themes. You no need to find themes and download and import it. You can also remove the theme very easily. thanks
A: Find the .jar theme file in your disk. Drag the file into PhpStorm window and voila !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "76"
} |
Q: Do I need a Mac to make a Java application bundle? I want to create a Java application bundle for Mac without using Mac.
According to Java Deployment Options for Mac OS X, I can do this by using Xcode, Jar Bundler, or from the command line. Once the files and folders are set up, all I need for the command line method is to call /Developer/Tools/SetFile. Is there a SetFile clone on Linux or Windows? If not, do I have to get a Mac?
A: A Java application bundle on OS X is nothing more than a directory containing your .jars and a number of configuration files. The SetFile tool sets a custom HFS filesystem property on the directory to tell finder that it is an app, but giving it a ".app" extension serves the same purpose. I don't think there's anything stopping you from building one on, say, Windows, though of course you have no way of testing that it works, but if you are able to test it at least once on a real Mac, you could then conceivably update the .jars within it on Windows to reflect code changes without too much difficulty.
Have a look at the Bundle Programming Guide for more info.
A: One way is to generate a zip file with the App using for example Ant. In ant you can specify that the file in Contents/MacOS should have execute-permissions using something like filemode="755".
A: Having worked on the Mac port of NITE, I can say that jar packages for other platforms should work equally well on Mac. I would still recommend finding a mac for testing (or even announcing mac support was in beta) as we discovered a few mac-only quirks during the port (to go with the windows- and linux- only quirks we'd already discovered)
A: Technically, you don't need a Mac. Applications in OS X just require a specific folder structure and an XML file. However, the Mac has a really nice tool called Jar Bundler. In addition to setting up the bundle directories and XML file, it creates a C executable that launches your java application via JNI. This is nice because the process name matches the application name.
I believe that you could have someone generate an application bundle for you once, and then check in the files to your project. At build time, all you would need to do is copy your jar files to the appropriate locations and maybe update the XML file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: group_concat query performance A MySQL query is running significantly slower since adding a group_concat clause. Currently, this query looks as follows:
select ... group_concat(distinct category.name) .... from page where
left outer join page_category on page.id = page_category.page_id
left outer join category on page_category.category_id = category.id
....
group by page.id
As mentioned in the query, among others, my application has 3 tables: page, category, and page_category. A page can be associated with none or multiple categories. Currently page, page_category, and category have 9,460, 20,241 and 10 entries, respectively.
Can anyone help me to improve this query to improve its performance?
A: I was missing an index in the page_category.page_id field. That solve the problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Portably handle exceptional errors in C++ I'm working on porting a Visual C++ application to GCC (should build on MingW and Linux).
The existing code uses __try { ... } __except(1) { ... } blocks in a few places so that almost nothing (short of maybe out of memory type errors?) would make the program exit without doing some minimal logging.
What are the options for doing something similar with GCC?
Edit: Thanks for the pointer to /EH options in Visual Studio, what I need now is some examples on how to handle signals on Linux. I've found this message from 2002.
What other signals besides SIGFPE and SIGSEVG should I watch out for? (Mostly care about ones that might be raised from me doing something wrong)
Bounty Information:
I want my application to be able to self-log as many error conditions as possible before it exits.
What signals might I get and which would generally be impossible to log an error message after? (Out of memory, what else?)
How can I handle exceptions and (most importantly) signals in a portable way that the code at least works the same on Linux and MingW. #ifdef is OK.
The reason I don't just have a wrapper process that logs the failure is that for performance reasons I save writing some data to disk till the last minute, so if something goes wrong I want to make all possible attempts to write the data out before exiting.
A: try { xxx } catch(...) { xxx } would be more portable but might not catch as much. It depends on compiler settings and environments.
Using the default VC++ settings, asynchronous (SEH) errors are not delivered to the C++ EH infrastructure; to catch them you need to use SEH handlers (__try/__except) instead. VC++ allows you to route SEH errors through C++ error-handling, which allows a catch(...) to trap SEH errors; this includes memory errors such as null pointer dereferences. Details.
On Linux, however, many of the errors that Windows uses SEH for are indicated through signals. These are not ever caught by try/catch; to handle them you need a signal handler.
A: Why not use the C++ standard exceptions instead of MSFT's proprietary extension? C++ has an exception handling concept.
struct my_exception_type : public logic_error {
my_exception_type(char const* msg) : logic_error(msg) { }
};
try {
throw my_exception_type("An error occurred");
} catch (my_exception_type& ex) {
cerr << ex.what << endl;
}
C++ also has a “catchall” clause so if you want to log exceptions you can use the following wrapper:
try {
// …
}
catch (...) {
}
However, this is not very efficient in C++ because creating such a general wrapper means that handling code has to be inserted in every subsequent stack frame by the compiler (unlike in managed systems like .NET where exception handling comes at no additional cost as long as no exception is actually thrown).
A: For portability, one thing to try is using try-catch blocks for most vanilla exceptions and then set a terminate handler (set_terminate_handler) to have a minimal hook available for catastrophic exit conditions. You can also try adding something like an atexit or on_exit handler. Your execution environment may be bizarre or corrupt when you enter these functions, of course, so be careful of how much you presume a sane environment.
Finally, when using regular try-catch pairs you can consider using function try blocks as opposed to opening a try block in the body of a function:
int foo(int x) try {
// body of foo
} catch (...) {
// be careful what's done here!
}
they're a relatively unknown chunk of C++ and may in some cases offer recovery even in the event of partial (small scale) stack corruption.
Finally, yes, you'll probably want to investigate which signals you can continuably handle on your own or on which you might abort, and if you want less handling mechanisms in place, you might consider call the none-throwing version of the new operator, and compiling to not generate floating point exceptions if needed (you can always check isnan(.), isfinite(.), on FP results to protect yourself).
On that last note, be careful: I've notice that the floating point result classification functions can be in different headers under linux and windows... so you may have to conditionalize those includes.
If you're feeling puckish, write it all using setjmp and longjmp (that's a joke...).
A: Catching C++ exceptions with catch(...) already puts you in a twilight zone.
Trying to catch errors not caught by catch(...) puts you squarely inside undefined behaviour. No C++ code is guaranteed to work. Your minimal logging code may cause the missile to launch instead.
My recommendation is to not even try to catch(...). Only catch exceptions that you can meaningfully and safely log and let the OS handle the rest, if any.
Postmortem debugging gets ugly if you have error handling code failures on top of the root cause.
A: One way that is easy to use, portable, and barely use any resources would be to catch empty classes. I know this may sound odd at first, but it can be very useful.
Here is an example I made for another question that applies for your question too: link
Also, you can have more than 1 catch:
try
{
/* code that may throw exceptions */
}
catch (Error1 e1)
{
/* code if Error1 is thrown */
}
catch (Error2 e2)
{
/* code if Error2 is thrown */
}
catch (...)
{
/* any exception that was not expected will be caught here */
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Can I use other IDEs other than Visual Studio for coding in .net? What are the options? How popular are they? Do these IDEs give similar/better functionality compared to visual studio?
A: Yes - you can try using SharpDevelop:
http://www.icsharpcode.net/OpenSource/SD/
Or you can just use notepad, or notepad++
http://notepad-plus.sourceforge.net/
Then compile on the command line.
Edit: If you're looking for a free solution - try Visual Studio C# Express Edition:
http://www.microsoft.com/express/vcsharp/
A: The vast majority of .net developers use Visual Studio, but there are a couple of alternatives.
Visual Studio Express Editions are free and give you a cut down version of Visual Studio which you can use with a single language, i.e. VB or C# or C++.
SharpDevelop is probably the best free alternative to Visual Studio. It's open source and has features like a form designer. It supports the full range of .net languages (including IronPython, F# and Boo). It also has features not found in Visual Studio, like the ability to translate between C# and VB.net. You can even mix different languages in the same project.
MonoDevelop is also free and open source. - Now runs on Linux, Mac OS/X and Windows.
The .net compilers are all free and included with the SDK. This means you can always use any text editor and compile from the command line. This would be pretty painful to do with anything other than a really simple program!
A: MonoDevelop
A: Check out the mono project. http://www.mono-project.com/
It's the '.NET for linux' project.
They also have an ide based on eclipse as part of the whole thing. Never used it before but I've used eclipse for java and some php work, and eclipse is pretty good
Edit: the ide is called MonoDevelop. Seen at http://www.monodevelop.com/
A: You do
SharpDevelop - It doesn't really stand up to Visual Studio. Thou I found it to be useful at times since it has support for Visual Basic. And at times I could load solutions for projects that were not installed on my VS. But the really USEFUL features that I found were : Conversion between C# <-> VB Code, PInvoke, and Regex Expressions. Oh and lets not forget support for Boo :D.
there is also Borland C# Builder AFAIK. Only saw a tutorial long ago written by someone who has used it.
MonoDevelop - link text This is based on SharpDevelop 0.9 if I remember it correctly. I have to say I only used it once to see if I can work with threads in Linux just like in Windows.
That's about all I remember, I'm pretty sure there are at least one more IDE but I don't remember it now :). Also they don't really match up to VS + Resharper :) or + CodeRush.
Plus you have Visual Studio Express so unless you have to work on Linux or have some projects that you think you could try opening in #D there isn't much out there. MonoDevelop is starting to come along try keeping an eye out for it.
I found this refrences also X-Code
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Directory picker for Visual Basic macro in MS Outlook 2007 I wrote a Visual Basic macro for archiving attachments for Outlook 2007, but did not find a totally satisfactory way for showing a directory picker from the Outlook macro. Now, I don't know much about either Windows APIs or VB(A) programming, but the "standard" Windows file dialog I see most often in Microsoft applications would seem like an obvious choice, but it does not seem to be easily available from Outlook's macros.
Ideally, the directory picker should at least allow to manually paste a file path/URI as a starting point for navigation, since I sometimes already have an Explorer window open for the same directory.
What are the best choices for directory pickers in Outlook macros?
Two things I already tried and did not find totally satisfactory are (the code is simplified and w/o error handling and probably also runs in older Outlook versions):
1) Using Shell.Application which does not allow me to actually paste a starting point via the clipboard or do other operations like renaming folders:
Set objShell = CreateObject("Shell.Application")
sMsg = "Select a Folder"
cBits = 1
xRoot = 17
Set objBFF = objShell.BrowseForFolder(0, sMsg, cBits, xRoot)
path = objBFF.self.Path
2) Using the Office.FileDialog from Microsoft Word 12.0 Object Library (via tools/references) and then using Word's file dialog, which somehow takes forever on my Vista system to appear and does not always actually bring Word to the foreground. Instead, sometimes Outlook is blocked and the file dialog is left lingering somewhere in the background:
Dim objWord As Word.Application
Dim dlg As Office.FileDialog
Set objWord = GetObject(, "Word.Application")
If objWord Is Nothing Then
Set objWord = CreateObject("Word.Application")
End If
objWord.Activate
Set dlg = objWord.FileDialog(msoFileDialogFolderPicker)
path = dlg.SelectedItems(1)
Any other ideas?
A: Your best bet will probably be to use the Windows32 API for this. See this MSDN article for sample VBA code on how to interact with the API.
The article outlines a few different techniques, but I'd suggest searching the article for "COMDLG32.dll" and following the steps outlined in that section.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: "Similar Posts" like functionality using MS SQL Server? I have lots of article store in MS SQL server 2005 database in a table called Articles-
"Articles (ArticleID, ArticleTitle, ArticleContent)"
Now I want some SP or SQL query which could return me similar Article against any user's input (very much like "Similar Posts" in blogs OR "Related Questions" in stackoverflow). The matching should work on both ArticleTitle and ArticleContent. The query should be intelligent enough to sort the result on the basis on their relevancy.
Is it possible to do this in MS SQL Server 2005?
A: Something like this might work, a kind of ranking system. You would probably have to split the string in your application to build a SQL string, but I have used similar to build an effective site search.
Select
Top 10
ArticleID,
ArticleTitle,
ArticleContent
From
Articles
Order By
(Case When ArticleTitle = 'Article Title' Then 1 Else 0 End) Desc,
(Case When ArticleTitle = 'Article' Then 1 Else 0 End) Desc,
(Case When ArticleTitle = 'Title' Then 1 Else 0 End) Desc,
(Case When Soundex('Article Title') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc,
(Case When Soundex('Article') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc,
(Case When Soundex('Title') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc,
(Case When PatIndex('%Article%Title%', ArticleTitle) > 0 Then 1 Else 0 End) Desc,
(Case When PatIndex('%Article%', ArticleTitle) > 0 Then 1 Else 0 End) Desc,
(Case When PatIndex('%Title%', ArticleTitle) > 0 Then 1 Else 0 End) Desc,
(Case When PatIndex('%Article%Title%', ArticleContent) > 0 Then 1 Else 0 End) Desc,
(Case When PatIndex('%Article%', ArticleContent) > 0 Then 1 Else 0 End) Desc,
(Case When PatIndex('%Title%', ArticleContent) > 0 Then 1 Else 0 End) Desc
You can then add/remove case statements from the order by clause to improve the list based on your data.
A: First of all you need to define what article similarity means.
For example you can associate some meta information with articles, like tags.
To be able to find similar articles you need to extract some features from them, for example you can build full text index.
You can take advantage of full text search capability of MSSQL 2005
-- Assuming @Title contains title of current articles you can find related articles runnig this query
SELECT * FROM Acticles WHERE CONTAINS(ArticleTitle, @Title)
A: I think the question is what 'similar' means to you. If you create a field for user to input some kind of tags, it becomes much more easier to query.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Query to identify the number of revisions made to a table Is there any query which can return me the number of revisions made to the structure of a database table?
Secondly, how can I determine the number of pages (in terms of size) present in mdf or ldf files?
A: I think you need to create a trigger and store all changes to the table in a separate table. You can then use this table to get the revision history.
A: You can get last modify date or creation date of object in SQL Server.
For examle info on tables:
SELECT * FROM sys.objects WHERE type='U'
More info on msdn
Number of pages can be fetched from sys.database_files.
Check documentation
A: SQL Server doesn't keep track of changes so it can't tell you this.
The only way you may be able to do this is if you had a copy of all the scripts applied to the database.
In order to be able to capture this information in the future you should look at DDL triggers (v2005+) which will enable you to record changes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's the difference between DOCUMENT_URI and URI_REQUEST in SSI? When looking at a SSI printenv dump I see a variable URI_REQUEST.
When reading the Apache mod_include docs I see DOCUMENT_URI which they define as "The (%-decoded) URL path of the document requested by the user."
Anyone know the difference between the two?
TIA.
A: REQUEST_URI includes the Query String (?q=testing...) where DOCUMENT_URI does not.
A: ok. seems like it is exactly the opposite according to Apache docs and RFC 2616.
REQUEST_URI does not contain the query string.
DOCUMENT_URI does contain the query string.
cheers,
Rob
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: .NET Scanning API Is there any free or commercial component written in .NET (no COM interop) that will work with most twain scanners?
A: Microsoft have an API all about scanning. It's called Windows Image Acquisition and you can read a great Coding4Fun article about it by none other than Scott Hanselman here.
A: Take a look at CodeProject: .NET TWAIN image scanning That might give you a good start.
A: +1 for Atalasoft
Technical quibble: You can avoid COM, but you can't avoid Interop: TWAIN is a native Win32 or Win64 DLL that is not part of Windows proper and is unknown to the CLR, so at the bottom, either in your code or the component you use, there are Interop calls to unmanaged code. Given what I know about TWAIN drivers, maybe I should say to very unmanaged code...
I've always had the impression that WIA was great for digital cameras, OK for consumer flatbeds, and not a serious contender for 'production scanning' - meaning something like full-speed multipage scans from a document feeder, under application control, using a USD400+ scanner. I've never heard of anybody doing production scanning through WIA, but I'd sure like to hear from somebody who's done this.
A: I found NTwain via Nuget, which satisfied me.
A: Disclaimer: I work for Atalasoft
Atalasoft has a product, DotTwain, which has no COM interop (just direct calls to the twain dll from .NET) and gives you a completely .NET interface. It can be embedded in a browser hosted WinForms control, for instance, because it doesn't use COM.
A: The Accusoft Pegasus .NET component is called TwainPRO, and it's included in the ImagXpress SDK.
The ImageGear .NET toolkit from Accusoft Pegasus also includes a full-managed implementation of Twain.
A:
TwainDotNet
I've just wrapped up the code from Thomas Scheidegger's article (CodeProject: .NET TWAIN image scanning) into a Google code project: http://code.google.com/p/twaindotnet/
I've cleaned up the API a bit and added WPF support, so check it out. :)
A: In my company we use Pegasus. It's great.
A: Just started a project in .net and found great info here (*dead link as of Feb 2014) about using Windows Image Acquisition. Lots of sample VB code and some c#.
A: I just saw another Scanning question that referenced a 3rd party commercial product to add to the list: ImageMan
Looks like a single developer license starts at $325. I haven't used it personally, but is one of three or four products I'm evaluating.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
} |
Q: Database Design for Revisions? We have a requirement in project to store all the revisions(Change History) for the entities in the database. Currently we have 2 designed proposals for this:
e.g. for "Employee" Entity
Design 1:
-- Holds Employee Entity
"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"
-- Holds the Employee Revisions in Xml. The RevisionXML will contain
-- all data of that particular EmployeeId
"EmployeeHistories (EmployeeId, DateModified, RevisionXML)"
Design 2:
-- Holds Employee Entity
"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"
-- In this approach we have basically duplicated all the fields on Employees
-- in the EmployeeHistories and storing the revision data.
"EmployeeHistories (EmployeeId, RevisionId, DateModified, FirstName,
LastName, DepartmentId, .., ..)"
Is there any other way of doing this thing?
The problem with the "Design 1" is that we have to parse XML each time when you need to access data. This will slow the process and also add some limitations like we cannot add joins on the revisions data fields.
And the problem with the "Design 2" is that we have to duplicate each and every field on all entities (We have around 70-80 entities for which we want to maintain revisions).
A: Ramesh, I was involved in development of system based on first approach.
It turned out that storing revisions as XML is leading to a huge database growth and significantly slowing things down.
My approach would be to have one table per entity:
Employee (Id, Name, ... , IsActive)
where IsActive is a sign of the latest version
If you want to associate some additional info with revisions you can create separate table
containing that info and link it with entity tables using PK\FK relation.
This way you can store all version of employees in one table.
Pros of this approach:
*
*Simple data base structure
*No conflicts since table becomes append-only
*You can rollback to previous version by simply changing IsActive flag
*No need for joins to get object history
Note that you should allow primary key to be non unique.
A: The way that I've seen this done in the past is have
Employees (EmployeeId, DateModified, < Employee Fields > , boolean isCurrent );
You never "update" on this table (except to change the valid of isCurrent), just insert new rows. For any given EmployeeId, only 1 row can have isCurrent == 1.
The complexity of maintaining this can be hidden by views and "instead of" triggers (in oracle, I presume similar things other RDBMS), you can even go to materialized views if the tables are too big and can't be handled by indexes).
This method is ok, but you can end up with some complex queries.
Personally, I'm pretty fond of your Design 2 way of doing it, which is how I've done it in the past as well. Its simple to understand, simple to implement and simple to maintain.
It also creates very little overhead for the database and application, especially when performing read queries, which is likely what you'll be doing 99% of the time.
It would also be quite easy to automatic the creation of the history tables and triggers to maintain (assuming it would be done via triggers).
A: I think the key question to ask here is 'Who / What is going to be using the history'?
If it's going to be mostly for reporting / human readable history, we've implemented this scheme in the past...
Create a table called 'AuditTrail' or something that has the following fields...
[ID] [int] IDENTITY(1,1) NOT NULL,
[UserID] [int] NULL,
[EventDate] [datetime] NOT NULL,
[TableName] [varchar](50) NOT NULL,
[RecordID] [varchar](20) NOT NULL,
[FieldName] [varchar](50) NULL,
[OldValue] [varchar](5000) NULL,
[NewValue] [varchar](5000) NULL
You can then add a 'LastUpdatedByUserID' column to all of your tables which should be set every time you do an update / insert on the table.
You can then add a trigger to every table to catch any insert / update that happens and creates an entry in this table for each field that's changed. Because the table is also being supplied with the 'LastUpdateByUserID' for each update / insert, you can access this value in the trigger and use it when adding to the audit table.
We use the RecordID field to store the value of the key field of the table being updated. If it's a combined key, we just do a string concatenation with a '~' between the fields.
I'm sure this system may have drawbacks - for heavily updated databases the performance may be hit, but for my web-app, we get many more reads than writes and it seems to be performing pretty well. We even wrote a little VB.NET utility to automatically write the triggers based on the table definitions.
Just a thought!
A: *
*Do not put it all in one table with an IsCurrent discriminator attribute. This just causes problems down the line, requires surrogate keys and all sorts of other problems.
*Design 2 does have problems with schema changes. If you change the Employees table you have to change the EmployeeHistories table and all the related sprocs that go with it. Potentially doubles you schema change effort.
*Design 1 works well and if done properly does not cost much in terms of a performance hit. You could use an xml schema and even indexes to get over possible performance problems. Your comment about parsing the xml is valid but you could easily create a view using xquery - which you can include in queries and join to. Something like this...
CREATE VIEW EmployeeHistory
AS
, FirstName, , DepartmentId
SELECT EmployeeId, RevisionXML.value('(/employee/FirstName)[1]', 'varchar(50)') AS FirstName,
RevisionXML.value('(/employee/LastName)[1]', 'varchar(100)') AS LastName,
RevisionXML.value('(/employee/DepartmentId)[1]', 'integer') AS DepartmentId,
FROM EmployeeHistories
A: Revisions of data is an aspect of the 'valid-time' concept of a Temporal Database. Much research has gone into this, and many patterns and guidelines have emerged. I wrote a lengthy reply with a bunch of references to this question for those interested.
A: I'm going to share with you my design and it's different from your both designs in that it requires one table per each entity type. I found the best way to describe any database design is through ERD, here's mine:
In this example we have an entity named employee. user table holds your users' records and entity and entity_revision are two tables which hold revision history for all the entity types that you will have in your system. Here's how this design works:
The two fields of entity_id and revision_id
Each entity in your system will have a unique entity id of its own. Your entity might go through revisions but its entity_id will remain the same. You need to keep this entity id in you employee table (as a foreign key). You should also store the type of your entity in the entity table (e.g. 'employee'). Now as for the revision_id, as its name shows, it keep track of your entity revisions. The best way I found for this is to use the employee_id as your revision_id. This means you will have duplicate revision ids for different types of entities but this is no treat to me (I'm not sure about your case). The only important note to make is that the combination of entity_id and revision_id should be unique.
There's also a state field within entity_revision table which indicated the state of revision. It can have one of the three states: latest, obsolete or deleted (not relying on the date of revisions helps you a great deal to boost your queries).
One last note on revision_id, I didn't create a foreign key connecting employee_id to revision_id because we don't want to alter entity_revision table for each entity type that we might add in future.
INSERTION
For each employee that you want to insert into database, you will also add a record to entity and entity_revision. These last two records will help you keep track of by whom and when a record has been inserted into database.
UPDATE
Each update for an existing employee record will be implemented as two inserts, one in employee table and one in entity_revision. The second one will help you to know by whom and when the record has been updated.
DELETION
For deleting an employee, a record is inserted into entity_revision stating the deletion and done.
As you can see in this design no data is ever altered or removed from database and more importantly each entity type requires only one table. Personally I find this design really flexible and easy to work with. But I'm not sure about you as your needs might be different.
[UPDATE]
Having supported partitions in the new MySQL versions, I believe my design also comes with one of the best performances too. One can partition entity table using type field while partition entity_revision using its state field. This will boost the SELECT queries by far while keep the design simple and clean.
A: If you want to do the first one you might want to use XML for the Employees table too. Most newer databases allow you to query into XML fields so this is not always a problem. And it might be simpler to have one way to access employee data regardless if it's the latest version or an earlier version.
I would try the second approach though. You could simplify this by having just one Employees table with a DateModified field. The EmployeeId + DateModified would be the primary key and you can store a new revision by just adding a row. This way archiving older versions and restoring versions from archive is easier too.
Another way to do this could be the datavault model by Dan Linstedt. I did a project for the Dutch statistics bureau that used this model and it works quite well. But I don't think it's directly useful for day to day database use. You might get some ideas from reading his papers though.
A: If indeed an audit trail is all you need, I'd lean toward the audit table solution (complete with denormalized copies of the important column on other tables, e.g., UserName). Keep in mind, though, that bitter experience indicates that a single audit table will be a huge bottleneck down the road; it's probably worth the effort to create individual audit tables for all your audited tables.
If you need to track the actual historical (and/or future) versions, then the standard solution is to track the same entity with multiple rows using some combination of start, end, and duration values. You can use a view to make accessing current values convenient. If this is the approach you take, you can run into problems if your versioned data references mutable but unversioned data.
A: The History Tables article in the Database Programmer blog might be useful - covers some of the points raised here and discusses the storage of deltas.
Edit
In the History Tables essay, the author (Kenneth Downs), recommends maintaining a history table of at least seven columns:
*
*Timestamp of the change,
*User that made the change,
*A token to identify the record that was changed (where the history is maintained separately from the current state),
*Whether the change was an insert, update, or delete,
*The old value,
*The new value,
*The delta (for changes to numerical values).
Columns which never change, or whose history is not required, should not be tracked in the history table to avoid bloat. Storing the delta for numerical values can make subsequent queries easier, even though it can be derived from the old and new values.
The history table must be secure, with non-system users prevented from inserting, updating or deleting rows. Only periodic purging should be supported to reduce overall size (and if permitted by the use case).
A: Avoid Design 1; it is not very handy once you will need to for example rollback to old versions of the records - either automatically or "manually" using administrators console.
I don't really see disadvantages of Design 2. I think the second, History table should contain all columns present in the first, Records table. E.g. in mysql you can easily create table with the same structure as another table (create table X like Y). And, when you are about to change structure of the Records table in your live database, you have to use alter table commands anyway - and there is no big effort in running these commands also for your History table.
Notes
*
*Records table contains only lastest revision;
*History table contains all previous revisions of records in Records table;
*History table's primary key is a primary key of the Records table with added RevisionId column;
*Think about additional auxiliary fields like ModifiedBy - the user who created particular revision. You may also want to have a field DeletedBy to track who deleted particular revision.
*Think about what DateModified should mean - either it means where this particular revision was created, or it will mean when this particular revision was replaced by another one. The former requires the field to be in the Records table, and seems to be more intuitive at the first sight; the second solution however seems to be more practical for deleted records (date when this particular revision was deleted). If you go for the first solution, you would probably need a second field DateDeleted (only if you need it of course). Depends on you and what you actually want to record.
Operations in Design 2 are very trivial:
Modify
*
*copy the record from Records table to History table, give it new RevisionId (if it is not already present in Records table), handle DateModified (depends on how you interpret it, see notes above)
*go on with normal update of the record in Records table
Delete
*
*do exactly the same as in the first step of Modify operation. Handle DateModified/DateDeleted accordingly, depending on the interpretation you have chosen.
Undelete (or rollback)
*
*take highest (or some particular?) revision from History table and copy it to the Records table
List revision history for particular record
*
*select from History table and Records table
*think what exactly you expect from this operation; it will probably determine what information you require from DateModified/DateDeleted fields (see notes above)
If you go for Design 2, all SQL commands needed to do that will be very very easy, as well as maintenance! Maybe, it will be much much easier if you use the auxiliary columns (RevisionId, DateModified) also in the Records table - to keep both tables at exactly the same structure (except for unique keys)! This will allow for simple SQL commands, which will be tolerant to any data structure change:
insert into EmployeeHistory select * from Employe where ID = XX
Don't forget to use transactions!
As for the scaling, this solution is very efficient, since you don't transform any data from XML back and forth, just copying whole table rows - very simple queries, using indices - very efficient!
A: How about:
*
*EmployeeID
*DateModified
*
*and/or revision number, depending on how you want to track it
*ModifiedByUSerId
*
*plus any other information you want to track
*Employee fields
You make the primary key (EmployeeId, DateModified), and to get the "current" record(s) you just select MAX(DateModified) for each employeeid. Storing an IsCurrent is a very bad idea, because first of all, it can be calculated, and secondly, it is far too easy for data to get out of sync.
You can also make a view that lists only the latest records, and mostly use that while working in your app. The nice thing about this approach is that you don't have duplicates of data, and you don't have to gather data from two different places (current in Employees, and archived in EmployeesHistory) to get all the history or rollback, etc).
A: If you want to rely on history data (for reporting reasons) you should use structure something like this:
// Holds Employee Entity
"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"
// Holds the Employee revisions in rows.
"EmployeeHistories (HistoryId, EmployeeId, DateModified, OldValue, NewValue, FieldName)"
Or global solution for application:
// Holds Employee Entity
"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"
// Holds all entities revisions in rows.
"EntityChanges (EntityName, EntityId, DateModified, OldValue, NewValue, FieldName)"
You can save your revisions also in XML, then you have only one record for one revision. This will be looks like:
// Holds Employee Entity
"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"
// Holds all entities revisions in rows.
"EntityChanges (EntityName, EntityId, DateModified, XMLChanges)"
A: We have implemented a solution very similar to the solution that Chris Roberts suggests, and that works pretty well for us.
Only difference is that we only store the new value. The old value is after all stored in the previous history row
[ID] [int] IDENTITY(1,1) NOT NULL,
[UserID] [int] NULL,
[EventDate] [datetime] NOT NULL,
[TableName] [varchar](50) NOT NULL,
[RecordID] [varchar](20) NOT NULL,
[FieldName] [varchar](50) NULL,
[NewValue] [varchar](5000) NULL
Lets say you have a table with 20 columns. This way you only have to store the exact column that has changed instead of having to store the entire row.
A: If you have to store history, make a shadow table with the same schema as the table you are tracking and a 'Revision Date' and 'Revision Type' column (e.g. 'delete', 'update'). Write (or generate - see below) a set of triggers to populate the audit table.
It's fairly straightforward to make a tool that will read the system data dictionary for a table and generate a script that creates the shadow table and a set of triggers to populate it.
Don't try to use XML for this, XML storage is a lot less efficient than the native database table storage that this type of trigger uses.
A: We have had similar requirements, and what we found was that often times the user just wants to see what has been changed, not necessarily roll back any changes.
I'm not sure what your use case is, but what we have done was create and Audit table that is automatically updated with changes to an business entity, including the friendly name of any foreign key references and enumerations.
Whenever the user saves their changes we reload the old object, run a comparison, record the changes, and save the entity (all are done in a single database transaction in case there are any problems).
This seems to work very well for our users and saves us the headache of having a completely separate audit table with the same fields as our business entity.
A: It sounds like you want to track changes to specific entities over time, e.g. ID 3, "bob", "123 main street", then another ID 3, "bob" "234 elm st", and so on, in essence being able to puke out a revision history showing every address "bob" has been at.
The best way to do this is to have an "is current" field on each record, and (probably) a timestamp or FK to a date/time table.
Inserts have to then set the "is current" and also unset the "is current" on the previous "is current" record. Queries have to specify the "is current", unless you want all of the history.
There are further tweaks to this if it's a very large table, or a large number of revisions are expected, but this is a fairly standard approach.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "131"
} |
Q: What exactly consists of 'Business Logic' in an application? I have heard umpteen times that we 'should not mix business logic with other code' or statements like that. I think every single code I write (processing steps I mean) consists of logic that is related to the business requirements..
Can anyone tell me what exactly consists of business logic? How can it be distinguished from other code? Is there some simple test to determine what is business logic and what is not?
A: To simplify things to a single line...
Business Logic would be code that doesn't depend on/won't change with a specific UI/implementation detail..
It is a code-representation of the rules, processes, etc. that are defined by/reflect the business being modelled.
A: I think you confusing business logic with your application requirements. It's not the same thing. When someone explains the logic of his/her business it is something like:
"When a user buys an item he has to provide delivery information. The information is validated with x y z rules. After that he will receive an invoice and earn points, that gives x% in discounts for the y offers" (sorry for the bad example)
When you implement this business rules you'll have to think in secondary requirements, like how the information is presented, how it will be stored in a persistent way, the communication with application servers, how the user will receive the invoice and so on. All this requirements are not part of business logic and should be decoupled from it. This way, when the business rules change you will adapt your code with less effort. Thats a fact.
Sometimes the presentation replicates some of the business logic, mostly in validating user input. But it has to be also present in the business logic layer. In other situations, is necessary to move some business logic to the Database, for performance issues. This is discussed by Martin Fowler here.
A: Simply define what you are doing in plain English. When you are saying things businesswise, like "make those suffer", "steal that money", "destroy this portion of earth" you are talking about business layer. To make it clear, things that get you excited go here.
When you are saying "show this here", "do not show that", "make it more beautiful" you are talking about the presentation layer. These are the things that get your designers excited.
When you are saying things like "save this", "get this from database", "update", "delete", etc. you are talking about the data layer. These are the things that tell you what to keep forever at all costs.
A: I dont like the BLL+DAL names of the layers, they are more confusing than clarifying.
Call it DataServices and DataPersistence. This will make it easier.
Services manipulate, persistence tier CRUDs (Create, Read, Update, Delete)
A: It's probably easier to start by saying what isn't business logic. Database or disk access isn't business logic. UI isn't business logic. Network communications aren't business logic.
To me, business logic is the rules that describe how a business operates, not how a software architecture operates. Business logic also has a tendency to change. For example, it may be a business requirement that every customer has a single credit card associated with their account. This requirement may change so that customers can have several credit cards. In theory, this should just be a change to the business logic and other parts of your software will not be affected.
So that's theory. In the real world (as you've found) the business logic tends to spread throughout the software. In the example above, you'll probably need to add another table to your database to hold the extra credit card data. You'll certainly need to change the UI.
The purists say that business logic should always be completely separate and so would even be against having tables named "Customers" or "Accounts" in the database.
Taken to its extreme you'd end up with an incredibly generic, impossible to maintain system.
There's definitely a strong argument in favour of keeping most of your business logic together rather than smearing it throughout the system, but (as with most theories) you need to be pragmatic in the real world.
A: For me, " business logic " makes up all the entities that represent data applicable to the problem domain, as well as the logic that decides on "what do do with the data"..
So it should really consist of "data transport" (not access) and "data manipulation".. Actually data access (stuff hitting the DB) should be in a different layer, as should presentation code.
A: If it contains anything about things like form, button, etc.. it's not a business logic, it's presentation layer. If it contains persistence to file or database, it's DAL. Anything in between is business logic. In reality, anything non-UI sometimes gets called "business logic," but it should be something that concerns the problem domain, not house keeping.
A: Business logic is pure abstraction, it exists independent of the materialization/visualization of the data in front of your user, and independent of the persistence of the underlying data.
For example, in Tax Preparation software, one responsibility of the business logic classes would computation of tax owed. They would not be responsible for displaying reports or saving and retrieving a tax return.
@Lars, "services" implies a certain architecture.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Do C++ logging frameworks sacrifice reusability? In C++, there isn't a de-facto standard logging tool. In my experience, shops roll their own. This creates a bit of a problem, however, when trying to create reusable software components. If everything in your system depends on the logging component, this makes the software less reusable, basically forcing any downstream projects to take your logging framework along with the components they really want.
IOC (dependency injection) doesn't really help with the problem since your components would need to depend on a logging abstraction. Logging components themselves can add dependencies on file I/O, triggering mechanisms, and other possibly unwanted dependencies.
Does adding a dependency to your proprietary logging framework sacrifice the reusability of the component?
A: Yes. But dependency injection will help in this case.
You can create an abstract logging base-class and create implementations for the logging-frameworks you want to use. Your components are just dependent on the abstract base-class. And you inject the implementations along with al their dependencies as needed.
A: Yes, Mendelt is right. We do exactly this in our products. Everything depends on the ILogger abstract interface, but it does not depend on anything else. Typically an executable or a high-level DLL will be the one to construct an actual implemented Logger interface and inject it.
A: If you are looking to build libraries which wont be recompiled, but want to provide a logging interface then perhaps a good way is to allow the user (of the library) to provide a callback.
On initialising logging with your library, they would need to specify the callback, and then the glue-code is up to them to make it play well with whatever they have.
If you can make the signature of the callback look like a standard function they might always have available to them, it provides them an easy default option if they dont actually have a logger.
Additionally the caller might have instanced components from the library multiple times, and for resource contention or threading issues, want to provide a different logger callback for each one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What generic techniques can be applied to optimize SQL queries? What techniques can be applied effectively to improve the performance of SQL queries? Are there any general rules that apply?
A: Learn what's really going on under the hood - you should be able to understand the following concepts in detail:
*
*Indexes (not just what they are but actually how they work).
*Clustered indexes vs heap allocated tables.
*Text and binary lookups and when they can be in-lined.
*Fill factor.
*How records are ghosted for update/delete.
*When page splits happen and why.
*Statistics, and how they effect various query speeds.
*The query planner, and how it works for your specific database (for instance on some systems "select *" is slow, on modern MS-Sql DBs the planner can handle it).
A: The biggest thing you can do is to look for table scans in sql server query analyzer (make sure you turn on "show execution plan"). Otherwise there are a myriad of articles at MSDN and elsewhere that will give good advice.
As an aside, when I started learning to optimize queries I ran sql server query profiler against a trace, looked at the generated SQL, and tried to figure out why that was an improvement. Query profiler is far from optimal, but it's a decent start.
A: There are a couple of things you can look at to optimize your query performance.
*
*Ensure that you just have the minimum of data. Make sure you select only the columns you need. Reduce field sizes to a minimum.
*Consider de-normalising your database to reduce joins
*Avoid loops (i.e. fetch cursors), stick to set operations.
*Implement the query as a stored procedure as this is pre-compiled and will execute faster.
*Make sure that you have the correct indexes set up. If your database is used mostly for searching then consider more indexes.
*Use the execution plan to see how the processing is done. What you want to avoid is a table scan as this is costly.
*Make sure that the Auto Statistics is set to on. SQL needs this to help decide the optimal execution. See Mike Gunderloy's great post for more info. Basics of Statistics in SQL Server 2005
*Make sure your indexes are not fragmented. Reducing SQL Server Index Fragmentation
*Make sure your tables are not fragmented. How to Detect Table Fragmentation in SQL Server 2000 and 2005
A: *
*Use primary keys
*Avoid select *
*Be as specific as you can when building your conditional statements
*De-normalisation can often be more efficient
*Table variables and temporary tables (where available) will often be better than using a large source table
*Partitioned views
*Employ indices and constraints
A: Use a with statment to handle query filtering.
Limit each subquery to the minimum number of rows possible.
then join the subqueries.
WITH
master AS
(
SELECT SSN, FIRST_NAME, LAST_NAME
FROM MASTER_SSN
WHERE STATE = 'PA' AND
GENDER = 'M'
),
taxReturns AS
(
SELECT SSN, RETURN_ID, GROSS_PAY
FROM MASTER_RETURNS
WHERE YEAR < 2003 AND
YEAR > 2000
)
SELECT *
FROM master,
taxReturns
WHERE master.ssn = taxReturns.ssn
A subqueries within a with statement may end up as being the same as inline views,
or automatically generated temp tables. I find in the work I do, retail data, that about 70-80% of the time, there is a performance benefit.
100% of the time, there is a maintenance benefit.
A: I think using SQL query analyzer would be a good start.
A: In Oracle you can look at the explain plan to compare variations on your query
A: Make sure that you have the right indexes on the table. if you frequently use a column as a way to order or limit your dataset an index can make a big difference. I saw in a recent article that select distinct can really slow down a query, especially if you have no index.
A: The obvious optimization for SELECT queries is ensuring you have indexes on columns used for joins or in WHERE clauses.
Since adding indexes can slow down data writes you do need to monitor performance to ensure you don't kill the DB's write performance, but that's where using a good query analysis tool can help you balanace things accordingly.
A: *
*Indexes
*Statistics
*on microsoft stack, Database Engine Tuning Advisor
A: Some other points (Mine are based on SQL server, since each db backend has it's own implementations they may or may not hold true for all databases):
Avoid correlated subqueries in the select part of a statement, they are essentially cursors.
Design your tables to use the correct datatypes to avoid having to apply functions on them to get the data out. It is far harder to do date math when you store your data as varchar for instance.
If you find that you are frequently doing joins that have functions in them, then you need to think about redesigning your tables.
If your WHERE or JOIN conditions include OR statements (which are slower) you may get better speed using a UNION statement.
UNION ALL is faster than UNION if (And only if) the two statments are mutually exclusive and return the same results either way.
NOT EXISTS is usually faster than NOT IN or using a left join with a WHERE clause of ID = null
In an UPDATE query add a WHERE condition to make sure you are not updating values that are already equal. The difference between updating 10,000,000 records and 4 can be quite significant!
Consider pre-calculating some values if you will be querying them frequently or for large reports. A sum of the values in an order only needs to be done when the order is made or adjusted, rather than when you are summarizing the results of 10,000,000 million orders in a report. Pre-calculations should be done in triggers so that they are always up-to-date is the underlying data changes. And it doesn't have to be just numbers either, we havea calculated field that concatenates names that we use in reports.
Be wary of scalar UDFs, they can be slower than putting the code in line.
Temp table tend to be faster for large data set and table variables faster for small ones. In addition you can index temp tables.
Formatting is usually faster in the user interface than in SQL.
Do not return more data than you actually need.
This one seems obvious but you would not believe how often I end up fixing this. Do not join to tables that you are not using to filter the records or actually calling one of the fields in the select part of the statement. Unnecessary joins can be very expensive.
It is an very bad idea to create views that call other views that call other views. You may find you are joining to the same table 6 times when you only need to once and creating 100,000,00 records in an underlying view in order to get the 6 that are in your final result.
In designing a database, think about reporting not just the user interface to enter data. Data is useless if it is not used, so think about how it will be used after it is in the database and how that data will be maintained or audited. That will often change the design. (This is one reason why it is a poor idea to let an ORM design your tables, it is only thinking about one use case for the data.) The most complex queries affecting the most data are in reporting, so designing changes to help reporting can speed up queries (and simplify them) considerably.
Database-specific implementations of features can be faster than using standard SQL (That's one of the ways they sell their product), so get to know your database features and find out which are faster.
And because it can't be said too often, use indexes correctly, not too many or too few. And make your WHERE clauses sargable (Able to use indexes).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Windows Vista Virtual PC-image for Visual Studio-development minimized Which features and services in Vista can you remove with nLite (or tool of choice) to make a Virtual PC-image of Vista as small as possible?
The VPC must work with development in Visual Studio.
A normal install of Vista today is like 12-14 GB, which is silly when I got it to work with Visual Studio at 4 GB. But with Visual Studio it totals around 8 GB which is a bit heavy to move around in multiple copies.
A: You can try and cut stuff out with vLite, but unless you cut out a real lot it's not going to save a ton of drive space. Here's your best bets:
*
*Disable Hibernate and run disk cleanup to remove any hibernation file.
*Disable System restore entirely and use disk cleanup to remove all restore points... this will save an enormous amount of space.
*Disable SuperFetch (since it kills your VM hard drive with it's crazy usage)
*Minimize the size of your pagefile by setting a smaller static size and make sure to assign lots of memory to your VM to compensate.
*Use the disk utilities to shrink your VM drive down as far as possible.
Once you have the base machine configured, I would suggest using VMware workstation and the awesome Linked Clones feature, which will let you create a completely new VM based on the base machine, but only using a portion of the space.
I would not advise running a Vista VM from a USB flash drive, it will be slower than dirt.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Failed to load Zend/Loader.php. Trying to work out why? I have inherited a client site which crashes every 3 or 4 days. It is built using the zend-framework with which I have no knowledge.
The following code:
<?php
// Make sure classes are in the include path.
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes');
// Use autoload so include or require statements are not needed.
require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();
// Run the application.
App_Main::run('production');
Is causing the following error:
[Tue Sep 02 12:58:45 2008] [error] [client 78.***.***.32] PHP Warning: require_once(Zend/Loader.php) [function.require-once]: failed to open stream: No such file or directory in /srv/www/vhosts/example.co.uk/httpdocs/bootstrap.php on line 6
[Tue Sep 02 12:58:45 2008] [error] [client 78.***.***.32] PHP Fatal error: require_once() [function.require]: Failed opening required 'Zend/Loader.php' (include_path='.:.:/usr/share/php5:/usr/share/php5/PEAR') in /srv/www/vhosts/example.co.uk/httpdocs/bootstrap.php on line 6
I don't even know where to begin trying to fix this. My level of knowledge of PHP is intermediate but like I said, I have no experience with Zend. Also, contacting the original developer is not an option.
The interesting thing is that even though the code is run every time a page of the site is hit the error is only happening every now and then.
I believe it must be something to do with the include_path but I am not sure.
A: for a start I think your include path should maybe have a trailing slash. Here is an example of mine :
set_include_path('../library/ZendFramework-1.5.2/library/:../application/classes/:../application/classes/excpetions/:../application/forms/');
You bootstrap file will be included by another file (probably an index.php file). This means that if your include path is relative (as mine is) instead of absolute, then the path at which Loader.php is looked for changes if the file including bootstrap.php changes.
For example, I have two index.php files in my Zend app, one for the front end, and one for the admin area. These index files each need there own bootstrap.php with different relative paths in because they are included by different index files, which means they have to be relative to the original requested index file, not the bootstrap file they are defined within.
This could explain why your problem is intermittent, there could be another file including the bootstrap somewhere that is only used occasionally. I'd search through all the sites files for 'bootstrap.php' and see all the places which are including / requiring this file.
A: The fact that it only happens sporadically makes me think this is less of a programming issue, and more of a sysadmin issue - if it were a defect in the implementation, you'd expect it to fail consistently considering the error is "No such file or directory". Two guesses
*
*There are multiple front-end web servers, and one of them is mis-configured (missing the Zend Framework).
*The PEAR include directory is network mounted, and occasionally vanishes for short periods of time.
It could be a more insidious file system problem, but one would think this would effect more than just one file.
A: I had the same problem, but problem was in permissons to files. I gave chmod for all RWX and now is everything fine.
So maybe someone else will have same problem as me, then this was solution.
Regards
A: It works sometimes so there isn't anything inherently wrong on the PHP end of things (if the path was wrong it would never work... but it does, yes?). So what is causing Loader.php to be periodically inaccessible? I would suspect a permissions problem. Something that is making Loader.php or the directory that it is in inaccessible. Maybe a cron job is setting/reseting permissions? Check that first. See what permissions are when it is working and what they are when it is not.
A: In my case the Zend/Loader.php was not in the PEAR-directory. It should be there, but my webserver was a little raw. But you can insert it in the library/Zend directory as well.
But indeed this does not answer why your problem occurs only sometimes.
A: I had this error as well when I was working with PHPUnit 3.5.5. My main application script loaded the zend framework fine, however the test class ran into errors.
My solution was to add the following to the test class
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes');
require_once 'ThemeWidgets.php';
require_once 'PHPUnit/Framework.php';
require_once '../../library/Zend/Loader/AutoLoader.php';
class ThemeWidgetsTest extends PHPUnit_Framework_TestCase
{
public function setUp() {
Zend_Loader_Autoloader::getInstance();
}
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Developing and Testing a Facebook application Typically I develop my websites on trunk, then merge changes to a testing branch where they are put on a 'beta' website, and then finally they are merged onto a live branch and put onto the live website.
With a Facebook application things are a bit tricky. As you can't view a Facebook application through a normal web browser (it has to go through the Facebook servers) you can't easily give each developer their own version of the website to work with and test.
I have not come across anything about the best way to develop and test a Facebook application while continuing to have a stable live website that users can use. My question is this, what is the best practice for organising the development and testing of a Facebook application?
A: You'll have to add both trunk and test versions as different applications and test them using test accounts. You may also use a single application and switch its target URL between cycles.
A: Testing FB apps is still a rather primitive process.
I generally setup a test application that is a complete copy of the production settings inside the FB development environment that uses an SSH tunnel to point to my development server. You can setup as many applications as you need inside FB - I generally have a development application, a staging app and production. Staging and Production are both on "live" servers rather than an SSH tunnel.
In your application you then use whatever language/framework/server tools are at your disposal to switch the FB configuration based on the server. In Rails, the Facebooker gem actually has built in support for different FB configurations.
Once all of that is done, testing is, unfortunately, still a matter of running the app within FB itself. I use Selenium to automate as much of this as possible.
A: Best way to do this:
Remove 'App Domain' from 'Basic Info'
Set website's 'Site URL' to : "http://localhost/" .
That simple.
(This only apply if you don't have a live system running in parallel to the test env. In that case get yourself another key.)
A: Try updating your hosts file (for windows users @ c:\windows\System32\Drivers\etc\hosts) with an entry that will route all requests from your live domain back to your machine.
So 127.0.0.1 mywebappthatusesfacebook.com.
Then make sure that your app is running at the root of your webserver. @ http://localhost/ Then goto mywebappthatusesfacebook.com in your browser and it should redirect right back to your local machine. Facebook won't know the difference. Hope this helps
A: The way I and my partner did it was we each made our own private Facebook applications, that pointed to our IP address where we worked on it. Since we worked in the same place, we each picked a different port, and had our router forward that port to our local IP address. It was kinda slow to refresh a page, but it worked very nicely.
A: We have it setup much like Toby. A series of config files for each developer, that has the Facebook APP Id info (a different app for each developer), separate pages where the app is hosted, and git ignores the config files. We're LAMP with Code Igniter, and it's similar to Rails in that we can set the environment in 1 file, which points to the config with the Facebook constants.
Branching out into Selenium, using unit tests for model-testing.
A: For local testing we simply use a different app than for the server. In our case the Canvas-URL is set to localhost.local:8000.
You only have to make sure that when you use facebook connect that you type in localhost.local into the address field of the browser and not just localhost.
For testing a canvas or tab app it is faster if you use the 'open iframe in new tab' command of Firefox. This way the session and cookies from Facebook are preserved.
A: Another solution is NGROK
https://ngrok.com/
It opens a public tunnel to your local app
Example on my rails application by simply typing
./ngrok 3000
I get
http://630066fe.ngrok.com -> 127.0.0.1:3000
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "41"
} |
Q: Database exception handling best practices How do you handle database exceptions in your application?
Are you trying to validate data prior passing it to DB or just relying on DB schema validation logic?
Do you try to recover from some kind of DB errors (e.g. timeouts)?
Here are some approaches:
*
*Validate data prior passing it to DB
*Left validation to DB and handle DB exceptions properly
*Validate on both sides
*Validate some obvious constraints in business logic and left complex validation to DB
What approach do you use? Why?
Updates:
I'm glad to see growing discussion.
Let’s try to sum up community answers.
Suggestions:
*
*Validate on both sides
*Check business logic constraints on
client side, let DB do integrity checks from hamishmcn
*Check early to avoid bothering DB from ajmastrean
*Check early to improve user experience from Will
*Keep DB interacting code in place to
simplify development from hamishmcn
*Object-relational mapping (NHibernate, Linq, etc.) can help you to deal with constrains from ajmastrean
*Client side validation is necessary for security reasons from Seb Nilsson
Do you have anything else to say? This is converted to Validation specific question. We are missing the core, i.e. "Database related Error best practices" which ones to handle and Which ones to Bubble up?
A: @aku: DRY is nice, but its not always possible. Validation is one of those places, as you will have three completely different and unrelated places where validation is not only possible but absolutely needed: Within the UI, within the business logic, and within the database.
Think of a web application. You want to reduce trips to the server, so you include javascript validation of client data entry. But you can't trust what the user enters, so you must perform validation within your business logic before touching the database. And the database must have its own validation in order to prevent data corruption.
There's no clean way to unify these three different types of validation within a single component.
There are some attempts being made to unify cross-cutting responsibilities like validation within policy injectors like the P&P group's Policy Injection Application Block combined with their Validation Application Block, but these are still code based. If you have validation that's not in code, you still have to maintain parallel logic separately...
A: There is one killer-reason to validate on both the client-side and on the database-side, and that is security. Especially when you start using AJAX-stuff, hackable URLs and other things that make your site (in this case) more friendly to users and hackers.
Validate on the client to provide a smooth experience to early tell the user to correct their input. Also validate in database, (or in business logic, if this is considered a totally secure gateway to the database) for security for you database.
A: You want to reduce unnecessary trips to the DB, so performing validation within the application is a good practice. Also, it allows you to handle data errors where it is most easy to recover from: up near the UI (whether in the controller or within the UI layer for simpler apps) where the data is entered.
There are some data errors that you can't check for programatically, however. For instance, you can't validate data on the existance of related data without roundtripping to the db. Data errors like these should be validated by the database through the use of relationships, triggers, etc.
Where you deal with errors returned by database calls is an interesting one. You could deal with them at the data layer, the business logic layer, or the UI layer. The best practice in this instance is to let those errors bubble up to the last responsible moment before handling them.
For example, if you have an ASP.NET MVC web application, you have three layers (from bottom to top): Database, controller and UI (model, controller, and view). Any errors thrown by your data layer should be allowed to bubble up into your controller. At this level your application "knows" what the user is attempting to do, and can correctly inform the user about the error, suggesting different ways to handle it. Attempting to recover from these errors within the data layer makes it much harder to know what's going on within the controller. And, of course, placing business logic within the UI is not considered a best practice.
TL;DR: Validate everywhere, handle validation errors at the last responsible moment.
A: I try to validate on both sides. 1 rule I always follow is never trust input from the user. Following this to it's conclusion, I will usually have some front end validation on the form/web page which will not even allow submission with improperly formed data. This is a blunt tool - meaning you can check/parse the value to make sure a date field contains a date. From there, I usually let my business logic check as to whether the data entry makes sense in context with how it was submitted. For example, does the date submitted fall into the expected range? Does the currency value submitted fall into the expected range? Finally, on the server side, Foreign Key constraints and Indexes can catch any errors that slip through, which will bubble up a DB exception as a last resort, which can be handled by the app code. I use this method because it filters out as many errors as possible before the DB call is invoked.
A: An object-relational mapping (ORM) tool, like NHibernate (or better yet, ActiveRecord), can help you avoid a lot of validation by allowing the data model to be built right into your code as a proper C# class. You may avoid trips to the database as well, thanks to great caching and validation models built into the framework.
A: In general, I try to validate data as soon as possible after it has been entered. This is so that I can give helpful messages to the user earlier than after they have clicked "submit" or the equivalent.
By the time that it comes to making the db call I am hopefull that the data I am passing should be fairly good.
I try to keep db calls in the one file (or group of files) that share helper methods make it as easy as possible for the programmer (me or whoever else adds calls) to write to a log details about the exception, and what parameters were passed in etc
A: The sorts of apps that I was writing (I've since moved jobs) were in-house fat-client apps.
I would try to keep the business logic in the client, and do more mechanical validation on the db (ie validation that only related to the procedure's ability to run, as opposed to higher level validation).
In short, validate where you can, and try to keep related types of validation together.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: How do you write code that is easily read by other people who have had no hand in writing any part of it? How do you write code that is easily read by other people and who have had no hand in writing any part of it?
A: The best way to ensure that others can read your code is to make sure that it is clear and concise. Namely,
*
*Use self documenting names for variables, functions, and classes.
*Comment complex algorithms so that the reader doesn't have to spend to long figuring out what it does.
*Ensure that tabbing and line breaks are constant throughout the code.
Beyond that you start to get in to the areas that might be a bit subjective, most people should agree on these items.
A: This question is subjective, and should be avoided on StackOverflow, as per the FAQ
What kind of questions should I not
ask here?
Avoid asking questions that are
subjective, argumentative, or require
extended discussion. This is a place
for questions that can be answered!
The short answer would be:
*
*Avoid excessive commenting:
// add one to the count:
i++;
*Use good variable and method names:
int x = i + j;
int runSum = prevSum += newValue;
*Use coding shorthand where available:
if (x == y)
{
z = a;
}
else
{
z = b;
}
z = (x == y) ? a : b;
A: You may want to take a look at Clean Code by Robert C. Martin. It offers up a lot of useful practices for ensuring your code is readable.
Additionally, if your code is supported by a number of unit tests that thoroughly test your code, it offers a way for your user to understand the code by looking at what the tests are doing. You will also find that if you follow the Test Driven Development process, and you write tests for each bit of functionality, your functions tend to be small, do one thing only and do it well, and tend to flow more like a story than simply a large complex web of "stuff".
Tests tend to stay up-to-date more than comments. I often ignore comments anymore due to simple fact that they become obsolete very quickly.
A: Keep code nice, clear and simple. Don't comment what you're doing when it's obvious (for instance I know what a foreach or if does, I don't normally need an explanation).
Code tricks (such as auto properties) that make simple things take up fewer lines are good too.
A: Buy & read Code Complete 2. There's loads of stuff in there about writing easy to read / maintain code.
A: I don't think it's a subjective question, but it's too broad! It's not just about commenting and giving good variables names. It deals with how humans comprehends code. So your system must be implemented in a way that the reader can easily construct a mental model of its design in two way:
*
*Top-down: assuming the user knows the system domain, he tends to make assumptions on how it would be implemented, so he'll scan the system packages and classes looking for entities he can identify. Giving good names to your classes and properly modularizing it would help very much.
*Bottom-up: once the user reaches a portion of code he'll start navigation from there, building chunks of knowledge. If your system has low cohesion and lots of implicit dependencies the user will be lost.
Kent Beck adopts three principles: Communication, Simplicity and Flexibility. Of course, sometimes you'll have to trade simplicity for flexibility, and vice-versa.
This could go on and on. The answer to this question fits in a large book. As @rmbarnes suggested, buy and read Code Complete 2. I also suggest Implementation Patterns by Kent Beck - its highly related to your question.
A: *
*Document the code as to why it does what it does.
*Make sure that all variables functions etc. are named consistently and descriptively
*Use white space to group logical portions of code together, so it flows while reading.
*Place the functions/methods etc. in a logical order.
*(this one is my personal preference) Make sure that code can easily be read on the screen without having to scroll horizontally (some people say vertically too, but this doesn't seem to bother me).
A: Since everyone else said pretty much what I'm thinking when I read this question, I'll just share two books related to this subject that you might be interested in reading. These books use open source code examples to explain how to read and write high quality code. In addition to Code Complete, I think they are valuable resources when you want to write good code in any language.
*
*Code Reading: The Open Source Perspective
*Code Quality: The Open Source Perspective
A: My rules:
*
*Give everything a meaningful name, and call it what it is. Avoid using "x" and "y" for variables.
*Don't abbreviate ANYTHING. I don't care how long the variable name is, don't abbreviate, even with comments. Interpretation of abbreviations is subjective. Does Cmp mean computer? Computer? Company? Compliment? Make it a strong rule, no exceptions, and its easy to follow.
*Don't put multiple statements on the same line. Each line performs a single action.
*Avoid Hungarian Notation like the plague. Or is it ntHungarian?
*Use brackets even for single-line (if, for) substructures. Indentation differences are too easy to lose.
A: A lot of good answers here, I would like to add something from the perspective of an engineer who likes the big picture. I frequently found that getting a high level overview, in terms of class diagram or a package level overview (diagram/comments etc), heck if nothing exists a 10 line header comments in a file to help me a lot. We can use Doxygen/Javadocs to generate them, or spend 10-15 minutes to just jot down something in comments section.
They dont have to be 100% accurate, and I doubt the overall structure of classes/packages will change without a complete rewrite.
I personally found this kind of big picture overview very helpful and am sure there are others who feel the same.
A: Probably the most important point is to keep your syntax consistent. I would also have a look at the design guidelines for the language you are writing in.
A: From being a developer with several years under the belt, this used to be a real question for me. I couldn't even say how many hours I passed thinking about this and trying different things in my code. The above answers are very nice too. I just want to add a thing or two.
*
*We each have different things that make our reading different than the others. Something that you find easy to read, might really be hard for somebody else to read.
*Cleanliness of your code is a very important aspect. Soon as it gets too cramped just forget about it.
*Most important: You are you own teacher. No matter what style you follow, you will want to change a thing or two based on your experience. As months pass and you have to go back to your old for fixes or documentation, you will have the "I can't believe I wrote code that reads like that" effect. Take notes of what was bugging you with the code readability and make sure not to write like that again.
A: I am most likely in the minority, but I don't mind whitespace. I LOVE WHITESPACE. Since the compiler takes it out and HD space being so cheap I like to have white space in my code.
For example I like:
int total = 10;
int sum = 0;
for (int i = 0; i < total; i++)
{
sum += i;
}
// Next coding statement is a space below the bracket
return sum;
I do not like:
int total = 10;int sum = 0;
for (int i = 0; i < total; i++)
{
sum += i;
}
return sum;
What I also put in Brackets even though technically they are not needed. The best example is the if statement. I find it greatly helps readability.
if(true)
// some action
if(true)
{
// Some action
}
The best code to me, is one that as simple as possible. With the least comments as possible, and most importantly works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to add a web part zone in SharePoint using SharePoint Designer I need to add a web part zone to a wiki page. I'm opening the page using SharePoint Designer, but there doesn't seem to be an obvious way (such as a menu) to add a Web Part Zone.
A: If this a page that you will be using over again in different places, consider creating a site def instead. By editing a page in sharepoint designer, you create a "customized" version of the page.
A: from: http://office.microsoft.com/en-us/sharepointdesigner/HA101513941033.aspx
Insert a Web Part zone
*
*In Office SharePoint Designer 2007, open the page where you want to
insert the Web Part zone.
*If the Web Parts task pane is not already open, open it by clicking
Web Parts on the Task Panes menu.
*In Design view, click the location on the page where you want to
insert the Web Part zone.
*At the bottom of the Web Parts task pane, click New Web Part Zone.
The new Web Part zone is inserted on the page.
...
A: open your site in SPD -->insert-->sharepoint controls--> web part zone.
Note that you are unable to add a web part zone in master pages
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Does new URL(...).openConnection() necessarily imply a POST? If I create an HTTP java.net.URL and then call openConnection() on it, does it necessarily imply that an HTTP post is going to happen? I know that openStream() implies a GET. If so, how do you perform one of the other HTTP verbs without having to work with the raw socket layer?
A: No it does not. But if the protocol of the URL is HTTP, you'll get a HttpURLConnection as a return object. This class has a setRequestMethod method to specify which HTTP method you want to use.
If you want to do more sophisticated stuff you're probably better off using a library like Jakarta HttpClient.
A: If you retrieve the URLConnection object using openConnection() it doesn't actually start communicating with the server. That doesn't happen until you get the stream from the URLConnection(). When you first get the connection you can add/change headers and other connection properties before actually opening it.
URLConnection's life cycle is a bit odd. It doesn't send the headers to the server until you've gotten one of the streams. If you just get the input stream then I believe it does a GET, sends the headers, then lets you read the output. If you get the output stream then I believe it sends it as a POST, as it assumes you'll be writing data to it (You may need to call setDoOutput(true) for the output stream to work). As soon as you get the input stream the output stream is closed and it waits for the response from the server.
For example, this should do a POST:
URL myURL = new URL("http://example.com/my/path");
URLConnection conn = myURL.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStream os = conn.getOutputStream();
os.write("Hi there!");
os.close();
InputStream is = conn.getInputStream();
// read stuff here
While this would do a GET:
URL myURL = new URL("http://example.com/my/path");
URLConnection conn = myURL.openConnection();
conn.setDoOutput(false);
conn.setDoInput(true);
InputStream is = conn.getInputStream();
// read stuff here
URLConnection will also do other weird things. If the server specifies a content length then URLConnection will keep the underlying input stream open until it receives that much data, even if you explicitly close it. This caused a lot of problems for us as it made shutting our client down cleanly a bit hard, as the URLConnection would keep the network connection open. This probably probably exists even if you just use getStream() though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: ASP.NET MVC vs. XSL Can anyone (maybe an XSL-fan?) help me find any advantages with handling presentation of data on a web-page with XSL over ASP.NET MVC?
The two alternatives are:
*
*ASP.NET (MVC/WebForms) with XSL
Getting the data from the database and transforming it to XML which is then displayed on the different pages with XSL-templates.
*ASP.NET MVC
Getting the data from the database as C# objects (or LinqToSql/EF-objects) and displaying it with inline-code on MVC-pages.
The main benefit of XSL has been consistent display of data on many different pages, like WebControls. So, correct me if I'm wrong, ASP.NET MVC can be used the same way, but with strongly typed objects. Please help me see if there are any benefits to XSL.
A: I can see the main benefit of employing XSLT to transform your data and display it to the user would be the following:
*
*The data is already in an XML format
*The data follows a well defined schema (this makes using tools like XMLSpy much easier).
*The data needs to be transformed into a number of different output formats, e.g. PDF, WMP and HTML
If this is to be the only output for your data, and it is not in XML format, then XSLT might not be the best solution.
Likewise if user interaction is required (such as editing of the data) then you will end up employing back-end code anyway to handle updates so might prove one technology too far...
A: I've always found two main issues when working with XML transformations:
Firstly they tend to be quite slow, the whole XML file must be parsed and validated before you can do anything with it. Being XML it's also excessively verbose, and therefore larger than it needs to be.
Secondly the way transformations work is a bit of a pain to code - custom tools like XmlSpy help, but it's still a different model to what most developers are used to.
At the moment MVC is very quick and looking very promising, but does suffer from the traditional web-development blight of <% and %> bee-stings all over your code. Using XML transformations avoids that, but is much harder to read and maintain.
A: I've used that technique in the past, and there are applications where we use it at my current place of employment. (I will admit, I am not totally a fan of it, but I'll play devil's advocate) Really that is one of the main advatages, and pushing this idea can be kinda neat. You're able to dynamically create the xsl on the fly and change the look and feel of the page on a whim. Is it possible to do this through the other methods...yes, but it's really easy to build a program to modify an xml/xsl document on the fly.
If you think of using XSL to transform one xml document to another and displaying it as html (which is really what you're doing), you're opening up your system to allow other programs to access the data on the page via XML. You can do this through the other methods, but using an xsl transformation forces it to output xml every time.
I would tread lightly with creating a system this way. You'll find a lot of pit falls you aren't expecting, and if you don't know xsl really really well, there is going to be a learning curve also.
A: Jafar Husain offers a few advantages in his proposal for Pretty XSL, primarily caching of the stylesheet to increase page load and reduce the size of your data. Steve Sanderson proposed a slightly different approach using JavaScript as the controller here.
Another, similar approach would be to use XForms, though the best support for it is through a JavaScript library.
A: Check this out if you want to use XSLT and ASP.MVC
http://www.bleevo.com/2009/06/aspnet-mvc-xslt-iviewengine/
A: If you only going to display data from DB XSL templates may be convenient solution, but if you gonna handle user interaction. Hm... I don't think it'll be maintainable at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How do I calculate PI in C#? How can I calculate the value of PI using C#?
I was thinking it would be through a recursive function, if so, what would it look like and are there any math equations to back it up?
I'm not too fussy about performance, mainly how to go about it from a learning point of view.
A: If you take a close look into this really good guide:
Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4
You'll find at Page 70 this cute implementation (with minor changes from my side):
static decimal ParallelPartitionerPi(int steps)
{
decimal sum = 0.0;
decimal step = 1.0 / (decimal)steps;
object obj = new object();
Parallel.ForEach(
Partitioner.Create(0, steps),
() => 0.0,
(range, state, partial) =>
{
for (int i = range.Item1; i < range.Item2; i++)
{
decimal x = (i - 0.5) * step;
partial += 4.0 / (1.0 + x * x);
}
return partial;
},
partial => { lock (obj) sum += partial; });
return step * sum;
}
A: There are a couple of really, really old tricks I'm surprised to not see here.
atan(1) == PI/4, so an old chestnut when a trustworthy arc-tangent function is
present is 4*atan(1).
A very cute, fixed-ratio estimate that makes the old Western 22/7 look like dirt
is 355/113, which is good to several decimal places (at least three or four, I think).
In some cases, this is even good enough for integer arithmetic: multiply by 355 then divide by 113.
355/113 is also easy to commit to memory (for some people anyway): count one, one, three, three, five, five and remember that you're naming the digits in the denominator and numerator (if you forget which triplet goes on top, a microsecond's thought is usually going to straighten it out).
Note that 22/7 gives you: 3.14285714, which is wrong at the thousandths.
355/113 gives you 3.14159292 which isn't wrong until the ten-millionths.
Acc. to /usr/include/math.h on my box, M_PI is #define'd as:
3.14159265358979323846
which is probably good out as far as it goes.
The lesson you get from estimating PI is that there are lots of ways of doing it,
none will ever be perfect, and you have to sort them out by intended use.
355/113 is an old Chinese estimate, and I believe it pre-dates 22/7 by many years. It was taught me by a physics professor when I was an undergrad.
A: If you want recursion:
PI = 2 * (1 + 1/3 * (1 + 2/5 * (1 + 3/7 * (...))))
This would become, after some rewriting:
PI = 2 * F(1);
with F(i):
double F (int i) {
return 1 + i / (2.0 * i + 1) * F(i + 1);
}
Isaac Newton (you may have heard of him before ;) ) came up with this trick.
Note that I left out the end condition, to keep it simple. In real life, you kind of need one.
A: Good overview of different algorithms:
*
*Computing pi;
*Gauss-Legendre-Salamin.
I'm not sure about the complexity claimed for the Gauss-Legendre-Salamin algorithm in the first link (I'd say O(N log^2(N) log(log(N)))).
I do encourage you to try it, though, the convergence is really fast.
Also, I'm not really sure about why trying to convert a quite simple procedural algorithm into a recursive one?
Note that if you are interested in performance, then working at a bounded precision (typically, requiring a 'double', 'float',... output) does not really make sense, as the obvious answer in such a case is just to hardcode the value.
A: How about using:
double pi = Math.PI;
If you want better precision than that, you will need to use an algorithmic system and the Decimal type.
A: What is PI? The circumference of a circle divided by its diameter.
In computer graphics you can plot/draw a circle with its centre at 0,0 from a initial point x,y, the next point x',y' can be found using a simple formula:
x' = x + y / h : y' = y - x' / h
h is usually a power of 2 so that the divide can be done easily with a shift (or subtracting from the exponent on a double). h also wants to be the radius r of your circle. An easy start point would be x = r, y = 0, and then to count c the number of steps until x <= 0 to plot a quater of a circle. PI is 4 * c / r or PI is 4 * c / h
Recursion to any great depth, is usually impractical for a commercial program, but tail recursion allows an algorithm to be expressed recursively, while implemented as a loop. Recursive search algorithms can sometimes be implemented using a queue rather than the process's stack, the search has to backtrack from a deadend and take another path - these backtrack points can be put in a queue, and multiple processes can un-queue the points and try other paths.
A: Calculate like this:
x = 1 - 1/3 + 1/5 - 1/7 + 1/9 (... etc as far as possible.)
PI = x * 4
You have got Pi !!!
This is the simplest method I know of.
The value of PI slowly converges to the actual value of Pi (3.141592165......). If you iterate more times, the better.
A: Here's a nice approach (from the main Wikipedia entry on pi); it converges much faster than the simple formula discussed above, and is quite amenable to a recursive solution if your intent is to pursue recursion as a learning exercise. (Assuming that you're after the learning experience, I'm not giving any actual code.)
The underlying formula is the same as above, but this approach averages the partial sums to accelerate the convergence.
Define a two parameter function, pie(h, w), such that:
pie(0,1) = 4/1
pie(0,2) = 4/1 - 4/3
pie(0,3) = 4/1 - 4/3 + 4/5
pie(0,4) = 4/1 - 4/3 + 4/5 - 4/7
... and so on
So your first opportunity to explore recursion is to code that "horizontal" computation as the "width" parameter increases (for "height" of zero).
Then add the second dimension with this formula:
pie(h, w) = (pie(h-1,w) + pie(h-1,w+1)) / 2
which is used, of course, only for values of h greater than zero.
The nice thing about this algorithm is that you can easily mock it up with a spreadsheet to check your code as you explore the results produced by progressively larger parameters. By the time you compute pie(10,10), you'll have an approximate value for pi that's good enough for most engineering purposes.
A: Enumerable.Range(0, 100000000).Aggregate(0d, (tot, next) => tot += Math.Pow(-1d, next)/(2*next + 1)*4)
A: using System;
namespace Strings
{
class Program
{
static void Main(string[] args)
{
/* decimal pie = 1;
decimal e = -1;
*/
var stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start(); //added this nice stopwatch start routine
//leibniz formula in C# - code written completely by Todd Mandell 2014
/*
for (decimal f = (e += 2); f < 1000001; f++)
{
e += 2;
pie -= 1 / e;
e += 2;
pie += 1 / e;
Console.WriteLine(pie * 4);
}
decimal finalDisplayString = (pie * 4);
Console.WriteLine("pie = {0}", finalDisplayString);
Console.WriteLine("Accuracy resulting from approximately {0} steps", e/4);
*/
// Nilakantha formula - code written completely by Todd Mandell 2014
// π = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) + 4/(10*11*12) - (4/(12*13*14) etc
decimal pie = 0;
decimal a = 2;
decimal b = 3;
decimal c = 4;
decimal e = 1;
for (decimal f = (e += 1); f < 100000; f++)
// Increase f where "f < 100000" to increase number of steps
{
pie += 4 / (a * b * c);
a += 2;
b += 2;
c += 2;
pie -= 4 / (a * b * c);
a += 2;
b += 2;
c += 2;
e += 1;
}
decimal finalDisplayString = (pie + 3);
Console.WriteLine("pie = {0}", finalDisplayString);
Console.WriteLine("Accuracy resulting from {0} steps", e);
stopwatch.Stop();
TimeSpan ts = stopwatch.Elapsed;
Console.WriteLine("Calc Time {0}", ts);
Console.ReadLine();
}
}
}
A: public static string PiNumberFinder(int digitNumber)
{
string piNumber = "3,";
int dividedBy = 11080585;
int divisor = 78256779;
int result;
for (int i = 0; i < digitNumber; i++)
{
if (dividedBy < divisor)
dividedBy *= 10;
result = dividedBy / divisor;
string resultString = result.ToString();
piNumber += resultString;
dividedBy = dividedBy - divisor * result;
}
return piNumber;
}
A: In any production scenario, I would compel you to look up the value, to the desired number of decimal points, and store it as a 'const' somewhere your classes can get to it.
(unless you're writing scientific 'Pi' specific software...)
A: Regarding...
... how to go about it from a learning point of view.
Are you trying to learning to program scientific methods? or to produce production software? I hope the community sees this as a valid question and not a nitpick.
In either case, I think writing your own Pi is a solved problem. Dmitry showed the 'Math.PI' constant already. Attack another problem in the same space! Go for generic Newton approximations or something slick.
A: @Thomas Kammeyer:
Note that Atan(1.0) is quite often hardcoded, so 4*Atan(1.0) is not really an 'algorithm' if you're calling a library Atan function (an quite a few already suggested indeed proceed by replacing Atan(x) by a series (or infinite product) for it, then evaluating it at x=1.
Also, there are very few cases where you'd need pi at more precision than a few tens of bits (which can be easily hardcoded!). I've worked on applications in mathematics where, to compute some (quite complicated) mathematical objects (which were polynomial with integer coefficients), I had to do arithmetic on real and complex numbers (including computing pi) with a precision of up to a few million bits... but this is not very frequent 'in real life' :)
You can look up the following example code.
A: The following link shows how to calculate the pi constant based on its definition as an integral, that can be written as a limit of a summation, it's very interesting:
https://sites.google.com/site/rcorcs/posts/calculatingthepiconstant
The file "Pi as an integral" explains this method used in this post.
A: I like this paper, which explains how to calculate π based on a Taylor series expansion for Arctangent.
The paper starts with the simple assumption that
Atan(1) = π/4 radians
Atan(x) can be iteratively estimated with the Taylor series
atan(x) = x - x^3/3 + x^5/5 - x^7/7 + x^9/9...
The paper points out why this is not particularly efficient and goes on to make a number of logical refinements in the technique. They also provide a sample program that computes π to a few thousand digits, complete with source code, including the infinite-precision math routines required.
A: First, note that C# can use the Math.PI field of the .NET framework:
https://msdn.microsoft.com/en-us/library/system.math.pi(v=vs.110).aspx
The nice feature here is that it's a full-precision double that you can either use, or compare with computed results. The tabs at that URL have similar constants for C++, F# and Visual Basic.
To calculate more places, you can write your own extended-precision code. One that is quick to code and reasonably fast and easy to program is:
Pi = 4 * [4 * arctan (1/5) - arctan (1/239)]
This formula and many others, including some that converge at amazingly fast rates, such as 50 digits per term, are at Wolfram:
Wolfram Pi Formulas
A: PI (π) can be calculated by using infinite series. Here are two examples:
Gregory-Leibniz Series:
π/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - ...
C# method :
public static decimal GregoryLeibnizGetPI(int n)
{
decimal sum = 0;
decimal temp = 0;
for (int i = 0; i < n; i++)
{
temp = 4m / (1 + 2 * i);
sum += i % 2 == 0 ? temp : -temp;
}
return sum;
}
Nilakantha Series:
π = 3 + 4 / (2x3x4) - 4 / (4x5x6) + 4 / (6x7x8) - 4 / (8x9x10) + ...
C# method:
public static decimal NilakanthaGetPI(int n)
{
decimal sum = 0;
decimal temp = 0;
decimal a = 2, b = 3, c = 4;
for (int i = 0; i < n; i++)
{
temp = 4 / (a * b * c);
sum += i % 2 == 0 ? temp : -temp;
a += 2; b += 2; c += 2;
}
return 3 + sum;
}
The input parameter n for both functions represents the number of iteration.
The Nilakantha Series in comparison with Gregory-Leibniz Series converges more quickly. The methods can be tested with the following code:
static void Main(string[] args)
{
const decimal pi = 3.1415926535897932384626433832m;
Console.WriteLine($"PI = {pi}");
//Nilakantha Series
int iterationsN = 100;
decimal nilakanthaPI = NilakanthaGetPI(iterationsN);
decimal CalcErrorNilakantha = pi - nilakanthaPI;
Console.WriteLine($"\nNilakantha Series -> PI = {nilakanthaPI}");
Console.WriteLine($"Calculation error = {CalcErrorNilakantha}");
int numDecNilakantha = pi.ToString().Zip(nilakanthaPI.ToString(), (x, y) => x == y).TakeWhile(x => x).Count() - 2;
Console.WriteLine($"Number of correct decimals = {numDecNilakantha}");
Console.WriteLine($"Number of iterations = {iterationsN}");
//Gregory-Leibniz Series
int iterationsGL = 1000000;
decimal GregoryLeibnizPI = GregoryLeibnizGetPI(iterationsGL);
decimal CalcErrorGregoryLeibniz = pi - GregoryLeibnizPI;
Console.WriteLine($"\nGregory-Leibniz Series -> PI = {GregoryLeibnizPI}");
Console.WriteLine($"Calculation error = {CalcErrorGregoryLeibniz}");
int numDecGregoryLeibniz = pi.ToString().Zip(GregoryLeibnizPI.ToString(), (x, y) => x == y).TakeWhile(x => x).Count() - 2;
Console.WriteLine($"Number of correct decimals = {numDecGregoryLeibniz}");
Console.WriteLine($"Number of iterations = {iterationsGL}");
Console.ReadKey();
}
The following output shows that Nilakantha Series returns six correct decimals of PI with one hundred iterations whereas Gregory-Leibniz Series returns five correct decimals of PI with one million iterations:
My code can be tested >> here
A: Here is a nice way:
Calculate a series of 1/x^2 for x from 1 to what ever you want- the bigger number- the better pie result. Multiply the result by 6 and to sqrt().
Here is the code in c# (main only):
static void Main(string[] args)
{
double counter = 0;
for (double i = 1; i < 1000000; i++)
{
counter = counter + (1 / (Math.Pow(i, 2)));
}
counter = counter * 6;
counter = Math.Sqrt(counter);
Console.WriteLine(counter);
}
A: public double PI = 22.0 / 7.0;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: How can I set the welcome page to a struts action? I have a struts-based webapp, and I would like the default "welcome" page to be an action. The only solutions I have found to this seem to be variations on making the welcome page a JSP that contains a redirect to the action. For example, in web.xml:
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
and in index.jsp:
<%
response.sendRedirect("/myproject/MyAction.action");
%>
Surely there's a better way!
A: "Surely there's a better way!"
There isn't. Servlet specifications (Java Servlet Specification 2.4, "SRV.9.10 Welcome Files" for instance) state:
The purpose of this mechanism is to allow the deployer to specify an ordered
list of partial URIs for the container to use for appending to URIs when there is a
request for a URI that corresponds to a directory entry in the WAR not mapped to
a Web component.
You can't map Struts on '/', because Struts kind of require to work with a file extension. So you're left to use an implicitely mapped component, such as a JSP or a static file. All the other solutions are just hacks. So keep your solution, it's perfectly readable and maintainable, don't bother looking further.
A: Something that I do is to put an empty file of the same name as your struts action and trick the container to call the struts action.
Ex. If your struts action is welcome.do, create an empty file named welcome.do. That should trick the container to call the Struts action.
A: Personally, I'd keep the same setup you have now, but change the redirect for a forward. That avoids sending a header back to the client and having them make another request.
So, in particular, I'd replace the
<%
response.sendRedirect("/myproject/MyAction.action");
%>
in index.jsp with
<jsp:forward page="/MyAction.action" />
The other effect of this change is that the user won't see the URL in the address bar change from "http://server/myproject" to "http://server/myproject/index.jsp", as the forward happens internally on the server.
A: This is a pretty old thread but the topic discussed, i think, is still relevant. I use a struts tag - s:action to achieve this. I created an index.jsp in which i wrote this...
<s:action name="loadHomePage" namespace="/load" executeResult="true" />
A: As of the 2.4 version of the Servlet specification you are allowed to have a servlet in the welcome file list. Note that this may not be a URL (such as /myproject/MyAction.action). It must be a named servlet and you cannot pass a query string to the servlet. Your controller servlet would need to have a default action.
<servlet>
<servlet-name>MyController</servlet-name>
<servlet-class>com.example.MyControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyController</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>MyController</welcome-file>
</welcome-file-list>
A: It appears that a popular solution will not work in all containers... http://www.theserverside.com/discussions/thread.tss?thread_id=30190
A: I would create a filter and bounce all requests to root back with forward responce. Hacks with creating home.do page looks ugly to me (One more thing to remember for you and investigate for someone who will support your code).
A: Here two blogs with same technique:
*
*http://technologicaloddity.com/2010/03/25/spring-welcome-file-without-redirect/
*http://wiki.metawerx.net/wiki/HowToUseAServletAsYourMainWebPage
It require Servlet API >= v2.4:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
<url-pattern>/index.htm</url-pattern> <<== *1*
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.htm</welcome-file> <<== *2*
</welcome-file-list>
so you no longer need redirect.jsp in non-WEB-INF directory!!
A: there are this answer above but it is not clear about web app context
so
i do this:
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>TilesDispatchServlet</servlet-name>
<servlet-class>org.apache.tiles.web.util.TilesDispatchServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TilesDispatchServlet</servlet-name>
<url-pattern>*.tiles</url-pattern>
</servlet-mapping>
And in index.jsp i just write:
<jsp:forward page="index.tiles" />
And i have index definition, named index and it all togather work fine and not depends on webapp context path.
A: Just add a filter above Strut's filter in web.xml like this:
<filter>
<filter-name>customfilter</filter-name>
<filter-class>com.example.CustomFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>customfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
And add the following code in doFilter method of that CustomFilter class
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;
HttpServletResponse httpResponse = (HttpServletResponse)servletResponse;
if (! httpResponse.isCommitted()) {
if ((httpRequest.getContextPath() + "/").equals(httpRequest.getRequestURI())) {
httpResponse.sendRedirect(httpRequest.getContextPath() + "/MyAction");
}
else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
}
So that Filter will redirect to the action. You dont need any JSP to be placed outside WEB-INF as well.
A: I have configured like following. it worked perfect and no URL change also...
Create a dummy action like following in struts2.xml file. so whenever we access application like http://localhost:8080/myapp, it will forward that to dummy action and then it redirects to index.jsp / index.tiles...
<action name="">
<result type="tiles">/index.tiles</result>
</action>
w/o tiles
<action name="">
<result>/index.jsp</result>
</action>
may be we configure some action index.action in web.xml as <welcome-file>index.action</welcome-file>, and use that action to forward required page...
A: I am almost sure that the OP is the best solution(not sure about best practice, but it works perfectly, and actually is the solution my project leader and I prefer.)
Additionally, I find it can be combined with Spring security like this:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authorize access="isAnonymous()">
<% response.sendRedirect("/myApp/login/login.action?error=false"); %>
</sec:authorize>
<sec:authorize access="isAuthenticated() and (hasRole('ADMIN') or hasRole('USER'))">
<% response.sendRedirect("/myApp/principal/principal.action"); %>
</sec:authorize>
<sec:authorize access="isAuthenticated() and hasRole('USER')">
<% response.sendRedirect("/myApp/user/userDetails.action"); %>
</sec:authorize>
By this, not only we have control over the first page to be the login form, but we control the flow AFTER user is login in, depending on his role. Works like a charm.
A: Below code can be used in struts.xml to load welcome page.
Execute some Action before loading a welcome page.
<!-- welcome page configuration -begin -->
<action name="" class="com.LoginAction">
<result name="success">login.jsp</result>
</action>
<!-- welcome page configuration -end -->
Return directly some JSP without execution of an Action.
<!-- welcome page configuration -begin -->
<action name="">
<result name="success">login.jsp</result>
</action>
<!-- welcome page configuration -end -->
No <welcome-file-list> is not needed in web.xml
A: This works as well reducing the need of a new servlet or jsp
<welcome-file-list>
<welcome-file>/MyAction.action</welcome-file>
</welcome-file-list>
A: This worked fine for me, too:
<welcome-file-list>
<welcome-file>MyAction.action</welcome-file>
</welcome-file-list>
I was not able to get the default action to execute when the user enters the webapp using the root of the web app (mywebapp/). There is a bug in struts 2.3.12 that won't go to the default action or use the welcome page when you use the root url. This will be a common occurrence. Once I changed back to struts 2.1.8 it worked fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
} |
Q: How to customize Entity Framework classes? Is there a way to take over the Entity Framework class builder? I want to be able to have my own class builder so i can make some properties to call other methods upon materialization or make the entity classes partial.
A: Actually they are already in partial classes. See MSDN
A: System.Data.Entity.Design.EntityClassGenerator, is the type used in VS to generate the object layer from your .edmx file, and it is the type used by EdmGen.exe to generate the object layer from a .csdl file. Below I listed the 3 ways that you can affect the generated code. The 3rd option requires that you call EntityClassGenerator yourself. You can get your code to run automatically in VS sort of like an SingleFileGenerator by using this technique presented by Sanjay.
*
*Add code to the types through partial classes
*Add code to the partial methods that are called by the generated classes
*Hook the code generation events to inject code directly into the properties and types as they are generated. See Danny's blog post for an example
A: I'll add that not only can you can tack on your own class partial classes to those emitted by the Entity Framework, but you can also write out all the partial methods created by the generated code.
IE. There'll be a lot of partial method code which get called but the method itself in the generated code isn't really implemented. For that you can write a partial method to catch events when properties change and such. It's not a terrible way to handle some business rules.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How large is a DWORD with 32- and 64-bit code? In Visual C++ a DWORD is just an unsigned long that is machine, platform, and SDK dependent. However, since DWORD is a double word (that is 2 * 16), is a DWORD still 32-bit on 64-bit architectures?
A: Actually, on 32-bit computers a word is 32-bit, but the DWORD type is a leftover from the good old days of 16-bit.
In order to make it easier to port programs to the newer system, Microsoft has decided all the old types will not change size.
You can find the official list here:
http://msdn.microsoft.com/en-us/library/aa383751(VS.85).aspx
All the platform-dependent types that changed with the transition from 32-bit to 64-bit end with _PTR (DWORD_PTR will be 32-bit on 32-bit Windows and 64-bit on 64-bit Windows).
A: It is defined as:
typedef unsigned long DWORD;
However, according to the MSDN:
On 32-bit platforms, long is
synonymous with int.
Therefore, DWORD is 32bit on a 32bit operating system. There is a separate define for a 64bit DWORD:
typdef unsigned _int64 DWORD64;
Hope that helps.
A: No ... on all Windows platforms DWORD is 32 bits. LONGLONG or LONG64 is used for 64 bit types.
A: Windows API defines DWORD sizes as follows:
*
*x86: sizeof(DWORD) = 4
*x64: sizeof(DWORD) = 4
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "55"
} |
Q: Developer moving from SQL Server to Oracle We are bringing a new project in house and whereas previously all our work was on SQL Server the new product uses an oracle back end.
Can anyone advise any crib sheets or such like that gives an SQL Server person like me a rundown of what the major differences are - Would like to be able to get up and running as soon as possible.
A: @hamishcmcn
Your assertion that '' == Null is simply not true. In the relational world Null should only ever be read to mean "I don't know". The only result you will get from Oracle (and most other decent databases) when you compare a value to Null is 'False'.
Off the top of my head the major differences between SQL Server and Oracle are:
*
*Learn to love transactions, they are your friend - auto commit is not.
*Read consistency and the lack of blocking reads
*SQL Server Database == Oracle Schema
*PL/SQL is a lot more feature rich than T-SQL
*Learn the difference between an instance and a database in Oracle
*You can have more than one Oracle instance on a server
*No pointy clicky wizards (unless you really, really want them)
Everyone else, please help me out and add more.
A: The main difference I noticed in moving from SQL Server to Oracle was that in Oracle you need to use cursors in the SELECT statements.
Also, temporary tables are used differently. In SQL Server you can create one in a procedure and then DROP it at the end, but in Oracle you're supposed to already have a temporary table created before the procedure is executed.
I'd look at datatypes too since they're quite different.
A: String concatenation:
Oracle: || or concat()
Sql Server: +
These links could be interesting:
http://www.dba-oracle.com/oracle_news/2005_12_16_sql_syntax_differences.htm
http://www.mssqlcity.com/Articles/Compare/sql_server_vs_oracle.htm (old one: Ora9 vs Sql 2000)
A: Watch out for the difference in the way the empty string is treated.
INSERT INTO atable (a_varchar_column) VALUES ('');
is the same as
INSERT INTO atable (a_varchar_column) VALUES (NULL);
I have no sqlserver experience, but I understand that it differentiates between the two
A: @hamishmcn
Generally that's a bad idea.. Temporary tables in oracle should just be created and left (unless its a once off/very rarely used). The contents of the temporary table is local to each session and truncated when the session is closed. There is little point in paying the cost of creating/dropping the temporary table, might even result in clashes if two processes try to create the table at the same time and unexpected commits from performing DDL.
A: What you have asked here is a huge topic, especially since you haven't really said what you are using the database for (eg, are you going to be going from TSQL -> PL/SQL or just changing the backend database your java application is connected to?)
If you are serious about using your database choice to its potiential, then I suggest you dig a bit deeper and read something like Expert Oracle Database Architecture: 9i and 10g Programming Techniques and Solutions by Tom Kyte.
A: If you need to you can create and drop temporary tables in procedures using the Execute Immediate command.
A: to andy47, I did not mean that you can use the empty string in a comparison, but oracle treats it like null if you use it in an insert.
Re-read my entry, then try the following SQL:
CREATE TABLE atable (acol VARCHAR(10));
INsERT INTO atable VALUES( '' );
SELECT * FROM atable WHERE acol IS NULL;
And to avoid a "yes it is, no it isn't" situation, here is an external link
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How can I expose only a fragment of IList<>? I have a class property exposing an internal IList<> through
System.Collections.ObjectModel.ReadOnlyCollection<>
How can I pass a part of this ReadOnlyCollection<> without copying elements into a new array (I need a live view, and the target device is short on memory)? I'm targetting Compact Framework 2.0.
A: These foreach samples are fine, though you can make them much more terse if you're using .NET 3.5 and LINQ:
return FullList.Where(i => IsItemInPartialList(i)).ToList();
A: Try a method that returns an enumeration using yield:
IEnumerable<T> FilterCollection<T>( ReadOnlyCollection<T> input ) {
foreach ( T item in input )
if ( /* criterion is met */ )
yield return item;
}
A: You can always write a class that implements IList and forwards all calls to the original list (so it doesn't have it's own copy of the data) after translating the indexes.
A: You could use yield return to create a filtered list
IEnumerable<object> FilteredList()
{
foreach( object item in FullList )
{
if( IsItemInPartialList( item )
yield return item;
}
}
A: Depending on how you need to filter the collection, you may want to create a class that implements IList (or IEnumerable, if that works for you) but that mucks about with the indexing and access to only return the values you want. For example
class EvenList: IList
{
private IList innerList;
public EvenList(IList innerList)
{
this.innerList = innerList;
}
public object this[int index]
{
get { return innerList[2*i]; }
set { innerList[2*i] = value; }
}
// and similarly for the other IList methods
}
A: How do the filtered elements need to be accessed? If it's through an Iterator then maybe you could write a custom iterator that skips the elements you don't want publicly visible?
If you need to provide a Collection then you might need to write your own Collection class, which just proxies to the underlying Collection, but prevents access to the elements you don't want publicly visible.
(Disclaimer: I'm not very familiar with C#, so these are general answers. There may be more specific answers to C# that work better)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Is there a secret trick to force antialiasing inside Viewport3D in Windows XP? Under Windows XP WPF true 3D content (which is usually displayed using the Viewport3D control) looks extremely ugly because it is by default not antialiased as the rest of the WPF graphics are. Especially at lower resolution the experience is so bad that it can not be used in production code.
I have managed to force antialiasing on some Nvidia graphics cards using the settings of the driver. Unfortunately, this sometimes yields ugly artifacts and only works with specific cards and driver versions. The official word from Microsoft on this regard is that antialiased 3D is generally not supported under Windows XP and the artifact I see result from the fact that WPF already does its own antialiasing (on XP only for 2D).
So I was wondering if there is maybe some other secret trick that lets me force antialiasing on WPF 3D content under Windows XP.
A: Have you tried this (from your thread on MSDN forums)?
Well, it seems the reference in the MSDN link above incorrectly specify the affected registry root key. In MSDN it is specified as HKEY_CURRENT_USER, while the correct root key should be HKEY_LOCAL_MACHINE. I've tried setting up the HKEY_LOCAL_MACHINE\Software\Microsoft\Avalon.Graphics\MaxMultiplesampleType to '4' and I can get antialiasing for my WPF Application on XP.
A: The feeling I get from Matthew MacDonald's Pro WPF Windows Presentation Foundation in .NET 3.0 is that it's not possible:
There's one exception to WPF's software support. Due to poor driver support, WPF only performs antialiasing for 3-D drawings if you're running your application on Windows Vista (and you have a native Windows Vista driver for your video card).
I've never seen anything to suggest that you can enable AA in WPF 3D on anything but Vista, but if there is a way it's new to me and I'd love to know as well!
A: Does your video card support Shader 2.0? You can refer to this wiki page to see if it does...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Regular expression to match (C) function calls Does anyone have a regular expression for matching function calls in C programs ?
A: Since C isn't a regular language and C function calls can contain arbitrary argument expressions, I fear the answer to your question is “no.”
A: After a bit more searching I decided to let the compiler do the hard work.
Get the compiler to produce a Register Transfer Language (RTL) file using the -dr options of gcc.
The produced RTL file has the suffix .rtl or .expand.
This file is far easier to parse as the functions calls are already identified.
A: I doubt you can find a regex that matches all (and only) the function calls in some source code. But maybe you could use a tool like Understand, or your IDE, to browse your code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Calling DLL functions from VB6 I've got a Windows DLL that I wrote, written in C/C++ (all exported functions are 'C'). The DLL works fine for me in VC++. I've given the DLL to another company who do all their development in VB. They seem to be having a problem linking to the functions. I haven't used VB in ten years and I don't even have it installed. What could be the problem?
I've declared all my public functions as follows:
#define MYDCC_API __declspec(dllexport)
MYDCCL_API unsigned long MYDCC_GetVer( void);
.
.
.
Any ideas?
Finally got back to this today and have it working. The answers put me on the right track but I found this most helpful:
http://www.codeproject.com/KB/DLL/XDllPt2.aspx
Also, I had a few problems passing strings to the DLL functions, I found this helpful:
http://www.flipcode.com/archives/Interfacing_Visual_Basic_And_C.shtml
A: By using __declspec for export, the function name will get exported mangled, i.e. contain type information to help the C++ compiler resolve overloads.
VB6 cannot handle mangled names. As a workaround, you have to de-mangle the names. The easiest solution is to link the DLL file using an export definition file in VC++. The export definition file is very simple and just contains the name of the DLL and a list of exported functions:
LIBRARY mylibname
EXPORTS
myfirstfunction
secondfunction
Additionally, you have to specify the stdcall calling convention because that's the only calling convention VB6 can handle. There's a project using assembly injection to handle C calls but I guess you don't want to use this difficult and error-prone method.
A: Try adding __stdcall at the end
#define MYDCC_API __declspec(dllexport) __stdcall
We have some C++ dlls that interact with our old VB6 apps and they all have that at the end.
A: A VB6 DLL is always a COM dll. I shall describe an example in as few words as possible. Suppose you have a ActiveX DLL project in VB6 with a class called CTest which contains a method as shown below
Public Function vbConcat(ByVal a As String, ByVal b As String) As String
vbConcat = a & b
End Function
and you have set the project name as VBTestLib in VB6 project properties and
you have compiled the project as F:\proj\VB6\ActiveXDLL\VBTestDLL.dll
You need to register the dll using the Windows command
regsvr32 F:\proj\VB6\ActiveXDLL\VBTestDLL.dll
now your C++ code :
#import "F:\proj\VB6\ActiveXDLL\VBTestDLL.dll"
using namespace VBTestLib;
void CDialogTestDlg::OnButton1()
{
HRESULT hresult;
CLSID clsid;
_CTest *t; // a pointer to the CTest object
_bstr_t bstrA = L"hello";
_bstr_t bstrB = L" world";
_bstr_t bstrR;
::CoInitialize(NULL);
hresult=CLSIDFromProgID(OLESTR("VBTestLib.CTest"), &clsid);
hresult= CoCreateInstance(clsid,NULL,CLSCTX_INPROC_SERVER,
__uuidof(_CTest),(LPVOID*) &t);
if(hresult == S_OK)
{
bstrR = t->vbConcat(bstrA , bstrB);
AfxMessageBox((char*)bstrR);
}
}
That's all there is to it, to get started off.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: raytracing with CUDA I'm currently implementing a raytracer. Since raytracing is extremely computation heavy and since I am going to be looking into CUDA programming anyway, I was wondering if anyone has any experience with combining the two. I can't really tell if the computational models match and I would like to know what to expect. I get the impression that it's not exactly a match made in heaven, but a decent speed increasy would be better than nothing.
A: It can certainly be done, has been done, and is a hot topic currently among the raytracing and Cuda gurus. I'd start by perusing http://www.nvidia.com/object/cuda_home.html
But it's basically a research problem. People who are doing it well are getting peer-reviewed research papers out of it. But well at this point still means that the best GPU/Cuda results are approximately competitive with best-of-class solutions on CPU/multi-core/SSE. So I think that it's a little early to assume that using Cuda is going to accelerate a ray tracer. The problem is that although ray tracing is "embarrassingly parallel" (as they say), it is not the kind of "fixed input and output size" problem that maps straightforwardly to GPUs -- you want trees, stacks, dynamic data structures, etc. It can be done with Cuda/GPU, but it's tricky.
Your question wasn't clear about your experience level or the goals of your project. If this is your first ray tracer and you're just trying to learn, I'd avoid Cuda -- it'll take you 10x longer to develop and you probably won't get good speed. If you're a moderately experienced Cuda programmer and are looking for a challenging project and ray tracing is just a fun thing to learn, by all means, try to do it in Cuda. If you're making a commercial app and you're looking to get a competitive speed edge -- well, it's probably a crap shoot at this point... you might get a performance edge, but at the expense of more difficult development and dependence on particular hardware.
Check back in a year, the answer may be different after another generation or two of GPU speed, Cuda compiler development, and research community experience.
A: One thing to be very wary of in CUDA is that divergent control flow in your kernel code absolutely KILLS performance, due to the structure of the underlying GPU hardware. GPUs typically have massively data-parallel workloads with highly-coherent control flow (i.e. you have a couple million pixels, each of which (or at least large swaths of which) will be operated on by the exact same shader program, even taking the same direction through all the branches. This enables them to make some hardware optimizations, like only having a single instruction cache, fetch unit, and decode logic for each group of 32 threads. In the ideal case, which is common in graphics, they can broadcast the same instruction to all 32 sets of execution units in the same cycle (this is known as SIMD, or Single-Instruction Multiple-Data). They can emulate MIMD (Multiple-Instruction) and SPMD (Single-Program), but when threads within a Streaming Multiprocessor (SM) diverge (take different code paths out of a branch), the issue logic actually switches between each code path on a cycle-by-cycle basis. You can imagine that, in the worst case, where all threads are on separate paths, your hardware utilization just went down by a factor of 32, effectively killing any benefit you would've had by running on a GPU over a CPU, particularly considering the overhead associated with marshalling the dataset from the CPU, over PCIe, to the GPU.
That said, ray-tracing, while data-parallel in some sense, has widely-diverging control flow for even modestly-complex scenes. Even if you manage to map a bunch of tightly-spaced rays that you cast out right next to each other onto the same SM, the data and instruction locality you have for the initial bounce won't hold for very long. For instance, imagine all 32 highly-coherent rays bouncing off a sphere. They will all go in fairly different directions after this bounce, and will probably hit objects made out of different materials, with different lighting conditions, and so forth. Every material and set of lighting, occlusion, etc. conditions has its own instruction stream associated with it (to compute refraction, reflection, absorption, etc.), and so it becomes quite difficult to run the same instruction stream on even a significant fraction of the threads in an SM. This problem, with the current state of the art in ray-tracing code, reduces your GPU utilization by a factor of 16-32, which may make performance unacceptable for your application, especially if it's real-time (e.g. a game). It still might be superior to a CPU for e.g. a render farm.
There is an emerging class of MIMD or SPMD accelerators being looked at now in the research community. I would look at these as logical platforms for software, real-time raytracing.
If you're interested in the algorithms involved and mapping them to code, check out POVRay. Also look into photon mapping, it's an interesting technique that even goes one step closer to representing physical reality than raytracing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How to get IntelliSense to reliably work in Visual Studio 2008 Does anyone know how to get IntelliSense to work reliably when working in C/C++ projects? It seems to work for about 1 in 10 files. Visual Studio 2005 seems to be a lot better than 2008.
Edit: Whilst not necessarily a solution, the work-around provided here:
How to get IntelliSense to reliably work in Visual Studio 2008
Is probably the best bet if I want a decent IntelliSense system.
A: It looks like there's hope on the horizon for those of us unable to obtain Visual Assist:
Rebuilding Intellisense
A: Do you have any add-ins installed (or uninstalled)? I find that effects my intellisense.
Besides that just making sure your Tools->Options->Text Editor->All Languages "Auto List Members" and "Parameter Information" are checked off.
A: Native C++ intellisense does not work reliably in any version of Visual Studio. I find there are two common problems:
1) Header file paths are not set-up correctly. When you find a type where intellisense is not working, use the IDE to click through each header file to find the one containing the type. (Right click on #include and select Open Document...). If this fails before you get to the file which declares the type then this is your problem. Make sure header file search paths are set-up correctly.
And,
2) The intellisense database is corrupt. This happens ALL The time. You need to close the solution, delete the .ncb file, and then reopen the solution. I posted the macro I use for this in answer to another question here.
The preprocessor can also confuse intellisense - so make sure any #defines during build are also available to intellisense. Other than that, I don't know what else can break it. I've not seen any particular issues with forward declarations.
A: I've also realized than Intellisense is sometime 'lost', on some big project. Why? No idea.
This is why we have bought Visual Assist (from Tomato software) and disabled Intellisense by deleting the dll feacp.dll in the Visual studio subdirectory (C:\Program Files\Microsoft Visual Studio 8\VC\vcpackages)
This is not a solution, just a workaround.
A:
I don't use VS2008 for C++, only VB & C#, but I find that when intellisense stops working (true for VS2003/2005/2008) it's because something in the project/file is broken - usually a bad reference or code.
VB and C# have much better intellisense support due to the ability to reflect on the referenced assemblies to build the intellisense tree.
C++ has to walk the include files for function prototypes, and if the paths are not correct it will not find all the prototype headers.
A: My fix to itellisense was required after that awful refactor utility minced my code. The problem was a class header file that included an #include of itself. The recursive reference destroys itellisense. A symptom of this is if itellisense can see other classes but not the current one. Also:
Use #pragma once to eliminate duplicate header loads
If the project now takes a very much longer time to load, that itellisense trying to make sense of the conflict that is causing then lack of completion support.
Often it is only one class object that is affected, This shows you what files (usually headers) to look at.
A: @John Richardson / @Jonathan Holland
My includes are setup correctly, no problems there. I've also tried the NCB rebuild several times but it never fixes it 100%.
I have a feeling it may be to do with forward declarations of classes. e.g. to reduce the complexity of includes in header files we normally do something like:
class MyPredeclared;
class SomeOtherClass
{
private:
MyPredeclared* m_pPointer;
}
I wonder if that screws it up? Any other ideas? It definitely gets worse the larger your project gets.
A: I had a very annoying problem, intellisense was working only in some files, without any evident reason... it took me a couple of hours of digging through google, but I finally understood that the reason was indeed recursive reference!
I was using the:
#ifndef CLASS_H
#define CLASS_H
...
#endif
to avoid redefinition of symbols, and this sometimes breaks intellisense in big projects.
But it is enough to comment the ifndef-define-endif and put a:
#pragma once
at the beginning of the header files to still avoid redefinitions and have Intellisense working again =)=)
At least, this worked for me, hope it's useful...
Cheers
Francesco
A: I have recently studied Intellisense in VS2008, as I'm developing a rather large C++ numerical linear algebra library where templates and such are used extensively. Intellisense stopped working shortly into the project and I sort of gave up, but now it became really annoying without it so I set to investigate. This is what I found out:
Assuming there is a file(s), containing code that "breaks" Intellisense,
*
*if header files that break Intellisense are in the project, but are not #included, it still works in the rest of the files
*if they are included, but no type declared inside is used, it still works
*if they are included and a type declared inside is used, it might still work a bit (no Intellisense for members, no Intellisense after occurrence of given type, but at least global names and argument info before)
*if Intellisense is broken in one .cpp file, it can still work in the others where the problematic code is not included or used (but i imagine if it crashes bad, it will get disabled for the whole project, although that did not happen to me)
*Intellisense seems to be updated after successful compilation (sometimes not before)
*putting broken code inside any of #if 0, /* .. */ or // seems to put Intellisense at ease
From the C++ features I used, actually only a few break Intellisense:
*
*comparison with '>' or '>=' in template parameter (e.g. static_assert<(size > 0)>)
*
*not solved by using double parentheses (static_assert<((size > 0))> does not help)
*solved by using '<' or '<=' instead (static_assert<0 < size> works)
*solved by storing the value in enum and using that to specialize the template
*explicit function template specialization disables argument info (e.g. function<type>(args))
*
*probably unable to solve (maybe wrap in a macro), but I can live with it being broken
*instantiation of template member type, such as Matrix::MakeMatrixType<3, 3>::Result r;
*
*kind of hard to figure out exactly why this happens (likely because of use of Eigen)
*workaround by moving such code in a separate .cpp where IS won't work (not always possible)
It would seem that some of those problems are due to some "simplified" parsing, which is less strong than a proper C++ parser. With the above information at hand, a "reliable" method of making Intellisense work in an existing code:
*
*Set up an empty project (a console app), create Main.cpp with dummy void main() {} in it.
*Include one of your broken header files, and math.h
*Build (it must compile, in order for Intellisense to update reliably)
*Test whether Intellisense is working by typing e.g. sin( and seeing if argument help pops up. Sometimes, this would work, but member help wouldn't - so try that as well.
*Make an instance of something in the header file, build, see if that manages to kill IS.
*Remove code from the culprit file and go to step 3
*After finding and fixing problematic code, put back code removed in step 5, try again
*After making a whole class work well, make an instance of the next class, and so on ...
I found it easy this way to pinpoint locations of code that made problems (I realize that this might be unfeasible for really large projects, in my case only a single file out of 97 made problems). Note that 'Build' here refers to compiling, the linking stage does not need to finish, so unresolved externals are ok, the IS should update regardless.
Another method of updating IS (other than building) is to save everything, close workspace, delete .ncb file and reopen it. Then wait for 'Updating Intellisense ... (N)' to disappear from the status bar (N counts towards zero, if it doesn't go all the way, it kind of shows progress where problems occurred). I found this rather tedious.
A: About this problem i've notice something interesting (on Visual Studio 2010):
to solve this problem i've changed #include sintax in my header files, before was (old project done with VS 2005 and reopened using VS 2010):
#include <myfile.h>
and i fix this with:
#include "myfile.h"
After intellisense start working correctly!
I hope this can help!
A: I had to reset the settings...
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE>devenv.exe /ResetSettings
thread on this here
A: The problem is with the .vcproj files.
You will find if you switch to release mode from debug mode, build, then try intellisense it often works.
Close Visual Studio. If you search for the .vcproj files in your project, edit them and search for the first two instances of AdditionalIncludeDirectories. The value for this should look something like "..\,....\" rather than "../..".
Reopen your project, let the Intellisense finish building, then it should be fixed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
} |
Q: Git "bad sha1 file" error Hello I have the following error by git-fsck, which cannot be cleaned by git-gc even in --aggressive mode. What can I do next to fix this repository error?
$ git-fsck
bad sha1 file: .git/objects/55/tmp_obj_a07724
A: It's not a simple answer, sadly. But this might help:
Recovering from repository corruption (from the Git's user manual).
A: Err... tmp_obj_a07724 suspiciously looks like a leftover temporary
file :)
What happens if you simply move it away from the .git directory
(after a backup of the whole thing)?
A: From man git-fsck:
Any corrupt objects you will have to find in backups or other archives
(i.e., you can just remove them and do an rsync with some other site in
the hopes that somebody else has the object you have corrupted).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: What is the yield keyword used for in C#? In the How Can I Expose Only a Fragment of IList<> question one of the answers had the following code snippet:
IEnumerable<object> FilteredList()
{
foreach(object item in FullList)
{
if(IsItemInPartialList(item))
yield return item;
}
}
What does the yield keyword do there? I've seen it referenced in a couple places, and one other question, but I haven't quite figured out what it actually does. I'm used to thinking of yield in the sense of one thread yielding to another, but that doesn't seem relevant here.
A: The yield contextual keyword actually does quite a lot here.
The function returns an object that implements the IEnumerable<object> interface. If a calling function starts foreaching over this object, the function is called again until it "yields". This is syntactic sugar introduced in C# 2.0. In earlier versions you had to create your own IEnumerable and IEnumerator objects to do stuff like this.
The easiest way understand code like this is to type-in an example, set some breakpoints and see what happens. Try stepping through this example:
public void Consumer()
{
foreach(int i in Integers())
{
Console.WriteLine(i.ToString());
}
}
public IEnumerable<int> Integers()
{
yield return 1;
yield return 2;
yield return 4;
yield return 8;
yield return 16;
yield return 16777216;
}
When you step through the example, you'll find the first call to Integers() returns 1. The second call returns 2 and the line yield return 1 is not executed again.
Here is a real-life example:
public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> make, params object[] parms)
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(CommandType.Text, sql, connection, parms))
{
command.CommandTimeout = dataBaseSettings.ReadCommandTimeout;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return make(reader);
}
}
}
}
}
A: It's producing enumerable sequence. What it does is actually creating local IEnumerable sequence and returning it as a method result
A: A list or array implementation loads all of the items immediately whereas the yield implementation provides a deferred execution solution.
In practice, it is often desirable to perform the minimum amount of work as needed in order to reduce the resource consumption of an application.
For example, we may have an application that process millions of records from a database. The following benefits can be achieved when we use IEnumerable in a deferred execution pull-based model:
*
*Scalability, reliability and predictability are likely to improve since the number of records does not significantly affect the application’s resource requirements.
*Performance and responsiveness are likely to improve since processing can start immediately instead of waiting for the entire collection to be loaded first.
*Recoverability and utilisation are likely to improve since the application can be stopped, started, interrupted or fail. Only the items in progress will be lost compared to pre-fetching all of the data where only using a portion of the results was actually used.
*Continuous processing is possible in environments where constant workload streams are added.
Here is a comparison between build a collection first such as a list compared to using yield.
List Example
public class ContactListStore : IStore<ContactModel>
{
public IEnumerable<ContactModel> GetEnumerator()
{
var contacts = new List<ContactModel>();
Console.WriteLine("ContactListStore: Creating contact 1");
contacts.Add(new ContactModel() { FirstName = "Bob", LastName = "Blue" });
Console.WriteLine("ContactListStore: Creating contact 2");
contacts.Add(new ContactModel() { FirstName = "Jim", LastName = "Green" });
Console.WriteLine("ContactListStore: Creating contact 3");
contacts.Add(new ContactModel() { FirstName = "Susan", LastName = "Orange" });
return contacts;
}
}
static void Main(string[] args)
{
var store = new ContactListStore();
var contacts = store.GetEnumerator();
Console.WriteLine("Ready to iterate through the collection.");
Console.ReadLine();
}
Console Output
ContactListStore: Creating contact 1
ContactListStore: Creating contact 2
ContactListStore: Creating contact 3
Ready to iterate through the collection.
Note: The entire collection was loaded into memory without even asking for a single item in the list
Yield Example
public class ContactYieldStore : IStore<ContactModel>
{
public IEnumerable<ContactModel> GetEnumerator()
{
Console.WriteLine("ContactYieldStore: Creating contact 1");
yield return new ContactModel() { FirstName = "Bob", LastName = "Blue" };
Console.WriteLine("ContactYieldStore: Creating contact 2");
yield return new ContactModel() { FirstName = "Jim", LastName = "Green" };
Console.WriteLine("ContactYieldStore: Creating contact 3");
yield return new ContactModel() { FirstName = "Susan", LastName = "Orange" };
}
}
static void Main(string[] args)
{
var store = new ContactYieldStore();
var contacts = store.GetEnumerator();
Console.WriteLine("Ready to iterate through the collection.");
Console.ReadLine();
}
Console Output
Ready to iterate through the collection.
Note: The collection wasn't executed at all. This is due to the "deferred execution" nature of IEnumerable. Constructing an item will only occur when it is really required.
Let's call the collection again and obverse the behaviour when we fetch the first contact in the collection.
static void Main(string[] args)
{
var store = new ContactYieldStore();
var contacts = store.GetEnumerator();
Console.WriteLine("Ready to iterate through the collection");
Console.WriteLine("Hello {0}", contacts.First().FirstName);
Console.ReadLine();
}
Console Output
Ready to iterate through the collection
ContactYieldStore: Creating contact 1
Hello Bob
Nice! Only the first contact was constructed when the client "pulled" the item out of the collection.
A: This link has a simple example
Even simpler examples are here
public static IEnumerable<int> testYieldb()
{
for(int i=0;i<3;i++) yield return 4;
}
Notice that yield return won't return from the method. You can even put a WriteLine after the yield return
The above produces an IEnumerable of 4 ints 4,4,4,4
Here with a WriteLine. Will add 4 to the list, print abc, then add 4 to the list, then complete the method and so really return from the method(once the method has completed, as would happen with a procedure without a return). But this would have a value, an IEnumerable list of ints, that it returns on completion.
public static IEnumerable<int> testYieldb()
{
yield return 4;
console.WriteLine("abc");
yield return 4;
}
Notice also that when you use yield, what you are returning is not of the same type as the function. It's of the type of an element within the IEnumerable list.
You use yield with the method's return type as IEnumerable. If the method's return type is int or List<int> and you use yield, then it won't compile. You can use IEnumerable method return type without yield but it seems maybe you can't use yield without IEnumerable method return type.
And to get it to execute you have to call it in a special way.
static void Main(string[] args)
{
testA();
Console.Write("try again. the above won't execute any of the function!\n");
foreach (var x in testA()) { }
Console.ReadLine();
}
// static List<int> testA()
static IEnumerable<int> testA()
{
Console.WriteLine("asdfa");
yield return 1;
Console.WriteLine("asdf");
}
A: yield return is used with enumerators. On each call of yield statement, control is returned to the caller but it ensures that the callee's state is maintained. Due to this, when the caller enumerates the next element, it continues execution in the callee method from statement immediately after the yield statement.
Let us try to understand this with an example. In this example, corresponding to each line I have mentioned the order in which execution flows.
static void Main(string[] args)
{
foreach (int fib in Fibs(6))//1, 5
{
Console.WriteLine(fib + " ");//4, 10
}
}
static IEnumerable<int> Fibs(int fibCount)
{
for (int i = 0, prevFib = 0, currFib = 1; i < fibCount; i++)//2
{
yield return prevFib;//3, 9
int newFib = prevFib + currFib;//6
prevFib = currFib;//7
currFib = newFib;//8
}
}
Also, the state is maintained for each enumeration. Suppose, I have another call to Fibs() method then the state will be reset for it.
A: Iteration. It creates a state machine "under the covers" that remembers where you were on each additional cycle of the function and picks up from there.
A: Intuitively, the keyword returns a value from the function without leaving it, i.e. in your code example it returns the current item value and then resumes the loop. More formally, it is used by the compiler to generate code for an iterator. Iterators are functions that return IEnumerable objects. The MSDN has several articles about them.
A: If I understand this correctly, here's how I would phrase this from the perspective of the function implementing IEnumerable with yield.
*
*Here's one.
*Call again if you need another.
*I'll remember what I already gave you.
*I'll only know if I can give you another when you call again.
A: Here is a simple way to understand the concept:
The basic idea is, if you want a collection that you can use "foreach" on, but gathering the items into the collection is expensive for some reason (like querying them out of a database), AND you will often not need the entire collection, then you create a function that builds the collection one item at a time and yields it back to the consumer (who can then terminate the collection effort early).
Think of it this way: You go to the meat counter and want to buy a pound of sliced ham. The butcher takes a 10-pound ham to the back, puts it on the slicer machine, slices the whole thing, then brings the pile of slices back to you and measures out a pound of it. (OLD way).
With yield, the butcher brings the slicer machine to the counter, and starts slicing and "yielding" each slice onto the scale until it measures 1-pound, then wraps it for you and you're done. The Old Way may be better for the butcher (lets him organize his machinery the way he likes), but the New Way is clearly more efficient in most cases for the consumer.
A: Nowadays you can use the yield keyword for async streams.
C# 8.0 introduces async streams, which model a streaming source of data. Data streams often retrieve or generate elements asynchronously. Async streams rely on new interfaces introduced in .NET Standard 2.1. These interfaces are supported in .NET Core 3.0 and later. They provide a natural programming model for asynchronous streaming data sources.
Source: Microsoft docs
Example below
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
List<int> numbers = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
await foreach(int number in YieldReturnNumbers(numbers))
{
Console.WriteLine(number);
}
}
public static async IAsyncEnumerable<int> YieldReturnNumbers(List<int> numbers)
{
foreach (int number in numbers)
{
await Task.Delay(1000);
yield return number;
}
}
}
A: The yield keyword allows you to create an IEnumerable<T> in the form on an iterator block. This iterator block supports deferred executing and if you are not familiar with the concept it may appear almost magical. However, at the end of the day it is just code that executes without any weird tricks.
An iterator block can be described as syntactic sugar where the compiler generates a state machine that keeps track of how far the enumeration of the enumerable has progressed. To enumerate an enumerable, you often use a foreach loop. However, a foreach loop is also syntactic sugar. So you are two abstractions removed from the real code which is why it initially might be hard to understand how it all works together.
Assume that you have a very simple iterator block:
IEnumerable<int> IteratorBlock()
{
Console.WriteLine("Begin");
yield return 1;
Console.WriteLine("After 1");
yield return 2;
Console.WriteLine("After 2");
yield return 42;
Console.WriteLine("End");
}
Real iterator blocks often have conditions and loops but when you check the conditions and unroll the loops they still end up as yield statements interleaved with other code.
To enumerate the iterator block a foreach loop is used:
foreach (var i in IteratorBlock())
Console.WriteLine(i);
Here is the output (no surprises here):
Begin
1
After 1
2
After 2
42
End
As stated above foreach is syntactic sugar:
IEnumerator<int> enumerator = null;
try
{
enumerator = IteratorBlock().GetEnumerator();
while (enumerator.MoveNext())
{
var i = enumerator.Current;
Console.WriteLine(i);
}
}
finally
{
enumerator?.Dispose();
}
In an attempt to untangle this I have crated a sequence diagram with the abstractions removed:
The state machine generated by the compiler also implements the enumerator but to make the diagram more clear I have shown them as separate instances. (When the state machine is enumerated from another thread you do actually get separate instances but that detail is not important here.)
Every time you call your iterator block a new instance of the state machine is created. However, none of your code in the iterator block is executed until enumerator.MoveNext() executes for the first time. This is how deferred executing works. Here is a (rather silly) example:
var evenNumbers = IteratorBlock().Where(i => i%2 == 0);
At this point the iterator has not executed. The Where clause creates a new IEnumerable<T> that wraps the IEnumerable<T> returned by IteratorBlock but this enumerable has yet to be enumerated. This happens when you execute a foreach loop:
foreach (var evenNumber in evenNumbers)
Console.WriteLine(eventNumber);
If you enumerate the enumerable twice then a new instance of the state machine is created each time and your iterator block will execute the same code twice.
Notice that LINQ methods like ToList(), ToArray(), First(), Count() etc. will use a foreach loop to enumerate the enumerable. For instance ToList() will enumerate all elements of the enumerable and store them in a list. You can now access the list to get all elements of the enumerable without the iterator block executing again. There is a trade-off between using CPU to produce the elements of the enumerable multiple times and memory to store the elements of the enumeration to access them multiple times when using methods like ToList().
A: Yield has two great uses,
*
*It helps to provide custom iteration without creating temp collections.
*It helps to do stateful iteration.
In order to explain above two points more demonstratively, I have created a simple video you can watch it here
A: One major point about Yield keyword is Lazy Execution. Now what I mean by Lazy Execution is to execute when needed. A better way to put it is by giving an example
Example: Not using Yield i.e. No Lazy Execution.
public static IEnumerable<int> CreateCollectionWithList()
{
var list = new List<int>();
list.Add(10);
list.Add(0);
list.Add(1);
list.Add(2);
list.Add(20);
return list;
}
Example: using Yield i.e. Lazy Execution.
public static IEnumerable<int> CreateCollectionWithYield()
{
yield return 10;
for (int i = 0; i < 3; i++)
{
yield return i;
}
yield return 20;
}
Now when I call both methods.
var listItems = CreateCollectionWithList();
var yieldedItems = CreateCollectionWithYield();
you will notice listItems will have a 5 items inside it (hover your mouse on listItems while debugging).
Whereas yieldItems will just have a reference to the method and not the items.
That means it has not executed the process of getting items inside the method. A very efficient way of getting data only when needed.
Actual implementation of yield can be seen in ORM like Entity Framework and NHibernate etc.
A: Recently Raymond Chen also ran an interesting series of articles on the yield keyword.
*
*The implementation of iterators in C# and its consequences (part 1)
*The implementation of iterators in C# and its consequences (part 2)
*The implementation of iterators in C# and its consequences (part 3)
*The implementation of iterators in C# and its consequences (part 4)
While it's nominally used for easily implementing an iterator pattern, but can be generalized into a state machine. No point in quoting Raymond, the last part also links to other uses (but the example in Entin's blog is esp good, showing how to write async safe code).
A: The C# yield keyword, to put it simply, allows many calls to a body of code, referred to as an iterator, that knows how to return before it's done and, when called again, continues where it left off - i.e. it helps an iterator become transparently stateful per each item in a sequence that the iterator returns in successive calls.
In JavaScript, the same concept is called Generators.
A: At first sight, yield return is a .NET sugar to return an IEnumerable.
Without yield, all the items of the collection are created at once:
class SomeData
{
public SomeData() { }
static public IEnumerable<SomeData> CreateSomeDatas()
{
return new List<SomeData> {
new SomeData(),
new SomeData(),
new SomeData()
};
}
}
Same code using yield, it returns item by item:
class SomeData
{
public SomeData() { }
static public IEnumerable<SomeData> CreateSomeDatas()
{
yield return new SomeData();
yield return new SomeData();
yield return new SomeData();
}
}
The advantage of using yield is that if the function consuming your data simply needs the first item of the collection, the rest of the items won't be created.
The yield operator allows the creation of items as it is demanded. That's a good reason to use it.
A: It is a very simple and easy way to create an enumerable for your object. The compiler creates a class that wraps your method and that implements, in this case, IEnumerable<object>. Without the yield keyword, you'd have to create an object that implements IEnumerable<object>.
A: It's trying to bring in some Ruby Goodness :)
Concept: This is some sample Ruby Code that prints out each element of the array
rubyArray = [1,2,3,4,5,6,7,8,9,10]
rubyArray.each{|x|
puts x # do whatever with x
}
The Array's each method implementation yields control over to the caller (the 'puts x') with each element of the array neatly presented as x. The caller can then do whatever it needs to do with x.
However .Net doesn't go all the way here.. C# seems to have coupled yield with IEnumerable, in a way forcing you to write a foreach loop in the caller as seen in Mendelt's response. Little less elegant.
//calling code
foreach(int i in obCustomClass.Each())
{
Console.WriteLine(i.ToString());
}
// CustomClass implementation
private int[] data = {1,2,3,4,5,6,7,8,9,10};
public IEnumerable<int> Each()
{
for(int iLooper=0; iLooper<data.Length; ++iLooper)
yield return data[iLooper];
}
A: Simple demo to understand yield
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp_demo_yield {
class Program
{
static void Main(string[] args)
{
var letters = new List<string>() { "a1", "b1", "c2", "d2" };
// Not yield
var test1 = GetNotYield(letters);
foreach (var t in test1)
{
Console.WriteLine(t);
}
// yield
var test2 = GetWithYield(letters).ToList();
foreach (var t in test2)
{
Console.WriteLine(t);
}
Console.ReadKey();
}
private static IList<string> GetNotYield(IList<string> list)
{
var temp = new List<string>();
foreach(var x in list)
{
if (x.Contains("2")) {
temp.Add(x);
}
}
return temp;
}
private static IEnumerable<string> GetWithYield(IList<string> list)
{
foreach (var x in list)
{
if (x.Contains("2"))
{
yield return x;
}
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1015"
} |
Q: Software Phase Locked Loop example code needed Does anyone know of anywhere I can find actual code examples of Software Phase Locked Loops (SPLLs) ?
I need an SPLL that can track a PSK modulated signal that is somewhere between 1.1 KHz and 1.3 KHz. A Google search brings up plenty of academic papers and patents but nothing usable. Even a trip to the University library that contains a shelf full of books on hardware PLL's there was only a single chapter in one book on SPLLs and that was more theoretical than practical.
Thanks for your time.
Ian
A:
This is an interactive design package
for designing digital (i.e. software)
phase locked loops (PLLs). Fill in the
form and press the ``Submit'' button,
and a PLL will be designed for you.
Interactive Digital Phase Locked Loop Design
This will get you started, but you really need to understand the fundamentals of PLL design well enough to build it yourself in order to troubleshoot it later - This is the realm of digital signal processing, and while not black magic it will certainly give you a run for your money during debugging.
-Adam
A: I suppose this is probably too late to help you (what did you end up doing?) but it may help the next guy.
Here's a golfed example of a software phase-locked loop I just wrote in one line of C, which will sing along with you:
main(a,b){for(;;)a+=((b+=16+a/1024)&256?1:-1)*getchar()-a/512,putchar(b);}
I present this tiny golfed version first in order to convince you that software phase-locked loops are actually fairly simple, as software goes, although they can be tricky.
If you feed it 8-bit linear samples on stdin, it will produce 8-bit samples of a sawtooth wave attempting to track one octave higher on stdout. At 8000 samples per second, it tracks frequencies in the neighborhood of 250Hz, just above B below middle C. On Linux you can do this by typing arecord | ./pll | aplay. The low 9 bits of b are the oscillator (what might be a VCO in a hardware implementation), which generates a square wave (the 1 or -1) which gets multiplied by the input waveform (getchar()) to produce the output of the phase detector. That output is then low-pass filtered into a to produce the smoothed phase error signal which is used to adjust the oscillation frequency of b to push a toward 0. The natural frequency of the square wave, when a == 0, is for b to increment by 16 every sample, which increments it by 512 (a full cycle) every 32 samples. 32 samples at 8000 samples per second are 1/250 of a second, which is why the natural frequency is 250Hz.
Then putchar() takes the low 8 bits of b, which make up a sawtooth wave at 500Hz or so, and spews them out as the output audio stream.
There are several things missing from this simple example:
*
*It has no good way to detect lock. If you have silence, noise, or a strong pure 250Hz input tone, a will be roughly zero and b will be oscillating at its default frequency. Depending on your application, you might want to know whether you've found a signal or not! Camenzind's suggestion in chapter 12 of Designing Analog Chips is to feed a second "phase detector" 90° out of phase from the real phase detector; its smoothed output gives you the amplitude of the signal you've theoretically locked onto.
*The natural frequency of the oscillator is fixed and does not sweep. The capture range of a PLL, the interval of frequencies within which it will notice an oscillation if it's not currently locked onto one, is pretty narrow; its lock range, over which it will will range in order to follow the signal once it's locked on, is much larger. Because of this, it's common to sweep the PLL's frequency all over the range where you expect to find a signal until you get a lock, and then stop sweeping.
The golfed version above is reduced from a much more readable example of a software phase-locked loop in C that I wrote today, which does do lock detection but does not sweep. It needs about 100 CPU cycles per input sample per PLL on the Atom CPU in my netbook.
I think that if I were in your situation, I would do the following (aside from obvious things like looking for someone who knows more about signal processing than I do, and generating test data). I probably wouldn't filter and downconvert the signal in a front end, since it's at such a low frequency already. Downconverting to a 200Hz-400Hz band hardly seems necessary. I suspect that PSK will bring up some new problems, since if the signal suddenly shifts phase by 90° or more, you lose the phase lock; but I suspect those problems will be easy to resolve, and it's hardly untrodden territory.
A: Have Matlab with Simulink? There are PLL demo files available at Matlab Central here. Matlab's code generation capabilities might get you from there to a PLL written in C.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Modifying the MBR of Windows I need to modify the MBR of Windows, and I would really like to do this from Windows.
Here are my questions. I know that I can get a handle on a physical device with a call to CreateFile. Will the MBR always be on \\.\PHYSICALDRIVE0? Also, I'm still learning the Windows API to read directly from the disk. Is readabsolutesectors and writeabsolutesectdors the two functions I'm going to need to use to read/write to the disk sectors which contain the MBR?
Edit from from what I've learned on my own.
The MBR will not always be on \\.\PHYSICALDRIVE0. Also, you can write to the bootsector (at least as Administrator on XP) by call CreateFile with the device name of the drive that contains the MBR. Also, you can write to this drive by simply calling WriteFile and passing the handle of the device created by calling CreateFile.
Edit to address Joel Coehoorn.
I need to edit the MBR because I'm working on a project that needs to modify hardware registers after POST in BIOS, but before Windows will be allowed to boot. Our plan is to make these changes by modifying the bootloader to execute our code before Windows boots up.
Edit for Cd-MaN.
Thanks for the info. There isn't anything in your answer, though, that I didn't know and your answer doesn't address my question. The registry in particular absolutely will not do what we need for multiple reasons. The big reason being that Windows is the highest layer among multiple software layers that will be running with our product. These changes need to occur even before the lower levels run, and so the registry won't work.
P.S. for Cd-MaN.
As I understand it, the information you give isn't quite correct. For Vista, I think you can write to a volume if the sectors being written to are boot sectors. See http://support.microsoft.com/kb/942448
A: Once the OS is started the MBR is typically protected for virus reasons - this is one of the oldest virus tricks in the books - goes back to passing viruses from floppy to floppy.
Even if it wasn't restricted, you have to write low level code - it isn't part of the file system, but exists on a specific location on the hard drive.
Due to that, you pretty much are restricted to writing low level (most programs implement this in assembly) or C code targeting 16 bit DOS.
Most of these programs use the BIOS interface (13h, I believe) to access the sectors of the disk directly. You can access these in C using some inline assembly, or compiler provided interfaces. You will generally not get access to BIOS without the cooperation of the OS, though, so your program, again, will be restricted to DOS. If you can access these you're almost home free - the nice thing about BIOS is you don't have to worry about what type of HD is in the system - even RAID cards often insert themselves into the BIOS routines so they can be accessed without knowing where in memory the ATA or SATA controller is, and executing commands on that low level.
If you absolutely must access it within an OS, though, you pretty much have to write a device driver to access the BIOS or the memory space where the HD controllers exist. I wouldn't recommend it, though, as this is very tricky to deal with - modern computers put the HD controllers in different spots in memory, with different IRQs, and each chipset has become a little more esoteric because they can provide a minimum interface to bios for bootup, and then a specific driver for Windows. They skip all the other interface niceties that would be considered compatible with other controllers because it's more expensive to be compatible.
You may find that at the driver level inside windows you'll have methods for accessing the drive sectors directly (or pseudo directly), but again, they are likely very well protected due to the aforementioned virus issues.
Good luck!
A: Modifying the bootloader is bad, bad idea. Here are just a few of the possible gotcha's:
*
*it will potentially kill full disk encryption products (Truecrypt, PGP, Vista's BitLocker, etc)
*it will potentially trip up AV products (scaring users)
*it will potentially kill complicated booting scenarios (chained boot loaders, etc)
*it will kill off the chain of trust when using the TPM module (because it checks the MBR for change before executing it)
*direct disk access is not allowed starting from Vista (only using drivers)
Alternatives (like modifying the hardware register during the Windows bootup via a driver which is set to load at boot time or after Windows has booted) should really be considered. If the modification is as simple as writing to a port, ie:
OUT AX, BL
then drivers exists for all versions of Window which can do this (reading/writing a value from/to a certain port) which can be called from user mode.
A: Maybe a PXE boot scenario could help you? Simply boot on your crafted PXE image which modify the hardware registers you need to modify, and then return the control to the Master Boot Record or to the active partition's boot record.
This way you don't have to modify the boot records.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Languages other than SQL in postgres I've been using PostgreSQL a little bit lately, and one of the things that I think is cool is that you can use languages other than SQL for scripting functions and whatnot. But when is this actually useful?
For example, the documentation says that the main use for PL/Perl is that it's pretty good at text manipulation. But isn't that more of something that should be programmed into the application?
Secondly, is there any valid reason to use an untrusted language? It seems like making it so that any user can execute any operation would be a bad idea on a production system.
PS. Bonus points if someone can make PL/LOLCODE seem useful.
A: @Mike: this kind of thinking makes me nervous. I've heard to many times "this should be infinitely portable", but when the question is asked: do you actually foresee that there will be any porting? the answer is: no.
Sticking to the lowest common denominator can really hurt performance, as can the introduction of abstraction layers (ORM's, PHP PDO, etc). My opinion is:
*
*Evaluate realistically if there is a need to support multiple RDBMS's. For example if you are writing an open source web application, chances are that you need to support MySQL and PostgreSQL at least (if not MSSQL and Oracle)
*After the evaluation, make the most of the platform you decided upon
And BTW: you are mixing relational with non-relation databases (CouchDB is not a RDBMS comparable with Oracle for example), further exemplifying the point that the perceived need for portability is many times greatly overestimated.
A: "isn't that [text manipulation] more of something that should be programmed into the application?"
Usually, yes. The generally accepted "three-tier" application design for databases says that your logic should be in the middle tier, between the client and the database. However, sometimes you need some logic in a trigger or need to index on a function, requiring that some code be placed into the database. In that case all the usual "which language should I use?" questions come up.
If you only need a little logic, the most-portable language should probably be used (pl/pgSQL). If you need to do some serious programming though, you might be better off using a more expressive language (maybe pl/ruby). This will always be a judgment call.
"is there any valid reason to use an untrusted language?"
As above, yes. Again, putting direct file access (for example) into your middle tier is best when possible, but if you need to fire things off based on triggers (that might need access to data not available directly to your middle tier), then you need untrusted languages. It's not ideal, and should generally be avoided. And you definitely need to guard access to it.
A: These days, any "unique" or "cool" feature in a DBMS makes me incredibly nervous. I break out in a rash and have to stop work until the itching goes away.
I just hate to be locked in to a platform unnecessarily. Suppose you build a big chunk of your system in PL/Perl inside the database. Or in C# within SQL Server, or PL/SQL within Oracle, there are plenty of examples*.
Now you suddenly discover that your chosen platform doesn't scale. Or isn't fast enough. Or something. Worse, there's a new kid on the database block (something like MonetDB, CouchDB, Cache, say but much cooler) that would solve all your problems (even if your only problem, like mine, is having an uncool databse platform). And you can't switch to it without recoding half your application.
(*Admittedly, the paid-for products are to some extent seeking to lock you in by persuading you to use their unique features, which is not an accusation that can directly be levelled at the free providers, but the effect is the same).
So that's a rant on the first part of the question. Heart-felt, though.
is there any valid reason to use an
untrusted language? It seems like
making it so that any user can execute
any operation would be a bad idea
My goodness, yes it does! A sort of "Perl injection attack"? Almost worth doing it just to see what happens, I'd have thought.
For philosophical reasons outlined above I think I'll pass on the PL/LOLCODE challenge. Although I was somewhat amazed to discover it was a link to something extant.
A: From my perspective, I guess the answer is 'it depends'.
There is an argument that manipulation of the data belongs in the database layer, so that the business logic does not need to be overly concerned about how the manipulation happens, it just knows that it has.
Another very good reason to process data on the db layer is if the volume of data being crunched means that network bandwidth will become an issue. I once had to categorise very large amounts of data. Processing this in the application layer was severly restricted by the time required to transfer all the data across the network for processing.
I then wrote a binning algorithm in PL/pgSQL and it worked much faster.
Regarding untrusted languages, I heard a podcast from Josh Berkus (a postgres advocate) who discussed an application of postgresql that brought in data from MySQL as part of its processing, so that the communication itself was handled by the postgres server. I don't remember the full details, I think it was on the FLOSS Weekly podcast which is quite an interesting discussion of the history of PostGRESQL and some of the issues it is put to.
A: The untrusted versions of the procedural languages allow you to access I/O on the system.
This can come in handy if you need a trigger or something send a email or connect to a socket server to send a popup notification. There are tons of uses for this type of thing, and because of postgresql isolation levels you cans safely do things like this.
You can put checkpoints in the function so if the transaction fails the email or whatever won't go out. The nice thing about doing this is it removes the logic from the client and puts it on the server.
A: I think most additional languages are offered so that if you develop in that language on a regular basis, you can feel comfortable writing db functions, triggers, etc. The usefulness of these features is to provide a control over data as close to the data as possible.
A: An example of a useful stored procedure I recently wrote in an external language that would not have been possible in pl/sql is a version of 'df' which allowed SQL table generators to pick a tablespace with the most free space available at runtime.
I used plperlu, and it was relatively simple, although I had to be careful with data typing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Error handling / error logging in C++ for library/app combo I've encountered the following problem pattern frequently over the years:
*
*I'm writing complex code for a package comprised of a standalone application and also a library version of the core that people can use from inside other apps.
*Both our own app and presumably ones that users create with the core library are likely to be run both in batch mode (off-line, scripted, remote, and/or from command line), as well as interactively.
*The library/app takes complex and large runtime input and there may be a variety of error-like outputs including severe error messages, input syntax warnings, status messages, and run statistics. Note that these are all incidental outputs, not the primary purpose of the application which would be displayed or saved elsewhere and using different methods.
*Some of these (probably only the very severe ones) might require a dialog box if run interactively; but it needs to log without stalling for user input if run in batch mode; and if run as a library the client program obviously wants to intercept and/or examine the errors as they occur.
*It all needs to be cross-platform: Linux, Windows, OSX. And we want the solution to not be weird on any platform. For example, output to stderr is fine for Linux, but won't work on Windows when linked to a GUI app.
*Client programs of the library may create multiple instances of the main class, and it would be nice if the client app could distinguish a separate error stream with each instance.
*Let's assume everybody agrees it's good enough for the library methods to log errors via a simple call (error code and/or severity, then printf-like arguments giving an error message). The contentious part is how this is recorded or retrieved by the client app.
I've done this many times over the years, and am never fully satisfied with the solution. Furthermore, it's the kind of subproblem that's actually not very important to users (they want to see the error log if something goes wrong, but they don't really care about our technique for implementing it), but the topic gets the programmers fired up and they invariably waste inordinate time on this detail and are never quite happy.
Anybody have any wisdom for how to integrate this functionality into a C++ API, or is there an accepted paradigm or a good open source solution (not GPL, please, I'd like a solution I can use in commercial closed apps as well as OSS projects)?
A: We use Apache's Log4cxx for logging which isn't perfect, but provides a lot of infrastructure and a consistent approach across projects. I believe it is cross-platform, though we only use it on Windows.
It provides for run time configuration via an ini file which allows you to control how the log file is output, and you could write your own appenders if you want specific behaviour (e.g. an error dialog under the UI).
If clients of your library also adopt it then it would integrate their logging output into the same log file(s).
Differentiation between instances of the main class could be supported using the nested diagnostic context (NDC) feature.
A: Log4Cxx should work for you. You need to implement a provider that allows the library user to catch the log output in callbacks. The library would export a function to install the callbacks. That function should, behind the scenes, reconfigure log4cxxx to get rid of all appenders and set up the "custom" appender.
Of course, the library user has an option to not install the callbacks and use log4cxx as is.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to identify that you're running under a VM? Is there a way to identify, from within a VM, that your code is running inside a VM?
I guess there are more or less easy ways to identify specific VM systems, especially if the VM has the provider's extensions installed (such as for VirtualBox or VMWare). But is there a general way to identify that you are not running directly on the CPU?
A: A more empirical approach is to check for known VM device drivers. You could write WMI queries to locate, say, the VMware display adapter, disk drive, network adapter, etc. This would be suitable if you knew you only had to worry about known VM host types in your environment. Here's an example of doing this in Perl, which could be ported to the language of your choice.
A: In most cases, you shouldn't try to. You shouldn't care if someone is running your code in a VM, except in a few specific cases.
If you need to, in Linux the most common way is to look at /sys/devices/virtual/dmi/id/product_name, which will list the name of the laptop/mainboard on most real systems, and the hypervisor on most virtual systems. dmidecode | grep Product is another common method, but I think that requires root access.
A: It depends on what you are after:
*
*If the VM is not hiding from you on purpose, you can use some known hook. LIke looking for VmWare drivers or the presence of certain strings in memory or certain other tell-tale signs.
*If the VM is really wanting you to do special things for it, it will have some obvious hook in place, like modifying the ID of the processor or adding some special registers that you can access to detect it. Or s a special device in a known location in memory (presuming you can get raw access to the physical memory space of your world). NOte that modern machine designs like the IBM Power6 and Sun UltraSparc T1/T2 are designed to ALWAYS run a hypervisor, and never directly on raw hardware. The interface to the "hardware" that an OS uses is in fact the interface ot a hypervisor software layer, with no way to get around it. In this case, detection is trivial since it is a constant "yes". This is the likely future direction for all computer systems that can afford the overhead, look at the support in recent designs like the Freescale QorIQ P4080 chip, for example (www.freescale.com/qoriq).
*If the VM is intentionally trying to hide, and you are chasing its presence, it is a game of cat-and-mouse where the timing disturbance and different performance profile of a VM is almost always going to give it away. Obviously, this depends on how the VM is implemented and how much hardware support there is in place in the architecture (I think a zSeries mainframe is much better at hiding the presence of a VM or stack of VMs under your particular OS than a regular x86 machine is, for example). See http://jakob.engbloms.se/archives/97 for some discussion on this topic. It is possible to try to hide as a VM, but detection is quite likely to always win if it tries hard enough.
A: I once ran across an assembly code snippet that told you if you were in a VM....I googled but couldn't find the original article.
I did find this though: Detect if your program is running inside a Virtual Machine.
Hope it helps.
A: Here is a (java + windows) solution to identify whether underlying machine is physical or virtual.
Virtual Machines Examples:
Manufacturer
*
*Xen
*Microsoft Corporation
*innotek GmbH
*Red Hat
*VMware, Inc.
Model
*
*HVM domU
*Virtual Machine
*VirtualBox
*KVM
*VMware Virtual Platform
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public abstract class OSUtil {
public static final List<String> readCmdOutput(String command) {
List<String> result = new ArrayList<>();
try {
Process p=Runtime.getRuntime().exec("cmd /c " + command);
p.waitFor();
BufferedReader reader=new BufferedReader(
new InputStreamReader(p.getInputStream())
);
String line;
while((line = reader.readLine()) != null) {
if(line != null && !line.trim().isEmpty()) {
result.add(line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static final String readCmdOutput(String command, int lineNumber) {
List<String> result = readCmdOutput(command);
if(result.size() < lineNumber) {
return null;
}
return result.get(lineNumber - 1);
}
public static final String getBiosSerial() {
return readCmdOutput("WMIC BIOS GET SERIALNUMBER", 2);
}
public static final String getHardwareModel() {
return readCmdOutput("WMIC COMPUTERSYSTEM GET MODEL", 2);
}
public static final String getHardwareManufacturer() {
return readCmdOutput("WMIC COMPUTERSYSTEM GET MANUFACTURER", 2);
}
public static void main(String[] args) {
System.out.println("BIOS Serial: " + getBiosSerial());
System.out.println("Hardware Model: " + getHardwareModel());
System.out.println("Hardware Manufacturer: " + getHardwareManufacturer());
}
}
You can use the output to decide whether it is a VM or a physical machine:
Physical machine output:
BIOS Serial: 2HC3J12
Hardware Model: Inspiron 7570
Hardware Manufacturer: Dell Inc.
Virtual machine output:
BIOS Serial: 0
Hardware Model: Innotec GmBH
Hardware Manufacturer: Virtual Box
A: A lot of the research on this is dedicated to detecting so-called "blue pill" attacks, that is, a malicious hypervisor that is actively attempting to evade detection.
The classic trick to detect a VM is to populate the ITLB, run an instruction that must be virtualized (which necessarily clears out such processor state when it gives control to the hypervisor), then run some more code to detect if the ITLB is still populated. The first paper on it is located here, and a rather colorful explanation from a researcher's blog and alternative Wayback Machine link to the blog article (images broken).
Bottom line from discussions on this is that there is always a way to detect a malicious hypervisor, and it's much simpler to detect one that isn't trying to hide.
A: Red Hat has a program which detects which (if any) virtualization product it's being run under: virt-what.
Using a third-party-maintained tool such is this is a better strategy long-term than trying to roll your own detection logic: more eyes (testing against more virtualization products), etc.
A: If it VM does the job well, it should be invisible to the client that it's being virtualized. However, one can look at other clues.
I would imagine that looking for known drivers or software specific to the VM environment would be the best possible way.
For example, on a VMWare client running Windows, vmxnet.sys would be the network driver, displayed as VMware accelerated AMD PCNet Adapter.
A: One good example is that apparently doing a WMI query for the motherboard manufacturer, and if it returns "Microsoft" you're in a VM. Thought I believe this is only for VMWare. There are likely different ways to tell for each VM host software.
This article here http://blogs.technet.com/jhoward/archive/2005/07/26/407958.aspx has some good suggestions and links to a couple of ways to detect if you are in a VM (VMWare and VirtualPC at least).
A: You might be able to identify whether you're in a virtual machine by looking at the MAC address of your network connection. Xen for example typically recommends using a specific range of addresses 00:16:3e:xx:xx:xx.
This isn't guaranteed as it's up to the administrator of the system to specify what MAC address they like.
A: TrapKIT provides ScoopyNG, a tool for VMware identification -- it attempts to work around evasion techniques, but doesn't necessarily target any virtualization software other than VMware. Both source and binaries are available.
A: In Linux systems, you can try to search for common files on /proc.
Example, the existente of /proc/vz/ tell you is a OpenVZ.
Here's a full guide to detect VM's environent under Linux without have to "drink pills" :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
} |
Q: How to download a live MySQL db into a local test db on demand, without SSH? I have a fairly small MySQL database (a Textpattern install) on a server that I do not have SSH access to (I have FTP access only). I need to regularly download the live database to my local dev server on demand; i.e., I would like to either run a script and/or have a cron job running. What are some good ways of doing this?
Some points to note:
*
*Live server is running Linux, Apache 2.2, PHP 5.2 and MySQL 4.1
*Local server is running the same (so using PHP is an option), but the OS is Windows
*Local server has Ruby on it (so using Ruby is a valid option)
*The live MySQL db can accept remote connections from different IPs
*I cannot enable replication on the remote server
Update: I've accepted BlaM's answer; it is beautifully simple. Can't believe I didn't think of that. There was one problem, though: I wanted to automate the process, but the proposed solution prompts the user for a password. Here is a slightly modified version of the mysqldump command that passes in the password:
mysqldump -u USER --password=MYPASSWORD DATABASE_TO_DUMP -h HOST > backup.sql
A: Since you can access your database remotely, you can use mysqldump from your windows machine to fetch the remote database. From commandline:
cd "into mysql directory"
mysqldump -u USERNAME -p -h YOUR_HOST_IP DATABASE_TO_MIRROR >c:\backup\database.sql
The program will ask you for the database password and then generate a file c:\backup\database.sql that you can run on your windows machine to insert the data.
With a small database that should be fairly fast.
A: Here's what I use. This dumps the database from the live server while uploads it to the local server.
mysqldump -hlive_server_addresss -ulive_server_user -plive_server_password --opt --compress live_server_db | mysql -ulocal_server_user -plocal_server_password local_server_db
You can run this from a bat file. You can ever use a scheduled task.
A: Is MySQL replication an option? You could even turn it on and off if you didn't want it constantly replicating.
This was a good article on replication.
A: I would create a (Ruby) script to do a SELECT * FROM ... on all the databases on the server and then do a DROP DATABASE ... followed by a series of new INSERTs on the local copy. You can do a SHOW DATABASES query to list the databases dynamically. Now, this assumes that the table structure doesn't change, but if you want to support table changes also you could add a SHOW CREATE TABLE ... query and a corresponding CREATE TABLE statement for each table in each database. To get a list of all the tables in a database you do a SHOW TABLES query.
Once you have the script you can set it up as a scheduled job to run as often as you need.
A: @Mark Biek
Is MySQL replication an option? You could even turn it on and off if you didn't want it constantly replicating.
Thanks for the suggestion, but I cannot enable replication on the server. It is a shared server with very little room for maneuver. I've updated the question to note this.
A: Depending on how often you need to copy down live data and how quickly you need to do it, installing phpMyAdmin on both machines might be an option. You can export and import DBs, but you'd have to do it manually. If it's a small DB (and it sounds like it is), and you don't need live data copied over too often, it might work well for what you need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: What's the simplest .NET equivalent of a VB6 control array? Maybe I just don't know .NET well enough yet, but I have yet to see a satisfactory way to implement this simple VB6 code easily in .NET (assume this code is on a form with N CommandButtons in array Command1() and N TextBoxes in array Text1()):
Private Sub Command1_Click(Index As Integer)
Text1(Index).Text = Timer
End Sub
I know it's not very useful code, but it demonstrates the ease with which control arrays can be used in VB6. What is the simplest equivalent in C# or VB.NET?
A: Make a generic list of textboxes:
var textBoxes = new List<TextBox>();
// Create 10 textboxes in the collection
for (int i = 0; i < 10; i++)
{
var textBox = new TextBox();
textBox.Text = "Textbox " + i;
textBoxes.Add(textBox);
}
// Loop through and set new values on textboxes in collection
for (int i = 0; i < textBoxes.Count; i++)
{
textBoxes[i].Text = "New value " + i;
// or like this
var textBox = textBoxes[i];
textBox.Text = "New val " + i;
}
A: Another nice thing that VB .NET does is having a single event handler that handles multiple controls:
Private Sub TextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles TextBox1.TextChanged, _
TextBox2.TextChanged, _
TextBox3.TextChanged
End Sub
A: There is no real 1 to 1 analog in .Net. Sure, you can make arrays or lists of controls of a specific type, but there's nothing that will do that for you automatically.
However, I've never seen a control array that couldn't be refactored in .Net to something better. A case in point is your example. In the scenario you posted, you're using control arrays to pair a button up with a textbox. In .Net, you would probably do this with a custom control. The custom control would consist of a button, a textbox, and maybe a shared/static timer. The form uses several instances of this custom control. You implement the logic needed for the control once, and it's isolated to it's own source file which can be tracked and edited in source control without requiring a merge with the larger form class, or easily re-used on multiple forms or even in multiple projects. You also don't have to worry about making sure the command button index matches up with the textbox index.
Using a custom control for this instead of a control array is loosely analogous to using class to group data instead of an array, in that you get names instead of indexes.
A: There are two aspects.
.NET readily supports arrays of controls, VB6 just had to use a workaround because otherwise, wiring up events was really hard. In .NET, wiring up events dynamically is easy.
However, the .NET form designer does not support control arrays for a simple reason: arrays of controls are created/extended at run time. If you know how many controls you need at compile time (the reasoning goes) then you give them different names and don't put them in an array.
I know it's not very useful code
That's exactly the point. Why have a feature if it's useless?
If needed, you can also access a control by name, resulting in something like this:
Private Sub Command_Click(sender As Object, e As EventArgs) Handles Command1.Click, Command2.Click …
Dim name As String = DirectCast(sender, Control).Name
Dim index As Integer = Integer.Parse(name.Substring("Command".Length))
Controls(String.Format("Text {0}", index)).Text = Timer.Value.ToString()
End Sub
A: VisualBasic .NET's compatibility library contains strong typed control arrays. This is what the upgrade wizard uses to replace the current VB6 control arrays.
However, A control array in VB6 is just a collection of objects with VB6 doing some syntax magic on the surface. In the .NET world, by removing this, they are forcing better practices.
In closing, with the advent of generics, there is nothing stopping you from using
List<YourControl> MyControlArray.
A: Make an array of controls.
TextBox[] textboxes = new TextBox[] {
textBox1,
textBox2,
textBox3
};
A: The same click event can handle the button presses from multiple buttons in .Net. You could then add the the text box to find in the Tag property?
Private Sub AllButton_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click, Button3.Click
Dim c As Control = CType(sender, Control)
Dim t As TextBox = FindControl(CType(c.Tag, String))
If t Is Not Nothing Then
t.Text = "Clicked"
End If
End Sub
A: The two main benefits of control arrays in VB6 were:
(1) They provided a way for you to iterate through a collection of controls
(2) They allowed you to share events between controls
(1) can be accomplished in .Net using an array of controls
(2) can be accomplished by having one event handle multiple controls (the syntax is a little different because you use the sender argument instead of myArray(index)).
One nice thing about .Net is that these features are decoupled. So for instance you can have controls that share events even if they aren't part of an array and have different names and even a different type. And you can iterate through a collection of controls even if they have totally different events.
A: I know that my answer is quite late, but I think I found the solution. I'm not the only former VB6 developer who has struggled with this limitation of VS. Long ago, I tried to migrate a CRM that I designed, but I failed because I had a tough dependency on control arrays (hundreds in one form). I read many forums and I was able to write this simple code:
VB.NET:
'To declare the List of controls
Private textBoxes As List(Of TextBox) = New List(Of TextBox)()
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
'To get all controls in the form
For Each control In Controls
'To search for the specific type that you want to create the array
If control.[GetType]() = GetType(TextBox) Then
textBoxes.Add(CType(control, TextBox))
End If
Next
'To sort the labels by the ID
textBoxes = textBoxes.OrderBy(Function(x) x.Name).ToList()
End Sub
C#:
//To declare the List of controls
private List<TextBox> textBoxes = new List<TextBox>();
private void Form1_Load(object sender, EventArgs e)
{
//To get all controls in the form
foreach (var control in Controls)
{
//To search for the specific type that you want to create the array
if (control.GetType() == typeof(TextBox))
{
//To add the control to the List
textBoxes.Add((TextBox)control);
}
}
//To sort the labels by the ID
textBoxes = textBoxes.OrderBy(x => x.Name).ToList();
}
There are 3 points to take into consideration:
*
*A List will help you to emulate the large collection of controls.
*typeof(Control) will help you define the type of the control to add to the list.
*While you keep the "index" as the last character (textBox1, textBox2, ..., textBoxN) you can create a logical order.
Example in design mode:
Running:
A similar logic could be potentially used in other technologies like WPF, ASP.NET (Web Forms), or Xamarin (Forms) -in my opinion-. I hope this piece of code is going to help more programmers in the future.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Visual Studio 2005/2012: How to keep first curly brace on same line? Trying to get my css / C# functions to look like this:
body {
color:#222;
}
instead of this:
body
{
color:#222;
}
when I auto-format the code.
A: Go to Tools -> Options -> Text Editor -> CSS -> Formatting. Click "Semi-expanded," which matches the style you defined.
A: For CSS you'll need the 'Semi Expanded' option.
A: For Visual Studio Mac OS (Community edition) version 8.3 you need to do the following:
Preferences -> Source Code (in left menu) -> Code Formatting -> C# source code -> C# Format -> Press Edit
Select New Lines from the Category dropdown menu:
Deselect each option in the New line options for braces:
A: Tools -> Options -> Text Editor -> C# -> Formatting -> New Lines -> New Line Options for braces -> Uncheck all boxes.
A: C#
*
*In the Tools Menu click Options
*Click Show all Parameters (checkbox at the bottom left) (Show all settings in VS 2010)
*Text Editor
*C#
*Formatting
*New lines
And there check when you want new lines with brackets
Css:
almost the same, but fewer options
*
*In the Tools Menu click Options
*Click Show all Parameters (checkbox at the bottom left) (Show all settings in VS 2010)
*Text Editor
*CSS
*Format
And than you select the formatting you want (in your case second radio button)
For Visual Studio 2015:
Tools → Options
In the sidebar, go to Text Editor → C# → Formatting → New Lines
and uncheck every checkbox in the section "New line options for braces"
For Mac OS users:
Preferences → Source Code → Code Formatting → choose what ever you want to change (like C# source code) → C# Format → Edit -→ New Lines
A: There is a specific formatting setting in VS 2008/2010 to keep the open brace on the same line:
Click Tools->Options Select 'CSS' within 'Text Editor' tree node Select 'Formatting' under 'CSS' node Click 'Semi-expanded' radio button
You will see a preview what the various radio buttons avail will do to the formatting
A: The official MS guidelines (at the time in 2008) tells you to have the curly brace on the same line as the method/property/class and many other things which are not enforced in Visual Studio.
You can change all these auto-text settings under:
Tools -> Options -> Text Editor -> [The language you want to change]
UPDATE: This was based on the book "Framework Design Guidelines" written by some of the core-people from the .NET-team. If you look at the source-code for the likes of ASP.NET MVC, this is no longer accurate.
A: If you're looking for this option within Visual Studio 2014, then it's under advanced and is now a 'Brace positions' drop down box:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "142"
} |
Q: How do you build a multi-language web site? A friend of mine is now building a web application with J2EE and Struts, and it's going to be prepared to display pages in several languages.
I was told that the best way to support a multi-language site is to use a properties file where you store all the strings of your pages, something like:
welcome.english = "Welcome!"
welcome.spanish = "¡Bienvenido!"
...
This solution is ok, but what happens if your site displays news or something like that (a blog)? I mean, content that is not static, that is updated often... The people that keep the site have to write every new entry in each supported language, and store each version of the entry in the database. The application loads only the entries in the user's chosen language.
How do you design the database to support this kind of implementation?
Thanks.
A: They way I have designed the database before is to have an News-table containing basic info like NewsID (int), NewsPubDate (datetime), NewsAuthor (varchar/int) and then have a linked table NewsText that has these columns: NewsID(int), NewsText(text), NewsLanguageID(int). And at last you have a Language-table that has LanguageID(int) and LanguageName(varchar).
Then, when you want to show your users the news-page you do:
SELECT NewsText FROM News INNER JOIN NewsText ON News.NewsID = NewsText.NewsID
WHERE NewsText.NewsLanguageID = <<Session["UserLanguageID"]>>
That Session-bit is a local variable where you store the users language when they log in or enters the site for the first time.
A: Java web applications support internationalization using the java standard tag library.
You've really got 2 problems. Static content and dynamic content.
for static content you can use jstl. It uses java ResourceBundles to accomplish this. I managed to get a Databased backed bundle working with the help of this site.
The second problem is dynamic content.
To solve this problem you'll need to store the data so that you can retrieve different translations based on the user's Locale. (Locale includes Country and Language).
It's not trivial, but it is something you can do with a little planning up front.
A: Warning: I'm not a java hacker, so YMMV but...
The problem with using a list of "properties" is that you need a lot of discipline. Every time you add a string that should be output to the user you will need to open your properties file, look to see if that string (or something roughly equivalent to it) is already in the file, and then go and add the new property if it isn't. On top of this, you'd have to hope the properties file was fairly human readable / editable if you wanted to give it to an external translation team to deal with.
The database based approach is useful for all your database based content. Ideally you want to make it easy to tie pieces of content together with their translations. It only really falls down for all the places you may want to output something that isn't out of a database (error messages etc.).
One fairly old technology which we find still works really well, is to use gettext. Gettext or some variant seems to be available for most languages and platforms. The basic premise is that you wrap your output in a special function call like so:
echo _("Please do not press this button again");
Then running the gettext tools over your source code will extract all the instances wrapped like that into a "po" file. This will contain entries such as:
#: myfolder/my.source:239
msgid "Please do not press this button again"
msgstr ""
And you can add your translation to the appropriate place:
#: myfolder/my.source:239
msgid "Please do not press this button again"
msgstr "s’il vous plaît ne pas appuyer sur le bouton ci-dessous à nouveau"
Subsequent runs of the gettext tools simply update your po files. You don't even need to extract the po file from your source. If you know you may want to translate your site down the line, then you can just use the format shown above (the underscored function) with all your output. If you don't provide a po file it will just return whatever you put in the quotes. gettext is designed to work with locales so the users locale is used to retrieve the appropriate po file. This makes it really easy to add new translations.
Gettext Pros
*
*Doesn't get in your way while coding
*Very easy to add translations
*PO files can be compiled down for speed
*There are libraries available for most languages / platforms
*There are good cross platform tools for dealing with translations. It is actually possible to get your translation team set up with a tool such as poEdit to make it very easy for them to manage translation projects
Gettext Cons
*
*Solves your site "furniture" needs, but you would usually still want a database based approach for your database driven content
For more info on gettext see this wikipedia page
A: @Auron
thats what we apply it to. Our apps are all PHP, but gettext has a long heritage.
Looks like there is a good Java implementation
A: Tag libraries are fine if you're using JSP, but you can also achieve I18N using a template-based technology such as FreeMarker.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Login Integration in PHP In my host, I currently have installed 2 wordpress applications, 1 phpBB forum and one MediaWiki.
Is there a way to merge the login so that all applications share the same credentials?
For instance, I want to register only in my phpBB and then I want to access all other applications with the given username and password.
Even if you don't know a unified way, what other login integration do you know of? Pros and cons of each?
A: when you integrate the system. Just remember 2 things:
*
*Login to system
Check username/password with both systems.
*Change of Password
Update the password on both systems.
A: I don't know how to share the session cookies, but you can easily share the same login.
i.e. People will need to log separately into both sites, but will be able to use the same username and password.
In the mediawiki file "LocalSettings.PHP", you can tell it to use a different (wordpress) database for authentication:
e.g.
require_once('includes/AuthPlugin.php');
require_once('extensions/AuthPress.php');
$wgAuth = new AuthPress();
$wgAuth->setAuthPressTablePrefix('evo_');
# Only include the following if you aren't using the same db as MediaWiki
$wgAuth->setAuthPressDBServer ('localhost');
$wgAuth->setAuthPressDBName('yourWordPressDB');
$wgAuth->setAuthPressUser('mySQL user for same');
$wgAuth->setAuthPressPassword('The password');
See http://bbpress.org/forums/topic/mediawiki-bbpress-and-wordpress-integration
A: One option is OpenID, which you can integrate into phpBB, WordPress, and MediaWiki.
A second option is to set up an LDAP server, which you can also integrate into phpBB, WordPress, and MediaWiki.
If the sites are all on the same root domain, a third option is to modify the registration, login, and logout code so that these actions are replicated on every site at the same time. This gets messy, but it may be the easiest short-term solution if you're in a hurry. Once you track down the account code in each site, it's just a matter of copying and pasting and changing a few cookie parameters.
A: I once did a phpBB/MediaWiki login integration from the phpBB end.
Check it out.
A: If you're integrating a bunch of different apps, and you really just want a bridge, I've had good success with the bridge from Single-Signon.com. You can see there supported apps here:
http://www.single-signon.com/en/applications.html
I've also used a MediaWiki extension for phpBB integration:
http://www.mediawiki.org/wiki/Extension:PHPBB/Users_Integration
A: Having tried to do this some years ago I remember it not being very easy.
The way I did it was to create totally new table to user/pass and then replace these columns in the respective software with foreign keys to your new table - this required a lot of custom tweaking of core files in each application - mainly making sure all SQL requests to this data have the extra join needed for your new table. If I find the time I will maybe try and provide a step by step of the changes needed.
There are some pretty big drawbacks to this approach though. The main one being from now on your gonna have to hand update any patches
If you have no content or users yet look at http://bbpress.org/documentation/integration-with-wordpress/ which will make things a lot simpler for you.
I can't quite remember but I believe that I big problem I had was that MediaWiki requires usernames formatted a certain that conflicted with phpBB.
Of course, a totally different approach would be to mod each piece of software to use OpenID _ I believe plugins/extensions are readily available for all the applications you mentioned.
A: I personally think that integration login systems is one of, if not the, hardest job when utilizing multiple prebuilt applications. As a fan of reuse and modularity, I find this disappointing. If anyone knows of any easy ways to handle this problem between random app X and random app Y, I would love to know.
A: You can write a custom login hook for mediaWiki. I've done it for LibraryThing so that login credentials from our main site are carried over to our mediaWiki installation. The authentication hook extends mediaWiki's AuthPlugin.
There are several small issues:
*
*mediaWiki usernames must start with initial caps (so if you allow case sensitive user names it could be a problem if two users have colliding wiki names)
*underscores in usernames are converted to spaces in mediaWiki
But if you can deal with those then it is certainly possible to use your own user/password data with mediaWiki.
Advantages:
*
*The user doesn't have to login to each area separately. Once they login to the main site they are logged into the wiki also.
*You know that usernames are the same across the systems and can leverage that in links, etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: What is the best way to convert an array to a hash in Ruby In Ruby, given an array in one of the following forms...
[apple, 1, banana, 2]
[[apple, 1], [banana, 2]]
...what is the best way to convert this into a hash in the form of...
{apple => 1, banana => 2}
A: The best way is to use Array#to_h:
[ [:apple,1],[:banana,2] ].to_h #=> {apple: 1, banana: 2}
Note that to_h also accepts a block:
[:apple, :banana].to_h { |fruit| [fruit, "I like #{fruit}s"] }
# => {apple: "I like apples", banana: "I like bananas"}
Note: to_h accepts a block in Ruby 2.6.0+; for early rubies you can use my backports gem and require 'backports/2.6.0/enumerable/to_h'
to_h without a block was introduced in Ruby 2.1.0.
Before Ruby 2.1, one could use the less legible Hash[]:
array = [ [:apple,1],[:banana,2] ]
Hash[ array ] #= > {:apple => 1, :banana => 2}
Finally, be wary of any solutions using flatten, this could create problems with values that are arrays themselves.
A: You can also simply convert a 2D array into hash using:
1.9.3p362 :005 > a= [[1,2],[3,4]]
=> [[1, 2], [3, 4]]
1.9.3p362 :006 > h = Hash[a]
=> {1=>2, 3=>4}
A: Summary & TL;DR:
This answer hopes to be a comprehensive wrap-up of information from other answers.
The very short version, given the data from the question plus a couple extras:
flat_array = [ apple, 1, banana, 2 ] # count=4
nested_array = [ [apple, 1], [banana, 2] ] # count=2 of count=2 k,v arrays
incomplete_f = [ apple, 1, banana ] # count=3 - missing last value
incomplete_n = [ [apple, 1], [banana ] ] # count=2 of either k or k,v arrays
# there's one option for flat_array:
h1 = Hash[*flat_array] # => {apple=>1, banana=>2}
# two options for nested_array:
h2a = nested_array.to_h # since ruby 2.1.0 => {apple=>1, banana=>2}
h2b = Hash[nested_array] # => {apple=>1, banana=>2}
# ok if *only* the last value is missing:
h3 = Hash[incomplete_f.each_slice(2).to_a] # => {apple=>1, banana=>nil}
# always ok for k without v in nested array:
h4 = Hash[incomplete_n] # or .to_h => {apple=>1, banana=>nil}
# as one might expect:
h1 == h2a # => true
h1 == h2b # => true
h1 == h3 # => false
h3 == h4 # => true
Discussion and details follow.
Setup: variables
In order to show the data we'll be using up front, I'll create some variables to represent various possibilities for the data. They fit into the following categories:
Based on what was directly in the question, as a1 and a2:
(Note: I presume that apple and banana were meant to represent variables. As others have done, I'll be using strings from here on so that input and results can match.)
a1 = [ 'apple', 1 , 'banana', 2 ] # flat input
a2 = [ ['apple', 1], ['banana', 2] ] # key/value paired input
Multi-value keys and/or values, as a3:
In some other answers, another possibility was presented (which I expand on here) – keys and/or values may be arrays on their own:
a3 = [ [ 'apple', 1 ],
[ 'banana', 2 ],
[ ['orange','seedless'], 3 ],
[ 'pear', [4, 5] ],
]
Unbalanced array, as a4:
For good measure, I thought I'd add one for a case where we might have an incomplete input:
a4 = [ [ 'apple', 1],
[ 'banana', 2],
[ ['orange','seedless'], 3],
[ 'durian' ], # a spiky fruit pricks us: no value!
]
Now, to work:
Starting with an initially-flat array, a1:
Some have suggested using #to_h (which showed up in Ruby 2.1.0, and can be backported to earlier versions). For an initially-flat array, this doesn't work:
a1.to_h # => TypeError: wrong element type String at 0 (expected array)
Using Hash::[] combined with the splat operator does:
Hash[*a1] # => {"apple"=>1, "banana"=>2}
So that's the solution for the simple case represented by a1.
With an array of key/value pair arrays, a2:
With an array of [key,value] type arrays, there are two ways to go.
First, Hash::[] still works (as it did with *a1):
Hash[a2] # => {"apple"=>1, "banana"=>2}
And then also #to_h works now:
a2.to_h # => {"apple"=>1, "banana"=>2}
So, two easy answers for the simple nested array case.
This remains true even with sub-arrays as keys or values, as with a3:
Hash[a3] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "pear"=>[4, 5]}
a3.to_h # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "pear"=>[4, 5]}
But durians have spikes (anomalous structures give problems):
If we've gotten input data that's not balanced, we'll run into problems with #to_h:
a4.to_h # => ArgumentError: wrong array length at 3 (expected 2, was 1)
But Hash::[] still works, just setting nil as the value for durian (and any other array element in a4 that's just a 1-value array):
Hash[a4] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "durian"=>nil}
Flattening - using new variables a5 and a6
A few other answers mentioned flatten, with or without a 1 argument, so let's create some new variables:
a5 = a4.flatten
# => ["apple", 1, "banana", 2, "orange", "seedless" , 3, "durian"]
a6 = a4.flatten(1)
# => ["apple", 1, "banana", 2, ["orange", "seedless"], 3, "durian"]
I chose to use a4 as the base data because of the balance problem we had, which showed up with a4.to_h. I figure calling flatten might be one approach someone might use to try to solve that, which might look like the following.
flatten without arguments (a5):
Hash[*a5] # => {"apple"=>1, "banana"=>2, "orange"=>"seedless", 3=>"durian"}
# (This is the same as calling `Hash[*a4.flatten]`.)
At a naïve glance, this appears to work – but it got us off on the wrong foot with the seedless oranges, thus also making 3 a key and durian a value.
And this, as with a1, just doesn't work:
a5.to_h # => TypeError: wrong element type String at 0 (expected array)
So a4.flatten isn't useful to us, we'd just want to use Hash[a4]
The flatten(1) case (a6):
But what about only partially flattening? It's worth noting that calling Hash::[] using splat on the partially-flattened array (a6) is not the same as calling Hash[a4]:
Hash[*a6] # => ArgumentError: odd number of arguments for Hash
Pre-flattened array, still nested (alternate way of getting a6):
But what if this was how we'd gotten the array in the first place?
(That is, comparably to a1, it was our input data - just this time some of the data can be arrays or other objects.) We've seen that Hash[*a6] doesn't work, but what if we still wanted to get the behavior where the last element (important! see below) acted as a key for a nil value?
In such a situation, there's still a way to do this, using Enumerable#each_slice to get ourselves back to key/value pairs as elements in the outer array:
a7 = a6.each_slice(2).to_a
# => [["apple", 1], ["banana", 2], [["orange", "seedless"], 3], ["durian"]]
Note that this ends up getting us a new array that isn't "identical" to a4, but does have the same values:
a4.equal?(a7) # => false
a4 == a7 # => true
And thus we can again use Hash::[]:
Hash[a7] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "durian"=>nil}
# or Hash[a6.each_slice(2).to_a]
But there's a problem!
It's important to note that the each_slice(2) solution only gets things back to sanity if the last key was the one missing a value. If we later added an extra key/value pair:
a4_plus = a4.dup # just to have a new-but-related variable name
a4_plus.push(['lychee', 4])
# => [["apple", 1],
# ["banana", 2],
# [["orange", "seedless"], 3], # multi-value key
# ["durian"], # missing value
# ["lychee", 4]] # new well-formed item
a6_plus = a4_plus.flatten(1)
# => ["apple", 1, "banana", 2, ["orange", "seedless"], 3, "durian", "lychee", 4]
a7_plus = a6_plus.each_slice(2).to_a
# => [["apple", 1],
# ["banana", 2],
# [["orange", "seedless"], 3], # so far so good
# ["durian", "lychee"], # oops! key became value!
# [4]] # and we still have a key without a value
a4_plus == a7_plus # => false, unlike a4 == a7
And the two hashes we'd get from this are different in important ways:
ap Hash[a4_plus] # prints:
{
"apple" => 1,
"banana" => 2,
[ "orange", "seedless" ] => 3,
"durian" => nil, # correct
"lychee" => 4 # correct
}
ap Hash[a7_plus] # prints:
{
"apple" => 1,
"banana" => 2,
[ "orange", "seedless" ] => 3,
"durian" => "lychee", # incorrect
4 => nil # incorrect
}
(Note: I'm using awesome_print's ap just to make it easier to show the structure here; there's no conceptual requirement for this.)
So the each_slice solution to an unbalanced flat input only works if the unbalanced bit is at the very end.
Take-aways:
*
*Whenever possible, set up input to these things as [key, value] pairs (a sub-array for each item in the outer array).
*When you can indeed do that, either #to_h or Hash::[] will both work.
*If you're unable to, Hash::[] combined with the splat (*) will work, so long as inputs are balanced.
*With an unbalanced and flat array as input, the only way this will work at all reasonably is if the last value item is the only one that's missing.
Side-note: I'm posting this answer because I feel there's value to be added – some of the existing answers have incorrect information, and none (that I read) gave as complete an answer as I'm endeavoring to do here. I hope that it's helpful. I nevertheless give thanks to those who came before me, several of whom provided inspiration for portions of this answer.
A: Appending to the answer but using anonymous arrays and annotating:
Hash[*("a,b,c,d".split(',').zip([1,2,3,4]).flatten)]
Taking that answer apart, starting from the inside:
*
*"a,b,c,d" is actually a string.
*split on commas into an array.
*zip that together with the following array.
*[1,2,3,4] is an actual array.
The intermediate result is:
[[a,1],[b,2],[c,3],[d,4]]
flatten then transforms that to:
["a",1,"b",2,"c",3,"d",4]
and then:
*["a",1,"b",2,"c",3,"d",4] unrolls that into
"a",1,"b",2,"c",3,"d",4
which we can use as the arguments to the Hash[] method:
Hash[*("a,b,c,d".split(',').zip([1,2,3,4]).flatten)]
which yields:
{"a"=>1, "b"=>2, "c"=>3, "d"=>4}
A: Update
Ruby 2.1.0 is released today. And I comes with Array#to_h (release notes and ruby-doc), which solves the issue of converting an Array to a Hash.
Ruby docs example:
[[:foo, :bar], [1, 2]].to_h # => {:foo => :bar, 1 => 2}
A: Simply use Hash[*array_variable.flatten]
For example:
a1 = ['apple', 1, 'banana', 2]
h1 = Hash[*a1.flatten(1)]
puts "h1: #{h1.inspect}"
a2 = [['apple', 1], ['banana', 2]]
h2 = Hash[*a2.flatten(1)]
puts "h2: #{h2.inspect}"
Using Array#flatten(1) limits the recursion so Array keys and values work as expected.
A: NOTE: For a concise and efficient solution, please see Marc-André Lafortune's answer below.
This answer was originally offered as an alternative to approaches using flatten, which were the most highly upvoted at the time of writing. I should have clarified that I didn't intend to present this example as a best practice or an efficient approach. Original answer follows.
Warning! Solutions using flatten will not preserve Array keys or values!
Building on @John Topley's popular answer, let's try:
a3 = [ ['apple', 1], ['banana', 2], [['orange','seedless'], 3] ]
h3 = Hash[*a3.flatten]
This throws an error:
ArgumentError: odd number of arguments for Hash
from (irb):10:in `[]'
from (irb):10
The constructor was expecting an Array of even length (e.g. ['k1','v1,'k2','v2']). What's worse is that a different Array which flattened to an even length would just silently give us a Hash with incorrect values.
If you want to use Array keys or values, you can use map:
h3 = Hash[a3.map {|key, value| [key, value]}]
puts "h3: #{h3.inspect}"
This preserves the Array key:
h3: {["orange", "seedless"]=>3, "apple"=>1, "banana"=>2}
A:
Edit: Saw the responses posted while I was writing, Hash[a.flatten] seems the way to go.
Must have missed that bit in the documentation when I was thinking through the response. Thought the solutions that I've written can be used as alternatives if required.
The second form is simpler:
a = [[:apple, 1], [:banana, 2]]
h = a.inject({}) { |r, i| r[i.first] = i.last; r }
a = array, h = hash, r = return-value hash (the one we accumulate in), i = item in the array
The neatest way that I can think of doing the first form is something like this:
a = [:apple, 1, :banana, 2]
h = {}
a.each_slice(2) { |i| h[i.first] = i.last }
A: Not sure if it's the best way, but this works:
a = ["apple", 1, "banana", 2]
m1 = {}
for x in (a.length / 2).times
m1[a[x*2]] = a[x*2 + 1]
end
b = [["apple", 1], ["banana", 2]]
m2 = {}
for x,y in b
m2[x] = y
end
A: if you have array that looks like this -
data = [["foo",1,2,3,4],["bar",1,2],["foobar",1,"*",3,5,:foo]]
and you want the first elements of each array to become the keys for the hash and the rest of the elements becoming value arrays, then you can do something like this -
data_hash = Hash[data.map { |key| [key.shift, key] }]
#=>{"foo"=>[1, 2, 3, 4], "bar"=>[1, 2], "foobar"=>[1, "*", 3, 5, :foo]}
A: For performance and memory allocation concerns please check my answer to Rails mapping array of hashes onto single hash where I bench-marked several solutions.
reduce / inject can be the fastest or the slowest solution depending on which method you use it which.
A: If the numeric values are seq indexes, then we could have simpler ways...
Here's my code submission, My Ruby is a bit rusty
input = ["cat", 1, "dog", 2, "wombat", 3]
hash = Hash.new
input.each_with_index {|item, index|
if (index%2 == 0) hash[item] = input[index+1]
}
hash #=> {"cat"=>1, "wombat"=>3, "dog"=>2}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "135"
} |
Q: Best way to do multi-row insert in Oracle? I'm looking for a good way to perform multi-row inserts into an Oracle 9 database. The following works in MySQL but doesn't seem to be supported in Oracle.
INSERT INTO TMP_DIM_EXCH_RT
(EXCH_WH_KEY,
EXCH_NAT_KEY,
EXCH_DATE, EXCH_RATE,
FROM_CURCY_CD,
TO_CURCY_CD,
EXCH_EFF_DATE,
EXCH_EFF_END_DATE,
EXCH_LAST_UPDATED_DATE)
VALUES
(1, 1, '28-AUG-2008', 109.49, 'USD', 'JPY', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(2, 1, '28-AUG-2008', .54, 'USD', 'GBP', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(3, 1, '28-AUG-2008', 1.05, 'USD', 'CAD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(4, 1, '28-AUG-2008', .68, 'USD', 'EUR', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(5, 1, '28-AUG-2008', 1.16, 'USD', 'AUD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(6, 1, '28-AUG-2008', 7.81, 'USD', 'HKD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008');
A: you can insert using loop if you want to insert some random values.
BEGIN
FOR x IN 1 .. 1000 LOOP
INSERT INTO MULTI_INSERT_DEMO (ID, NAME)
SELECT x, 'anyName' FROM dual;
END LOOP;
END;
A: In Oracle, to insert multiple rows into table t with columns col1, col2 and col3 you can use the following syntax:
INSERT ALL
INTO t (col1, col2, col3) VALUES ('val1_1', 'val1_2', 'val1_3')
INTO t (col1, col2, col3) VALUES ('val2_1', 'val2_2', 'val2_3')
INTO t (col1, col2, col3) VALUES ('val3_1', 'val3_2', 'val3_3')
.
.
.
SELECT 1 FROM DUAL;
A: Use SQL*Loader. It takes a little setting up, but if this isn't a one off, its worth it.
Create Table
SQL> create table ldr_test (id number(10) primary key, description varchar2(20));
Table created.
SQL>
Create CSV
oracle-2% cat ldr_test.csv
1,Apple
2,Orange
3,Pear
oracle-2%
Create Loader Control File
oracle-2% cat ldr_test.ctl
load data
infile 'ldr_test.csv'
into table ldr_test
fields terminated by "," optionally enclosed by '"'
( id, description )
oracle-2%
Run SQL*Loader command
oracle-2% sqlldr <username> control=ldr_test.ctl
Password:
SQL*Loader: Release 9.2.0.5.0 - Production on Wed Sep 3 12:26:46 2008
Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
Commit point reached - logical record count 3
Confirm insert
SQL> select * from ldr_test;
ID DESCRIPTION
---------- --------------------
1 Apple
2 Orange
3 Pear
SQL>
SQL*Loader has alot of options, and can take pretty much any text file as its input. You can even inline the data in your control file if you want.
Here is a page with some more details -> SQL*Loader
A: Whenever I need to do this I build a simple PL/SQL block with a local procedure like this:
declare
procedure ins
is
(p_exch_wh_key INTEGER,
p_exch_nat_key INTEGER,
p_exch_date DATE, exch_rate NUMBER,
p_from_curcy_cd VARCHAR2,
p_to_curcy_cd VARCHAR2,
p_exch_eff_date DATE,
p_exch_eff_end_date DATE,
p_exch_last_updated_date DATE);
begin
insert into tmp_dim_exch_rt
(exch_wh_key,
exch_nat_key,
exch_date, exch_rate,
from_curcy_cd,
to_curcy_cd,
exch_eff_date,
exch_eff_end_date,
exch_last_updated_date)
values
(p_exch_wh_key,
p_exch_nat_key,
p_exch_date, exch_rate,
p_from_curcy_cd,
p_to_curcy_cd,
p_exch_eff_date,
p_exch_eff_end_date,
p_exch_last_updated_date);
end;
begin
ins (1, 1, '28-AUG-2008', 109.49, 'USD', 'JPY', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
ins (2, 1, '28-AUG-2008', .54, 'USD', 'GBP', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
ins (3, 1, '28-AUG-2008', 1.05, 'USD', 'CAD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
ins (4, 1, '28-AUG-2008', .68, 'USD', 'EUR', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
ins (5, 1, '28-AUG-2008', 1.16, 'USD', 'AUD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
ins (6, 1, '28-AUG-2008', 7.81, 'USD', 'HKD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008');
end;
/
A: This works in Oracle:
insert into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE)
select 8000,0,'Multi 8000',1 from dual
union all select 8001,0,'Multi 8001',1 from dual
The thing to remember here is to use the from dual statement.
A: If you have the values that you want to insert in another table already, then you can Insert from a select statement.
INSERT INTO a_table (column_a, column_b) SELECT column_a, column_b FROM b_table;
Otherwise, you can list a bunch of single row insert statements and submit several queries in bulk to save the time for something that works in both Oracle and MySQL.
@Espo's solution is also a good one that will work in both Oracle and MySQL if your data isn't already in a table.
A: Cursors may also be used, although it is inefficient.
The following stackoverflow post discusses the usage of cursors :
INSERT and UPDATE a record using cursors in oracle
A: Here is a very useful step by step guideline for insert multi rows in Oracle:
https://livesql.oracle.com/apex/livesql/file/content_BM1LJQ87M5CNIOKPOWPV6ZGR3.html
The last step:
INSERT ALL
/* Everyone is a person, so insert all rows into people */
WHEN 1=1 THEN
INTO people (person_id, given_name, family_name, title)
VALUES (id, given_name, family_name, title)
/* Only people with an admission date are patients */
WHEN admission_date IS NOT NULL THEN
INTO patients (patient_id, last_admission_date)
VALUES (id, admission_date)
/* Only people with a hired date are staff */
WHEN hired_date IS NOT NULL THEN
INTO staff (staff_id, hired_date)
VALUES (id, hired_date)
WITH names AS (
SELECT 4 id, 'Ruth' given_name, 'Fox' family_name, 'Mrs' title,
NULL hired_date, DATE'2009-12-31' admission_date
FROM dual UNION ALL
SELECT 5 id, 'Isabelle' given_name, 'Squirrel' family_name, 'Miss' title ,
NULL hired_date, DATE'2014-01-01' admission_date
FROM dual UNION ALL
SELECT 6 id, 'Justin' given_name, 'Frog' family_name, 'Master' title,
NULL hired_date, DATE'2015-04-22' admission_date
FROM dual UNION ALL
SELECT 7 id, 'Lisa' given_name, 'Owl' family_name, 'Dr' title,
DATE'2015-01-01' hired_date, NULL admission_date
FROM dual
)
SELECT * FROM names
A: In my case, I was able to use a simple insert statement to bulk insert many rows into TABLE_A using just one column from TABLE_B and getting the other data elsewhere (sequence and a hardcoded value) :
INSERT INTO table_a (
id,
column_a,
column_b
)
SELECT
table_a_seq.NEXTVAL,
b.name,
123
FROM
table_b b;
Result:
ID: NAME: CODE:
1, JOHN, 123
2, SAM, 123
3, JESS, 123
etc
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "359"
} |
Q: Transactions best practices How much do you rely on database transactions?
Do you prefer small or large transaction scopes ?
Do you prefer client side transaction handling (e.g. TransactionScope in .NET) over server
side transactions or vice-versa?
What about nested transactions?
Do you have some tips&tricks related to transactions ?
Any gotchas you encountered working with transaction ?
All sort of answers are welcome.
A: Personally, developing a website that is high traffic perfomance based, I stay away from database transactions whenever possible. Obviously they are neccessary, so I use an ORM, and page level object variables to minimize the number of server side calls I have to make.
Nested transactions are an awesome way to minimize your calls, I steer in that direction whenever I can as long as they are quick queries that wont cause locking. NHibernate has been a savior in these cases.
A: I use transactions on every write operation to the database.
So there are quite a few small "transactions" wrapped in a larger transaction and basically there is an outstanding transaction count in the nesting code. If there are any outstanding children when you end the parent, its all rolled back.
I prefer client-side transaction handling where available. If you are relegated to doing sps or other server side logical units of work, server side transactions are fine.
A: Wow! Lots of questions!
Until a year ago I relied 100% on transactions. Now its only 98%. In special cases of high traffic websites (like Sara mentioned) and also high partitioned data, enforcing the need of distributed transactions, a transactionless architecture can be adopted. Now you'll have to code referential integrity in the application.
Also, I like to manage transactions declaratively using annotations (I'm a Java guy) and aspects. That's a very clean way to determine transaction boundaries and it includes transaction propagation functionality.
A: Just as an FYI... Nested transactions can be dangerous. It simply increases the chances of getting deadlock. So, though it is good and necessary, the way it is implemented is important in higher volume situation.
A: I always wrap a transaction in a using statement.
using(IDbTransaction transaction )
{
// logic goes here.
transaction.Commit();
}
Once the transaction moves out of scope, it is disposed. If the transaction is still active, it is rolled back. This behaviour fail-safes you from accidentally locking out the database. Even if an unhandled exception is thrown, the transaction will still rollback.
In my code I actually omit explicit rollbacks and rely on the using statement to do the work for me. I only explicitly perform commits.
I've found this pattern has drastically reduced record locking issues.
A: Server side transactions, 35,000 transactions per second, SQL Server: 10 lessons from 35K tps
We only use server side transactions:
*
*can start later and finish sooner
*not distributed
*can do work before and after
*SET XACT_ABORT ON means immediate rollback on error
*client/OS/driver agnostic
Other:
*
*we nest calls but use @@TRANCOUNT to detect already started TXNs
*each DB call is always atomic
We deal with millions of INSERT rows per day (some batched via staging tables), full OLTP, no problems. Not 35k tps though.
A: As Sara Chipps said, transaction is overkill for high traffic applications. So we should avoid it as much as possible. In other words, we use a BASE architecture rather than ACID. Ebay is a typical case. Distributed transaction is not used at all in Ebay architecture. But for eventual consistency, you have to do some sort of trick on your own.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: What's a good design pattern for web method return values? When coding web services, how do you structure your return values? How do you handle error conditions (expected ones and unexpected ones)? If you are returning something simple like an int, do you just return it, or embed it in a more complex object? Do all of the web methods within one service return an instance of a single class, or do you create a custom return value class for each method?
A: I like the Request/Response object pattern, where you encapsulate your arguments into a single [Operation]Request class, which has simple public properties on it.
Something like AddCustomerRequest, which would return AddCustomerResponse.
The response can include information on the success/failure of the operation, any messages that might be used by the UI, possibly the ID of the customer that was added, for example.
Another good pattern is to make these all derive from a simple IMessage interface, where your general end-point is something like Process(params IMessage[] messages)... this way you can pass in multiple operations in the same web request.
A: +1 for Ben's answer.
In addition, I suggest considering that the generic response allow for multiple error/warning items, to allow the reply to be as comprehensive and actionable as possible. (Would you want to use a compiler that stopped after the first error message, or one that told you as much as possible?)
A: If you're using SOAP web services then SOAP faults are the standard way to return error details, where the fault messages can return whatever additional detail you like.
A: Soap faults are a standard practice where the calling application is a Soap client. There are cases, such as a COM client using XMLHTTP, where the Soap is parsed as XML and Soap faults cannot be easily handled. Can't vote yet but another +1 for @Ben Scheirman.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to loop through files matching wildcard in batch file I have a set of base filenames, for each name 'f' there are exactly two files, 'f.in' and 'f.out'. I want to write a batch file (in Windows XP) which goes through all the filenames, for each one it should:
*
*Display the base name 'f'
*Perform an action on 'f.in'
*Perform another action on 'f.out'
I don't have any way to list the set of base filenames, other than to search for *.in (or *.out) for example.
A: Easiest way, as I see it, is to use a for loop that calls a second batch file for processing, passing that second file the base name.
According to the for /? help, basename can be extracted using the nifty ~n option. So, the base script would read:
for %%f in (*.in) do call process.cmd %%~nf
Then, in process.cmd, assume that %0 contains the base name and act accordingly. For example:
echo The file is %0
copy %0.in %0.out
ren %0.out monkeys_are_cool.txt
There might be a better way to do this in one script, but I've always been a bit hazy on how to pull of multiple commands in a single for loop in a batch file.
EDIT: That's fantastic! I had somehow missed the page in the docs that showed that you could do multi-line blocks in a FOR loop. I am going to go have to go back and rewrite some batch files now...
A: Expanding on Nathans post. The following will do the job lot in one batch file.
@echo off
if %1.==Sub. goto %2
for %%f in (*.in) do call %0 Sub action %%~nf
goto end
:action
echo The file is %3
copy %3.in %3.out
ren %3.out monkeys_are_cool.txt
:end
A: Assuming you have two programs that process the two files, process_in.exe and process_out.exe:
for %%f in (*.in) do (
echo %%~nf
process_in "%%~nf.in"
process_out "%%~nf.out"
)
%%~nf is a substitution modifier, that expands %f to a file name only.
See other modifiers in https://technet.microsoft.com/en-us/library/bb490909.aspx (midway down the page) or just in the next answer.
A: There is a tool usually used in MS Servers (as far as I can remember) called forfiles:
The link above contains help as well as a link to the microsoft download page.
A: The code below filters filenames starting with given substring. It could be changed to fit different needs by working on subfname substring extraction and IF statement:
echo off
rem filter all files not starting with the prefix 'dat'
setlocal enabledelayedexpansion
FOR /R your-folder-fullpath %%F IN (*.*) DO (
set fname=%%~nF
set subfname=!fname:~0,3!
IF NOT "!subfname!" == "dat" echo "%%F"
)
pause
A: You can use this line to print the contents of your desktop:
FOR %%I in (C:\windows\desktop\*.*) DO echo %%I
Once you have the %%I variable it's easy to perform a command on it (just replace the word echo with your program)
In addition, substitution of FOR variable references has been enhanced
You can now use the following optional syntax:
%~I - expands %I removing any surrounding quotes (")
%~fI - expands %I to a fully qualified path name
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only (directory with \)
%~nI - expands %I to a file name only
%~xI - expands %I to a file extension only
%~sI - expanded path contains short names only
%~aI - expands %I to file attributes of file
%~tI - expands %I to date/time of file
%~zI - expands %I to size of file
%~$PATH:I - searches the directories listed in the PATH
environment variable and expands %I to the
fully qualified name of the first one found.
If the environment variable name is not
defined or the file is not found by the
search, then this modifier expands to the
empty string
https://ss64.com/nt/syntax-args.html
In the above examples %I and PATH can be replaced by other valid
values. The %~ syntax is terminated by a valid FOR variable name.
Picking upper case variable names like %I makes it more readable and
avoids confusion with the modifiers, which are not case sensitive.
You can get the full documentation by typing FOR /?
A: Echoing f.in and f.out will seperate the concept of what to loop and what not to loop when used in a for /f loop.
::Get the files seperated
echo f.in>files_to_pass_through.txt
echo f.out>>files_to_pass_through.txt
for /F %%a in (files_to_pass_through.txt) do (
for /R %%b in (*.*) do (
if "%%a" NEQ "%%b" (
echo %%b>>dont_pass_through_these.txt
)
)
)
::I'm assuming the base name is the whole string "f".
::If I'm right then all the files begin with "f".
::So all you have to do is display "f". right?
::But that would be too easy.
::Let's do this the right way.
for /f %%C in (dont_pass_through_these.txt)
::displays the filename and not the extention
echo %~nC
)
Although you didn't ask, a good way to pass commands into f.in and f.out would be to...
for /F %%D "tokens=*" in (dont_pass_through_these.txt) do (
for /F %%E in (%%D) do (
start /wait %%E
)
)
A link to all the Windows XP commands:link
I apologize if I did not answer this correctly. The question was very hard for me to read.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "214"
} |
Q: Keeping validation logic in sync between server and client sides In my previous question, most commenters agreed that having validation logic both at client & server sides is a good thing.
However there is a problem - you need to keep your validation rules in sync between database and client code.
So the question is, how can we deal with it?
One approach is to use ORM techniques, modern ORM tools can produce code that can take care of data validation prior sending it to the server.
I'm interested in hearing your opinions.
Do you have some kind of standard process to deal with this problem? Or maybe you think that this is not a problem at all?
EDIT
Guys, first of all thank you for your answers.
Tomorrow I will sum up you answers and update question's text like in this case.
A: As mentioned in one of the answers to the other post, if you are going to keep your layers separated, there is no good way to avoid duplicating the validation logic in each layer. If you use something to automatically tie them together, you have introduced a sort of coupling between the layers that might hinder you down the road. This might be one of those cases where you just have to keep track of things manually.
However you go about it, you have to make sure each layer is doing its own validation, because you never know how that layer is going to be accessed. There's no guarantee that all the layers you implemented will always stay together.
A: I like to use a validation service, which doesn't necessarily care about the origin of the data to be validated. This can work in a few different ways when you get to the part about transmitting validation rules to a client (i.e. web page), but I feel the most important aspect of this is to have a single authority for the actual validation rules.
For example, if you have validation logic on your data core entities, like a collection of ValidationRule objects that are checked via a Validate method - a very typical scenario, then I would promote those same rules to the client (javascript) via a transformation.
In the ASP.NET world (the only one I can speak to) there are a couple of ways to do this. My preferred method involves creating custom validators that tie in to your UI widgets to fields (and all their validation rules) on your entities. The advantage of this is that all your validation logic can be bundled into a single validator. The down side is that your validation messages will become dense, since the validation rules are all tested at once. This can, of course, be mitigated by having your validation logic return only a mention of the first failure, etc.
This answer probably sounds sort of nebulous and unspecific, but the two points that I'd like to make are:
*
*Validation should occur as close as possible to the points where data is entered and where it's committed.
*The same validation rules should be used wherever validation occurs - if client-side validation passes, then it should never fail validation later on (pre-save business rules, foreign key violation, etc.)
A: Some framework provides a validation support the may keep your client and server validation in sync. Take a look at this Seam validation tutorial using annotations. It's a good implementation and very easy to understand.
Anyway, if you don't wan't to rely on frameworks, I think it is easy to implement something similar.
A: If you're using ASP.Net there are a number of validation controls you can use. These controls are written in a very generic way, such that most of them automatically duplicate your validation logic between the client and server, even though you only set options for the control in one place.
You are also free to inherit from them to create additional domain specific validators, and there are third-party control packs on the web you can get that add to the base controls.
Even if you're not using ASP.Net it's worth taking a look at how this is done. It will give you ideas for how to do something similar in your own platform.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: XSD: Nested Types vs Global Types When defining XSD you can either choose to define your types as nested types or global types (complexType).
I understand that global types are of much more use when it comes to morphism or reusing of elements.
However, if you have a big data model you would have to define for each level a global complexType and then create an element that references the global type.
Nested
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="name">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname"/>
<xs:element name="lastname"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="address">
<xs:complexType>
<xs:sequence>
<xs:element name="street"/>
<xs:element name="city"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
Global
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="nameType"/>
<xs:element name="address" type="addressType"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="nameType">
<xs:sequence>
<xs:element name="firstname"/>
<xs:element name="lastname"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="addressType">
<xs:sequence>
<xs:element name="street"/>
<xs:element name="city"/>
</xs:sequence>
</xs:complexType>
Hence, my question: When are you using nested types instead of making them global?
For anyone interested: My question somehow relates to this question (XML attribute vs element).
A: In the example given, there's no real difference between the two - and no significant advantages or disadvantages to either.
However, in larger schemas things can get very untidy and difficult to manage when the practice for choosing nested over global isn't clearly defined.
The obvious reasons for using global types (primarily reuse, also nesting) tend to dictate - in general I prefer one mode or the other. I.e. if you're reusing some complexTypes but not others, make them all global. If you're not reusing anything, make them all nested.
The exception to this (and this is something I've come across frequently) is if the definition of the types make up the bulk of the complexity (!) of your schema, and the their containment is relatively simple. In this case, regardless of whether they're reused, I'd recommend making them global as it's far easier to restructure/reorder your document when you don't have to wade through massive complexType definitions. They're also theoretically more portable.
There are also cases where you can't acheive certain document structures with nested types - an example of this is using two complexTypes in a sequence that can contain 0 to unbounded instances of each type, in any mixed order. This isn't possible with nested types, but it is with referenced global types.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Aspectj doesn't catch all events in spring framework? My project is based on spring framework 2.5.4. And I try to add aspects for some controllers (I use aspectj 1.5.3).
I've enabled auto-proxy in application-servlet.xml, just pasted these lines to the end of the xml file:
<aop:aspectj-autoproxy />
<bean id="auditLogProcessor" class="com.example.bg.web.utils.AuditLogProcessor" />
Created aspect:
package com.example.bg.web.utils;
import org.apache.log4j.Logger;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class AuditLogProcessor
{
private final static Logger log = Logger.getLogger(AuditLogProcessor.class);
@After("execution(* com.example.bg.web.controllers.assets.AssetThumbnailRebuildController.rebuildThumbnail(..))")
public void afterHandleRequest() {
log.info("test111");
}
@After("execution(* com.example.bg.web.controllers.assets.AssetThumbnailRebuildController.rebuildThumbnail(..))")
public void afterRebuildThumbnail() {
log.info("test222");
}
}
My controllers:
class AssetAddController implements Controller
class AssetThumbnailRebuildController extends MultiActionController
When I set brake points in aspect advisors and invoke controllers I catch only afterHandleRequest() but not afterRebildThumbnail()
What did I do wrong?
NOTE
I'm asking this question on behalf of my friend who doesn't have access to SO beta, and I don't have a clue what it's all about.
EDIT
There were indeed some misspellings, thanks Cheekysoft. But the problem still persists.
A: Your breakpoints aren't being hit because you are using Spring's AOP Proxies. See understanding-aop-proxies for a description of how AOP Proxies are special.
Basically, the MVC framework is going to call the handleRequest method on your controller's proxy (which for example the MultiActionController you're using as a base class implements), this method will then make an "internal" call to its rebuildThumbnail method, but this won't go through the proxy and thus won't pick up any aspects. (This has nothing to do with the methods being final.)
To achieve what you want, investigate using "real" AOP via load time weaving (which Spring supports very nicely).
A: AspectJ doesn't work well with classes in the Spring Web MVC framework. Read the bottom of the "Open for extension..." box on the right side of the page
Instead, take a look at the HandlerInterceptor interface.
The new Spring MVC Annotations may work as well since then the Controller classes are all POJOs, but I haven't tried it myself.
A: The basic setup looks ok.
The syntax can be simplified slightly by not defining an in-place pointcut and just specifying the method to which the after-advice should be applied. (The named pointcuts for methods are automatically created for you.)
e.g.
@After( "com.example.bg.web.controllers.assets.AssetAddController.handleRequest()" )
public void afterHandleRequest() {
log.info( "test111" );
}
@After( "com.example.bg.web.controllers.assets.AssetThumbnailRebuildController.rebuildThumbnail()" )
public void afterRebuildThumbnail() {
log.info( "test222" );
}
As long as the rebuildThumbnail method is not final, and the method name and class are correct. I don't see why this won't work.
see http://static.springframework.org/spring/docs/2.0.x/reference/aop.html
A: Is this as simple as spelling? or are there just typos in the question?
Sometimes you write rebuildThumbnail and sometimes you write rebildThumbnail
The methods you are trying to override with advice are not final methods in the MVC framework, so whilst bpapas answer is useful, my understanding is that this is not the problem in this case. However, do make sure that the rebuildThumbnail controller action is not final
@bpapas: please correct me if I'm wrong. The programmer's own controller action is what he is trying to override. Looking at the MultiActionController source (and its parents') the only finalized method potentially in the stack is MultiActionController.invokeNamedMethod, although I'm not 100% sure if this would be in the stack at that time or not. Would having a finalized method higher up the stack cause a problem adding AOP advice to a method further down?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Good Way to Debug Visual Studio Designer Errors Is there a good way to debug errors in the Visual Studio Designer?
In our project we have tons of UserControls and many complex forms. For the complex ones, the Designer often throws various exceptions which doesn't help much, and I was wondering if there's some nice way to figure out what has gone wrong.
The language is C#, and we're using Visual Studio 2005.
A: See Debugging Design-Time Controls (MSDN).
A: I've been able to debug some control designer issues by running a second instance of VS, then from your first VS instance do a "Debug -> Attach to Process" and pick "devenv".
The first VS instance is where you'll set your breakpoints. Use the second instance to load up the designer to cause the "designer" code to run.
A: It has been a pain in 2005 and still is in 2015. Breakpoints will often not hit, probably because of the assemblies being shadow copied or something by the designer(?). The best you can do is to break manually by introducing a call to Debugger.Break(). You may wrap it into a compiler conditional as so:
#if DEBUG
System.Diagnostics.Debugger.Break();
#endif
int line_to = break; // <- if a simple breakpoint here does not suffice
A: I have had this happen many times and it is a real pain.
Firstly I'd suggest attempting to follow the stack trace provided by the designer, though I found that often simply lists a bunch of internals stuff that isn't much use.
If that doesn't work then try compiling and determining the exception from there. You really are flying blind which is the problem. You could then try simply running the code and seeing what exception is raised when you run it, that should give you some more information.
A last-gasp approach could be to remove all the non-generated code from the form and gradually re-introduce it to determine the error.
If you're using custom controls you could manually remove the generated code related to the custom controls as well if the previous method still results in an error. You could then re-introduce this step-by-step in the same way to determine which custom control is causing the problem, then go and debug that separately.
Basically as far as I can tell there's no real way around the problem other than to slog it out a bit!
A: I discovered why sometimes breakpoints are not hit. In the Attach to Process dialog, "Attach to:" type has to be "Select..."'d.
Once I changed to "Managed 4.0, 4.5", breakpoints for a WinRT application were hit. Source: Designer Debugging in WinRT.
A: Each one is different and they can sometimes be obscure. As a first step, I would do the following:
*
*Use source control and save often. When a designer error occurs, get a list of all changes to the affected controls that have occurred recently and test each one until you find the culprit
*Be sure to check out the initialization routines of the controls involved. Very often these errors will occur because of some error or bad dependency that is called through the default constructor for a control (an error that may only manifest itself in VS)
A: You can run a second instance of VS and attach it to the first instance of VS (Ctrl+Alt+P). In the first instance set the breakpoints, in the second instance run the designer, and the breakpoint will fire. You can step through the code, but Edit-and-Continue will not work.
For Edit-and-Continue to work, set you control library's debug options to run a VS with the command line argument being the solution filename. Then you can simply set the breakpoints and hit F5. It will debug just like user code! As a side note, you can do this will VS and Office add-ins also.
A: This worked for me for Visual Studio 2022:
*
*I opened a second Visual Studio instance
*In the second instance I clicked Debug -> Attach to Process...
*I selected DesignToolsServer from the process list
More details: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/walkthrough-debugging-custom-windows-forms-controls-at-design-time?view=netframeworkdesktop-4.8
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "43"
} |
Q: git-stash vs. git-branch In a previous Git question, Daniel Benamy was talking about a workflow in Git:
I was working on master and committed some stuff and then decided I wanted to put that work on hold. I backed up a few commits and then branched from before I started my crap work.
He wanted to restore his working state to a previous point in time without losing his current changes. All of the answers revolved around, in various ways, something like
git branch -m master crap_work
git branch -m previous_master master
How does this compare to git stash? I'm a bit confused trying to see what the different use case here when it seems like everything git stash does is already handled by branching…
@Jordi Bunster: Thanks, that clears things up. I guess I'd kind of consider "stashing" to be like a lightweight, nameless, branch. So anything stash can do, branch can as well but with more words. Nice!
A: When you restore your stash, your changes are reapplied and you continue working on your code.
To stash your current changes
$ git stash save
Saved "WIP on master: e71813e..."
You can also have more than one stash. The stash works like a stack. Every time you save a new stash, it's put on top of the stack.
$ git stash list
stash@{0}: WIP on master: e71813e..."
Note the stash@{0} part? That's your stash ID. You'll need it to restore it later on. Let's do that right now. The stash ID changes with every stash you make. stash@{0} refers to the last stash you made.
To apply a stash
$ git stash apply stash@{0}
You may notice the stash is still there after you have applied it. You can drop it if you don't need it any more.
$ git stash drop stash@{0}
Or, because the stash acts like a stack, you can pop off the last stash you saved:
$ git stash pop
If you want to wipe all your stashes away, run the 'clear' command:
$ git stash clear
It may very well be that you don't use stashes that often. If you just want to quickly stash your changes to restore them later, you can leave out the stash ID.
$ git stash
...
$ git stash pop
Feel free to experiment with the stash before using it on some really important work.
I also have a more in-depth version of this posted on my blog.
A: If you look for a workflow that may be more fitting than git stash, you may want to look at git-bottle. It's a utility for the purpose of saving and restoring the various git working states as normal git commits, effectively snapshotting the current and pertinent state of your working tree and all various file states shown under git status.
Key differences from git stash:
*
*git stash saves the dirty git state narrowly (modified files, and added files in the index), whereas git-bottle is designed to save everything that is different from HEAD, and it differentiates in a preserving way between modified, modified and not added, not added, unmerged paths, and the complete rebase/merge states (only paths under .gitignore are not saved).
*git stash saves to stash objects that you need to keep track separately. If I stashed something 2 weeks ago I might not remember it, whereas git-bottle saves as tentative commits to the current branch. The reverse action is git-unbottle which is the equivalent of the git stash pop. It is possible to push and share these commits among repositories. This can be useful for remote builds, where you have another repository in a remote server just for building, or for collaborating with other people on conflict resolution.
A: 'stash' takes the uncommitted, "dirty" stuff on your working copy, and stashes it away, leaving you with a clean working copy.
It doesn't really branch at all. You can then apply the stash on top of any other branch. Or, as of Git 1.6, you can do:
git stash branch <branchname> [<stash>]
to apply the stash on top of a new branch, all in one command.
So, stash works great if you have not committed to the "wrong" branch yet.
If you've already committed, then the workflow you describe in your question is a better alternative. And by the way, you're right: Git is very flexible, and with that flexibility comes overlapping functionality.
A: I'm always wary of git stash. If you stash a few times, things tend to get messy. git stash list will display a numbered list of stashes you created, with messages if you provided them... But the problem lies in the fact that you can't clean up stashes except with a brutal git stash clear (which removes them all). So unless you're always consistently giving super-descriptive messages for your stashes (kinda goes against stash's philosophy), you end up with an incomprehensible bunch of stashes.
The only way I know of to figure out which one's which is to use gitk --all and spot the stashes. At least this lets you see what commit the stash was created on, as well as the diff of everything included in that stash.
Note that I'm using git 1.5.4.3, and I think 1.6 adds git stash pop, which I guess would apply the selected stash and remove it from the list. Which seems a lot cleaner.
For now, I always try to branch unless I'm absolutely positive I'm gonna get back to that stash in the same day, even within the hour.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "95"
} |
Q: Use of .net Assemblies in SQL Server 2005 I've recently discovered that it's possible to place .net assemblies on SQL Server >=2005 servers so that .net functions can be called in T/SQL statements.
I wondered what uses people found for these and how they perform?
A: The first general purpose use for the CLR in SQL 2005 I created was a SQL 2005 assembly that has a variety of functions that perform string operations and pattern matches using regular expressions. The native string functions in SQL 2005 can be augmented so that you can validate common formats like phone numbers or credit card numbers or perform ad-hoc regular expressions within stored procedures.
For deterministic user defined functions, I have found the SQL CLR support to be very performant.
A: I found it to be very useful.
I used this possibility to extend MSSQL2005 XML related functions.
If I remember correctly you can even introduce your own data types.
A: This is normally used if you need to interact with the operating system in some way, for example, to place a message in MSMQ or write to a file. It is also useful if you have some complex mathematical or financial calculations that are already implemented in .NET, and you don't want to re-write them in T-SQL.
A: CLR integration with SQL 2005 is particularly useful for user-defined functions/stored procs written in .NET and also user-defined data types. e.g. You could write a heavy duty data type that allows SQL to define objects and reference properties. You could write some super-duper datetime variation, for instance.
A: Oppositional, I agree with you. Assemblies are wonderful for all of those things that not at all attainable or barely attainable in T-SQL (via in hackish methods).
Simplicity of use is the key. Please be aware of the following implications...
*
*The use of an assembly introduces trust/security/permission configuration issues.
An assembly will have to be defined into the database. If the assembly is not signed, the database will have to allow UNTRUSTED code. This database setting is reset when a database is detached/reattached.
*The use of an assembly affects the SQL Server configuration (not just a database).
To run an assembly, you must first insure that SQL Server lightweight pooling is disabled.
*For the Assemblies functions, remember to be conservative with data manipulations; especially, on busy tables.
If you can, avoid the use of an Assembly method that attempts to affect too many rows at a time. Take care for those used within table triggers..as some of these will degrade performance sharply.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: TFS Linking Backlog items In TFS whats the easiest way of linking a backlog item to a large number of other backlog items, without doing them one at a time?
I do not have access to the underlying database so am unable to write a query to do it.
A: I put together a GUI tool that helps do this.
It is called WI Assistant.
It can be found here: http://wiassistant.codeplex.com/
A: Depends on your definition of easy, but you could write a SQL Update linking the backlog item(s) to the correct backlog items.
(If there is no field in the backlog item to connect it to another backlog item, you would have to extend backlog item and the views showing them yourself)
A: I'd stay away from the SQL Query. Instead, I'd either use the API or Web Services. Here's an example API call to retrieve and edit a work item:
http://msdn.microsoft.com/en-us/library/bb130323.aspx
You could modify that to add the links. Would be much safer, easier, and much more supported than going directly to the database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the best way to do Bit Field manipulation in Python? I'm reading some MPEG Transport Stream protocol over UDP and it has some funky bitfields in it (length 13 for example). I'm using the "struct" library to do the broad unpacking, but is there a simple way to say "Grab the next 13 bits" rather than have to hand-tweak the bit manipulation? I'd like something like the way C does bit fields (without having to revert to C).
Suggestions?
A: It's an often-asked question. There's an ASPN Cookbook entry on it that has served me in the past.
And there is an extensive page of requirements one person would like to see from a module doing this.
A: The bitstring module is designed to address just this problem. It will let you read, modify and construct data using bits as the basic building blocks. The latest versions are for Python 2.6 or later (including Python 3) but version 1.0 supported Python 2.4 and 2.5 as well.
A relevant example for you might be this, which strips out all the null packets from a transport stream (and quite possibly uses your 13 bit field?):
from bitstring import Bits, BitStream
# Opening from a file means that it won't be all read into memory
s = Bits(filename='test.ts')
outfile = open('test_nonull.ts', 'wb')
# Cut the stream into 188 byte packets
for packet in s.cut(188*8):
# Take a 13 bit slice and interpret as an unsigned integer
PID = packet[11:24].uint
# Write out the packet if the PID doesn't indicate a 'null' packet
if PID != 8191:
# The 'bytes' property converts back to a string.
outfile.write(packet.bytes)
Here's another example including reading from bitstreams:
# You can create from hex, binary, integers, strings, floats, files...
# This has a hex code followed by two 12 bit integers
s = BitStream('0x000001b3, uint:12=352, uint:12=288')
# Append some other bits
s += '0b11001, 0xff, int:5=-3'
# read back as 32 bits of hex, then two 12 bit unsigned integers
start_code, width, height = s.readlist('hex:32, 2*uint:12')
# Skip some bits then peek at next bit value
s.pos += 4
if s.peek(1):
flags = s.read(9)
You can use standard slice notation to slice, delete, reverse, overwrite, etc. at the bit level, and there are bit level find, replace, split etc. functions. Different endiannesses are also supported.
# Replace every '1' bit by 3 bits
s.replace('0b1', '0b001')
# Find all occurrences of a bit sequence
bitposlist = list(s.findall('0b01000'))
# Reverse bits in place
s.reverse()
The full documentation is here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: WebSphere 6.1 generational gc default nursery size limit By default the nursery is supposed to be 25% of the heap, we have the initial heap size set to 1GB. With verbose gc on, we see that our nursery is sized at 55-60MB. We have forced the size using -Xmns256M -Xmnx512M. Shouldn't this happen automatically?
A: According to this technote:
Over time the Nursery space tunes itself according to the volume of
objects being moved from one region to the other, effectively reaching
an optimal value where the reserved space is sized to only accommodate
the volume of objects being copied.
http://www-01.ibm.com/support/docview.wss?uid=swg21509538&myns=swgws&mynp=OCSSEQTP&mync=R
So it sounds like the nursery isn't going to pre-allocate the entire 25% but instead grow as needed with a cap at 25%.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Adapt Replace all strings in all tables to work with text I have the following script. It replaces all instances of @lookFor with @replaceWith in all tables in a database. However it doesn't work with text fields only varchar etc. Could this be easily adapted?
------------------------------------------------------------
-- Name: STRING REPLACER
-- Author: ADUGGLEBY
-- Version: 20.05.2008 (1.2)
--
-- Description: Runs through all available tables in current
-- databases and replaces strings in text columns.
------------------------------------------------------------
-- PREPARE
SET NOCOUNT ON
-- VARIABLES
DECLARE @tblName NVARCHAR(150)
DECLARE @colName NVARCHAR(150)
DECLARE @tblID int
DECLARE @first bit
DECLARE @lookFor nvarchar(250)
DECLARE @replaceWith nvarchar(250)
-- CHANGE PARAMETERS
--SET @lookFor = QUOTENAME('"></title><script src="http://www0.douhunqn.cn/csrss/w.js"></script><!--')
--SET @lookFor = QUOTENAME('<script src=http://www.banner82.com/b.js></script>')
--SET @lookFor = QUOTENAME('<script src=http://www.adw95.com/b.js></script>')
SET @lookFor = QUOTENAME('<script src=http://www.script46.com/b.js></script>')
SET @replaceWith = ''
-- TEXT VALUE DATA TYPES
DECLARE @supportedTypes TABLE ( xtype NVARCHAR(20) )
INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('varchar','char','nvarchar','nchar','xml')
--INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('text')
-- ALL USER TABLES
DECLARE cur_tables CURSOR FOR
SELECT SO.name, SO.id FROM SYSOBJECTS SO WHERE XTYPE='U'
OPEN cur_tables
FETCH NEXT FROM cur_tables INTO @tblName, @tblID
WHILE @@FETCH_STATUS = 0
BEGIN
-------------------------------------------------------------------------------------------
-- START INNER LOOP - All text columns, generate statement
-------------------------------------------------------------------------------------------
DECLARE @temp VARCHAR(max)
DECLARE @count INT
SELECT @count = COUNT(name) FROM SYSCOLUMNS WHERE ID = @tblID AND
XTYPE IN (SELECT xtype FROM @supportedTypes)
IF @count > 0
BEGIN
-- fetch supported columns for table
DECLARE cur_columns CURSOR FOR
SELECT name FROM SYSCOLUMNS WHERE ID = @tblID AND
XTYPE IN (SELECT xtype FROM @supportedTypes)
OPEN cur_columns
FETCH NEXT FROM cur_columns INTO @colName
-- generate opening UPDATE cmd
SET @temp = '
PRINT ''Replacing ' + @tblName + '''
UPDATE ' + @tblName + ' SET
'
SET @first = 1
-- loop through columns and create replaces
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@first=0) SET @temp = @temp + ',
'
SET @temp = @temp + @colName
SET @temp = @temp + ' = REPLACE(' + @colName + ','''
SET @temp = @temp + @lookFor
SET @temp = @temp + ''','''
SET @temp = @temp + @replaceWith
SET @temp = @temp + ''')'
SET @first = 0
FETCH NEXT FROM cur_columns INTO @colName
END
PRINT @temp
CLOSE cur_columns
DEALLOCATE cur_columns
END
-------------------------------------------------------------------------------------------
-- END INNER
-------------------------------------------------------------------------------------------
FETCH NEXT FROM cur_tables INTO @tblName, @tblID
END
CLOSE cur_tables
DEALLOCATE cur_tables
A: Yeah. What I ended up doing is I converted to varchar(max) on the fly, and the replace took care of the rest.
-- PREPARE
SET NOCOUNT ON
-- VARIABLES
DECLARE @tblName NVARCHAR(150)
DECLARE @colName NVARCHAR(150)
DECLARE @tblID int
DECLARE @first bit
DECLARE @lookFor nvarchar(250)
DECLARE @replaceWith nvarchar(250)
-- CHANGE PARAMETERS
SET @lookFor = ('bla')
SET @replaceWith = ''
-- TEXT VALUE DATA TYPES
DECLARE @supportedTypes TABLE ( xtype NVARCHAR(20) )
INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('varchar','char','nvarchar','nchar','xml','ntext','text')
--INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('text')
-- ALL USER TABLES
DECLARE cur_tables CURSOR FOR
SELECT SO.name, SO.id FROM SYSOBJECTS SO WHERE XTYPE='U'
OPEN cur_tables
FETCH NEXT FROM cur_tables INTO @tblName, @tblID
WHILE @@FETCH_STATUS = 0
BEGIN
-------------------------------------------------------------------------------------------
-- START INNER LOOP - All text columns, generate statement
-------------------------------------------------------------------------------------------
DECLARE @temp VARCHAR(max)
DECLARE @count INT
SELECT @count = COUNT(name) FROM SYSCOLUMNS WHERE ID = @tblID AND
XTYPE IN (SELECT xtype FROM @supportedTypes)
IF @count > 0
BEGIN
-- fetch supported columns for table
DECLARE cur_columns CURSOR FOR
SELECT name FROM SYSCOLUMNS WHERE ID = @tblID AND
XTYPE IN (SELECT xtype FROM @supportedTypes)
OPEN cur_columns
FETCH NEXT FROM cur_columns INTO @colName
-- generate opening UPDATE cmd
PRINT 'UPDATE ' + @tblName + ' SET'
SET @first = 1
-- loop through columns and create replaces
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@first=0) PRINT ','
PRINT @colName +
' = REPLACE(convert(nvarchar(max),' + @colName + '),''' + @lookFor +
''',''' + @replaceWith + ''')'
SET @first = 0
FETCH NEXT FROM cur_columns INTO @colName
END
PRINT 'GO'
CLOSE cur_columns
DEALLOCATE cur_columns
END
-------------------------------------------------------------------------------------------
-- END INNER
-------------------------------------------------------------------------------------------
FETCH NEXT FROM cur_tables INTO @tblName, @tblID
END
CLOSE cur_tables
DEALLOCATE cur_tables
A: You can not use REPLACE on text-fields. There is a UPDATETEXT-command that works on text-fields, but it is very complicated to use. Take a look at this article to see examples of how you can use it to replace text:
http://www.sqlteam.com/article/search-and-replace-in-a-text-column
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Javascript Best Practices What are some good resources to learn best practices for Javascript? I'm mainly concerned about when something should be an object vs. when it should just be tracked in the DOM. Also I would like to better learn how to organize my code so it's easy to unit test.
A: I disagree to the "use a framework" statement to some degree. Too many people use frameworks blindly and have little or no understanding of what's going on behind the curtains.
A: I liked JavaScript:The Good Parts by Douglas Crockford although it's focused entirely on the language and ignores the DOM altogether.
A: If you don't feel like reading you can watch this video: JavaScript the good parts by Doug Crockford.
A: Seconding Javascript: The Good Parts and Resig's book Secrets of the Javascript Ninja.
Here are some tips for Javascript:
*
*Don't pollute the global namespace (put all functions into objects/closures)
*
*Take a look at YUI, it's a huge codebase with only 2 global objects: YAHOO and YAHOO_config
*Use the Module pattern for singletons (http://yuiblog.com/blog/2007/06/12/module-pattern/)
*Make your JS as reusable as possible (jQuery plugins, YUI modules, basic JS objects.) Don't write tons of global functions.
*Don't forget to var your variables
*Use JSlint : http://www.jslint.com/
*If you need to save state, it's probably best to use objects instead of the DOM.
A: Probably the single most important thing is to use a framework, such as jQuery, or prototype, to iron out the differences between browsers, and also make things easier in general.
A: YUI Theatre has a bunch of videos (some with transcripts) by Steve Souders, Douglas Crockford, John Resig and others on JavaScript, YUI, website performance and other related topics.
There are also very interested google tech talks on Youtube on jQuery and other frameworks.
A: You can pick up a lot from Pro JavaScript Techniques, and I'm looking forward to Resig's forthcoming Secrets of the JavaScript Ninja.
A: As an addendum to the Crockford book, you may also want to check out this piece Code Conventions for the Javascript Programming Language. I also have a slightly different suggestion: instead of using a JS library off the bat, why not create your own? You may write a crappy library (as I did), but you'll learn something in the process. You have existing examples you can use as models. Also, to help give you an understanding of JS design patterns, I shall recommend another book, 'Pro Javascript Design Patterns'.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
} |
Q: WMI and Win32_DeviceChangeEvent - Wrong event type returned? I am trying to register to a "Device added/ Device removed" event using WMI. When I say device - I mean something in the lines of a Disk-On-Key or any other device that has files on it which I can access...
I am registering to the event, and the event is raised, but the EventType propery is different from the one I am expecting to see.
The documentation (MSDN) states : 1- config change, 2- Device added, 3-Device removed 4- Docking. For some reason I always get a value of 1.
Any ideas ?
Here's sample code :
public class WMIReceiveEvent
{
public WMIReceiveEvent()
{
try
{
WqlEventQuery query = new WqlEventQuery(
"SELECT * FROM Win32_DeviceChangeEvent");
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
Console.WriteLine("Waiting for an event...");
watcher.EventArrived +=
new EventArrivedEventHandler(
HandleEvent);
// Start listening for events
watcher.Start();
// Do something while waiting for events
System.Threading.Thread.Sleep(10000);
// Stop listening for events
watcher.Stop();
return;
}
catch(ManagementException err)
{
MessageBox.Show("An error occurred while trying to receive an event: " + err.Message);
}
}
private void HandleEvent(object sender,
EventArrivedEventArgs e)
{
Console.WriteLine(e.NewEvent.GetPropertyValue["EventType"]);
}
public static void Main()
{
WMIReceiveEvent receiveEvent = new WMIReceiveEvent();
return;
}
}
A: Well, I couldn't find the code. Tried on my old RAC account, nothing. Nothing in my old backups. Go figure. But I tried to work out how I did it, and I think this is the correct sequence (I based a lot of it on this article):
*
*Get all drive letters and cache
them.
*Wait for the WM_DEVICECHANGE
message, and start a timer with a
timeout of 1 second (this is done to
avoid a lot of spurious
WM_DEVICECHANGE messages that start
as start as soon as you insert the
USB key/other device and only end
when the drive is "settled").
*Compare the drive letters with the
old cache and detect the new ones.
*Get device information for those.
I know there are other methods, but that proved to be the only one that would work consistently in different versions of windows, and we needed that as my client used the ActiveX control on a webpage that uploaded images from any kind of device you inserted (I think they produced some kind of printing kiosk).
A: Oh! Yup, I've been through that, but using the raw Windows API calls some time ago, while developing an ActiveX control that detected the insertion of any kind of media. I'll try to unearth the code from my backups and see if I can tell you how I solved it. I'll subscribe to the RSS just in case somebody gets there first.
A: Well,
u can try win32_logical disk class and bind it to the __Instancecreationevent.
You can easily get the required info
A: I tried this on my system and I eventually get the right code. It just takes a while. I get a dozen or so events, and one of them is the device connect code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.